diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4ea99c2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,395 @@ +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/README.md b/README.md index 0f62012..cab2fe9 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,38 @@ -# project.lecture-wasm -A project repository to test WASM compatibility and limitations for QuantEcon Lectures +# QuantEcon WASM project + +This repository contains a subset of the [lecture-python-intro](https://intro.quantecon.org/intro.html). + +This project is powered by Pyodide kernel which allows us to run the lectures in the browser without +any installaion. + +## Development + +The script `update_lectures.py` is used to fetch the latest version of lectures from the +[wasm branch of lecture-python-intro series](https://github.com/QuantEcon/lecture-python-intro/tree/wasm). + +In order to build and test the project locally, please install the required libraries using +``` +pip install -r requirements.txt +``` + +And run a local server using +``` +teachbooks serve +``` + +To stop the server use: +``` +teachbooks serve stop +``` + +### Update a lecture? + +In order to update any lecture, it's recommended to update the same lecture in the +[wasm branch of lecture-python-intro series](https://github.com/QuantEcon/lecture-python-intro/tree/wasm) and +run the script +``` +python update_lectures.py +``` + +This allows us the keep all the lectures up-to-date in a single place and keep this repository a mirror of the +main repository. diff --git a/_config_copy.yml b/_config_copy.yml new file mode 100644 index 0000000..32e949a --- /dev/null +++ b/_config_copy.yml @@ -0,0 +1,83 @@ +author: QuantEcon team + +execute: + execute_notebooks: "off" + +only_build_toc_files: true + +html: + favicon : "figures/favicon.ico" + baseurl : "https://quantecon.org/" + +sphinx: + config: + html_js_files: + - https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js + thebe_config: + use_thebe_lite: true + exclude_patterns: ["**/_*.yml", "**/*.md", "**/*.ipynb"] + html_theme_options: + logo: + text: QuantEcon Intro Lectures + image_light: figures/qe-logo.png + image_dark: figures/qe-logo.png + authors: + - name: Thomas J. Sargent + url: http://www.tomsargent.com/ + - name: John Stachurski + url: https://johnstachurski.net/ + header_organisation_url: https://quantecon.org + header_organisation: QuantEcon + repository_url: https://github.com/QuantEcon/lecture-python-advanced.myst + nb_repository_url: https://github.com/QuantEcon/lecture-python-advanced.notebooks + twitter: quantecon + twitter_logo_url: https://assets.quantecon.org/img/qe-twitter-logo.png + og_logo_url: https://assets.quantecon.org/img/qe-og-logo.png + description: This website presents a set of lectures on advanced quantitative economic modeling, designed and written by Thomas J. Sargent and John Stachurski. + keywords: Python, QuantEcon, Quantitative Economics, Economics, Sloan, Alfred P. Sloan Foundation, Tom J. Sargent, John Stachurski + analytics: + google_analytics_id: G-KZLV7PM9LL + launch_buttons: + thebe: true + #colab_url : https://colab.research.google.com + mathjax3_config: + tex: + macros: + "argmax": "arg\\,max" + "argmin": "arg\\,min" + "col": "col" + "Span": "span" + "epsilon": "\\varepsilon" + "EE": "\\mathbb{E}" + "PP": "\\mathbb{P}" + "RR": "\\mathbb{R}" + "NN": "\\mathbb{N}" + "ZZ": "\\mathbb{Z}" + "aA": "\\mathcal{A}" + "bB": "\\mathcal{B}" + "cC": "\\mathcal{C}" + "dD": "\\mathcal{D}" + "eE": "\\mathcal{E}" + "fF": "\\mathcal{F}" + "gG": "\\mathcal{G}" + "hH": "\\mathcal{H}" + html_show_copyright: false + html_last_updated_fmt: '%B %-d, %Y' + html_static_path: ["figures"] # add folders that contain files that need to be included, such as the location of the logo(s) + mathjax3_config: + chtml: { + mtextInheritFont: true # To typeset text within math prettier + } + extra_extensions: + - sphinx.ext.imgconverter + - jupyterbook_patches + - download_link_replacer + - sphinx.ext.extlinks + - sphinx_image_inverter + - sphinx_exercise + - sphinx_proof + - sphinx_tojupyter + - sphinx_reredirects + +bibtex_bibfiles: + - references.bib diff --git a/book/_build/.doctrees/about.doctree b/book/_build/.doctrees/about.doctree new file mode 100644 index 0000000..1a99427 Binary files /dev/null and b/book/_build/.doctrees/about.doctree differ diff --git a/book/_build/.doctrees/ar1_processes.doctree b/book/_build/.doctrees/ar1_processes.doctree new file mode 100644 index 0000000..d0fa151 Binary files /dev/null and b/book/_build/.doctrees/ar1_processes.doctree differ diff --git a/book/_build/.doctrees/business_cycle.doctree b/book/_build/.doctrees/business_cycle.doctree new file mode 100644 index 0000000..d977a70 Binary files /dev/null and b/book/_build/.doctrees/business_cycle.doctree differ diff --git a/book/_build/.doctrees/cagan_adaptive.doctree b/book/_build/.doctrees/cagan_adaptive.doctree new file mode 100644 index 0000000..01a8717 Binary files /dev/null and b/book/_build/.doctrees/cagan_adaptive.doctree differ diff --git a/book/_build/.doctrees/cagan_ree.doctree b/book/_build/.doctrees/cagan_ree.doctree new file mode 100644 index 0000000..fff1cbe Binary files /dev/null and b/book/_build/.doctrees/cagan_ree.doctree differ diff --git a/book/_build/.doctrees/cobweb.doctree b/book/_build/.doctrees/cobweb.doctree new file mode 100644 index 0000000..3226246 Binary files /dev/null and b/book/_build/.doctrees/cobweb.doctree differ diff --git a/book/_build/.doctrees/commod_price.doctree b/book/_build/.doctrees/commod_price.doctree new file mode 100644 index 0000000..c600df6 Binary files /dev/null and b/book/_build/.doctrees/commod_price.doctree differ diff --git a/book/_build/.doctrees/complex_and_trig.doctree b/book/_build/.doctrees/complex_and_trig.doctree new file mode 100644 index 0000000..f3cbef6 Binary files /dev/null and b/book/_build/.doctrees/complex_and_trig.doctree differ diff --git a/book/_build/.doctrees/cons_smooth.doctree b/book/_build/.doctrees/cons_smooth.doctree new file mode 100644 index 0000000..ea353b1 Binary files /dev/null and b/book/_build/.doctrees/cons_smooth.doctree differ diff --git a/book/_build/.doctrees/eigen_I.doctree b/book/_build/.doctrees/eigen_I.doctree new file mode 100644 index 0000000..e218a96 Binary files /dev/null and b/book/_build/.doctrees/eigen_I.doctree differ diff --git a/book/_build/.doctrees/eigen_II.doctree b/book/_build/.doctrees/eigen_II.doctree new file mode 100644 index 0000000..f43f923 Binary files /dev/null and b/book/_build/.doctrees/eigen_II.doctree differ diff --git a/book/_build/.doctrees/environment.pickle b/book/_build/.doctrees/environment.pickle new file mode 100644 index 0000000..b4f45fd Binary files /dev/null and b/book/_build/.doctrees/environment.pickle differ diff --git a/book/_build/.doctrees/equalizing_difference.doctree b/book/_build/.doctrees/equalizing_difference.doctree new file mode 100644 index 0000000..8970dcb Binary files /dev/null and b/book/_build/.doctrees/equalizing_difference.doctree differ diff --git a/book/_build/.doctrees/french_rev.doctree b/book/_build/.doctrees/french_rev.doctree new file mode 100644 index 0000000..85d31b5 Binary files /dev/null and b/book/_build/.doctrees/french_rev.doctree differ diff --git a/book/_build/.doctrees/geom_series.doctree b/book/_build/.doctrees/geom_series.doctree new file mode 100644 index 0000000..bd50a7f Binary files /dev/null and b/book/_build/.doctrees/geom_series.doctree differ diff --git a/book/_build/.doctrees/greek_square.doctree b/book/_build/.doctrees/greek_square.doctree new file mode 100644 index 0000000..b14b53c Binary files /dev/null and b/book/_build/.doctrees/greek_square.doctree differ diff --git a/book/_build/.doctrees/heavy_tails.doctree b/book/_build/.doctrees/heavy_tails.doctree new file mode 100644 index 0000000..008b184 Binary files /dev/null and b/book/_build/.doctrees/heavy_tails.doctree differ diff --git a/book/_build/.doctrees/inequality.doctree b/book/_build/.doctrees/inequality.doctree new file mode 100644 index 0000000..98640ce Binary files /dev/null and b/book/_build/.doctrees/inequality.doctree differ diff --git a/book/_build/.doctrees/inflation_history.doctree b/book/_build/.doctrees/inflation_history.doctree new file mode 100644 index 0000000..770ad76 Binary files /dev/null and b/book/_build/.doctrees/inflation_history.doctree differ diff --git a/book/_build/.doctrees/input_output.doctree b/book/_build/.doctrees/input_output.doctree new file mode 100644 index 0000000..2093a63 Binary files /dev/null and b/book/_build/.doctrees/input_output.doctree differ diff --git a/book/_build/.doctrees/intro.doctree b/book/_build/.doctrees/intro.doctree new file mode 100644 index 0000000..69a4c34 Binary files /dev/null and b/book/_build/.doctrees/intro.doctree differ diff --git a/book/_build/.doctrees/intro_supply_demand.doctree b/book/_build/.doctrees/intro_supply_demand.doctree new file mode 100644 index 0000000..e993adc Binary files /dev/null and b/book/_build/.doctrees/intro_supply_demand.doctree differ diff --git a/book/_build/.doctrees/laffer_adaptive.doctree b/book/_build/.doctrees/laffer_adaptive.doctree new file mode 100644 index 0000000..282b293 Binary files /dev/null and b/book/_build/.doctrees/laffer_adaptive.doctree differ diff --git a/book/_build/.doctrees/lake_model.doctree b/book/_build/.doctrees/lake_model.doctree new file mode 100644 index 0000000..16372f4 Binary files /dev/null and b/book/_build/.doctrees/lake_model.doctree differ diff --git a/book/_build/.doctrees/linear_equations.doctree b/book/_build/.doctrees/linear_equations.doctree new file mode 100644 index 0000000..ba1e8df Binary files /dev/null and b/book/_build/.doctrees/linear_equations.doctree differ diff --git a/book/_build/.doctrees/lln_clt.doctree b/book/_build/.doctrees/lln_clt.doctree new file mode 100644 index 0000000..9ab7525 Binary files /dev/null and b/book/_build/.doctrees/lln_clt.doctree differ diff --git a/book/_build/.doctrees/long_run_growth.doctree b/book/_build/.doctrees/long_run_growth.doctree new file mode 100644 index 0000000..aaf9cee Binary files /dev/null and b/book/_build/.doctrees/long_run_growth.doctree differ diff --git a/book/_build/.doctrees/lp_intro.doctree b/book/_build/.doctrees/lp_intro.doctree new file mode 100644 index 0000000..7e5cd32 Binary files /dev/null and b/book/_build/.doctrees/lp_intro.doctree differ diff --git a/book/_build/.doctrees/markov_chains_I.doctree b/book/_build/.doctrees/markov_chains_I.doctree new file mode 100644 index 0000000..cbf2bc2 Binary files /dev/null and b/book/_build/.doctrees/markov_chains_I.doctree differ diff --git a/book/_build/.doctrees/markov_chains_II.doctree b/book/_build/.doctrees/markov_chains_II.doctree new file mode 100644 index 0000000..23c4ad0 Binary files /dev/null and b/book/_build/.doctrees/markov_chains_II.doctree differ diff --git a/book/_build/.doctrees/mle.doctree b/book/_build/.doctrees/mle.doctree new file mode 100644 index 0000000..b81541f Binary files /dev/null and b/book/_build/.doctrees/mle.doctree differ diff --git a/book/_build/.doctrees/money_inflation.doctree b/book/_build/.doctrees/money_inflation.doctree new file mode 100644 index 0000000..395e7d1 Binary files /dev/null and b/book/_build/.doctrees/money_inflation.doctree differ diff --git a/book/_build/.doctrees/money_inflation_nonlinear.doctree b/book/_build/.doctrees/money_inflation_nonlinear.doctree new file mode 100644 index 0000000..3d24a04 Binary files /dev/null and b/book/_build/.doctrees/money_inflation_nonlinear.doctree differ diff --git a/book/_build/.doctrees/monte_carlo.doctree b/book/_build/.doctrees/monte_carlo.doctree new file mode 100644 index 0000000..79afa65 Binary files /dev/null and b/book/_build/.doctrees/monte_carlo.doctree differ diff --git a/book/_build/.doctrees/networks.doctree b/book/_build/.doctrees/networks.doctree new file mode 100644 index 0000000..0695bb7 Binary files /dev/null and b/book/_build/.doctrees/networks.doctree differ diff --git a/book/_build/.doctrees/olg.doctree b/book/_build/.doctrees/olg.doctree new file mode 100644 index 0000000..fa88655 Binary files /dev/null and b/book/_build/.doctrees/olg.doctree differ diff --git a/book/_build/.doctrees/prob_dist.doctree b/book/_build/.doctrees/prob_dist.doctree new file mode 100644 index 0000000..258abc9 Binary files /dev/null and b/book/_build/.doctrees/prob_dist.doctree differ diff --git a/book/_build/.doctrees/pv.doctree b/book/_build/.doctrees/pv.doctree new file mode 100644 index 0000000..2f7d791 Binary files /dev/null and b/book/_build/.doctrees/pv.doctree differ diff --git a/book/_build/.doctrees/scalar_dynam.doctree b/book/_build/.doctrees/scalar_dynam.doctree new file mode 100644 index 0000000..53db913 Binary files /dev/null and b/book/_build/.doctrees/scalar_dynam.doctree differ diff --git a/book/_build/.doctrees/schelling.doctree b/book/_build/.doctrees/schelling.doctree new file mode 100644 index 0000000..1ce294b Binary files /dev/null and b/book/_build/.doctrees/schelling.doctree differ diff --git a/book/_build/.doctrees/short_path.doctree b/book/_build/.doctrees/short_path.doctree new file mode 100644 index 0000000..851c2da Binary files /dev/null and b/book/_build/.doctrees/short_path.doctree differ diff --git a/book/_build/.doctrees/simple_linear_regression.doctree b/book/_build/.doctrees/simple_linear_regression.doctree new file mode 100644 index 0000000..ace49a0 Binary files /dev/null and b/book/_build/.doctrees/simple_linear_regression.doctree differ diff --git a/book/_build/.doctrees/solow.doctree b/book/_build/.doctrees/solow.doctree new file mode 100644 index 0000000..5e4194d Binary files /dev/null and b/book/_build/.doctrees/solow.doctree differ diff --git a/book/_build/.doctrees/status.doctree b/book/_build/.doctrees/status.doctree new file mode 100644 index 0000000..4bce960 Binary files /dev/null and b/book/_build/.doctrees/status.doctree differ diff --git a/book/_build/.doctrees/supply_demand_heterogeneity.doctree b/book/_build/.doctrees/supply_demand_heterogeneity.doctree new file mode 100644 index 0000000..871387e Binary files /dev/null and b/book/_build/.doctrees/supply_demand_heterogeneity.doctree differ diff --git a/book/_build/.doctrees/supply_demand_multiple_goods.doctree b/book/_build/.doctrees/supply_demand_multiple_goods.doctree new file mode 100644 index 0000000..32b9bd4 Binary files /dev/null and b/book/_build/.doctrees/supply_demand_multiple_goods.doctree differ diff --git a/book/_build/.doctrees/time_series_with_matrices.doctree b/book/_build/.doctrees/time_series_with_matrices.doctree new file mode 100644 index 0000000..5b016f9 Binary files /dev/null and b/book/_build/.doctrees/time_series_with_matrices.doctree differ diff --git a/book/_build/.doctrees/troubleshooting.doctree b/book/_build/.doctrees/troubleshooting.doctree new file mode 100644 index 0000000..ce2ea8f Binary files /dev/null and b/book/_build/.doctrees/troubleshooting.doctree differ diff --git a/book/_build/.doctrees/unpleasant.doctree b/book/_build/.doctrees/unpleasant.doctree new file mode 100644 index 0000000..3a6657a Binary files /dev/null and b/book/_build/.doctrees/unpleasant.doctree differ diff --git a/book/_build/.doctrees/zreferences.doctree b/book/_build/.doctrees/zreferences.doctree new file mode 100644 index 0000000..f0aa350 Binary files /dev/null and b/book/_build/.doctrees/zreferences.doctree differ diff --git a/book/_build/html/.buildinfo b/book/_build/html/.buildinfo new file mode 100644 index 0000000..53f3fb3 --- /dev/null +++ b/book/_build/html/.buildinfo @@ -0,0 +1,4 @@ +# Sphinx build info version 1 +# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. +config: 50cb353efd1d91078461a3644c2c991f +tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/book/_build/html/_images/Hamilton.png b/book/_build/html/_images/Hamilton.png new file mode 100644 index 0000000..caeccf2 Binary files /dev/null and b/book/_build/html/_images/Hamilton.png differ diff --git a/book/_build/html/_images/Irre_1.png b/book/_build/html/_images/Irre_1.png new file mode 100644 index 0000000..5510b4d Binary files /dev/null and b/book/_build/html/_images/Irre_1.png differ diff --git a/book/_build/html/_images/Irre_2.png b/book/_build/html/_images/Irre_2.png new file mode 100644 index 0000000..2661a24 Binary files /dev/null and b/book/_build/html/_images/Irre_2.png differ diff --git a/book/_build/html/_images/Temple.png b/book/_build/html/_images/Temple.png new file mode 100644 index 0000000..41f07a0 Binary files /dev/null and b/book/_build/html/_images/Temple.png differ diff --git a/book/_build/html/_images/example4.png b/book/_build/html/_images/example4.png new file mode 100644 index 0000000..a7844b4 Binary files /dev/null and b/book/_build/html/_images/example4.png differ diff --git a/book/_build/html/_images/graph.png b/book/_build/html/_images/graph.png new file mode 100644 index 0000000..2b451a4 Binary files /dev/null and b/book/_build/html/_images/graph.png differ diff --git a/book/_build/html/_images/graph2.png b/book/_build/html/_images/graph2.png new file mode 100644 index 0000000..7bc5a5d Binary files /dev/null and b/book/_build/html/_images/graph2.png differ diff --git a/book/_build/html/_images/graph3.png b/book/_build/html/_images/graph3.png new file mode 100644 index 0000000..13b2463 Binary files /dev/null and b/book/_build/html/_images/graph3.png differ diff --git a/book/_build/html/_images/graph4.png b/book/_build/html/_images/graph4.png new file mode 100644 index 0000000..b817225 Binary files /dev/null and b/book/_build/html/_images/graph4.png differ diff --git a/book/_build/html/_images/lake_model_worker.png b/book/_build/html/_images/lake_model_worker.png new file mode 100644 index 0000000..802a23c Binary files /dev/null and b/book/_build/html/_images/lake_model_worker.png differ diff --git a/content/lectures/_static/lecture_specific/troubleshooting/launch.png b/book/_build/html/_images/launch.png similarity index 100% rename from content/lectures/_static/lecture_specific/troubleshooting/launch.png rename to book/_build/html/_images/launch.png diff --git a/book/_build/html/_images/mc.png b/book/_build/html/_images/mc.png new file mode 100644 index 0000000..caeccf2 Binary files /dev/null and b/book/_build/html/_images/mc.png differ diff --git a/book/_build/html/_images/poverty_trap_1.png b/book/_build/html/_images/poverty_trap_1.png new file mode 100644 index 0000000..e3bda2a Binary files /dev/null and b/book/_build/html/_images/poverty_trap_1.png differ diff --git a/book/_build/html/_images/poverty_trap_2.png b/book/_build/html/_images/poverty_trap_2.png new file mode 100644 index 0000000..71f2d31 Binary files /dev/null and b/book/_build/html/_images/poverty_trap_2.png differ diff --git a/book/_build/html/_images/properties.png b/book/_build/html/_images/properties.png new file mode 100644 index 0000000..7098688 Binary files /dev/null and b/book/_build/html/_images/properties.png differ diff --git a/book/_build/html/_images/tooze_ch1_graph.png b/book/_build/html/_images/tooze_ch1_graph.png new file mode 100644 index 0000000..3ae6891 Binary files /dev/null and b/book/_build/html/_images/tooze_ch1_graph.png differ diff --git a/book/_build/html/_images/weighted.png b/book/_build/html/_images/weighted.png new file mode 100644 index 0000000..5510b4d Binary files /dev/null and b/book/_build/html/_images/weighted.png differ diff --git a/book/_build/html/_sources/about.md b/book/_build/html/_sources/about.md new file mode 100644 index 0000000..ac8c6f3 --- /dev/null +++ b/book/_build/html/_sources/about.md @@ -0,0 +1,75 @@ +# About These Lectures + + +## About + +This lecture series introduces quantitative economics using elementary +mathematics and statistics plus computer code written in +[Python](https://www.python.org/). + +The lectures emphasize simulation and visualization through code as a way to +convey ideas, rather than focusing on mathematical details. + +Although the presentation is quite novel, the ideas are rather foundational. + +We emphasize the deep and fundamental importance of economic theory, as well +as the value of analyzing data and understanding stylized facts. + +The lectures can be used for university courses, self-study, reading groups or +workshops. + +Researchers and policy professionals might also find some parts of the series +valuable for their work. + +We hope the lectures will be of interest to students of economics +who want to learn both economics and computing, as well as students from +fields such as computer science and engineering who are curious about +economics. + +## Level + +The lecture series is aimed at undergraduate students. + +The level of the lectures varies from truly introductory (suitable for first +year undergraduates or even high school students) to more intermediate. + +The +more intermediate lectures require comfort with linear algebra and some +mathematical maturity (e.g., calmly reading theorems and trying to understand +their meaning). + +In general, easier lectures occur earlier in the lecture +series and harder lectures occur later. + +We assume that readers have covered the easier parts of the QuantEcon lecture +series [on Python +programming](https://python-programming.quantecon.org/intro.html). + +In +particular, readers should be familiar with basic Python syntax including +Python functions. Knowledge of classes and Matplotlib will be beneficial but +not essential. + +## Credits + +In building this lecture series, we had invaluable assistance from research +assistants at QuantEcon, as well as our QuantEcon colleagues. Without their +help this series would not have been possible. + +In particular, we sincerely thank and give credit to + +- [Aakash Gupta](https://github.com/AakashGfude) +- [Shu Hu](https://github.com/shlff) +- Jiacheng Li +- [Jiarui Zhang](https://github.com/Jiarui-ZH) +- [Smit Lunagariya](https://github.com/Smit-create) +- [Maanasee Sharma](https://github.com/maanasee) +- [Matthew McKay](https://github.com/mmcky) +- [Margaret Beisenbek](https://github.com/mbek0605) +- [Phoebe Grosser](https://github.com/pgrosser1) +- [Longye Tian](https://github.com/longye-tian) +- [Humphrey Yang](https://github.com/HumphreyYang) +- [Sylvia Zhao](https://github.com/SylviaZhaooo) + +We also thank Noritaka Kudoh for encouraging us to start this project and providing thoughtful suggestions. + diff --git a/book/_build/html/_sources/ar1_processes.ipynb b/book/_build/html/_sources/ar1_processes.ipynb new file mode 100644 index 0000000..d62f8a1 --- /dev/null +++ b/book/_build/html/_sources/ar1_processes.ipynb @@ -0,0 +1,830 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "06599583", + "metadata": {}, + "source": [ + "(ar1)=\n", + "```{raw} html\n", + "
\n", + " \n", + " \"QuantEcon\"\n", + " \n", + "
\n", + "```\n", + "\n", + "(ar1_processes)=\n", + "# AR(1) Processes\n", + "\n", + "```{index} single: Autoregressive processes\n", + "```\n", + "\n", + "## Overview\n", + "\n", + "In this lecture we are going to study a very simple class of stochastic\n", + "models called AR(1) processes.\n", + "\n", + "These simple models are used again and again in economic research to represent the dynamics of series such as\n", + "\n", + "* labor income\n", + "* dividends\n", + "* productivity, etc.\n", + "\n", + "We are going to study AR(1) processes partly because they are useful and\n", + "partly because they help us understand important concepts. \n", + "\n", + "Let's start with some imports:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "731a6973", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "plt.rcParams[\"figure.figsize\"] = (11, 5) #set default figure size" + ] + }, + { + "cell_type": "markdown", + "id": "ec4c9d96", + "metadata": {}, + "source": [ + "## The AR(1) model\n", + "\n", + "The **AR(1) model** (autoregressive model of order 1) takes the form\n", + "\n", + "```{math}\n", + ":label: can_ar1\n", + "\n", + "X_{t+1} = a X_t + b + c W_{t+1}\n", + "```\n", + "\n", + "where $a, b, c$ are scalar-valued parameters \n", + "\n", + "(Equation {eq}`can_ar1` is sometimes called a **stochastic difference equation**.)\n", + "\n", + "```{prf:example}\n", + ":label: ar1_ex_ar\n", + "\n", + "For example, $X_t$ might be \n", + "\n", + "* the log of labor income for a given household, or\n", + "* the log of money demand in a given economy.\n", + "\n", + "In either case, {eq}`can_ar1` shows that the current value evolves as a linear function\n", + "of the previous value and an IID shock $W_{t+1}$.\n", + "\n", + "(We use $t+1$ for the subscript of $W_{t+1}$ because this random variable is not\n", + "observed at time $t$.)\n", + "```\n", + "\n", + "The specification {eq}`can_ar1` generates a time series $\\{ X_t\\}$ as soon as we\n", + "specify an initial condition $X_0$.\n", + "\n", + "To make things even simpler, we will assume that\n", + "\n", + "* the process $\\{ W_t \\}$ is {ref}`IID ` and standard normal,\n", + "* the initial condition $X_0$ is drawn from the normal distribution $N(\\mu_0, v_0)$ and\n", + "* the initial condition $X_0$ is independent of $\\{ W_t \\}$.\n", + "\n", + "\n", + "\n", + "\n", + "### Moving average representation\n", + "\n", + "Iterating backwards from time $t$, we obtain\n", + "\n", + "$$\n", + "X_t = a X_{t-1} + b + c W_t\n", + " = a^2 X_{t-2} + a b + a c W_{t-1} + b + c W_t\n", + " = a^3 X_{t-3} + a^2 b + a^2 c W_{t-2} + b + c W_t\n", + " = \\cdots\n", + "$$\n", + "\n", + "If we work all the way back to time zero, we get\n", + "\n", + "```{math}\n", + ":label: ar1_ma\n", + "\n", + "X_t = a^t X_0 + b \\sum_{j=0}^{t-1} a^j +\n", + " c \\sum_{j=0}^{t-1} a^j W_{t-j}\n", + "```\n", + "\n", + "Equation {eq}`ar1_ma` shows that $X_t$ is a well defined random variable, the value of which depends on\n", + "\n", + "* the parameters,\n", + "* the initial condition $X_0$ and\n", + "* the shocks $W_1, \\ldots W_t$ from time $t=1$ to the present.\n", + "\n", + "Throughout, the symbol $\\psi_t$ will be used to refer to the\n", + "density of this random variable $X_t$.\n", + "\n", + "### Distribution dynamics\n", + "\n", + "One of the nice things about this model is that it's so easy to trace out the sequence of distributions $\\{ \\psi_t \\}$ corresponding to the time\n", + "series $\\{ X_t\\}$.\n", + "\n", + "To see this, we first note that $X_t$ is normally distributed for each $t$.\n", + "\n", + "This is immediate from {eq}`ar1_ma`, since linear combinations of independent\n", + "normal random variables are normal.\n", + "\n", + "Given that $X_t$ is normally distributed, we will know the full distribution\n", + "$\\psi_t$ if we can pin down its first two [moments](https://en.wikipedia.org/wiki/Moment_(mathematics)).\n", + "\n", + "Let $\\mu_t$ and $v_t$ denote the mean and variance of $X_t$ respectively.\n", + "\n", + "We can pin down these values from {eq}`ar1_ma` or we can use the following\n", + "recursive expressions:\n", + "\n", + "```{math}\n", + ":label: dyn_tm\n", + "\n", + "\\mu_{t+1} = a \\mu_t + b\n", + "\\quad \\text{and} \\quad\n", + "v_{t+1} = a^2 v_t + c^2\n", + "```\n", + "\n", + "These expressions are obtained from {eq}`can_ar1` by taking, respectively, the expectation and variance of both sides of the equality.\n", + "\n", + "In calculating the second expression, we are using the fact that $X_t$\n", + "and $W_{t+1}$ are independent.\n", + "\n", + "(This follows from our assumptions and {eq}`ar1_ma`.)\n", + "\n", + "Given the dynamics in {eq}`ar1_ma` and initial conditions $\\mu_0,\n", + "v_0$, we obtain $\\mu_t, v_t$ and hence\n", + "\n", + "$$\n", + "\\psi_t = N(\\mu_t, v_t)\n", + "$$\n", + "\n", + "The following code uses these facts to track the sequence of marginal distributions $\\{ \\psi_t \\}$.\n", + "\n", + "The parameters are" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d5e587ea", + "metadata": {}, + "outputs": [], + "source": [ + "a, b, c = 0.9, 0.1, 0.5\n", + "\n", + "mu, v = -3.0, 0.6 # initial conditions mu_0, v_0" + ] + }, + { + "cell_type": "markdown", + "id": "0da85415", + "metadata": {}, + "source": [ + "Here's the sequence of distributions:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e1a3f93d", + "metadata": {}, + "outputs": [], + "source": [ + "from scipy.stats import norm\n", + "\n", + "sim_length = 10\n", + "grid = np.linspace(-5, 7, 120)\n", + "\n", + "fig, ax = plt.subplots()\n", + "\n", + "for t in range(sim_length):\n", + " mu = a * mu + b\n", + " v = a**2 * v + c**2\n", + " ax.plot(grid, norm.pdf(grid, loc=mu, scale=np.sqrt(v)),\n", + " label=f\"$\\psi_{t}$\",\n", + " alpha=0.7)\n", + "\n", + "ax.legend(bbox_to_anchor=[1.05,1],loc=2,borderaxespad=1)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "92743b1e", + "metadata": {}, + "source": [ + "## Stationarity and asymptotic stability\n", + "\n", + "When we use models to study the real world, it is generally preferable that our\n", + "models have clear, sharp predictions.\n", + "\n", + "For dynamic problems, sharp predictions are related to stability.\n", + "\n", + "For example, if a dynamic model predicts that inflation always converges to some\n", + "kind of steady state, then the model gives a sharp prediction.\n", + "\n", + "(The prediction might be wrong, but even this is helpful, because we can judge the quality of the model.)\n", + "\n", + "Notice that, in the figure above, the sequence $\\{ \\psi_t \\}$ seems to be converging to a limiting distribution, suggesting some kind of stability.\n", + "\n", + "This is even clearer if we project forward further into the future:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1fbb6210", + "metadata": {}, + "outputs": [], + "source": [ + "def plot_density_seq(ax, mu_0=-3.0, v_0=0.6, sim_length=40):\n", + " mu, v = mu_0, v_0\n", + " for t in range(sim_length):\n", + " mu = a * mu + b\n", + " v = a**2 * v + c**2\n", + " ax.plot(grid,\n", + " norm.pdf(grid, loc=mu, scale=np.sqrt(v)),\n", + " alpha=0.5)\n", + "\n", + "fig, ax = plt.subplots()\n", + "plot_density_seq(ax)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "0f644019", + "metadata": {}, + "source": [ + "Moreover, the limit does not depend on the initial condition.\n", + "\n", + "For example, this alternative density sequence also converges to the same limit." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8623820d", + "metadata": {}, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "plot_density_seq(ax, mu_0=4.0)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "57c613de", + "metadata": {}, + "source": [ + "In fact it's easy to show that such convergence will occur, regardless of the initial condition, whenever $|a| < 1$.\n", + "\n", + "To see this, we just have to look at the dynamics of the first two moments, as\n", + "given in {eq}`dyn_tm`.\n", + "\n", + "When $|a| < 1$, these sequences converge to the respective limits\n", + "\n", + "```{math}\n", + ":label: mu_sig_star\n", + "\n", + "\\mu^* := \\frac{b}{1-a}\n", + "\\quad \\text{and} \\quad\n", + "v^* = \\frac{c^2}{1 - a^2}\n", + "```\n", + "\n", + "(See our {doc}`lecture on one dimensional dynamics ` for background on deterministic convergence.)\n", + "\n", + "Hence\n", + "\n", + "```{math}\n", + ":label: ar1_psi_star\n", + "\n", + "\\psi_t \\to \\psi^* = N(\\mu^*, v^*)\n", + "\\quad \\text{as }\n", + "t \\to \\infty\n", + "```\n", + "\n", + "We can confirm this is valid for the sequence above using the following code." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d352e207", + "metadata": {}, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "plot_density_seq(ax, mu_0=4.0)\n", + "\n", + "mu_star = b / (1 - a)\n", + "std_star = np.sqrt(c**2 / (1 - a**2)) # square root of v_star\n", + "psi_star = norm.pdf(grid, loc=mu_star, scale=std_star)\n", + "ax.plot(grid, psi_star, 'k-', lw=2, label=\"$\\psi^*$\")\n", + "ax.legend()\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "b07eb048", + "metadata": {}, + "source": [ + "As claimed, the sequence $\\{ \\psi_t \\}$ converges to $\\psi^*$.\n", + "\n", + "We see that, at least for these parameters, the AR(1) model has strong stability\n", + "properties.\n", + "\n", + "\n", + "\n", + "\n", + "### Stationary distributions\n", + "\n", + "Let's try to better understand the limiting distribution $\\psi^*$.\n", + "\n", + "A stationary distribution is a distribution that is a \"fixed point\" of the update rule for the AR(1) process.\n", + "\n", + "In other words, if $\\psi_t$ is stationary, then $\\psi_{t+j} = \\psi_t$ for all $j$ in $\\mathbb N$.\n", + "\n", + "A different way to put this, specialized to the current setting, is as follows: a density $\\psi$ on $\\mathbb R$ is **stationary** for the AR(1) process if\n", + "\n", + "$$\n", + "X_t \\sim \\psi\n", + "\\quad \\implies \\quad\n", + "a X_t + b + c W_{t+1} \\sim \\psi\n", + "$$\n", + "\n", + "The distribution $\\psi^*$ in {eq}`ar1_psi_star` has this property ---\n", + "checking this is an exercise.\n", + "\n", + "(Of course, we are assuming that $|a| < 1$ so that $\\psi^*$ is\n", + "well defined.)\n", + "\n", + "In fact, it can be shown that no other distribution on $\\mathbb R$ has this property.\n", + "\n", + "Thus, when $|a| < 1$, the AR(1) model has exactly one stationary density and that density is given by $\\psi^*$.\n", + "\n", + "## Ergodicity\n", + "\n", + "The concept of ergodicity is used in different ways by different authors.\n", + "\n", + "One way to understand it in the present setting is that a version of the law\n", + "of large numbers is valid for $\\{X_t\\}$, even though it is not IID.\n", + "\n", + "In particular, averages over time series converge to expectations under the\n", + "stationary distribution.\n", + "\n", + "Indeed, it can be proved that, whenever $|a| < 1$, we have\n", + "\n", + "```{math}\n", + ":label: ar1_ergo\n", + "\n", + "\\frac{1}{m} \\sum_{t = 1}^m h(X_t) \\to\n", + "\\int h(x) \\psi^*(x) dx\n", + " \\quad \\text{as } m \\to \\infty\n", + "```\n", + "\n", + "whenever the integral on the right hand side is finite and well defined.\n", + "\n", + "Notes:\n", + "\n", + "* In {eq}`ar1_ergo`, convergence holds with probability one.\n", + "* The textbook by {cite}`MeynTweedie2009` is a classic reference on ergodicity.\n", + "\n", + "```{prf:example}\n", + ":label: ar1_ex_id\n", + "\n", + "If we consider the identity function $h(x) = x$, we get\n", + "\n", + "$$\n", + "\\frac{1}{m} \\sum_{t = 1}^m X_t \\to\n", + "\\int x \\psi^*(x) dx\n", + " \\quad \\text{as } m \\to \\infty\n", + "$$\n", + "\n", + "In other words, the time series sample mean converges to the mean of the stationary distribution.\n", + "```\n", + "\n", + "Ergodicity is important for a range of reasons.\n", + "\n", + "For example, {eq}`ar1_ergo` can be used to test theory.\n", + "\n", + "In this equation, we can use observed data to evaluate the left hand side of {eq}`ar1_ergo`.\n", + "\n", + "And we can use a theoretical AR(1) model to calculate the right hand side.\n", + "\n", + "If $\\frac{1}{m} \\sum_{t = 1}^m X_t$ is not close to $\\psi^(x)$, even for many\n", + "observations, then our theory seems to be incorrect and we will need to revise\n", + "it.\n", + "\n", + "\n", + "## Exercises\n", + "\n", + "```{exercise}\n", + ":label: ar1p_ex1\n", + "\n", + "Let $k$ be a natural number.\n", + "\n", + "The $k$-th central moment of a random variable is defined as\n", + "\n", + "$$\n", + "M_k := \\mathbb E [ (X - \\mathbb E X )^k ]\n", + "$$\n", + "\n", + "When that random variable is $N(\\mu, \\sigma^2)$, it is known that\n", + "\n", + "$$\n", + "M_k =\n", + "\\begin{cases}\n", + " 0 & \\text{ if } k \\text{ is odd} \\\\\n", + " \\sigma^k (k-1)!! & \\text{ if } k \\text{ is even}\n", + "\\end{cases}\n", + "$$\n", + "\n", + "Here $n!!$ is the [double factorial](https://en.wikipedia.org/wiki/Double_factorial).\n", + "\n", + "According to {eq}`ar1_ergo`, we should have, for any $k \\in \\mathbb N$,\n", + "\n", + "$$\n", + "\\frac{1}{m} \\sum_{t = 1}^m\n", + " (X_t - \\mu^* )^k\n", + " \\approx M_k\n", + "$$\n", + "\n", + "when $m$ is large.\n", + "\n", + "Confirm this by simulation at a range of $k$ using the default parameters from the lecture.\n", + "```\n", + "\n", + "\n", + "```{solution-start} ar1p_ex1\n", + ":class: dropdown\n", + "```\n", + "\n", + "Here is one solution:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c5ccb412", + "metadata": {}, + "outputs": [], + "source": [ + "from numba import njit\n", + "from scipy.special import factorial2\n", + "\n", + "@njit\n", + "def sample_moments_ar1(k, m=100_000, mu_0=0.0, sigma_0=1.0, seed=1234):\n", + " np.random.seed(seed)\n", + " sample_sum = 0.0\n", + " x = mu_0 + sigma_0 * np.random.randn()\n", + " for t in range(m):\n", + " sample_sum += (x - mu_star)**k\n", + " x = a * x + b + c * np.random.randn()\n", + " return sample_sum / m\n", + "\n", + "def true_moments_ar1(k):\n", + " if k % 2 == 0:\n", + " return std_star**k * factorial2(k - 1)\n", + " else:\n", + " return 0\n", + "\n", + "k_vals = np.arange(6) + 1\n", + "sample_moments = np.empty_like(k_vals)\n", + "true_moments = np.empty_like(k_vals)\n", + "\n", + "for k_idx, k in enumerate(k_vals):\n", + " sample_moments[k_idx] = sample_moments_ar1(k)\n", + " true_moments[k_idx] = true_moments_ar1(k)\n", + "\n", + "fig, ax = plt.subplots()\n", + "ax.plot(k_vals, true_moments, label=\"true moments\")\n", + "ax.plot(k_vals, sample_moments, label=\"sample moments\")\n", + "ax.legend()\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "0b8a62aa", + "metadata": {}, + "source": [ + "```{solution-end}\n", + "```\n", + "\n", + "\n", + "```{exercise}\n", + ":label: ar1p_ex2\n", + "\n", + "Write your own version of a one dimensional [kernel density\n", + "estimator](https://en.wikipedia.org/wiki/Kernel_density_estimation),\n", + "which estimates a density from a sample.\n", + "\n", + "Write it as a class that takes the data $X$ and bandwidth\n", + "$h$ when initialized and provides a method $f$ such that\n", + "\n", + "$$\n", + "f(x) = \\frac{1}{hn} \\sum_{i=1}^n\n", + "K \\left( \\frac{x-X_i}{h} \\right)\n", + "$$\n", + "\n", + "For $K$ use the Gaussian kernel ($K$ is the standard normal\n", + "density).\n", + "\n", + "Write the class so that the bandwidth defaults to Silverman’s rule (see\n", + "the “rule of thumb” discussion on [this\n", + "page](https://en.wikipedia.org/wiki/Kernel_density_estimation)). Test\n", + "the class you have written by going through the steps\n", + "\n", + "1. simulate data $X_1, \\ldots, X_n$ from distribution $\\phi$\n", + "1. plot the kernel density estimate over a suitable range\n", + "1. plot the density of $\\phi$ on the same figure\n", + "\n", + "for distributions $\\phi$ of the following types\n", + "\n", + "- [beta\n", + " distribution](https://en.wikipedia.org/wiki/Beta_distribution)\n", + " with $\\alpha = \\beta = 2$\n", + "- [beta\n", + " distribution](https://en.wikipedia.org/wiki/Beta_distribution)\n", + " with $\\alpha = 2$ and $\\beta = 5$\n", + "- [beta\n", + " distribution](https://en.wikipedia.org/wiki/Beta_distribution)\n", + " with $\\alpha = \\beta = 0.5$\n", + "\n", + "Use $n=500$.\n", + "\n", + "Make a comment on your results. (Do you think this is a good estimator\n", + "of these distributions?)\n", + "```\n", + "\n", + "\n", + "```{solution-start} ar1p_ex2\n", + ":class: dropdown\n", + "```\n", + "\n", + "Here is one solution:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a3755542", + "metadata": {}, + "outputs": [], + "source": [ + "K = norm.pdf\n", + "\n", + "class KDE:\n", + "\n", + " def __init__(self, x_data, h=None):\n", + "\n", + " if h is None:\n", + " c = x_data.std()\n", + " n = len(x_data)\n", + " h = 1.06 * c * n**(-1/5)\n", + " self.h = h\n", + " self.x_data = x_data\n", + "\n", + " def f(self, x):\n", + " if np.isscalar(x):\n", + " return K((x - self.x_data) / self.h).mean() * (1/self.h)\n", + " else:\n", + " y = np.empty_like(x)\n", + " for i, x_val in enumerate(x):\n", + " y[i] = K((x_val - self.x_data) / self.h).mean() * (1/self.h)\n", + " return y" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2d67afef", + "metadata": {}, + "outputs": [], + "source": [ + "def plot_kde(ϕ, x_min=-0.2, x_max=1.2):\n", + " x_data = ϕ.rvs(n)\n", + " kde = KDE(x_data)\n", + "\n", + " x_grid = np.linspace(-0.2, 1.2, 100)\n", + " fig, ax = plt.subplots()\n", + " ax.plot(x_grid, kde.f(x_grid), label=\"estimate\")\n", + " ax.plot(x_grid, ϕ.pdf(x_grid), label=\"true density\")\n", + " ax.legend()\n", + " plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2b9be722", + "metadata": {}, + "outputs": [], + "source": [ + "from scipy.stats import beta\n", + "\n", + "n = 500\n", + "parameter_pairs= (2, 2), (2, 5), (0.5, 0.5)\n", + "for α, β in parameter_pairs:\n", + " plot_kde(beta(α, β))" + ] + }, + { + "cell_type": "markdown", + "id": "d5822302", + "metadata": {}, + "source": [ + "We see that the kernel density estimator is effective when the underlying\n", + "distribution is smooth but less so otherwise.\n", + "\n", + "```{solution-end}\n", + "```\n", + "\n", + "\n", + "```{exercise}\n", + ":label: ar1p_ex3\n", + "\n", + "In the lecture we discussed the following fact: for the $AR(1)$ process\n", + "\n", + "$$\n", + "X_{t+1} = a X_t + b + c W_{t+1}\n", + "$$\n", + "\n", + "with $\\{ W_t \\}$ iid and standard normal,\n", + "\n", + "$$\n", + "\\psi_t = N(\\mu, s^2) \\implies \\psi_{t+1}\n", + "= N(a \\mu + b, a^2 s^2 + c^2)\n", + "$$\n", + "\n", + "Confirm this, at least approximately, by simulation. Let\n", + "\n", + "- $a = 0.9$\n", + "- $b = 0.0$\n", + "- $c = 0.1$\n", + "- $\\mu = -3$\n", + "- $s = 0.2$\n", + "\n", + "First, plot $\\psi_t$ and $\\psi_{t+1}$ using the true\n", + "distributions described above.\n", + "\n", + "Second, plot $\\psi_{t+1}$ on the same figure (in a different\n", + "color) as follows:\n", + "\n", + "1. Generate $n$ draws of $X_t$ from the $N(\\mu, s^2)$\n", + " distribution\n", + "1. Update them all using the rule\n", + " $X_{t+1} = a X_t + b + c W_{t+1}$\n", + "1. Use the resulting sample of $X_{t+1}$ values to produce a\n", + " density estimate via kernel density estimation.\n", + "\n", + "Try this for $n=2000$ and confirm that the\n", + "simulation based estimate of $\\psi_{t+1}$ does converge to the\n", + "theoretical distribution.\n", + "```\n", + "\n", + "```{solution-start} ar1p_ex3\n", + ":class: dropdown\n", + "```\n", + "\n", + "Here is our solution" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "380bd5b9", + "metadata": {}, + "outputs": [], + "source": [ + "a = 0.9\n", + "b = 0.0\n", + "c = 0.1\n", + "μ = -3\n", + "s = 0.2" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8af1e3f3", + "metadata": {}, + "outputs": [], + "source": [ + "μ_next = a * μ + b\n", + "s_next = np.sqrt(a**2 * s**2 + c**2)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "409143ce", + "metadata": {}, + "outputs": [], + "source": [ + "ψ = lambda x: K((x - μ) / s)\n", + "ψ_next = lambda x: K((x - μ_next) / s_next)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8a203dd4", + "metadata": {}, + "outputs": [], + "source": [ + "ψ = norm(μ, s)\n", + "ψ_next = norm(μ_next, s_next)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "aa021068", + "metadata": {}, + "outputs": [], + "source": [ + "n = 2000\n", + "x_draws = ψ.rvs(n)\n", + "x_draws_next = a * x_draws + b + c * np.random.randn(n)\n", + "kde = KDE(x_draws_next)\n", + "\n", + "x_grid = np.linspace(μ - 1, μ + 1, 100)\n", + "fig, ax = plt.subplots()\n", + "\n", + "ax.plot(x_grid, ψ.pdf(x_grid), label=\"$\\psi_t$\")\n", + "ax.plot(x_grid, ψ_next.pdf(x_grid), label=\"$\\psi_{t+1}$\")\n", + "ax.plot(x_grid, kde.f(x_grid), label=\"estimate of $\\psi_{t+1}$\")\n", + "\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "65eb10a0", + "metadata": {}, + "source": [ + "The simulated distribution approximately coincides with the theoretical\n", + "distribution, as predicted.\n", + "\n", + "```{solution-end}\n", + "```" + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst" + } + }, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "source_map": [ + 10, + 43, + 47, + 163, + 167, + 171, + 189, + 209, + 222, + 228, + 232, + 263, + 274, + 409, + 443, + 501, + 525, + 538, + 545, + 602, + 610, + 615, + 620, + 625, + 640 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/ar1_processes.md b/book/_build/html/_sources/ar1_processes.md new file mode 100644 index 0000000..fe54d3d --- /dev/null +++ b/book/_build/html/_sources/ar1_processes.md @@ -0,0 +1,646 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst +kernelspec: + display_name: Python 3 + language: python + name: python3 +--- + +(ar1)= +```{raw} html + +``` + +(ar1_processes)= +# AR(1) Processes + +```{index} single: Autoregressive processes +``` + +## Overview + +In this lecture we are going to study a very simple class of stochastic +models called AR(1) processes. + +These simple models are used again and again in economic research to represent the dynamics of series such as + +* labor income +* dividends +* productivity, etc. + +We are going to study AR(1) processes partly because they are useful and +partly because they help us understand important concepts. + +Let's start with some imports: + +```{code-cell} ipython +import numpy as np +import matplotlib.pyplot as plt +plt.rcParams["figure.figsize"] = (11, 5) #set default figure size +``` + +## The AR(1) model + +The **AR(1) model** (autoregressive model of order 1) takes the form + +```{math} +:label: can_ar1 + +X_{t+1} = a X_t + b + c W_{t+1} +``` + +where $a, b, c$ are scalar-valued parameters + +(Equation {eq}`can_ar1` is sometimes called a **stochastic difference equation**.) + +```{prf:example} +:label: ar1_ex_ar + +For example, $X_t$ might be + +* the log of labor income for a given household, or +* the log of money demand in a given economy. + +In either case, {eq}`can_ar1` shows that the current value evolves as a linear function +of the previous value and an IID shock $W_{t+1}$. + +(We use $t+1$ for the subscript of $W_{t+1}$ because this random variable is not +observed at time $t$.) +``` + +The specification {eq}`can_ar1` generates a time series $\{ X_t\}$ as soon as we +specify an initial condition $X_0$. + +To make things even simpler, we will assume that + +* the process $\{ W_t \}$ is {ref}`IID ` and standard normal, +* the initial condition $X_0$ is drawn from the normal distribution $N(\mu_0, v_0)$ and +* the initial condition $X_0$ is independent of $\{ W_t \}$. + + + + +### Moving average representation + +Iterating backwards from time $t$, we obtain + +$$ +X_t = a X_{t-1} + b + c W_t + = a^2 X_{t-2} + a b + a c W_{t-1} + b + c W_t + = a^3 X_{t-3} + a^2 b + a^2 c W_{t-2} + b + c W_t + = \cdots +$$ + +If we work all the way back to time zero, we get + +```{math} +:label: ar1_ma + +X_t = a^t X_0 + b \sum_{j=0}^{t-1} a^j + + c \sum_{j=0}^{t-1} a^j W_{t-j} +``` + +Equation {eq}`ar1_ma` shows that $X_t$ is a well defined random variable, the value of which depends on + +* the parameters, +* the initial condition $X_0$ and +* the shocks $W_1, \ldots W_t$ from time $t=1$ to the present. + +Throughout, the symbol $\psi_t$ will be used to refer to the +density of this random variable $X_t$. + +### Distribution dynamics + +One of the nice things about this model is that it's so easy to trace out the sequence of distributions $\{ \psi_t \}$ corresponding to the time +series $\{ X_t\}$. + +To see this, we first note that $X_t$ is normally distributed for each $t$. + +This is immediate from {eq}`ar1_ma`, since linear combinations of independent +normal random variables are normal. + +Given that $X_t$ is normally distributed, we will know the full distribution +$\psi_t$ if we can pin down its first two [moments](https://en.wikipedia.org/wiki/Moment_(mathematics)). + +Let $\mu_t$ and $v_t$ denote the mean and variance of $X_t$ respectively. + +We can pin down these values from {eq}`ar1_ma` or we can use the following +recursive expressions: + +```{math} +:label: dyn_tm + +\mu_{t+1} = a \mu_t + b +\quad \text{and} \quad +v_{t+1} = a^2 v_t + c^2 +``` + +These expressions are obtained from {eq}`can_ar1` by taking, respectively, the expectation and variance of both sides of the equality. + +In calculating the second expression, we are using the fact that $X_t$ +and $W_{t+1}$ are independent. + +(This follows from our assumptions and {eq}`ar1_ma`.) + +Given the dynamics in {eq}`ar1_ma` and initial conditions $\mu_0, +v_0$, we obtain $\mu_t, v_t$ and hence + +$$ +\psi_t = N(\mu_t, v_t) +$$ + +The following code uses these facts to track the sequence of marginal distributions $\{ \psi_t \}$. + +The parameters are + +```{code-cell} python3 +a, b, c = 0.9, 0.1, 0.5 + +mu, v = -3.0, 0.6 # initial conditions mu_0, v_0 +``` + +Here's the sequence of distributions: + +```{code-cell} python3 +from scipy.stats import norm + +sim_length = 10 +grid = np.linspace(-5, 7, 120) + +fig, ax = plt.subplots() + +for t in range(sim_length): + mu = a * mu + b + v = a**2 * v + c**2 + ax.plot(grid, norm.pdf(grid, loc=mu, scale=np.sqrt(v)), + label=f"$\psi_{t}$", + alpha=0.7) + +ax.legend(bbox_to_anchor=[1.05,1],loc=2,borderaxespad=1) + +plt.show() +``` + + + +## Stationarity and asymptotic stability + +When we use models to study the real world, it is generally preferable that our +models have clear, sharp predictions. + +For dynamic problems, sharp predictions are related to stability. + +For example, if a dynamic model predicts that inflation always converges to some +kind of steady state, then the model gives a sharp prediction. + +(The prediction might be wrong, but even this is helpful, because we can judge the quality of the model.) + +Notice that, in the figure above, the sequence $\{ \psi_t \}$ seems to be converging to a limiting distribution, suggesting some kind of stability. + +This is even clearer if we project forward further into the future: + +```{code-cell} python3 +def plot_density_seq(ax, mu_0=-3.0, v_0=0.6, sim_length=40): + mu, v = mu_0, v_0 + for t in range(sim_length): + mu = a * mu + b + v = a**2 * v + c**2 + ax.plot(grid, + norm.pdf(grid, loc=mu, scale=np.sqrt(v)), + alpha=0.5) + +fig, ax = plt.subplots() +plot_density_seq(ax) +plt.show() +``` + +Moreover, the limit does not depend on the initial condition. + +For example, this alternative density sequence also converges to the same limit. + +```{code-cell} python3 +fig, ax = plt.subplots() +plot_density_seq(ax, mu_0=4.0) +plt.show() +``` + +In fact it's easy to show that such convergence will occur, regardless of the initial condition, whenever $|a| < 1$. + +To see this, we just have to look at the dynamics of the first two moments, as +given in {eq}`dyn_tm`. + +When $|a| < 1$, these sequences converge to the respective limits + +```{math} +:label: mu_sig_star + +\mu^* := \frac{b}{1-a} +\quad \text{and} \quad +v^* = \frac{c^2}{1 - a^2} +``` + +(See our {doc}`lecture on one dimensional dynamics ` for background on deterministic convergence.) + +Hence + +```{math} +:label: ar1_psi_star + +\psi_t \to \psi^* = N(\mu^*, v^*) +\quad \text{as } +t \to \infty +``` + +We can confirm this is valid for the sequence above using the following code. + +```{code-cell} python3 +fig, ax = plt.subplots() +plot_density_seq(ax, mu_0=4.0) + +mu_star = b / (1 - a) +std_star = np.sqrt(c**2 / (1 - a**2)) # square root of v_star +psi_star = norm.pdf(grid, loc=mu_star, scale=std_star) +ax.plot(grid, psi_star, 'k-', lw=2, label="$\psi^*$") +ax.legend() + +plt.show() +``` + +As claimed, the sequence $\{ \psi_t \}$ converges to $\psi^*$. + +We see that, at least for these parameters, the AR(1) model has strong stability +properties. + + + + +### Stationary distributions + +Let's try to better understand the limiting distribution $\psi^*$. + +A stationary distribution is a distribution that is a "fixed point" of the update rule for the AR(1) process. + +In other words, if $\psi_t$ is stationary, then $\psi_{t+j} = \psi_t$ for all $j$ in $\mathbb N$. + +A different way to put this, specialized to the current setting, is as follows: a density $\psi$ on $\mathbb R$ is **stationary** for the AR(1) process if + +$$ +X_t \sim \psi +\quad \implies \quad +a X_t + b + c W_{t+1} \sim \psi +$$ + +The distribution $\psi^*$ in {eq}`ar1_psi_star` has this property --- +checking this is an exercise. + +(Of course, we are assuming that $|a| < 1$ so that $\psi^*$ is +well defined.) + +In fact, it can be shown that no other distribution on $\mathbb R$ has this property. + +Thus, when $|a| < 1$, the AR(1) model has exactly one stationary density and that density is given by $\psi^*$. + +## Ergodicity + +The concept of ergodicity is used in different ways by different authors. + +One way to understand it in the present setting is that a version of the law +of large numbers is valid for $\{X_t\}$, even though it is not IID. + +In particular, averages over time series converge to expectations under the +stationary distribution. + +Indeed, it can be proved that, whenever $|a| < 1$, we have + +```{math} +:label: ar1_ergo + +\frac{1}{m} \sum_{t = 1}^m h(X_t) \to +\int h(x) \psi^*(x) dx + \quad \text{as } m \to \infty +``` + +whenever the integral on the right hand side is finite and well defined. + +Notes: + +* In {eq}`ar1_ergo`, convergence holds with probability one. +* The textbook by {cite}`MeynTweedie2009` is a classic reference on ergodicity. + +```{prf:example} +:label: ar1_ex_id + +If we consider the identity function $h(x) = x$, we get + +$$ +\frac{1}{m} \sum_{t = 1}^m X_t \to +\int x \psi^*(x) dx + \quad \text{as } m \to \infty +$$ + +In other words, the time series sample mean converges to the mean of the stationary distribution. +``` + +Ergodicity is important for a range of reasons. + +For example, {eq}`ar1_ergo` can be used to test theory. + +In this equation, we can use observed data to evaluate the left hand side of {eq}`ar1_ergo`. + +And we can use a theoretical AR(1) model to calculate the right hand side. + +If $\frac{1}{m} \sum_{t = 1}^m X_t$ is not close to $\psi^(x)$, even for many +observations, then our theory seems to be incorrect and we will need to revise +it. + + +## Exercises + +```{exercise} +:label: ar1p_ex1 + +Let $k$ be a natural number. + +The $k$-th central moment of a random variable is defined as + +$$ +M_k := \mathbb E [ (X - \mathbb E X )^k ] +$$ + +When that random variable is $N(\mu, \sigma^2)$, it is known that + +$$ +M_k = +\begin{cases} + 0 & \text{ if } k \text{ is odd} \\ + \sigma^k (k-1)!! & \text{ if } k \text{ is even} +\end{cases} +$$ + +Here $n!!$ is the [double factorial](https://en.wikipedia.org/wiki/Double_factorial). + +According to {eq}`ar1_ergo`, we should have, for any $k \in \mathbb N$, + +$$ +\frac{1}{m} \sum_{t = 1}^m + (X_t - \mu^* )^k + \approx M_k +$$ + +when $m$ is large. + +Confirm this by simulation at a range of $k$ using the default parameters from the lecture. +``` + + +```{solution-start} ar1p_ex1 +:class: dropdown +``` + +Here is one solution: + +```{code-cell} python3 +from numba import njit +from scipy.special import factorial2 + +@njit +def sample_moments_ar1(k, m=100_000, mu_0=0.0, sigma_0=1.0, seed=1234): + np.random.seed(seed) + sample_sum = 0.0 + x = mu_0 + sigma_0 * np.random.randn() + for t in range(m): + sample_sum += (x - mu_star)**k + x = a * x + b + c * np.random.randn() + return sample_sum / m + +def true_moments_ar1(k): + if k % 2 == 0: + return std_star**k * factorial2(k - 1) + else: + return 0 + +k_vals = np.arange(6) + 1 +sample_moments = np.empty_like(k_vals) +true_moments = np.empty_like(k_vals) + +for k_idx, k in enumerate(k_vals): + sample_moments[k_idx] = sample_moments_ar1(k) + true_moments[k_idx] = true_moments_ar1(k) + +fig, ax = plt.subplots() +ax.plot(k_vals, true_moments, label="true moments") +ax.plot(k_vals, sample_moments, label="sample moments") +ax.legend() + +plt.show() +``` + +```{solution-end} +``` + + +```{exercise} +:label: ar1p_ex2 + +Write your own version of a one dimensional [kernel density +estimator](https://en.wikipedia.org/wiki/Kernel_density_estimation), +which estimates a density from a sample. + +Write it as a class that takes the data $X$ and bandwidth +$h$ when initialized and provides a method $f$ such that + +$$ +f(x) = \frac{1}{hn} \sum_{i=1}^n +K \left( \frac{x-X_i}{h} \right) +$$ + +For $K$ use the Gaussian kernel ($K$ is the standard normal +density). + +Write the class so that the bandwidth defaults to Silverman’s rule (see +the “rule of thumb” discussion on [this +page](https://en.wikipedia.org/wiki/Kernel_density_estimation)). Test +the class you have written by going through the steps + +1. simulate data $X_1, \ldots, X_n$ from distribution $\phi$ +1. plot the kernel density estimate over a suitable range +1. plot the density of $\phi$ on the same figure + +for distributions $\phi$ of the following types + +- [beta + distribution](https://en.wikipedia.org/wiki/Beta_distribution) + with $\alpha = \beta = 2$ +- [beta + distribution](https://en.wikipedia.org/wiki/Beta_distribution) + with $\alpha = 2$ and $\beta = 5$ +- [beta + distribution](https://en.wikipedia.org/wiki/Beta_distribution) + with $\alpha = \beta = 0.5$ + +Use $n=500$. + +Make a comment on your results. (Do you think this is a good estimator +of these distributions?) +``` + + +```{solution-start} ar1p_ex2 +:class: dropdown +``` + +Here is one solution: + +```{code-cell} ipython3 +K = norm.pdf + +class KDE: + + def __init__(self, x_data, h=None): + + if h is None: + c = x_data.std() + n = len(x_data) + h = 1.06 * c * n**(-1/5) + self.h = h + self.x_data = x_data + + def f(self, x): + if np.isscalar(x): + return K((x - self.x_data) / self.h).mean() * (1/self.h) + else: + y = np.empty_like(x) + for i, x_val in enumerate(x): + y[i] = K((x_val - self.x_data) / self.h).mean() * (1/self.h) + return y +``` + +```{code-cell} ipython3 +def plot_kde(ϕ, x_min=-0.2, x_max=1.2): + x_data = ϕ.rvs(n) + kde = KDE(x_data) + + x_grid = np.linspace(-0.2, 1.2, 100) + fig, ax = plt.subplots() + ax.plot(x_grid, kde.f(x_grid), label="estimate") + ax.plot(x_grid, ϕ.pdf(x_grid), label="true density") + ax.legend() + plt.show() +``` + +```{code-cell} ipython3 +from scipy.stats import beta + +n = 500 +parameter_pairs= (2, 2), (2, 5), (0.5, 0.5) +for α, β in parameter_pairs: + plot_kde(beta(α, β)) +``` + +We see that the kernel density estimator is effective when the underlying +distribution is smooth but less so otherwise. + +```{solution-end} +``` + + +```{exercise} +:label: ar1p_ex3 + +In the lecture we discussed the following fact: for the $AR(1)$ process + +$$ +X_{t+1} = a X_t + b + c W_{t+1} +$$ + +with $\{ W_t \}$ iid and standard normal, + +$$ +\psi_t = N(\mu, s^2) \implies \psi_{t+1} += N(a \mu + b, a^2 s^2 + c^2) +$$ + +Confirm this, at least approximately, by simulation. Let + +- $a = 0.9$ +- $b = 0.0$ +- $c = 0.1$ +- $\mu = -3$ +- $s = 0.2$ + +First, plot $\psi_t$ and $\psi_{t+1}$ using the true +distributions described above. + +Second, plot $\psi_{t+1}$ on the same figure (in a different +color) as follows: + +1. Generate $n$ draws of $X_t$ from the $N(\mu, s^2)$ + distribution +1. Update them all using the rule + $X_{t+1} = a X_t + b + c W_{t+1}$ +1. Use the resulting sample of $X_{t+1}$ values to produce a + density estimate via kernel density estimation. + +Try this for $n=2000$ and confirm that the +simulation based estimate of $\psi_{t+1}$ does converge to the +theoretical distribution. +``` + +```{solution-start} ar1p_ex3 +:class: dropdown +``` + +Here is our solution + +```{code-cell} ipython3 +a = 0.9 +b = 0.0 +c = 0.1 +μ = -3 +s = 0.2 +``` + +```{code-cell} ipython3 +μ_next = a * μ + b +s_next = np.sqrt(a**2 * s**2 + c**2) +``` + +```{code-cell} ipython3 +ψ = lambda x: K((x - μ) / s) +ψ_next = lambda x: K((x - μ_next) / s_next) +``` + +```{code-cell} ipython3 +ψ = norm(μ, s) +ψ_next = norm(μ_next, s_next) +``` + +```{code-cell} ipython3 +n = 2000 +x_draws = ψ.rvs(n) +x_draws_next = a * x_draws + b + c * np.random.randn(n) +kde = KDE(x_draws_next) + +x_grid = np.linspace(μ - 1, μ + 1, 100) +fig, ax = plt.subplots() + +ax.plot(x_grid, ψ.pdf(x_grid), label="$\psi_t$") +ax.plot(x_grid, ψ_next.pdf(x_grid), label="$\psi_{t+1}$") +ax.plot(x_grid, kde.f(x_grid), label="estimate of $\psi_{t+1}$") + +ax.legend() +plt.show() +``` + +The simulated distribution approximately coincides with the theoretical +distribution, as predicted. + +```{solution-end} +``` diff --git a/content/lectures/business_cycle.ipynb b/book/_build/html/_sources/business_cycle.ipynb similarity index 77% rename from content/lectures/business_cycle.ipynb rename to book/_build/html/_sources/business_cycle.ipynb index c82eb38..1b6e1f8 100644 --- a/content/lectures/business_cycle.ipynb +++ b/book/_build/html/_sources/business_cycle.ipynb @@ -2,31 +2,28 @@ "cells": [ { "cell_type": "markdown", - "id": "11b8ef2e", - "metadata": { - "user_expressions": [] - }, + "id": "caf98cc7", + "metadata": {}, "source": [ "# Business Cycles\n", "\n", "## Overview\n", "\n", - "In this lecture we study business cycles\n", + "In this lecture we review some empirical aspects of business cycles.\n", "\n", "Business cycles are fluctuations in economic activity over time.\n", "\n", - "These fluctuations are in the form of expansions (booms), contractions (recessions), and recoveries.\n", + "These include expansions (also called booms) and contractions (also called recessions).\n", "\n", - "We will look into a series of economic indicators to visualize the expansions and contractions of economies using [World Bank](https://documents.worldbank.org/en/publication/documents-reports/api) and [FRED](https://fred.stlouisfed.org/) data.\n", + "For our study, we will use economic indicators from the [World Bank](https://documents.worldbank.org/en/publication/documents-reports/api) and [FRED](https://fred.stlouisfed.org/).\n", "\n", - "In addition to those installed by Anaconda, this lecture requires\n", - "libraries to obtain World Bank and FRED data:" + "In addition to the packages already installed by Anaconda, this lecture requires" ] }, { "cell_type": "code", "execution_count": null, - "id": "97df2b46", + "id": "00e4a748", "metadata": { "tags": [ "hide-output" @@ -40,7 +37,7 @@ }, { "cell_type": "markdown", - "id": "c0529c90", + "id": "87b4f82a", "metadata": {}, "source": [ "We use the following imports" @@ -49,23 +46,29 @@ { "cell_type": "code", "execution_count": null, - "id": "d30d82c8", + "id": "914537c0", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import pandas as pd\n", - "import numpy as np\n", - "import scipy.stats as st\n", "import datetime\n", "import wbgapi as wb\n", "import pandas_datareader.data as web" ] }, + { + "cell_type": "markdown", + "id": "b45301f9", + "metadata": {}, + "source": [ + "Here's some minor code to help with colors in our plots." + ] + }, { "cell_type": "code", "execution_count": null, - "id": "92c80cad", + "id": "d0c634bd", "metadata": { "tags": [ "hide-input" @@ -73,7 +76,7 @@ }, "outputs": [], "source": [ - "# Set Graphical Parameters\n", + "# Set graphical parameters\n", "cycler = plt.cycler(linestyle=['-', '-.', '--', ':'], \n", " color=['#377eb8', '#ff7f00', '#4daf4a', '#ff334f'])\n", "plt.rc('axes', prop_cycle=cycler)" @@ -81,28 +84,23 @@ }, { "cell_type": "markdown", - "id": "cec6e879", - "metadata": { - "user_expressions": [] - }, + "id": "5fc2d1ff", + "metadata": {}, "source": [ "## Data acquisition\n", "\n", - "We will use `wbgapi` and `pandas_datareader` to retrieve data throughout this\n", - "lecture.\n", - "\n", - "Let's explore how to query data first.\n", + "We will use the World Bank's data API `wbgapi` and `pandas_datareader` to retrieve data.\n", "\n", "We can use `wb.series.info` with the argument `q` to query available data from\n", "the [World Bank](https://www.worldbank.org/en/home).\n", "\n", - "For example, let's retrieve the ID to query GDP growth data." + "For example, let's retrieve the GDP growth data ID to query GDP growth data." ] }, { "cell_type": "code", "execution_count": null, - "id": "0685f5f4", + "id": "ab47b32f", "metadata": {}, "outputs": [], "source": [ @@ -111,10 +109,8 @@ }, { "cell_type": "markdown", - "id": "3e4ba1dc", - "metadata": { - "user_expressions": [] - }, + "id": "23ebd2c9", + "metadata": {}, "source": [ "Now we use this series ID to obtain the data." ] @@ -122,12 +118,8 @@ { "cell_type": "code", "execution_count": null, - "id": "2eeb9846", - "metadata": { - "tags": [ - "hide-output" - ] - }, + "id": "e04a685b", + "metadata": {}, "outputs": [], "source": [ "gdp_growth = wb.data.DataFrame('NY.GDP.MKTP.KD.ZG',\n", @@ -138,18 +130,16 @@ }, { "cell_type": "markdown", - "id": "2b9c80b6", - "metadata": { - "user_expressions": [] - }, + "id": "c91aff26", + "metadata": {}, "source": [ - "We can the metadata to learn more about the series." + "We can look at the series' metadata to learn more about the series (click to expand)." ] }, { "cell_type": "code", "execution_count": null, - "id": "e45f314c", + "id": "89771623", "metadata": { "tags": [ "hide-output" @@ -162,17 +152,13 @@ }, { "cell_type": "markdown", - "id": "999d432d", - "metadata": { - "user_expressions": [] - }, + "id": "1febc7f1", + "metadata": {}, "source": [ - "Let's dive into the data with the tools we have.\n", - "\n", "(gdp_growth)=\n", "## GDP growth rate\n", "\n", - "First we look at the GDP growth rate. \n", + "First we look at GDP growth. \n", "\n", "Let's source our data from the World Bank and clean it." ] @@ -180,11 +166,11 @@ { "cell_type": "code", "execution_count": null, - "id": "10fc11b3", + "id": "73518684", "metadata": {}, "outputs": [], "source": [ - "# Use the series ID retrived before\n", + "# Use the series ID retrieved before\n", "gdp_growth = wb.data.DataFrame('NY.GDP.MKTP.KD.ZG',\n", " ['USA', 'ARG', 'GBR', 'GRC', 'JPN'], \n", " labels=True)\n", @@ -194,7 +180,7 @@ }, { "cell_type": "markdown", - "id": "9f3fc314", + "id": "9e8c31b2", "metadata": {}, "source": [ "Here's a first look at the data" @@ -203,7 +189,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b689e1c1", + "id": "2ea9091c", "metadata": {}, "outputs": [], "source": [ @@ -212,16 +198,16 @@ }, { "cell_type": "markdown", - "id": "5f34aace", + "id": "f3b8c8a1", "metadata": {}, "source": [ - "Now we can write a function to generate plots for individual countries taking into account the recessions." + "We write a function to generate plots for individual countries taking into account the recessions." ] }, { "cell_type": "code", "execution_count": null, - "id": "4bfe95ee", + "id": "f63709bd", "metadata": { "tags": [ "hide-input" @@ -266,7 +252,7 @@ "\n", " ax.plot(data.loc[country], label=country, **g_params)\n", " \n", - " # Highlight Recessions\n", + " # Highlight recessions\n", " ax.axvspan(1973, 1975, **b_params)\n", " ax.axvspan(1990, 1992, **b_params)\n", " ax.axvspan(2007, 2009, **b_params)\n", @@ -302,20 +288,16 @@ }, { "cell_type": "markdown", - "id": "16b26069", - "metadata": { - "user_expressions": [] - }, + "id": "513aa2a0", + "metadata": {}, "source": [ - "Now we can plot the data as a time series.\n", - "\n", "Let's start with the United States." ] }, { "cell_type": "code", "execution_count": null, - "id": "4b689bee", + "id": "8c7cba82", "metadata": { "mystnb": { "figure": { @@ -338,7 +320,7 @@ }, { "cell_type": "markdown", - "id": "9893f9cc", + "id": "9c43750a", "metadata": { "user_expressions": [] }, @@ -352,7 +334,7 @@ }, { "cell_type": "markdown", - "id": "3b0154a3", + "id": "29de286d", "metadata": {}, "source": [ "The United Kingdom (UK) has a similar pattern to the US, with a slow decline\n", @@ -364,7 +346,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f543e2ee", + "id": "a3be0141", "metadata": { "mystnb": { "figure": { @@ -386,7 +368,7 @@ }, { "cell_type": "markdown", - "id": "bd115d5f", + "id": "a7e7a83f", "metadata": { "user_expressions": [] }, @@ -395,13 +377,13 @@ "1970s, followed by slowed expansion in the past two decades.\n", "\n", "Major dips in the growth rate coincided with the Oil Crisis of the 1970s, the\n", - "GFC and the Covid-19 pandemic." + "Global Financial Crisis (GFC) and the Covid-19 pandemic." ] }, { "cell_type": "code", "execution_count": null, - "id": "1f7e9b88", + "id": "0b3b1e65", "metadata": { "mystnb": { "figure": { @@ -423,7 +405,7 @@ }, { "cell_type": "markdown", - "id": "d4f24268", + "id": "f36b97eb", "metadata": {}, "source": [ "Now let's study Greece." @@ -432,7 +414,7 @@ { "cell_type": "code", "execution_count": null, - "id": "10ef6b82", + "id": "5ffc23f7", "metadata": { "mystnb": { "figure": { @@ -454,10 +436,10 @@ }, { "cell_type": "markdown", - "id": "53324961", + "id": "1ad571b8", "metadata": {}, "source": [ - "Greece had a significant drop in GDP growth around 2010-2011, during the peak\n", + "Greece experienced a very large drop in GDP growth around 2010-2011, during the peak\n", "of the Greek debt crisis.\n", "\n", "Next let's consider Argentina." @@ -466,7 +448,7 @@ { "cell_type": "code", "execution_count": null, - "id": "dc6f53e6", + "id": "f29c8960", "metadata": { "mystnb": { "figure": { @@ -488,39 +470,27 @@ }, { "cell_type": "markdown", - "id": "7cad6b79", - "metadata": { - "user_expressions": [] - }, + "id": "5fe617e0", + "metadata": {}, "source": [ - "The figure shows that Argentina has experienced more volatile cycles than\n", - "the economies mentioned above.\n", + "Notice that Argentina has experienced far more volatile cycles than\n", + "the economies examined above.\n", + "\n", + "At the same time, Argentina's growth rate did not fall during the two developed\n", + "economy recessions in the 1970s and 1990s.\n", + "\n", "\n", - "At the same time, growth of Argentina did not fall during the two developed\n", - "economy recessions in the 1970s and 1990s." - ] - }, - { - "cell_type": "markdown", - "id": "f819f097", - "metadata": { - "user_expressions": [] - }, - "source": [ "## Unemployment\n", "\n", "Another important measure of business cycles is the unemployment rate.\n", "\n", - "During a recession, it is more likely that a larger proportion of the working\n", - "population will be laid off.\n", - "\n", - "We demonstrate this using a long-run unemployment rate from FRED spanning from [1929-1942](https://fred.stlouisfed.org/series/M0892AUSM156SNBR) to [1948-2022](https://fred.stlouisfed.org/series/UNRATE) with the unemployment rate between 1942 and 1948 estimated by the [Census Bureau](https://www.census.gov/library/publications/1975/compendia/hist_stats_colonial-1970.html)." + "We study unemployment using rate data from FRED spanning from [1929-1942](https://fred.stlouisfed.org/series/M0892AUSM156SNBR) to [1948-2022](https://fred.stlouisfed.org/series/UNRATE), combined unemployment rate data over 1942-1948 estimated by the [Census Bureau](https://www.census.gov/library/publications/1975/compendia/hist_stats_colonial-1970.html)." ] }, { "cell_type": "code", "execution_count": null, - "id": "48ca10a1", + "id": "52af17f7", "metadata": { "tags": [ "hide-input" @@ -545,16 +515,17 @@ }, { "cell_type": "markdown", - "id": "59434cf3", + "id": "18a29b40", "metadata": {}, "source": [ - "Now we plot the long-run unemployment rate in the US from 1929 to 2022 with recession defined by NBER" + "Let's plot the unemployment rate in the US from 1929 to 2022 with recessions\n", + "defined by the NBER." ] }, { "cell_type": "code", "execution_count": null, - "id": "00dd2ab1", + "id": "b85a210f", "metadata": { "mystnb": { "figure": { @@ -612,52 +583,40 @@ }, { "cell_type": "markdown", - "id": "ad3c06d5", - "metadata": { - "user_expressions": [] - }, + "id": "a2eb1642", + "metadata": {}, "source": [ - "In the plot, we can see that the expansions and contractions of the labor\n", - "market have been highly correlated with recessions. \n", - "\n", - "However, there is often a delay in the recovery of the labor market after\n", - "recessions.\n", + "The plot shows that \n", "\n", - "This trend is clearly visible in the 1930s, as well as in recessions in the\n", - "1980s. \n", + "* expansions and contractions of the labor market have been highly correlated\n", + " with recessions. \n", + "* cycles are, in general, asymmetric: sharp rises in unemployment are followed\n", + " by slow recoveries.\n", "\n", - "It also shows us how unique labor market conditions have been during the\n", + "It also shows us how unique labor market conditions were in the US during the\n", "post-pandemic recovery. \n", "\n", - "The labor market has recovered at an unprecedented rate, leading to the\n", - "tightest point in the past decades after the shock in 2020-2021." - ] - }, - { - "cell_type": "markdown", - "id": "a7408189", - "metadata": { - "user_expressions": [] - }, - "source": [ + "The labor market recovered at an unprecedented rate after the shock in 2020-2021.\n", + "\n", + "\n", "(synchronization)=\n", "## Synchronization\n", "\n", "In our {ref}`previous discussion`, we found that developed economies have had\n", "relatively synchronized periods of recession. \n", "\n", - "At the same time, this synchronization does not appear in Argentina until the 2000s. \n", + "At the same time, this synchronization did not appear in Argentina until the 2000s. \n", "\n", "Let's examine this trend further. \n", "\n", "With slight modifications, we can use our previous function to draw a plot\n", - "that includes many countries" + "that includes multiple countries." ] }, { "cell_type": "code", "execution_count": null, - "id": "5d0c832f", + "id": "e59fe92c", "metadata": { "tags": [ "hide-input" @@ -706,7 +665,7 @@ " for country in countries:\n", " ax.plot(data.loc[country], label=country, **g_params)\n", " \n", - " # Highlight Recessions\n", + " # Highlight recessions\n", " ax.axvspan(1973, 1975, **b_params)\n", " ax.axvspan(1990, 1992, **b_params)\n", " ax.axvspan(2007, 2009, **b_params)\n", @@ -739,7 +698,7 @@ }, { "cell_type": "markdown", - "id": "9e6dfa7a", + "id": "6fbe4b76", "metadata": {}, "source": [ "Here we compare the GDP growth rate of developed economies and developing economies." @@ -748,7 +707,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5958d778", + "id": "5d0c82c9", "metadata": { "tags": [ "hide-input" @@ -766,16 +725,16 @@ }, { "cell_type": "markdown", - "id": "0362e477", + "id": "e2fb4854", "metadata": {}, "source": [ - "We use the United Kingdom, United States, Germany, and Japan as examples of developed economies" + "We use the United Kingdom, United States, Germany, and Japan as examples of developed economies." ] }, { "cell_type": "code", "execution_count": null, - "id": "8e0ffe1a", + "id": "96f20aa9", "metadata": { "mystnb": { "figure": { @@ -801,16 +760,16 @@ }, { "cell_type": "markdown", - "id": "cf3f9ca5", + "id": "bab2ea48", "metadata": {}, "source": [ - "We choose Brazil, China, Argentina, and Mexico as representative developing economies" + "We choose Brazil, China, Argentina, and Mexico as representative developing economies." ] }, { "cell_type": "code", "execution_count": null, - "id": "69915fec", + "id": "ee361485", "metadata": { "mystnb": { "figure": { @@ -835,31 +794,29 @@ }, { "cell_type": "markdown", - "id": "32ce06aa", - "metadata": { - "user_expressions": [] - }, + "id": "bf1df65d", + "metadata": {}, "source": [ - "The comparison of GDP growth rates above shows that \n", + "The comparison of GDP growth rates above suggests that \n", "business cycles are becoming more synchronized in 21st-century recessions.\n", "\n", "However, emerging and less developed economies often experience more volatile\n", "changes throughout the economic cycles. \n", "\n", - "Despite of the synchronization in GDP growth, the experience of individual countries during\n", + "Despite the synchronization in GDP growth, the experience of individual countries during\n", "the recession often differs. \n", "\n", - "We use unemployment rate and the recovery of labor market conditions\n", + "We use the unemployment rate and the recovery of labor market conditions\n", "as another example.\n", "\n", "Here we compare the unemployment rate of the United States, \n", - "United Kingdom, Japan, and France" + "the United Kingdom, Japan, and France." ] }, { "cell_type": "code", "execution_count": null, - "id": "9f04da26", + "id": "d6c39f02", "metadata": { "mystnb": { "figure": { @@ -890,24 +847,16 @@ }, { "cell_type": "markdown", - "id": "732fcf4f", + "id": "5b2f65f1", "metadata": {}, "source": [ - "France, with its strong labor unions, has a prolonged labor market recovery\n", - "compared to the US and UK. \n", + "We see that France, with its strong labor unions, typically experiences\n", + "relatively slow labor market recoveries after negative shocks.\n", + "\n", + "We also notice that Japan has a history of very low and stable unemployment rates.\n", "\n", - "However, Japan has a history of very low and stable unemployment rates due to\n", - "a constellation of social, demographic, and cultural factors." - ] - }, - { - "cell_type": "markdown", - "id": "b2f76eec", - "metadata": { - "user_expressions": [] - }, - "source": [ - "## Leading indicators and correlated factors for business cycles\n", + "\n", + "## Leading indicators and correlated factors \n", "\n", "Examining leading indicators and correlated factors helps policymakers to\n", "understand the causes and results of business cycles. \n", @@ -915,38 +864,25 @@ "We will discuss potential leading indicators and correlated factors from three\n", "perspectives: consumption, production, and credit level.\n", "\n", - "### Consumption" - ] - }, - { - "cell_type": "markdown", - "id": "0596c926", - "metadata": { - "user_expressions": [] - }, - "source": [ + "\n", + "### Consumption\n", + "\n", "Consumption depends on consumers' confidence towards their\n", "income and the overall performance of the economy in the future. \n", "\n", "One widely cited indicator for consumer confidence is the [consumer sentiment index](https://fred.stlouisfed.org/series/UMCSENT) published by the University\n", "of Michigan.\n", "\n", - "Consumer sentiment remains high during during expansion, but there are significant drops before recession hits.\n", - "\n", - "There is also a clear negative correlation between consumer sentiment and [core consumer price index](https://fred.stlouisfed.org/series/CPILFESL).\n", - "\n", - "This trend is more significant in the during [stagflation](https://en.wikipedia.org/wiki/Stagflation).\n", - "\n", - "When the price of consumer commodities rises, consumer confidence diminishes.\n", - "\n", - "We plot the University of Michigan Consumer Sentiment Index and\n", - "Year-over-year Consumer Price Index Change from 1978-2022 in the US to show this trend" + "Here we plot the University of Michigan Consumer Sentiment Index and\n", + "year-on-year \n", + "[core consumer price index](https://fred.stlouisfed.org/series/CPILFESL)\n", + "(CPI) change from 1978-2022 in the US." ] }, { "cell_type": "code", "execution_count": null, - "id": "ce2b6221", + "id": "e7b31adf", "metadata": { "mystnb": { "figure": { @@ -1013,35 +949,40 @@ }, { "cell_type": "markdown", - "id": "712c4f74", - "metadata": { - "user_expressions": [] - }, + "id": "7106ce20", + "metadata": {}, "source": [ - "### Production\n", + "We see that \n", "\n", - "Consumers' confidence often influences their consumption pattern.\n", + "* consumer sentiment often remains high during expansions and\n", + "drops before recessions.\n", + "* there is a clear negative correlation between consumer sentiment and the CPI.\n", + "\n", + "When the price of consumer commodities rises, consumer confidence diminishes.\n", "\n", - "This often manifests on the production side.\n", + "This trend is more significant during [stagflation](https://en.wikipedia.org/wiki/Stagflation).\n", + "\n", + "\n", + "\n", + "### Production\n", "\n", - "The real industrial output is highly correlated with\n", - "recessions in the economy. \n", + "Real industrial output is highly correlated with recessions in the economy. \n", "\n", "However, it is not a leading indicator, as the peak of contraction in production \n", - "delays compared to consumer confidence and inflation.\n", + "is delayed relative to consumer confidence and inflation.\n", "\n", "We plot the real industrial output change from the previous year \n", - "from 1919 to 2022 in the US to show this trend" + "from 1919 to 2022 in the US to show this trend." ] }, { "cell_type": "code", "execution_count": null, - "id": "10c7ee74", + "id": "b7c2ad3f", "metadata": { "mystnb": { "figure": { - "caption": "YoY real ouput change, US (%)", + "caption": "YoY real output change, US (%)", "name": "roc" } }, @@ -1056,13 +997,13 @@ "\n", "nber = web.DataReader('USREC', 'fred', \n", " start_date, end_date)\n", - "consumer_confidence = web.DataReader('INDPRO', 'fred', \n", + "industrial_output = web.DataReader('INDPRO', 'fred', \n", " start_date, end_date).pct_change(12)*100\n", "\n", "fig, ax = plt.subplots()\n", - "ax.plot(consumer_confidence, **g_params, \n", + "ax.plot(industrial_output, **g_params, \n", " color='#377eb8', linestyle='-', \n", - " linewidth=2, label='Consumer price index')\n", + " linewidth=2, label='Industrial production index')\n", "ax.fill_between(nber.index, 0, 1,\n", " where=nber['USREC']==1, \n", " color='grey', edgecolor='none',\n", @@ -1070,43 +1011,36 @@ " transform=ax.get_xaxis_transform(), \n", " label='NBER recession indicators')\n", "ax.set_ylim([ax.get_ylim()[0], ax.get_ylim()[1]])\n", - "ax.set_ylabel('YoY real ouput change (%)')\n", + "ax.set_ylabel('YoY real output change (%)')\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "f57196ce", + "id": "26cc287c", "metadata": {}, "source": [ - "We observe the delayed contraction in the plot across recessions." - ] - }, - { - "cell_type": "markdown", - "id": "83813a5e", - "metadata": { - "user_expressions": [] - }, - "source": [ + "We observe the delayed contraction in the plot across recessions.\n", + "\n", + "\n", "### Credit level\n", "\n", "Credit contractions often occur during recessions, as lenders become more\n", "cautious and borrowers become more hesitant to take on additional debt.\n", "\n", - "This can be due to several factors such as a decrease in overall economic\n", - "activity, rising unemployment, and gloomy expectations for the future.\n", + "This is due to factors such as a decrease in overall economic\n", + "activity and gloomy expectations for the future.\n", "\n", "One example is domestic credit to the private sector by banks in the UK.\n", "\n", - "The following graph shows the domestic credit to the private sector \n", - "as a percentage of GDP by banks from 1970 to 2022 in the UK" + "The following graph shows the domestic credit to the private sector as a\n", + "percentage of GDP by banks from 1970 to 2022 in the UK." ] }, { "cell_type": "code", "execution_count": null, - "id": "d88e4cf5", + "id": "b10dfac2", "metadata": { "mystnb": { "figure": { @@ -1137,31 +1071,81 @@ }, { "cell_type": "markdown", - "id": "0c430dea", - "metadata": { - "user_expressions": [] - }, + "id": "45287194", + "metadata": {}, "source": [ - "Note that the credit rises during economic expansion\n", + "Note that the credit rises during economic expansions\n", "and stagnates or even contracts after recessions." ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f678b37e", - "metadata": {}, - "outputs": [], - "source": [] } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.5" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 12, + 28, + 33, + 37, + 43, + 47, + 54, + 66, + 68, + 73, + 78, + 83, + 87, + 98, + 105, + 109, + 111, + 115, + 187, + 192, + 210, + 218, + 225, + 242, + 250, + 265, + 269, + 284, + 291, + 306, + 321, + 337, + 342, + 391, + 420, + 495, + 499, + 511, + 515, + 532, + 536, + 552, + 570, + 592, + 622, + 680, + 704, + 734, + 752, + 774 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/business_cycle.md b/book/_build/html/_sources/business_cycle.md new file mode 100644 index 0000000..b2ed848 --- /dev/null +++ b/book/_build/html/_sources/business_cycle.md @@ -0,0 +1,777 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.5 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Business Cycles + +## Overview + +In this lecture we review some empirical aspects of business cycles. + +Business cycles are fluctuations in economic activity over time. + +These include expansions (also called booms) and contractions (also called recessions). + +For our study, we will use economic indicators from the [World Bank](https://documents.worldbank.org/en/publication/documents-reports/api) and [FRED](https://fred.stlouisfed.org/). + +In addition to the packages already installed by Anaconda, this lecture requires + +```{code-cell} ipython3 +:tags: [hide-output] + +%pip install wbgapi +%pip install pandas-datareader +``` + +We use the following imports + +```{code-cell} ipython3 +import matplotlib.pyplot as plt +import pandas as pd +import datetime +import wbgapi as wb +import pandas_datareader.data as web +``` + +Here's some minor code to help with colors in our plots. + +```{code-cell} ipython3 +:tags: [hide-input] + +# Set graphical parameters +cycler = plt.cycler(linestyle=['-', '-.', '--', ':'], + color=['#377eb8', '#ff7f00', '#4daf4a', '#ff334f']) +plt.rc('axes', prop_cycle=cycler) +``` + + +## Data acquisition + +We will use the World Bank's data API `wbgapi` and `pandas_datareader` to retrieve data. + +We can use `wb.series.info` with the argument `q` to query available data from +the [World Bank](https://www.worldbank.org/en/home). + +For example, let's retrieve the GDP growth data ID to query GDP growth data. + +```{code-cell} ipython3 +wb.series.info(q='GDP growth') +``` + + +Now we use this series ID to obtain the data. + +```{code-cell} ipython3 +gdp_growth = wb.data.DataFrame('NY.GDP.MKTP.KD.ZG', + ['USA', 'ARG', 'GBR', 'GRC', 'JPN'], + labels=True) +gdp_growth +``` + + +We can look at the series' metadata to learn more about the series (click to expand). + +```{code-cell} ipython3 +:tags: [hide-output] + +wb.series.metadata.get('NY.GDP.MKTP.KD.ZG') +``` + + + +(gdp_growth)= +## GDP growth rate + +First we look at GDP growth. + +Let's source our data from the World Bank and clean it. + +```{code-cell} ipython3 +# Use the series ID retrieved before +gdp_growth = wb.data.DataFrame('NY.GDP.MKTP.KD.ZG', + ['USA', 'ARG', 'GBR', 'GRC', 'JPN'], + labels=True) +gdp_growth = gdp_growth.set_index('Country') +gdp_growth.columns = gdp_growth.columns.str.replace('YR', '').astype(int) +``` + +Here's a first look at the data + +```{code-cell} ipython3 +gdp_growth +``` + +We write a function to generate plots for individual countries taking into account the recessions. + +```{code-cell} ipython3 +:tags: [hide-input] + +def plot_series(data, country, ylabel, + txt_pos, ax, g_params, + b_params, t_params, ylim=15, baseline=0): + """ + Plots a time series with recessions highlighted. + + Parameters + ---------- + data : pd.DataFrame + Data to plot + country : str + Name of the country to plot + ylabel : str + Label of the y-axis + txt_pos : float + Position of the recession labels + y_lim : float + Limit of the y-axis + ax : matplotlib.axes._subplots.AxesSubplot + Axes to plot on + g_params : dict + Parameters for the line + b_params : dict + Parameters for the recession highlights + t_params : dict + Parameters for the recession labels + baseline : float, optional + Dashed baseline on the plot, by default 0 + + Returns + ------- + ax : matplotlib.axes.Axes + Axes with the plot. + """ + + ax.plot(data.loc[country], label=country, **g_params) + + # Highlight recessions + ax.axvspan(1973, 1975, **b_params) + ax.axvspan(1990, 1992, **b_params) + ax.axvspan(2007, 2009, **b_params) + ax.axvspan(2019, 2021, **b_params) + if ylim != None: + ax.set_ylim([-ylim, ylim]) + else: + ylim = ax.get_ylim()[1] + ax.text(1974, ylim + ylim*txt_pos, + 'Oil Crisis\n(1974)', **t_params) + ax.text(1991, ylim + ylim*txt_pos, + '1990s recession\n(1991)', **t_params) + ax.text(2008, ylim + ylim*txt_pos, + 'GFC\n(2008)', **t_params) + ax.text(2020, ylim + ylim*txt_pos, + 'Covid-19\n(2020)', **t_params) + + # Add a baseline for reference + if baseline != None: + ax.axhline(y=baseline, + color='black', + linestyle='--') + ax.set_ylabel(ylabel) + ax.legend() + return ax + +# Define graphical parameters +g_params = {'alpha': 0.7} +b_params = {'color':'grey', 'alpha': 0.2} +t_params = {'color':'grey', 'fontsize': 9, + 'va':'center', 'ha':'center'} +``` + + +Let's start with the United States. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "United States (GDP growth rate %)" + name: us_gdp +--- + +fig, ax = plt.subplots() + +country = 'United States' +ylabel = 'GDP growth rate (%)' +plot_series(gdp_growth, country, + ylabel, 0.1, ax, + g_params, b_params, t_params) +plt.show() +``` + ++++ {"user_expressions": []} + +GDP growth is positive on average and trending slightly downward over time. + +We also see fluctuations over GDP growth over time, some of which are quite large. + +Let's look at a few more countries to get a basis for comparison. + ++++ + +The United Kingdom (UK) has a similar pattern to the US, with a slow decline +in the growth rate and significant fluctuations. + +Notice the very large dip during the Covid-19 pandemic. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "United Kingdom (GDP growth rate %)" + name: uk_gdp +--- + +fig, ax = plt.subplots() + +country = 'United Kingdom' +plot_series(gdp_growth, country, + ylabel, 0.1, ax, + g_params, b_params, t_params) +plt.show() +``` + ++++ {"user_expressions": []} + +Now let's consider Japan, which experienced rapid growth in the 1960s and +1970s, followed by slowed expansion in the past two decades. + +Major dips in the growth rate coincided with the Oil Crisis of the 1970s, the +Global Financial Crisis (GFC) and the Covid-19 pandemic. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Japan (GDP growth rate %)" + name: jp_gdp +--- + +fig, ax = plt.subplots() + +country = 'Japan' +plot_series(gdp_growth, country, + ylabel, 0.1, ax, + g_params, b_params, t_params) +plt.show() +``` + +Now let's study Greece. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Greece (GDP growth rate %)" + name: gc_gdp +--- + +fig, ax = plt.subplots() + +country = 'Greece' +plot_series(gdp_growth, country, + ylabel, 0.1, ax, + g_params, b_params, t_params) +plt.show() +``` + +Greece experienced a very large drop in GDP growth around 2010-2011, during the peak +of the Greek debt crisis. + +Next let's consider Argentina. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Argentina (GDP growth rate %)" + name: arg_gdp +--- + +fig, ax = plt.subplots() + +country = 'Argentina' +plot_series(gdp_growth, country, + ylabel, 0.1, ax, + g_params, b_params, t_params) +plt.show() +``` + +Notice that Argentina has experienced far more volatile cycles than +the economies examined above. + +At the same time, Argentina's growth rate did not fall during the two developed +economy recessions in the 1970s and 1990s. + + +## Unemployment + +Another important measure of business cycles is the unemployment rate. + +We study unemployment using rate data from FRED spanning from [1929-1942](https://fred.stlouisfed.org/series/M0892AUSM156SNBR) to [1948-2022](https://fred.stlouisfed.org/series/UNRATE), combined unemployment rate data over 1942-1948 estimated by the [Census Bureau](https://www.census.gov/library/publications/1975/compendia/hist_stats_colonial-1970.html). + +```{code-cell} ipython3 +:tags: [hide-input] + +start_date = datetime.datetime(1929, 1, 1) +end_date = datetime.datetime(1942, 6, 1) + +unrate_history = web.DataReader('M0892AUSM156SNBR', + 'fred', start_date,end_date) +unrate_history.rename(columns={'M0892AUSM156SNBR': 'UNRATE'}, + inplace=True) + +start_date = datetime.datetime(1948, 1, 1) +end_date = datetime.datetime(2022, 12, 31) + +unrate = web.DataReader('UNRATE', 'fred', + start_date, end_date) +``` + +Let's plot the unemployment rate in the US from 1929 to 2022 with recessions +defined by the NBER. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Long-run unemployment rate, US (%)" + name: lrunrate +tags: [hide-input] +--- + +# We use the census bureau's estimate for the unemployment rate +# between 1942 and 1948 +years = [datetime.datetime(year, 6, 1) for year in range(1942, 1948)] +unrate_census = [4.7, 1.9, 1.2, 1.9, 3.9, 3.9] + +unrate_census = {'DATE': years, 'UNRATE': unrate_census} +unrate_census = pd.DataFrame(unrate_census) +unrate_census.set_index('DATE', inplace=True) + +# Obtain the NBER-defined recession periods +start_date = datetime.datetime(1929, 1, 1) +end_date = datetime.datetime(2022, 12, 31) + +nber = web.DataReader('USREC', 'fred', start_date, end_date) + +fig, ax = plt.subplots() + +ax.plot(unrate_history, **g_params, + color='#377eb8', + linestyle='-', linewidth=2) +ax.plot(unrate_census, **g_params, + color='black', linestyle='--', + label='Census estimates', linewidth=2) +ax.plot(unrate, **g_params, color='#377eb8', + linestyle='-', linewidth=2) + +# Draw gray boxes according to NBER recession indicators +ax.fill_between(nber.index, 0, 1, + where=nber['USREC']==1, + color='grey', edgecolor='none', + alpha=0.3, + transform=ax.get_xaxis_transform(), + label='NBER recession indicators') +ax.set_ylim([0, ax.get_ylim()[1]]) +ax.legend(loc='upper center', + bbox_to_anchor=(0.5, 1.1), + ncol=3, fancybox=True, shadow=True) +ax.set_ylabel('unemployment rate (%)') + +plt.show() +``` + + +The plot shows that + +* expansions and contractions of the labor market have been highly correlated + with recessions. +* cycles are, in general, asymmetric: sharp rises in unemployment are followed + by slow recoveries. + +It also shows us how unique labor market conditions were in the US during the +post-pandemic recovery. + +The labor market recovered at an unprecedented rate after the shock in 2020-2021. + + +(synchronization)= +## Synchronization + +In our {ref}`previous discussion`, we found that developed economies have had +relatively synchronized periods of recession. + +At the same time, this synchronization did not appear in Argentina until the 2000s. + +Let's examine this trend further. + +With slight modifications, we can use our previous function to draw a plot +that includes multiple countries. + +```{code-cell} ipython3 +--- +tags: [hide-input] +--- + + +def plot_comparison(data, countries, + ylabel, txt_pos, y_lim, ax, + g_params, b_params, t_params, + baseline=0): + """ + Plot multiple series on the same graph + + Parameters + ---------- + data : pd.DataFrame + Data to plot + countries : list + List of countries to plot + ylabel : str + Label of the y-axis + txt_pos : float + Position of the recession labels + y_lim : float + Limit of the y-axis + ax : matplotlib.axes._subplots.AxesSubplot + Axes to plot on + g_params : dict + Parameters for the lines + b_params : dict + Parameters for the recession highlights + t_params : dict + Parameters for the recession labels + baseline : float, optional + Dashed baseline on the plot, by default 0 + + Returns + ------- + ax : matplotlib.axes.Axes + Axes with the plot. + """ + + # Allow the function to go through more than one series + for country in countries: + ax.plot(data.loc[country], label=country, **g_params) + + # Highlight recessions + ax.axvspan(1973, 1975, **b_params) + ax.axvspan(1990, 1992, **b_params) + ax.axvspan(2007, 2009, **b_params) + ax.axvspan(2019, 2021, **b_params) + if y_lim != None: + ax.set_ylim([-y_lim, y_lim]) + ylim = ax.get_ylim()[1] + ax.text(1974, ylim + ylim*txt_pos, + 'Oil Crisis\n(1974)', **t_params) + ax.text(1991, ylim + ylim*txt_pos, + '1990s recession\n(1991)', **t_params) + ax.text(2008, ylim + ylim*txt_pos, + 'GFC\n(2008)', **t_params) + ax.text(2020, ylim + ylim*txt_pos, + 'Covid-19\n(2020)', **t_params) + if baseline != None: + ax.hlines(y=baseline, xmin=ax.get_xlim()[0], + xmax=ax.get_xlim()[1], color='black', + linestyle='--') + ax.set_ylabel(ylabel) + ax.legend() + return ax + +# Define graphical parameters +g_params = {'alpha': 0.7} +b_params = {'color':'grey', 'alpha': 0.2} +t_params = {'color':'grey', 'fontsize': 9, + 'va':'center', 'ha':'center'} +``` + +Here we compare the GDP growth rate of developed economies and developing economies. + +```{code-cell} ipython3 +--- +tags: [hide-input] +--- + +# Obtain GDP growth rate for a list of countries +gdp_growth = wb.data.DataFrame('NY.GDP.MKTP.KD.ZG', + ['CHN', 'USA', 'DEU', 'BRA', 'ARG', 'GBR', 'JPN', 'MEX'], + labels=True) +gdp_growth = gdp_growth.set_index('Country') +gdp_growth.columns = gdp_growth.columns.str.replace('YR', '').astype(int) + +``` + +We use the United Kingdom, United States, Germany, and Japan as examples of developed economies. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Developed economies (GDP growth rate %)" + name: adv_gdp +tags: [hide-input] +--- + +fig, ax = plt.subplots() +countries = ['United Kingdom', 'United States', 'Germany', 'Japan'] +ylabel = 'GDP growth rate (%)' +plot_comparison(gdp_growth.loc[countries, 1962:], + countries, ylabel, + 0.1, 20, ax, + g_params, b_params, t_params) +plt.show() +``` + +We choose Brazil, China, Argentina, and Mexico as representative developing economies. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Developing economies (GDP growth rate %)" + name: deve_gdp +tags: [hide-input] +--- + +fig, ax = plt.subplots() +countries = ['Brazil', 'China', 'Argentina', 'Mexico'] +plot_comparison(gdp_growth.loc[countries, 1962:], + countries, ylabel, + 0.1, 20, ax, + g_params, b_params, t_params) +plt.show() +``` + + +The comparison of GDP growth rates above suggests that +business cycles are becoming more synchronized in 21st-century recessions. + +However, emerging and less developed economies often experience more volatile +changes throughout the economic cycles. + +Despite the synchronization in GDP growth, the experience of individual countries during +the recession often differs. + +We use the unemployment rate and the recovery of labor market conditions +as another example. + +Here we compare the unemployment rate of the United States, +the United Kingdom, Japan, and France. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Developed economies (unemployment rate %)" + name: adv_unemp +tags: [hide-input] +--- + +unempl_rate = wb.data.DataFrame('SL.UEM.TOTL.NE.ZS', + ['USA', 'FRA', 'GBR', 'JPN'], labels=True) +unempl_rate = unempl_rate.set_index('Country') +unempl_rate.columns = unempl_rate.columns.str.replace('YR', '').astype(int) + +fig, ax = plt.subplots() + +countries = ['United Kingdom', 'United States', 'Japan', 'France'] +ylabel = 'unemployment rate (national estimate) (%)' +plot_comparison(unempl_rate, countries, + ylabel, 0.05, None, ax, g_params, + b_params, t_params, baseline=None) +plt.show() +``` + +We see that France, with its strong labor unions, typically experiences +relatively slow labor market recoveries after negative shocks. + +We also notice that Japan has a history of very low and stable unemployment rates. + + +## Leading indicators and correlated factors + +Examining leading indicators and correlated factors helps policymakers to +understand the causes and results of business cycles. + +We will discuss potential leading indicators and correlated factors from three +perspectives: consumption, production, and credit level. + + +### Consumption + +Consumption depends on consumers' confidence towards their +income and the overall performance of the economy in the future. + +One widely cited indicator for consumer confidence is the [consumer sentiment index](https://fred.stlouisfed.org/series/UMCSENT) published by the University +of Michigan. + +Here we plot the University of Michigan Consumer Sentiment Index and +year-on-year +[core consumer price index](https://fred.stlouisfed.org/series/CPILFESL) +(CPI) change from 1978-2022 in the US. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Consumer sentiment index and YoY CPI change, US" + name: csicpi +tags: [hide-input] +--- + +start_date = datetime.datetime(1978, 1, 1) +end_date = datetime.datetime(2022, 12, 31) + +# Limit the plot to a specific range +start_date_graph = datetime.datetime(1977, 1, 1) +end_date_graph = datetime.datetime(2023, 12, 31) + +nber = web.DataReader('USREC', 'fred', start_date, end_date) +consumer_confidence = web.DataReader('UMCSENT', 'fred', + start_date, end_date) + +fig, ax = plt.subplots() +ax.plot(consumer_confidence, **g_params, + color='#377eb8', linestyle='-', + linewidth=2) +ax.fill_between(nber.index, 0, 1, + where=nber['USREC']==1, + color='grey', edgecolor='none', + alpha=0.3, + transform=ax.get_xaxis_transform(), + label='NBER recession indicators') +ax.set_ylim([0, ax.get_ylim()[1]]) +ax.set_ylabel('consumer sentiment index') + +# Plot CPI on another y-axis +ax_t = ax.twinx() +inflation = web.DataReader('CPILFESL', 'fred', + start_date, end_date).pct_change(12)*100 + +# Add CPI on the legend without drawing the line again +ax_t.plot(2020, 0, **g_params, linestyle='-', + linewidth=2, label='consumer sentiment index') +ax_t.plot(inflation, **g_params, + color='#ff7f00', linestyle='--', + linewidth=2, label='CPI YoY change (%)') + +ax_t.fill_between(nber.index, 0, 1, + where=nber['USREC']==1, + color='grey', edgecolor='none', + alpha=0.3, + transform=ax.get_xaxis_transform(), + label='NBER recession indicators') +ax_t.set_ylim([0, ax_t.get_ylim()[1]]) +ax_t.set_xlim([start_date_graph, end_date_graph]) +ax_t.legend(loc='upper center', + bbox_to_anchor=(0.5, 1.1), + ncol=3, fontsize=9) +ax_t.set_ylabel('CPI YoY change (%)') +plt.show() +``` + +We see that + +* consumer sentiment often remains high during expansions and +drops before recessions. +* there is a clear negative correlation between consumer sentiment and the CPI. + +When the price of consumer commodities rises, consumer confidence diminishes. + +This trend is more significant during [stagflation](https://en.wikipedia.org/wiki/Stagflation). + + + +### Production + +Real industrial output is highly correlated with recessions in the economy. + +However, it is not a leading indicator, as the peak of contraction in production +is delayed relative to consumer confidence and inflation. + +We plot the real industrial output change from the previous year +from 1919 to 2022 in the US to show this trend. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "YoY real output change, US (%)" + name: roc +tags: [hide-input] +--- + +start_date = datetime.datetime(1919, 1, 1) +end_date = datetime.datetime(2022, 12, 31) + +nber = web.DataReader('USREC', 'fred', + start_date, end_date) +industrial_output = web.DataReader('INDPRO', 'fred', + start_date, end_date).pct_change(12)*100 + +fig, ax = plt.subplots() +ax.plot(industrial_output, **g_params, + color='#377eb8', linestyle='-', + linewidth=2, label='Industrial production index') +ax.fill_between(nber.index, 0, 1, + where=nber['USREC']==1, + color='grey', edgecolor='none', + alpha=0.3, + transform=ax.get_xaxis_transform(), + label='NBER recession indicators') +ax.set_ylim([ax.get_ylim()[0], ax.get_ylim()[1]]) +ax.set_ylabel('YoY real output change (%)') +plt.show() +``` + +We observe the delayed contraction in the plot across recessions. + + +### Credit level + +Credit contractions often occur during recessions, as lenders become more +cautious and borrowers become more hesitant to take on additional debt. + +This is due to factors such as a decrease in overall economic +activity and gloomy expectations for the future. + +One example is domestic credit to the private sector by banks in the UK. + +The following graph shows the domestic credit to the private sector as a +percentage of GDP by banks from 1970 to 2022 in the UK. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Domestic credit to private sector by banks (% of GDP)" + name: dcpc +tags: [hide-input] +--- + +private_credit = wb.data.DataFrame('FS.AST.PRVT.GD.ZS', + ['GBR'], labels=True) +private_credit = private_credit.set_index('Country') +private_credit.columns = private_credit.columns.str.replace('YR', '').astype(int) + +fig, ax = plt.subplots() + +countries = 'United Kingdom' +ylabel = 'credit level (% of GDP)' +ax = plot_series(private_credit, countries, + ylabel, 0.05, ax, g_params, b_params, + t_params, ylim=None, baseline=None) +plt.show() +``` + +Note that the credit rises during economic expansions +and stagnates or even contracts after recessions. diff --git a/book/_build/html/_sources/cagan_adaptive.ipynb b/book/_build/html/_sources/cagan_adaptive.ipynb new file mode 100644 index 0000000..937efbd --- /dev/null +++ b/book/_build/html/_sources/cagan_adaptive.ipynb @@ -0,0 +1,548 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "ec9c9875", + "metadata": {}, + "source": [ + "# Monetarist Theory of Price Levels with Adaptive Expectations\n", + "\n", + "## Overview\n", + "\n", + "\n", + "This lecture is a sequel or prequel to {doc}`cagan_ree`.\n", + "\n", + "We'll use linear algebra to do some experiments with an alternative \"monetarist\" or \"fiscal\" theory of price levels.\n", + "\n", + "Like the model in {doc}`cagan_ree`, the model asserts that when a government persistently spends more than it collects in taxes and prints money to finance the shortfall, it puts upward pressure on the price level and generates persistent inflation.\n", + "\n", + "Instead of the \"perfect foresight\" or \"rational expectations\" version of the model in {doc}`cagan_ree`, our model in the present lecture is an \"adaptive expectations\" version of a model that {cite}`Cagan` used to study the monetary dynamics of hyperinflations. \n", + "\n", + "It combines these components:\n", + "\n", + "* a demand function for real money balances that asserts that the logarithm of the quantity of real balances demanded depends inversely on the public's expected rate of inflation\n", + "\n", + "* an **adaptive expectations** model that describes how the public's anticipated rate of inflation responds to past values of actual inflation\n", + "\n", + "* an equilibrium condition that equates the demand for money to the supply\n", + "\n", + "* an exogenous sequence of rates of growth of the money supply\n", + "\n", + "Our model stays quite close to Cagan's original specification. \n", + "\n", + "As in {doc}`pv` and {doc}`cons_smooth`, the only linear algebra operations that we'll be using are matrix multiplication and matrix inversion.\n", + "\n", + "To facilitate using linear matrix algebra as our principal mathematical tool, we'll use a finite horizon version of\n", + "the model.\n", + "\n", + "## Structure of the model\n", + "\n", + "Let \n", + "\n", + "* $ m_t $ be the log of the supply of nominal money balances;\n", + "* $\\mu_t = m_{t+1} - m_t $ be the net rate of growth of nominal balances;\n", + "* $p_t $ be the log of the price level;\n", + "* $\\pi_t = p_{t+1} - p_t $ be the net rate of inflation between $t$ and $ t+1$;\n", + "* $\\pi_t^*$ be the public's expected rate of inflation between $t$ and $t+1$;\n", + "* $T$ the horizon -- i.e., the last period for which the model will determine $p_t$\n", + "* $\\pi_0^*$ public's initial expected rate of inflation between time $0$ and time $1$.\n", + " \n", + " \n", + "The demand for real balances $\\exp\\left(m_t^d-p_t\\right)$ is governed by the following version of the Cagan demand function\n", + " \n", + "$$ \n", + "m_t^d - p_t = -\\alpha \\pi_t^* \\: , \\: \\alpha > 0 ; \\quad t = 0, 1, \\ldots, T .\n", + "$$ (eq:caganmd_ad)\n", + "\n", + "\n", + "This equation asserts that the demand for real balances\n", + "is inversely related to the public's expected rate of inflation with sensitivity $\\alpha$.\n", + "\n", + "Equating the logarithm $m_t^d$ of the demand for money to the logarithm $m_t$ of the supply of money in equation {eq}`eq:caganmd_ad` and solving for the logarithm $p_t$\n", + "of the price level gives\n", + "\n", + "$$\n", + "p_t = m_t + \\alpha \\pi_t^*\n", + "$$ (eq:eqfiscth1)\n", + "\n", + "Taking the difference between equation {eq}`eq:eqfiscth1` at time $t+1$ and at time \n", + "$t$ gives\n", + "\n", + "$$\n", + "\\pi_t = \\mu_t + \\alpha \\pi_{t+1}^* - \\alpha \\pi_t^*\n", + "$$ (eq:eq%pipi)\n", + "\n", + "We assume that the expected rate of inflation $\\pi_t^*$ is governed\n", + "by the following adaptive expectations scheme proposed by {cite}`Friedman1956` and {cite}`Cagan`, where $\\lambda\\in [0,1]$ denotes the weight on expected inflation.\n", + "\n", + "$$\n", + "\\pi_{t+1}^* = \\lambda \\pi_t^* + (1 -\\lambda) \\pi_t \n", + "$$ (eq:adaptexpn)\n", + "\n", + "As exogenous inputs into the model, we take initial conditions $m_0, \\pi_0^*$\n", + "and a money growth sequence $\\mu = \\{\\mu_t\\}_{t=0}^T$. \n", + "\n", + "As endogenous outputs of our model we want to find sequences $\\pi = \\{\\pi_t\\}_{t=0}^T, p = \\{p_t\\}_{t=0}^T$ as functions of the exogenous inputs.\n", + "\n", + "We'll do some mental experiments by studying how the model outputs vary as we vary\n", + "the model inputs.\n", + "\n", + "## Representing key equations with linear algebra\n", + "\n", + "We begin by writing the equation {eq}`eq:adaptexpn` adaptive expectations model for $\\pi_t^*$ for $t=0, \\ldots, T$ as\n", + "\n", + "$$\n", + "\\begin{bmatrix} 1 & 0 & 0 & \\cdots & 0 & 0 \\cr\n", + "-\\lambda & 1 & 0 & \\cdots & 0 & 0 \\cr\n", + "0 & - \\lambda & 1 & \\cdots & 0 & 0 \\cr\n", + "\\vdots & \\vdots & \\vdots & \\cdots & \\vdots & \\vdots \\cr\n", + "0 & 0 & 0 & \\cdots & -\\lambda & 1\n", + "\\end{bmatrix}\n", + "\\begin{bmatrix} \\pi_0^* \\cr\n", + " \\pi_1^* \\cr\n", + " \\pi_2^* \\cr\n", + " \\vdots \\cr\n", + " \\pi_{T+1}^* \n", + " \\end{bmatrix} =\n", + " (1-\\lambda) \\begin{bmatrix} \n", + " 0 & 0 & 0 & \\cdots & 0 \\cr\n", + " 1 & 0 & 0 & \\cdots & 0 \\cr\n", + " 0 & 1 & 0 & \\cdots & 0 \\cr\n", + " \\vdots &\\vdots & \\vdots & \\cdots & \\vdots \\cr\n", + " 0 & 0 & 0 & \\cdots & 1 \\end{bmatrix}\n", + " \\begin{bmatrix}\\pi_0 \\cr \\pi_1 \\cr \\pi_2 \\cr \\vdots \\cr \\pi_T\n", + " \\end{bmatrix} +\n", + " \\begin{bmatrix} \\pi_0^* \\cr 0 \\cr 0 \\cr \\vdots \\cr 0 \\end{bmatrix}\n", + "$$\n", + "\n", + "Write this equation as\n", + "\n", + "$$\n", + " A \\pi^* = (1-\\lambda) B \\pi + \\pi_0^*\n", + "$$ (eq:eq1)\n", + "\n", + "where the $(T+2) \\times (T+2) $matrix $A$, the $(T+2)\\times (T+1)$ matrix $B$, and the vectors $\\pi^* , \\pi_0, \\pi_0^*$\n", + "are defined implicitly by aligning these two equations.\n", + "\n", + "Next we write the key equation {eq}`eq:eq%pipi` in matrix notation as\n", + "\n", + "$$ \n", + "\\begin{bmatrix}\n", + "\\pi_0 \\cr \\pi_1 \\cr \\pi_1 \\cr \\vdots \\cr \\pi_T \\end{bmatrix}\n", + "= \\begin{bmatrix}\n", + "\\mu_0 \\cr \\mu_1 \\cr \\mu_2 \\cr \\vdots \\cr \\mu_T \\end{bmatrix}\n", + "+ \\begin{bmatrix} - \\alpha & \\alpha & 0 & \\cdots & 0 & 0 \\cr\n", + "0 & -\\alpha & \\alpha & \\cdots & 0 & 0 \\cr\n", + "0 & 0 & -\\alpha & \\cdots & 0 & 0 \\cr\n", + "\\vdots & \\vdots & \\vdots & \\cdots & \\alpha & 0 \\cr\n", + "0 & 0 & 0 & \\cdots & -\\alpha & \\alpha \n", + "\\end{bmatrix}\n", + "\\begin{bmatrix} \\pi_0^* \\cr\n", + " \\pi_1^* \\cr\n", + " \\pi_2^* \\cr\n", + " \\vdots \\cr\n", + " \\pi_{T+1}^* \n", + " \\end{bmatrix}\n", + "$$\n", + "\n", + "Represent the previous equation system in terms of vectors and matrices as\n", + "\n", + "$$\n", + "\\pi = \\mu + C \\pi^*\n", + "$$ (eq:eq2)\n", + "\n", + "where the $(T+1) \\times (T+2)$ matrix $C$ is defined implicitly to align this equation with the preceding\n", + "equation system.\n", + "\n", + "## Harvesting insights from our matrix formulation\n", + "\n", + "We now have all of the ingredients we need to solve for $\\pi$ as\n", + "a function of $\\mu, \\pi_0, \\pi_0^*$. \n", + "\n", + "Combine equations {eq}`eq:eq1`and {eq}`eq:eq2` to get\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "A \\pi^* & = (1-\\lambda) B \\pi + \\pi_0^* \\cr\n", + " & = (1-\\lambda) B \\left[ \\mu + C \\pi^* \\right] + \\pi_0^*\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "which implies that\n", + "\n", + "$$\n", + "\\left[ A - (1-\\lambda) B C \\right] \\pi^* = (1-\\lambda) B \\mu+ \\pi_0^*\n", + "$$\n", + "\n", + "Multiplying both sides of the above equation by the inverse of the matrix on the left side gives\n", + "\n", + "$$\n", + "\\pi^* = \\left[ A - (1-\\lambda) B C \\right]^{-1} \\left[ (1-\\lambda) B \\mu+ \\pi_0^* \\right]\n", + "$$ (eq:eq4)\n", + "\n", + "Having solved equation {eq}`eq:eq4` for $\\pi^*$, we can use equation {eq}`eq:eq2` to solve for $\\pi$:\n", + "\n", + "$$\n", + "\\pi = \\mu + C \\pi^*\n", + "$$\n", + "\n", + "\n", + "We have thus solved for two of the key endogenous time series determined by our model, namely, the sequence $\\pi^*$\n", + "of expected inflation rates and the sequence $\\pi$ of actual inflation rates. \n", + "\n", + "Knowing these, we can then quickly calculate the associated sequence $p$ of the logarithm of the price level\n", + "from equation {eq}`eq:eqfiscth1`. \n", + "\n", + "Let's fill in the details for this step.\n", + "\n", + "Since we now know $\\mu$ it is easy to compute $m$.\n", + "\n", + "Thus, notice that we can represent the equations \n", + "\n", + "$$ \n", + "m_{t+1} = m_t + \\mu_t , \\quad t = 0, 1, \\ldots, T\n", + "$$\n", + "\n", + "as the matrix equation\n", + "\n", + "$$\n", + "\\begin{bmatrix}\n", + "1 & 0 & 0 & \\cdots & 0 & 0 \\cr\n", + "-1 & 1 & 0 & \\cdots & 0 & 0 \\cr\n", + "0 & -1 & 1 & \\cdots & 0 & 0 \\cr\n", + "\\vdots & \\vdots & \\vdots & \\vdots & 0 & 0 \\cr\n", + "0 & 0 & 0 & \\cdots & 1 & 0 \\cr\n", + "0 & 0 & 0 & \\cdots & -1 & 1 \n", + "\\end{bmatrix}\n", + "\\begin{bmatrix} \n", + "m_1 \\cr m_2 \\cr m_3 \\cr \\vdots \\cr m_T \\cr m_{T+1}\n", + "\\end{bmatrix}\n", + "= \\begin{bmatrix} \n", + "\\mu_0 \\cr \\mu_1 \\cr \\mu_2 \\cr \\vdots \\cr \\mu_{T-1} \\cr \\mu_T\n", + "\\end{bmatrix}\n", + "+ \\begin{bmatrix} \n", + "m_0 \\cr 0 \\cr 0 \\cr \\vdots \\cr 0 \\cr 0\n", + "\\end{bmatrix}\n", + "$$ (eq:eq101_ad)\n", + "\n", + "Multiplying both sides of equation {eq}`eq:eq101_ad` with the inverse of the matrix on the left will give \n", + "\n", + "$$\n", + "m_t = m_0 + \\sum_{s=0}^{t-1} \\mu_s, \\quad t =1, \\ldots, T+1\n", + "$$ (eq:mcum_ad)\n", + "\n", + "Equation {eq}`eq:mcum_ad` shows that the log of the money supply at $t$ equals the log $m_0$ of the initial money supply \n", + "plus accumulation of rates of money growth between times $0$ and $t$.\n", + "\n", + "We can then compute $p_t$ for each $t$ from equation {eq}`eq:eqfiscth1`.\n", + "\n", + "We can write a compact formula for $p $ as\n", + "\n", + "$$ \n", + "p = m + \\alpha \\hat \\pi^*\n", + "$$\n", + "\n", + "where \n", + "\n", + "$$\n", + "\\hat \\pi^* = \\begin{bmatrix} \\pi_0^* \\cr\n", + " \\pi_1^* \\cr\n", + " \\pi_2^* \\cr\n", + " \\vdots \\cr\n", + " \\pi_{T}^* \n", + " \\end{bmatrix},\n", + " $$\n", + "\n", + "which is just $\\pi^*$ with the last element dropped.\n", + " \n", + "## Forecast errors and model computation\n", + "\n", + "Our computations will verify that \n", + "\n", + "$$\n", + "\\hat \\pi^* \\neq \\pi,\n", + "$$\n", + "\n", + "so that in general\n", + "\n", + "$$ \n", + "\\pi_t^* \\neq \\pi_t, \\quad t = 0, 1, \\ldots , T\n", + "$$ (eq:notre)\n", + "\n", + "This outcome is typical in models in which adaptive expectations hypothesis like equation {eq}`eq:adaptexpn` appear as a\n", + "component. \n", + "\n", + "In {doc}`cagan_ree`, we studied a version of the model that replaces hypothesis {eq}`eq:adaptexpn` with\n", + "a \"perfect foresight\" or \"rational expectations\" hypothesis.\n", + "\n", + "But now, let's dive in and do some computations with the adaptive expectations version of the model.\n", + "\n", + "As usual, we'll start by importing some Python modules." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a81435c9", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "from collections import namedtuple\n", + "import matplotlib.pyplot as plt" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "882cca45", + "metadata": {}, + "outputs": [], + "source": [ + "Cagan_Adaptive = namedtuple(\"Cagan_Adaptive\", \n", + " [\"α\", \"m0\", \"Eπ0\", \"T\", \"λ\"])\n", + "\n", + "def create_cagan_adaptive_model(α = 5, m0 = 1, Eπ0 = 0.5, T=80, λ = 0.9):\n", + " return Cagan_Adaptive(α, m0, Eπ0, T, λ)\n", + "\n", + "md = create_cagan_adaptive_model()" + ] + }, + { + "cell_type": "markdown", + "id": "08b24fa4", + "metadata": { + "user_expressions": [] + }, + "source": [ + "We solve the model and plot variables of interests using the following functions." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "08e871f5", + "metadata": {}, + "outputs": [], + "source": [ + "def solve_cagan_adaptive(model, μ_seq):\n", + " \" Solve the Cagan model in finite time. \"\n", + " α, m0, Eπ0, T, λ = model\n", + " \n", + " A = np.eye(T+2, T+2) - λ*np.eye(T+2, T+2, k=-1)\n", + " B = np.eye(T+2, T+1, k=-1)\n", + " C = -α*np.eye(T+1, T+2) + α*np.eye(T+1, T+2, k=1)\n", + " Eπ0_seq = np.append(Eπ0, np.zeros(T+1))\n", + "\n", + " # Eπ_seq is of length T+2\n", + " Eπ_seq = np.linalg.solve(A - (1-λ)*B @ C, (1-λ) * B @ μ_seq + Eπ0_seq)\n", + "\n", + " # π_seq is of length T+1\n", + " π_seq = μ_seq + C @ Eπ_seq\n", + "\n", + " D = np.eye(T+1, T+1) - np.eye(T+1, T+1, k=-1) # D is the coefficient matrix in Equation (14.8)\n", + " m0_seq = np.append(m0, np.zeros(T))\n", + "\n", + " # m_seq is of length T+2\n", + " m_seq = np.linalg.solve(D, μ_seq + m0_seq)\n", + " m_seq = np.append(m0, m_seq)\n", + "\n", + " # p_seq is of length T+2\n", + " p_seq = m_seq + α * Eπ_seq\n", + "\n", + " return π_seq, Eπ_seq, m_seq, p_seq" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cc0bc6f9", + "metadata": {}, + "outputs": [], + "source": [ + "def solve_and_plot(model, μ_seq):\n", + " \n", + " π_seq, Eπ_seq, m_seq, p_seq = solve_cagan_adaptive(model, μ_seq)\n", + " \n", + " T_seq = range(model.T+2)\n", + " \n", + " fig, ax = plt.subplots(5, 1, figsize=[5, 12], dpi=200)\n", + " ax[0].plot(T_seq[:-1], μ_seq)\n", + " ax[1].plot(T_seq[:-1], π_seq, label=r'$\\pi_t$')\n", + " ax[1].plot(T_seq, Eπ_seq, label=r'$\\pi^{*}_{t}$')\n", + " ax[2].plot(T_seq, m_seq - p_seq)\n", + " ax[3].plot(T_seq, m_seq)\n", + " ax[4].plot(T_seq, p_seq)\n", + " \n", + " y_labs = [r'$\\mu$', r'$\\pi$', r'$m - p$', r'$m$', r'$p$']\n", + " subplot_title = [r'Money supply growth', r'Inflation', r'Real balances', r'Money supply', r'Price level']\n", + "\n", + " for i in range(5):\n", + " ax[i].set_xlabel(r'$t$')\n", + " ax[i].set_ylabel(y_labs[i])\n", + " ax[i].set_title(subplot_title[i])\n", + "\n", + " ax[1].legend()\n", + " plt.tight_layout()\n", + " plt.show()\n", + " \n", + " return π_seq, Eπ_seq, m_seq, p_seq" + ] + }, + { + "cell_type": "markdown", + "id": "77b89a45", + "metadata": { + "user_expressions": [] + }, + "source": [ + "## Technical condition for stability\n", + "\n", + "In constructing our examples, we shall assume that $(\\lambda, \\alpha)$ satisfy\n", + "\n", + "$$\n", + "\\Bigl| \\frac{\\lambda-\\alpha(1-\\lambda)}{1-\\alpha(1-\\lambda)} \\Bigr| < 1\n", + "$$ (eq:suffcond)\n", + "\n", + "The source of this condition is the following string of deductions:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "\\pi_{t}&=\\mu_{t}+\\alpha\\pi_{t+1}^{*}-\\alpha\\pi_{t}^{*}\\\\\\pi_{t+1}^{*}&=\\lambda\\pi_{t}^{*}+(1-\\lambda)\\pi_{t}\\\\\\pi_{t}&=\\frac{\\mu_{t}}{1-\\alpha(1-\\lambda)}-\\frac{\\alpha(1-\\lambda)}{1-\\alpha(1-\\lambda)}\\pi_{t}^{*}\\\\\\implies\\pi_{t}^{*}&=\\frac{1}{\\alpha(1-\\lambda)}\\mu_{t}-\\frac{1-\\alpha(1-\\lambda)}{\\alpha(1-\\lambda)}\\pi_{t}\\\\\\pi_{t+1}&=\\frac{\\mu_{t+1}}{1-\\alpha(1-\\lambda)}-\\frac{\\alpha(1-\\lambda)}{1-\\alpha(1-\\lambda)}\\left(\\lambda\\pi_{t}^{*}+(1-\\lambda)\\pi_{t}\\right)\\\\&=\\frac{\\mu_{t+1}}{1-\\alpha(1-\\lambda)}-\\frac{\\lambda}{1-\\alpha(1-\\lambda)}\\mu_{t}+\\frac{\\lambda-\\alpha(1-\\lambda)}{1-\\alpha(1-\\lambda)}\\pi_{t}\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "By assuring that the coefficient on $\\pi_t$ is less than one in absolute value, condition {eq}`eq:suffcond` assures stability of the dynamics of $\\{\\pi_t\\}$ described by the last line of our string of deductions. \n", + "\n", + "The reader is free to study outcomes in examples that violate condition {eq}`eq:suffcond`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "44369819", + "metadata": {}, + "outputs": [], + "source": [ + "print(np.abs((md.λ - md.α*(1-md.λ))/(1 - md.α*(1-md.λ))))" + ] + }, + { + "cell_type": "markdown", + "id": "2bf89ede", + "metadata": {}, + "source": [ + "## Experiments\n", + "\n", + "Now we'll turn to some experiments.\n", + "\n", + "### Experiment 1\n", + "\n", + "We'll study a situation in which the rate of growth of the money supply is $\\mu_0$\n", + "from $t=0$ to $t= T_1$ and then permanently falls to $\\mu^*$ at $t=T_1$.\n", + "\n", + "Thus, let $T_1 \\in (0, T)$. \n", + "\n", + "So where $\\mu_0 > \\mu^*$, we assume that\n", + "\n", + "$$\n", + "\\mu_{t} = \\begin{cases}\n", + " \\mu_0 , & t = 0, \\ldots, T_1 -1 \\\\\n", + " \\mu^* , & t \\geq T_1\n", + " \\end{cases}\n", + "$$\n", + "\n", + "Notice that we studied exactly this experiment in a rational expectations version of the model in {doc}`cagan_ree`.\n", + "\n", + "So by comparing outcomes across the two lectures, we can learn about consequences of assuming adaptive expectations, as we do here, instead of rational expectations as we assumed in that other lecture." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bebb9444", + "metadata": {}, + "outputs": [], + "source": [ + "# Parameters for the experiment 1\n", + "T1 = 60\n", + "μ0 = 0.5\n", + "μ_star = 0\n", + "\n", + "μ_seq_1 = np.append(μ0*np.ones(T1), μ_star*np.ones(md.T+1-T1))\n", + "\n", + "# solve and plot\n", + "π_seq_1, Eπ_seq_1, m_seq_1, p_seq_1 = solve_and_plot(md, μ_seq_1)" + ] + }, + { + "cell_type": "markdown", + "id": "403379b7", + "metadata": {}, + "source": [ + "We invite the reader to compare outcomes with those under rational expectations studied in {doc}`cagan_ree`.\n", + "\n", + "Please note how the actual inflation rate $\\pi_t$ \"overshoots\" its ultimate steady-state value at the time of the sudden reduction in the rate of growth of the money supply at time $T_1$.\n", + "\n", + "We invite you to explain to yourself the source of this overshooting and why it does not occur in the rational expectations version of the model.\n", + "\n", + "### Experiment 2\n", + "\n", + "Now we'll do a different experiment, namely, a gradual stabilization in which the rate of growth of the money supply smoothly \n", + "decline from a high value to a persistently low value. \n", + "\n", + "While price level inflation eventually falls, it falls more slowly than the driving force that ultimately causes it to fall, namely, the falling rate of growth of the money supply.\n", + "\n", + "The sluggish fall in inflation is explained by how anticipated inflation $\\pi_t^*$ persistently exceeds actual inflation $\\pi_t$ during the transition from a high inflation to a low inflation situation." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d58b285b", + "metadata": {}, + "outputs": [], + "source": [ + "# parameters\n", + "ϕ = 0.9\n", + "μ_seq_2 = np.array([ϕ**t * μ0 + (1-ϕ**t)*μ_star for t in range(md.T)])\n", + "μ_seq_2 = np.append(μ_seq_2, μ_star)\n", + "\n", + "\n", + "# solve and plot\n", + "π_seq_2, Eπ_seq_2, m_seq_2, p_seq_2 = solve_and_plot(md, μ_seq_2)" + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.5" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 288, + 294, + 303, + 307, + 338, + 368, + 392, + 394, + 420, + 430, + 447 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/cagan_adaptive.md b/book/_build/html/_sources/cagan_adaptive.md new file mode 100644 index 0000000..b8403bf --- /dev/null +++ b/book/_build/html/_sources/cagan_adaptive.md @@ -0,0 +1,456 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.5 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Monetarist Theory of Price Levels with Adaptive Expectations + +## Overview + + +This lecture is a sequel or prequel to {doc}`cagan_ree`. + +We'll use linear algebra to do some experiments with an alternative "monetarist" or "fiscal" theory of price levels. + +Like the model in {doc}`cagan_ree`, the model asserts that when a government persistently spends more than it collects in taxes and prints money to finance the shortfall, it puts upward pressure on the price level and generates persistent inflation. + +Instead of the "perfect foresight" or "rational expectations" version of the model in {doc}`cagan_ree`, our model in the present lecture is an "adaptive expectations" version of a model that {cite}`Cagan` used to study the monetary dynamics of hyperinflations. + +It combines these components: + +* a demand function for real money balances that asserts that the logarithm of the quantity of real balances demanded depends inversely on the public's expected rate of inflation + +* an **adaptive expectations** model that describes how the public's anticipated rate of inflation responds to past values of actual inflation + +* an equilibrium condition that equates the demand for money to the supply + +* an exogenous sequence of rates of growth of the money supply + +Our model stays quite close to Cagan's original specification. + +As in {doc}`pv` and {doc}`cons_smooth`, the only linear algebra operations that we'll be using are matrix multiplication and matrix inversion. + +To facilitate using linear matrix algebra as our principal mathematical tool, we'll use a finite horizon version of +the model. + +## Structure of the model + +Let + +* $ m_t $ be the log of the supply of nominal money balances; +* $\mu_t = m_{t+1} - m_t $ be the net rate of growth of nominal balances; +* $p_t $ be the log of the price level; +* $\pi_t = p_{t+1} - p_t $ be the net rate of inflation between $t$ and $ t+1$; +* $\pi_t^*$ be the public's expected rate of inflation between $t$ and $t+1$; +* $T$ the horizon -- i.e., the last period for which the model will determine $p_t$ +* $\pi_0^*$ public's initial expected rate of inflation between time $0$ and time $1$. + + +The demand for real balances $\exp\left(m_t^d-p_t\right)$ is governed by the following version of the Cagan demand function + +$$ +m_t^d - p_t = -\alpha \pi_t^* \: , \: \alpha > 0 ; \quad t = 0, 1, \ldots, T . +$$ (eq:caganmd_ad) + + +This equation asserts that the demand for real balances +is inversely related to the public's expected rate of inflation with sensitivity $\alpha$. + +Equating the logarithm $m_t^d$ of the demand for money to the logarithm $m_t$ of the supply of money in equation {eq}`eq:caganmd_ad` and solving for the logarithm $p_t$ +of the price level gives + +$$ +p_t = m_t + \alpha \pi_t^* +$$ (eq:eqfiscth1) + +Taking the difference between equation {eq}`eq:eqfiscth1` at time $t+1$ and at time +$t$ gives + +$$ +\pi_t = \mu_t + \alpha \pi_{t+1}^* - \alpha \pi_t^* +$$ (eq:eq%pipi) + +We assume that the expected rate of inflation $\pi_t^*$ is governed +by the following adaptive expectations scheme proposed by {cite}`Friedman1956` and {cite}`Cagan`, where $\lambda\in [0,1]$ denotes the weight on expected inflation. + +$$ +\pi_{t+1}^* = \lambda \pi_t^* + (1 -\lambda) \pi_t +$$ (eq:adaptexpn) + +As exogenous inputs into the model, we take initial conditions $m_0, \pi_0^*$ +and a money growth sequence $\mu = \{\mu_t\}_{t=0}^T$. + +As endogenous outputs of our model we want to find sequences $\pi = \{\pi_t\}_{t=0}^T, p = \{p_t\}_{t=0}^T$ as functions of the exogenous inputs. + +We'll do some mental experiments by studying how the model outputs vary as we vary +the model inputs. + +## Representing key equations with linear algebra + +We begin by writing the equation {eq}`eq:adaptexpn` adaptive expectations model for $\pi_t^*$ for $t=0, \ldots, T$ as + +$$ +\begin{bmatrix} 1 & 0 & 0 & \cdots & 0 & 0 \cr +-\lambda & 1 & 0 & \cdots & 0 & 0 \cr +0 & - \lambda & 1 & \cdots & 0 & 0 \cr +\vdots & \vdots & \vdots & \cdots & \vdots & \vdots \cr +0 & 0 & 0 & \cdots & -\lambda & 1 +\end{bmatrix} +\begin{bmatrix} \pi_0^* \cr + \pi_1^* \cr + \pi_2^* \cr + \vdots \cr + \pi_{T+1}^* + \end{bmatrix} = + (1-\lambda) \begin{bmatrix} + 0 & 0 & 0 & \cdots & 0 \cr + 1 & 0 & 0 & \cdots & 0 \cr + 0 & 1 & 0 & \cdots & 0 \cr + \vdots &\vdots & \vdots & \cdots & \vdots \cr + 0 & 0 & 0 & \cdots & 1 \end{bmatrix} + \begin{bmatrix}\pi_0 \cr \pi_1 \cr \pi_2 \cr \vdots \cr \pi_T + \end{bmatrix} + + \begin{bmatrix} \pi_0^* \cr 0 \cr 0 \cr \vdots \cr 0 \end{bmatrix} +$$ + +Write this equation as + +$$ + A \pi^* = (1-\lambda) B \pi + \pi_0^* +$$ (eq:eq1) + +where the $(T+2) \times (T+2) $matrix $A$, the $(T+2)\times (T+1)$ matrix $B$, and the vectors $\pi^* , \pi_0, \pi_0^*$ +are defined implicitly by aligning these two equations. + +Next we write the key equation {eq}`eq:eq%pipi` in matrix notation as + +$$ +\begin{bmatrix} +\pi_0 \cr \pi_1 \cr \pi_1 \cr \vdots \cr \pi_T \end{bmatrix} += \begin{bmatrix} +\mu_0 \cr \mu_1 \cr \mu_2 \cr \vdots \cr \mu_T \end{bmatrix} ++ \begin{bmatrix} - \alpha & \alpha & 0 & \cdots & 0 & 0 \cr +0 & -\alpha & \alpha & \cdots & 0 & 0 \cr +0 & 0 & -\alpha & \cdots & 0 & 0 \cr +\vdots & \vdots & \vdots & \cdots & \alpha & 0 \cr +0 & 0 & 0 & \cdots & -\alpha & \alpha +\end{bmatrix} +\begin{bmatrix} \pi_0^* \cr + \pi_1^* \cr + \pi_2^* \cr + \vdots \cr + \pi_{T+1}^* + \end{bmatrix} +$$ + +Represent the previous equation system in terms of vectors and matrices as + +$$ +\pi = \mu + C \pi^* +$$ (eq:eq2) + +where the $(T+1) \times (T+2)$ matrix $C$ is defined implicitly to align this equation with the preceding +equation system. + +## Harvesting insights from our matrix formulation + +We now have all of the ingredients we need to solve for $\pi$ as +a function of $\mu, \pi_0, \pi_0^*$. + +Combine equations {eq}`eq:eq1`and {eq}`eq:eq2` to get + +$$ +\begin{aligned} +A \pi^* & = (1-\lambda) B \pi + \pi_0^* \cr + & = (1-\lambda) B \left[ \mu + C \pi^* \right] + \pi_0^* +\end{aligned} +$$ + +which implies that + +$$ +\left[ A - (1-\lambda) B C \right] \pi^* = (1-\lambda) B \mu+ \pi_0^* +$$ + +Multiplying both sides of the above equation by the inverse of the matrix on the left side gives + +$$ +\pi^* = \left[ A - (1-\lambda) B C \right]^{-1} \left[ (1-\lambda) B \mu+ \pi_0^* \right] +$$ (eq:eq4) + +Having solved equation {eq}`eq:eq4` for $\pi^*$, we can use equation {eq}`eq:eq2` to solve for $\pi$: + +$$ +\pi = \mu + C \pi^* +$$ + + +We have thus solved for two of the key endogenous time series determined by our model, namely, the sequence $\pi^*$ +of expected inflation rates and the sequence $\pi$ of actual inflation rates. + +Knowing these, we can then quickly calculate the associated sequence $p$ of the logarithm of the price level +from equation {eq}`eq:eqfiscth1`. + +Let's fill in the details for this step. + +Since we now know $\mu$ it is easy to compute $m$. + +Thus, notice that we can represent the equations + +$$ +m_{t+1} = m_t + \mu_t , \quad t = 0, 1, \ldots, T +$$ + +as the matrix equation + +$$ +\begin{bmatrix} +1 & 0 & 0 & \cdots & 0 & 0 \cr +-1 & 1 & 0 & \cdots & 0 & 0 \cr +0 & -1 & 1 & \cdots & 0 & 0 \cr +\vdots & \vdots & \vdots & \vdots & 0 & 0 \cr +0 & 0 & 0 & \cdots & 1 & 0 \cr +0 & 0 & 0 & \cdots & -1 & 1 +\end{bmatrix} +\begin{bmatrix} +m_1 \cr m_2 \cr m_3 \cr \vdots \cr m_T \cr m_{T+1} +\end{bmatrix} += \begin{bmatrix} +\mu_0 \cr \mu_1 \cr \mu_2 \cr \vdots \cr \mu_{T-1} \cr \mu_T +\end{bmatrix} ++ \begin{bmatrix} +m_0 \cr 0 \cr 0 \cr \vdots \cr 0 \cr 0 +\end{bmatrix} +$$ (eq:eq101_ad) + +Multiplying both sides of equation {eq}`eq:eq101_ad` with the inverse of the matrix on the left will give + +$$ +m_t = m_0 + \sum_{s=0}^{t-1} \mu_s, \quad t =1, \ldots, T+1 +$$ (eq:mcum_ad) + +Equation {eq}`eq:mcum_ad` shows that the log of the money supply at $t$ equals the log $m_0$ of the initial money supply +plus accumulation of rates of money growth between times $0$ and $t$. + +We can then compute $p_t$ for each $t$ from equation {eq}`eq:eqfiscth1`. + +We can write a compact formula for $p $ as + +$$ +p = m + \alpha \hat \pi^* +$$ + +where + +$$ +\hat \pi^* = \begin{bmatrix} \pi_0^* \cr + \pi_1^* \cr + \pi_2^* \cr + \vdots \cr + \pi_{T}^* + \end{bmatrix}, + $$ + +which is just $\pi^*$ with the last element dropped. + +## Forecast errors and model computation + +Our computations will verify that + +$$ +\hat \pi^* \neq \pi, +$$ + +so that in general + +$$ +\pi_t^* \neq \pi_t, \quad t = 0, 1, \ldots , T +$$ (eq:notre) + +This outcome is typical in models in which adaptive expectations hypothesis like equation {eq}`eq:adaptexpn` appear as a +component. + +In {doc}`cagan_ree`, we studied a version of the model that replaces hypothesis {eq}`eq:adaptexpn` with +a "perfect foresight" or "rational expectations" hypothesis. + +But now, let's dive in and do some computations with the adaptive expectations version of the model. + +As usual, we'll start by importing some Python modules. + +```{code-cell} ipython3 +import numpy as np +from collections import namedtuple +import matplotlib.pyplot as plt +``` + +```{code-cell} ipython3 +Cagan_Adaptive = namedtuple("Cagan_Adaptive", + ["α", "m0", "Eπ0", "T", "λ"]) + +def create_cagan_adaptive_model(α = 5, m0 = 1, Eπ0 = 0.5, T=80, λ = 0.9): + return Cagan_Adaptive(α, m0, Eπ0, T, λ) + +md = create_cagan_adaptive_model() +``` ++++ {"user_expressions": []} + +We solve the model and plot variables of interests using the following functions. + +```{code-cell} ipython3 +def solve_cagan_adaptive(model, μ_seq): + " Solve the Cagan model in finite time. " + α, m0, Eπ0, T, λ = model + + A = np.eye(T+2, T+2) - λ*np.eye(T+2, T+2, k=-1) + B = np.eye(T+2, T+1, k=-1) + C = -α*np.eye(T+1, T+2) + α*np.eye(T+1, T+2, k=1) + Eπ0_seq = np.append(Eπ0, np.zeros(T+1)) + + # Eπ_seq is of length T+2 + Eπ_seq = np.linalg.solve(A - (1-λ)*B @ C, (1-λ) * B @ μ_seq + Eπ0_seq) + + # π_seq is of length T+1 + π_seq = μ_seq + C @ Eπ_seq + + D = np.eye(T+1, T+1) - np.eye(T+1, T+1, k=-1) # D is the coefficient matrix in Equation (14.8) + m0_seq = np.append(m0, np.zeros(T)) + + # m_seq is of length T+2 + m_seq = np.linalg.solve(D, μ_seq + m0_seq) + m_seq = np.append(m0, m_seq) + + # p_seq is of length T+2 + p_seq = m_seq + α * Eπ_seq + + return π_seq, Eπ_seq, m_seq, p_seq +``` + ++++ {"user_expressions": []} + +```{code-cell} ipython3 +def solve_and_plot(model, μ_seq): + + π_seq, Eπ_seq, m_seq, p_seq = solve_cagan_adaptive(model, μ_seq) + + T_seq = range(model.T+2) + + fig, ax = plt.subplots(5, 1, figsize=[5, 12], dpi=200) + ax[0].plot(T_seq[:-1], μ_seq) + ax[1].plot(T_seq[:-1], π_seq, label=r'$\pi_t$') + ax[1].plot(T_seq, Eπ_seq, label=r'$\pi^{*}_{t}$') + ax[2].plot(T_seq, m_seq - p_seq) + ax[3].plot(T_seq, m_seq) + ax[4].plot(T_seq, p_seq) + + y_labs = [r'$\mu$', r'$\pi$', r'$m - p$', r'$m$', r'$p$'] + subplot_title = [r'Money supply growth', r'Inflation', r'Real balances', r'Money supply', r'Price level'] + + for i in range(5): + ax[i].set_xlabel(r'$t$') + ax[i].set_ylabel(y_labs[i]) + ax[i].set_title(subplot_title[i]) + + ax[1].legend() + plt.tight_layout() + plt.show() + + return π_seq, Eπ_seq, m_seq, p_seq +``` + ++++ {"user_expressions": []} + + + +## Technical condition for stability + +In constructing our examples, we shall assume that $(\lambda, \alpha)$ satisfy + +$$ +\Bigl| \frac{\lambda-\alpha(1-\lambda)}{1-\alpha(1-\lambda)} \Bigr| < 1 +$$ (eq:suffcond) + +The source of this condition is the following string of deductions: + +$$ +\begin{aligned} +\pi_{t}&=\mu_{t}+\alpha\pi_{t+1}^{*}-\alpha\pi_{t}^{*}\\\pi_{t+1}^{*}&=\lambda\pi_{t}^{*}+(1-\lambda)\pi_{t}\\\pi_{t}&=\frac{\mu_{t}}{1-\alpha(1-\lambda)}-\frac{\alpha(1-\lambda)}{1-\alpha(1-\lambda)}\pi_{t}^{*}\\\implies\pi_{t}^{*}&=\frac{1}{\alpha(1-\lambda)}\mu_{t}-\frac{1-\alpha(1-\lambda)}{\alpha(1-\lambda)}\pi_{t}\\\pi_{t+1}&=\frac{\mu_{t+1}}{1-\alpha(1-\lambda)}-\frac{\alpha(1-\lambda)}{1-\alpha(1-\lambda)}\left(\lambda\pi_{t}^{*}+(1-\lambda)\pi_{t}\right)\\&=\frac{\mu_{t+1}}{1-\alpha(1-\lambda)}-\frac{\lambda}{1-\alpha(1-\lambda)}\mu_{t}+\frac{\lambda-\alpha(1-\lambda)}{1-\alpha(1-\lambda)}\pi_{t} +\end{aligned} +$$ + +By assuring that the coefficient on $\pi_t$ is less than one in absolute value, condition {eq}`eq:suffcond` assures stability of the dynamics of $\{\pi_t\}$ described by the last line of our string of deductions. + +The reader is free to study outcomes in examples that violate condition {eq}`eq:suffcond`. + +```{code-cell} ipython3 +print(np.abs((md.λ - md.α*(1-md.λ))/(1 - md.α*(1-md.λ)))) +``` + +## Experiments + +Now we'll turn to some experiments. + +### Experiment 1 + +We'll study a situation in which the rate of growth of the money supply is $\mu_0$ +from $t=0$ to $t= T_1$ and then permanently falls to $\mu^*$ at $t=T_1$. + +Thus, let $T_1 \in (0, T)$. + +So where $\mu_0 > \mu^*$, we assume that + +$$ +\mu_{t} = \begin{cases} + \mu_0 , & t = 0, \ldots, T_1 -1 \\ + \mu^* , & t \geq T_1 + \end{cases} +$$ + +Notice that we studied exactly this experiment in a rational expectations version of the model in {doc}`cagan_ree`. + +So by comparing outcomes across the two lectures, we can learn about consequences of assuming adaptive expectations, as we do here, instead of rational expectations as we assumed in that other lecture. + +```{code-cell} ipython3 +# Parameters for the experiment 1 +T1 = 60 +μ0 = 0.5 +μ_star = 0 + +μ_seq_1 = np.append(μ0*np.ones(T1), μ_star*np.ones(md.T+1-T1)) + +# solve and plot +π_seq_1, Eπ_seq_1, m_seq_1, p_seq_1 = solve_and_plot(md, μ_seq_1) +``` + +We invite the reader to compare outcomes with those under rational expectations studied in {doc}`cagan_ree`. + +Please note how the actual inflation rate $\pi_t$ "overshoots" its ultimate steady-state value at the time of the sudden reduction in the rate of growth of the money supply at time $T_1$. + +We invite you to explain to yourself the source of this overshooting and why it does not occur in the rational expectations version of the model. + +### Experiment 2 + +Now we'll do a different experiment, namely, a gradual stabilization in which the rate of growth of the money supply smoothly +decline from a high value to a persistently low value. + +While price level inflation eventually falls, it falls more slowly than the driving force that ultimately causes it to fall, namely, the falling rate of growth of the money supply. + +The sluggish fall in inflation is explained by how anticipated inflation $\pi_t^*$ persistently exceeds actual inflation $\pi_t$ during the transition from a high inflation to a low inflation situation. + +```{code-cell} ipython3 +# parameters +ϕ = 0.9 +μ_seq_2 = np.array([ϕ**t * μ0 + (1-ϕ**t)*μ_star for t in range(md.T)]) +μ_seq_2 = np.append(μ_seq_2, μ_star) + + +# solve and plot +π_seq_2, Eπ_seq_2, m_seq_2, p_seq_2 = solve_and_plot(md, μ_seq_2) +``` diff --git a/book/_build/html/_sources/cagan_ree.ipynb b/book/_build/html/_sources/cagan_ree.ipynb new file mode 100644 index 0000000..de74277 --- /dev/null +++ b/book/_build/html/_sources/cagan_ree.ipynb @@ -0,0 +1,799 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "e435e52c", + "metadata": {}, + "source": [ + "# A Monetarist Theory of Price Levels\n", + "\n", + "## Overview\n", + "\n", + "\n", + "We'll use linear algebra first to explain and then do some experiments with a \"monetarist theory of price levels\".\n", + "\n", + "Economists call it a \"monetary\" or \"monetarist\" theory of price levels because effects on price levels occur via a central bank's decisions to print money supply. \n", + "\n", + " * a goverment's fiscal policies determine whether its _expenditures_ exceed its _tax collections_\n", + " * if its expenditures exceed its tax collections, the government can instruct the central bank to cover the difference by _printing money_\n", + " * that leads to effects on the price level as price level path adjusts to equate the supply of money to the demand for money\n", + "\n", + "Such a theory of price levels was described by Thomas Sargent and Neil Wallace in chapter 5 of \n", + "{cite}`sargent2013rational`, which reprints a 1981 Federal Reserve Bank of Minneapolis article entitled \"Unpleasant Monetarist Arithmetic\". \n", + "\n", + "Sometimes this theory is also called a \"fiscal theory of price levels\" to emphasize the importance of fiscal deficits in shaping changes in the money supply. \n", + "\n", + "The theory has been extended, criticized, and applied by John Cochrane {cite}`cochrane2023fiscal`.\n", + "\n", + "In another lecture {doc}`price level histories `, we described some European hyperinflations that occurred in the wake of World War I.\n", + "\n", + "Elemental forces at work in the fiscal theory of the price level help to understand those episodes.\n", + "\n", + "\n", + "According to this theory, when the government persistently spends more than it collects in taxes and prints money to finance the shortfall (the \"shortfall\" is called the \"government deficit\"), it puts upward pressure on the price level and generates\n", + "persistent inflation.\n", + "\n", + "The \"monetarist\" or \"fiscal theory of price levels\" asserts that \n", + "\n", + "* to _start_ a persistent inflation the government begins persistently to run a money-financed government deficit\n", + "\n", + "* to _stop_ a persistent inflation the government stops persistently running a money-financed government deficit\n", + "\n", + "The model in this lecture is a \"rational expectations\" (or \"perfect foresight\") version of a model that Philip Cagan {cite}`Cagan` used to study the monetary dynamics of hyperinflations. \n", + "\n", + "While Cagan didn't use that \"rational expectations\" version of the model, Thomas Sargent {cite}`sargent1982ends` did when he studied the Ends of Four Big Inflations in Europe after World War I.\n", + "\n", + "* this lecture {doc}`fiscal theory of the price level with adaptive expectations ` describes a version of the model that does not impose \"rational expectations\" but instead uses \n", + " what Cagan and his teacher Milton Friedman called \"adaptive expectations\"\n", + "\n", + " * a reader of both lectures will notice that the algebra is less complicated in the present rational expectations version of the model\n", + " * the difference in algebra complications can be traced to the following source: the adaptive expectations version of the model has more endogenous variables and more free parameters \n", + "\n", + "Some of our quantitative experiments with the rational expectations version of the model are designed to illustrate how the fiscal theory explains the abrupt end of those big inflations.\n", + "\n", + "In those experiments, we'll encounter an instance of a \"velocity dividend\" that has sometimes accompanied successful inflation stabilization programs. \n", + "\n", + "To facilitate using linear matrix algebra as our main mathematical tool, we'll use a finite horizon version of the model.\n", + "\n", + "As in the {doc}`present values ` and {doc}`consumption smoothing` lectures, our mathematical tools are matrix multiplication and matrix inversion.\n", + "\n", + "\n", + "## Structure of the model\n", + "\n", + "\n", + "The model consists of\n", + "\n", + "* a function that expresses the demand for real balances of government printed money as an inverse function of the public's expected rate of inflation\n", + "\n", + "* an exogenous sequence of rates of growth of the money supply. The money supply grows because the government prints it to pay for goods and services\n", + "\n", + "* an equilibrium condition that equates the demand for money to the supply\n", + "\n", + "* a \"perfect foresight\" assumption that the public's expected rate of inflation equals the actual rate of inflation.\n", + " \n", + "To represent the model formally, let \n", + "\n", + "* $ m_t $ be the log of the supply of nominal money balances;\n", + "* $\\mu_t = m_{t+1} - m_t $ be the net rate of growth of nominal balances;\n", + "* $p_t $ be the log of the price level;\n", + "* $\\pi_t = p_{t+1} - p_t $ be the net rate of inflation between $t$ and $ t+1$;\n", + "* $\\pi_t^*$ be the public's expected rate of inflation between $t$ and $t+1$;\n", + "* $T$ the horizon -- i.e., the last period for which the model will determine $p_t$\n", + "* $\\pi_{T+1}^*$ the terminal rate of inflation between times $T$ and $T+1$.\n", + "\n", + "The demand for real balances $\\exp\\left(m_t^d - p_t\\right)$ is governed by the following version of the Cagan demand function\n", + " \n", + "$$ \n", + "m_t^d - p_t = -\\alpha \\pi_t^* \\: , \\: \\alpha > 0 ; \\quad t = 0, 1, \\ldots, T .\n", + "$$ (eq:caganmd)\n", + "\n", + "This equation asserts that the demand for real balances\n", + "is inversely related to the public's expected rate of inflation with sensitivity $\\alpha$.\n", + "\n", + "People somehow acquire **perfect foresight** by their having solved a forecasting\n", + "problem.\n", + "\n", + "This lets us set\n", + "\n", + "$$ \n", + "\\pi_t^* = \\pi_t , % \\forall t \n", + "$$ (eq:ree)\n", + "\n", + "while equating demand for money to supply lets us set $m_t^d = m_t$ for all $t \\geq 0$. \n", + "\n", + "The preceding equations then imply\n", + "\n", + "$$\n", + "m_t - p_t = -\\alpha(p_{t+1} - p_t)\n", + "$$ (eq:cagan)\n", + "\n", + "To fill in details about what it means for private agents\n", + "to have perfect foresight, we subtract equation {eq}`eq:cagan` at time $ t $ from the same equation at $ t+1$ to get\n", + "\n", + "$$\n", + "\\mu_t - \\pi_t = -\\alpha \\pi_{t+1} + \\alpha \\pi_t ,\n", + "$$\n", + "\n", + "which we rewrite as a forward-looking first-order linear difference\n", + "equation in $\\pi_s$ with $\\mu_s$ as a \"forcing variable\":\n", + "\n", + "$$\n", + "\\pi_t = \\frac{\\alpha}{1+\\alpha} \\pi_{t+1} + \\frac{1}{1+\\alpha} \\mu_t , \\quad t= 0, 1, \\ldots , T \n", + "$$\n", + "\n", + "where $ 0< \\frac{\\alpha}{1+\\alpha} <1 $.\n", + "\n", + "Setting $\\delta =\\frac{\\alpha}{1+\\alpha}$, let's us represent the preceding equation as\n", + "\n", + "$$\n", + "\\pi_t = \\delta \\pi_{t+1} + (1-\\delta) \\mu_t , \\quad t =0, 1, \\ldots, T\n", + "$$\n", + "\n", + "Write this system of $T+1$ equations as the single matrix equation\n", + "\n", + "$$\n", + "\\begin{bmatrix} 1 & -\\delta & 0 & 0 & \\cdots & 0 & 0 \\cr\n", + " 0 & 1 & -\\delta & 0 & \\cdots & 0 & 0 \\cr\n", + " 0 & 0 & 1 & -\\delta & \\cdots & 0 & 0 \\cr\n", + " \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & -\\delta & 0 \\cr\n", + " 0 & 0 & 0 & 0 & \\cdots & 1 & -\\delta \\cr\n", + " 0 & 0 & 0 & 0 & \\cdots & 0 & 1 \\end{bmatrix}\n", + "\\begin{bmatrix} \\pi_0 \\cr \\pi_1 \\cr \\pi_2 \\cr \\vdots \\cr \\pi_{T-1} \\cr \\pi_T \n", + "\\end{bmatrix} \n", + "= (1 - \\delta) \\begin{bmatrix} \n", + "\\mu_0 \\cr \\mu_1 \\cr \\mu_2 \\cr \\vdots \\cr \\mu_{T-1} \\cr \\mu_T\n", + "\\end{bmatrix}\n", + "+ \\begin{bmatrix} \n", + "0 \\cr 0 \\cr 0 \\cr \\vdots \\cr 0 \\cr \\delta \\pi_{T+1}^*\n", + "\\end{bmatrix}\n", + "$$ (eq:pieq)\n", + "\n", + "By multiplying both sides of equation {eq}`eq:pieq` by the inverse of the matrix on the left side, we can calculate\n", + "\n", + "$$\n", + "\\pi \\equiv \\begin{bmatrix} \\pi_0 \\cr \\pi_1 \\cr \\pi_2 \\cr \\vdots \\cr \\pi_{T-1} \\cr \\pi_T \n", + "\\end{bmatrix} \n", + "$$\n", + "\n", + "It turns out that\n", + "\n", + "$$\n", + "\\pi_t = (1-\\delta) \\sum_{s=t}^T \\delta^{s-t} \\mu_s + \\delta^{T+1-t} \\pi_{T+1}^*\n", + "$$ (eq:fisctheory1)\n", + "\n", + "We can represent the equations \n", + "\n", + "$$ \n", + "m_{t+1} = m_t + \\mu_t , \\quad t = 0, 1, \\ldots, T\n", + "$$\n", + "\n", + "as the matrix equation\n", + "\n", + "$$\n", + "\\begin{bmatrix}\n", + "1 & 0 & 0 & \\cdots & 0 & 0 \\cr\n", + "-1 & 1 & 0 & \\cdots & 0 & 0 \\cr\n", + "0 & -1 & 1 & \\cdots & 0 & 0 \\cr\n", + "\\vdots & \\vdots & \\vdots & \\vdots & 0 & 0 \\cr\n", + "0 & 0 & 0 & \\cdots & 1 & 0 \\cr\n", + "0 & 0 & 0 & \\cdots & -1 & 1 \n", + "\\end{bmatrix}\n", + "\\begin{bmatrix} \n", + "m_1 \\cr m_2 \\cr m_3 \\cr \\vdots \\cr m_T \\cr m_{T+1}\n", + "\\end{bmatrix}\n", + "= \\begin{bmatrix} \n", + "\\mu_0 \\cr \\mu_1 \\cr \\mu_2 \\cr \\vdots \\cr \\mu_{T-1} \\cr \\mu_T\n", + "\\end{bmatrix}\n", + "+ \\begin{bmatrix} \n", + "m_0 \\cr 0 \\cr 0 \\cr \\vdots \\cr 0 \\cr 0\n", + "\\end{bmatrix}\n", + "$$ (eq:eq101)\n", + "\n", + "Multiplying both sides of equation {eq}`eq:eq101` with the inverse of the matrix on the left will give \n", + "\n", + "$$\n", + "m_t = m_0 + \\sum_{s=0}^{t-1} \\mu_s, \\quad t =1, \\ldots, T+1\n", + "$$ (eq:mcum)\n", + "\n", + "Equation {eq}`eq:mcum` shows that the log of the money supply at $t$ equals the log of the initial money supply $m_0$\n", + "plus accumulation of rates of money growth between times $0$ and $T$.\n", + "\n", + "## Continuation values\n", + "\n", + "To determine the continuation inflation rate $\\pi_{T+1}^*$ we shall proceed by applying the following infinite-horizon\n", + "version of equation {eq}`eq:fisctheory1` at time $t = T+1$:\n", + "\n", + "$$\n", + "\\pi_t = (1-\\delta) \\sum_{s=t}^\\infty \\delta^{s-t} \\mu_s , \n", + "$$ (eq:fisctheory2)\n", + "\n", + "and by also assuming the following continuation path for $\\mu_t$ beyond $T$:\n", + "\n", + "$$\n", + "\\mu_{t+1} = \\gamma^* \\mu_t, \\quad t \\geq T .\n", + "$$\n", + "\n", + "Plugging the preceding equation into equation {eq}`eq:fisctheory2` at $t = T+1$ and rearranging we can deduce that\n", + "\n", + "$$ \n", + "\\pi_{T+1}^* = \\frac{1 - \\delta}{1 - \\delta \\gamma^*} \\gamma^* \\mu_T\n", + "$$ (eq:piterm)\n", + "\n", + "where we require that $\\vert \\gamma^* \\delta \\vert < 1$.\n", + "\n", + "Let's implement and solve this model.\n", + "\n", + "\n", + "As usual, we'll start by importing some Python modules." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c8a5b5e9", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "from collections import namedtuple\n", + "import matplotlib.pyplot as plt" + ] + }, + { + "cell_type": "markdown", + "id": "39cb0268", + "metadata": {}, + "source": [ + "First, we store parameters in a `namedtuple`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "593512ee", + "metadata": {}, + "outputs": [], + "source": [ + "# Create the rational expectation version of Cagan model in finite time\n", + "CaganREE = namedtuple(\"CaganREE\", \n", + " [\"m0\", # initial money supply\n", + " \"μ_seq\", # sequence of rate of growth\n", + " \"α\", # sensitivity parameter\n", + " \"δ\", # α/(1 + α)\n", + " \"π_end\" # terminal expected inflation\n", + " ])\n", + "\n", + "def create_cagan_model(m0=1, α=5, μ_seq=None):\n", + " δ = α/(1 + α)\n", + " π_end = μ_seq[-1] # compute terminal expected inflation\n", + " return CaganREE(m0, μ_seq, α, δ, π_end)" + ] + }, + { + "cell_type": "markdown", + "id": "7a646e4d", + "metadata": {}, + "source": [ + "Now we can solve the model to compute $\\pi_t$, $m_t$ and $p_t$ for $t =1, \\ldots, T+1$ using the matrix equation above" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b141be4e", + "metadata": {}, + "outputs": [], + "source": [ + "def solve(model, T):\n", + " m0, π_end, μ_seq, α, δ = (model.m0, model.π_end, \n", + " model.μ_seq, model.α, model.δ)\n", + " \n", + " # Create matrix representation above\n", + " A1 = np.eye(T+1, T+1) - δ * np.eye(T+1, T+1, k=1)\n", + " A2 = np.eye(T+1, T+1) - np.eye(T+1, T+1, k=-1)\n", + "\n", + " b1 = (1-δ) * μ_seq + np.concatenate([np.zeros(T), [δ * π_end]])\n", + " b2 = μ_seq + np.concatenate([[m0], np.zeros(T)])\n", + "\n", + " π_seq = np.linalg.solve(A1, b1)\n", + " m_seq = np.linalg.solve(A2, b2)\n", + "\n", + " π_seq = np.append(π_seq, π_end)\n", + " m_seq = np.append(m0, m_seq)\n", + "\n", + " p_seq = m_seq + α * π_seq\n", + "\n", + " return π_seq, m_seq, p_seq" + ] + }, + { + "cell_type": "markdown", + "id": "4afc6cb4", + "metadata": {}, + "source": [ + "### Some quantitative experiments\n", + "\n", + "In the experiments below, we'll use formula {eq}`eq:piterm` as our terminal condition for expected inflation.\n", + "\n", + "In devising these experiments, we'll make assumptions about $\\{\\mu_t\\}$ that are consistent with formula\n", + "{eq}`eq:piterm`.\n", + "\n", + "We describe several such experiments.\n", + "\n", + "In all of them, \n", + "\n", + "$$ \n", + "\\mu_t = \\mu^* , \\quad t \\geq T_1\n", + "$$\n", + "\n", + "so that, in terms of our notation and formula for $\\pi_{T+1}^*$ above, $\\gamma^* = 1$. \n", + "\n", + "#### Experiment 1: Foreseen sudden stabilization\n", + "\n", + "In this experiment, we'll study how, when $\\alpha >0$, a foreseen inflation stabilization has effects on inflation that proceed it.\n", + "\n", + "We'll study a situation in which the rate of growth of the money supply is $\\mu_0$\n", + "from $t=0$ to $t= T_1$ and then permanently falls to $\\mu^*$ at $t=T_1$.\n", + "\n", + "Thus, let $T_1 \\in (0, T)$. \n", + "\n", + "So where $\\mu_0 > \\mu^*$, we assume that\n", + "\n", + "$$\n", + "\\mu_{t+1} = \\begin{cases}\n", + " \\mu_0 , & t = 0, \\ldots, T_1 -1 \\\\\n", + " \\mu^* , & t \\geq T_1\n", + " \\end{cases}\n", + "$$\n", + "\n", + "We'll start by executing a version of our \"experiment 1\" in which the government implements a _foreseen_ sudden permanent reduction in the rate of money creation at time $T_1$. \n", + "\n", + "Let's experiment with the following parameters" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "02813994", + "metadata": {}, + "outputs": [], + "source": [ + "T1 = 60\n", + "μ0 = 0.5\n", + "μ_star = 0\n", + "T = 80\n", + "\n", + "μ_seq_1 = np.append(μ0*np.ones(T1+1), μ_star*np.ones(T-T1))\n", + "\n", + "cm = create_cagan_model(μ_seq=μ_seq_1)\n", + "\n", + "# solve the model\n", + "π_seq_1, m_seq_1, p_seq_1 = solve(cm, T)" + ] + }, + { + "cell_type": "markdown", + "id": "f69c9e6a", + "metadata": {}, + "source": [ + "Now we use the following function to plot the result" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "20caab8e", + "metadata": {}, + "outputs": [], + "source": [ + "def plot_sequences(sequences, labels):\n", + " fig, axs = plt.subplots(len(sequences), 1, figsize=(5, 12), dpi=200)\n", + " for ax, seq, label in zip(axs, sequences, labels):\n", + " ax.plot(range(len(seq)), seq, label=label)\n", + " ax.set_ylabel(label)\n", + " ax.set_xlabel('$t$')\n", + " ax.legend()\n", + " plt.tight_layout()\n", + " plt.show()\n", + "\n", + "sequences = (μ_seq_1, π_seq_1, m_seq_1 - p_seq_1, m_seq_1, p_seq_1)\n", + "plot_sequences(sequences, (r'$\\mu$', r'$\\pi$', r'$m - p$', r'$m$', r'$p$'))" + ] + }, + { + "cell_type": "markdown", + "id": "e6d6d7ae", + "metadata": {}, + "source": [ + "The plot of the money growth rate $\\mu_t$ in the top level panel portrays\n", + "a sudden reduction from $.5$ to $0$ at time $T_1 = 60$. \n", + "\n", + "This brings about a gradual reduction of the inflation rate $\\pi_t$ that precedes the\n", + "money supply growth rate reduction at time $T_1$.\n", + "\n", + "Notice how the inflation rate declines smoothly (i.e., continuously) to $0$ at $T_1$ -- \n", + "unlike the money growth rate, it does not suddenly \"jump\" downward at $T_1$.\n", + "\n", + "This is because the reduction in $\\mu$ at $T_1$ has been foreseen from the start. \n", + "\n", + "While the log money supply portrayed in the bottom panel has a kink at $T_1$, the log price level does not -- it is \"smooth\" -- once again a consequence of the fact that the\n", + "reduction in $\\mu$ has been foreseen.\n", + "\n", + "To set the stage for our next experiment, we want to study the determinants of the price level a little more.\n", + "\n", + "\n", + "### The log price level\n", + "\n", + "We can use equations {eq}`eq:caganmd` and {eq}`eq:ree`\n", + "to discover that the log of the price level satisfies\n", + "\n", + "$$\n", + "p_t = m_t + \\alpha \\pi_t\n", + "$$ (eq:pformula2)\n", + "\n", + "or, by using equation {eq}`eq:fisctheory1`,\n", + "\n", + "$$ \n", + "p_t = m_t + \\alpha \\left[ (1-\\delta) \\sum_{s=t}^T \\delta^{s-t} \\mu_s + \\delta^{T+1-t} \\pi_{T+1}^* \\right] \n", + "$$ (eq:pfiscaltheory2)\n", + "\n", + "In our next experiment, we'll study a \"surprise\" permanent change in the money growth that beforehand \n", + "was completely unanticipated. \n", + "\n", + "At time $T_1$ when the \"surprise\" money growth rate change occurs, to satisfy\n", + "equation {eq}`eq:pformula2`, the log of real balances jumps \n", + "_upward_ as $\\pi_t$ jumps _downward_.\n", + "\n", + "But in order for $m_t - p_t$ to jump, which variable jumps, $m_{T_1}$ or $p_{T_1}$?\n", + "\n", + "We'll study that interesting question next.\n", + "\n", + "### What jumps?\n", + "\n", + "What jumps at $T_1$?\n", + "\n", + "Is it $p_{T_1}$ or $m_{T_1}$?\n", + "\n", + "If we insist that the money supply $m_{T_1}$ is locked at its value $m_{T_1}^1$ inherited from the past, then formula {eq}`eq:pformula2` implies that the price level jumps downward at time $T_1$, to coincide with the downward jump in \n", + "$\\pi_{T_1}$ \n", + "\n", + "An alternative assumption about the money supply level is that as part of the \"inflation stabilization\",\n", + "the government resets $m_{T_1}$ according to\n", + "\n", + "$$\n", + "m_{T_1}^2 - m_{T_1}^1 = \\alpha (\\pi_{T_1}^1 - \\pi_{T_1}^2),\n", + "$$ (eq:eqnmoneyjump)\n", + "\n", + "which describes how the government could reset the money supply at $T_1$ in response to the jump in expected inflation associated with monetary stabilization. \n", + "\n", + "Doing this would let the price level be continuous at $T_1$.\n", + "\n", + "By letting money jump according to equation {eq}`eq:eqnmoneyjump` the monetary authority prevents the price level from _falling_ at the moment that the unanticipated stabilization arrives.\n", + "\n", + "In various research papers about stabilizations of high inflations, the jump in the money supply described by equation {eq}`eq:eqnmoneyjump` has been called\n", + "\"the velocity dividend\" that a government reaps from implementing a regime change that sustains a permanently lower inflation rate.\n", + "\n", + "#### Technical details about whether $p$ or $m$ jumps at $T_1$\n", + "\n", + "We have noted that with a constant expected forward sequence $\\mu_s = \\bar \\mu$ for $s\\geq t$, $\\pi_{t} =\\bar{\\mu}$.\n", + "\n", + "A consequence is that at $T_1$, either $m$ or $p$ must \"jump\" at $T_1$.\n", + "\n", + "We'll study both cases. \n", + "\n", + "#### $m_{T_{1}}$ does not jump.\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "m_{T_{1}}&=m_{T_{1}-1}+\\mu_{0}\\\\\\pi_{T_{1}}&=\\mu^{*}\\\\p_{T_{1}}&=m_{T_{1}}+\\alpha\\pi_{T_{1}}\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "Simply glue the sequences $t\\leq T_1$ and $t > T_1$.\n", + "\n", + "#### $m_{T_{1}}$ jumps.\n", + "\n", + "We reset $m_{T_{1}}$ so that $p_{T_{1}}=\\left(m_{T_{1}-1}+\\mu_{0}\\right)+\\alpha\\mu_{0}$, with $\\pi_{T_{1}}=\\mu^{*}$.\n", + "\n", + "Then, \n", + "\n", + "$$ \n", + "m_{T_{1}}=p_{T_{1}}-\\alpha\\pi_{T_{1}}=\\left(m_{T_{1}-1}+\\mu_{0}\\right)+\\alpha\\left(\\mu_{0}-\\mu^{*}\\right) \n", + "$$\n", + "\n", + "We then compute for the remaining $T-T_{1}$ periods with $\\mu_{s}=\\mu^{*},\\forall s\\geq T_{1}$ and the initial condition $m_{T_{1}}$ from above.\n", + "\n", + "We are now technically equipped to discuss our next experiment.\n", + "\n", + "#### Experiment 2: an unforeseen sudden stabilization\n", + "\n", + "This experiment deviates a little bit from a pure version of our \"perfect foresight\"\n", + "assumption by assuming that a sudden permanent reduction in $\\mu_t$ like that\n", + "analyzed in experiment 1 is completely unanticipated. \n", + "\n", + "Such a completely unanticipated shock is popularly known as an \"MIT shock\".\n", + "\n", + "The mental experiment involves switching at time $T_1$ from an initial \"continuation path\" for $\\{\\mu_t, \\pi_t\\} $ to another path that involves a permanently lower inflation rate. \n", + "\n", + "**Initial Path:** $\\mu_t = \\mu_0$ for all $t \\geq 0$. So this path is for $\\{\\mu_t\\}_{t=0}^\\infty$; the associated \n", + "path for $\\pi_t$ has $\\pi_t = \\mu_0$. \n", + "\n", + "**Revised Continuation Path** Where $ \\mu_0 > \\mu^*$, we construct a continuation path $\\{\\mu_s\\}_{s=T_1}^\\infty$\n", + "by setting $\\mu_s = \\mu^*$ for all $s \\geq T_1$. The perfect foresight continuation path for \n", + "$\\pi$ is $\\pi_s = \\mu^*$ \n", + "\n", + "To capture a \"completely unanticipated permanent shock to the $\\{\\mu_t\\}$ process at time $T_1$, we simply glue the $\\mu_t, \\pi_t$\n", + "that emerges under path 2 for $t \\geq T_1$ to the $\\mu_t, \\pi_t$ path that had emerged under path 1 for $ t=0, \\ldots,\n", + "T_1 -1$.\n", + "\n", + "We can do the MIT shock calculations mostly by hand. \n", + "\n", + "Thus, for path 1, $\\pi_t = \\mu_0 $ for all $t \\in [0, T_1-1]$, while for path 2,\n", + "$\\mu_s = \\mu^*$ for all $s \\geq T_1$. \n", + "\n", + "We now move on to experiment 2, our \"MIT shock\", completely unforeseen \n", + "sudden stabilization.\n", + "\n", + "We set this up so that the $\\{\\mu_t\\}$ sequences that describe the sudden stabilization\n", + "are identical to those for experiment 1, the foreseen sudden stabilization.\n", + "\n", + "The following code does the calculations and plots outcomes." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7e89c727", + "metadata": {}, + "outputs": [], + "source": [ + "# path 1\n", + "μ_seq_2_path1 = μ0 * np.ones(T+1)\n", + "\n", + "cm1 = create_cagan_model(μ_seq=μ_seq_2_path1)\n", + "π_seq_2_path1, m_seq_2_path1, p_seq_2_path1 = solve(cm1, T)\n", + "\n", + "# continuation path\n", + "μ_seq_2_cont = μ_star * np.ones(T-T1)\n", + "\n", + "cm2 = create_cagan_model(m0=m_seq_2_path1[T1+1], \n", + " μ_seq=μ_seq_2_cont)\n", + "π_seq_2_cont, m_seq_2_cont1, p_seq_2_cont1 = solve(cm2, T-1-T1)\n", + "\n", + "\n", + "# regime 1 - simply glue π_seq, μ_seq\n", + "μ_seq_2 = np.concatenate((μ_seq_2_path1[:T1+1],\n", + " μ_seq_2_cont))\n", + "π_seq_2 = np.concatenate((π_seq_2_path1[:T1+1], \n", + " π_seq_2_cont))\n", + "m_seq_2_regime1 = np.concatenate((m_seq_2_path1[:T1+1], \n", + " m_seq_2_cont1))\n", + "p_seq_2_regime1 = np.concatenate((p_seq_2_path1[:T1+1], \n", + " p_seq_2_cont1))\n", + "\n", + "# regime 2 - reset m_T1\n", + "m_T1 = (m_seq_2_path1[T1] + μ0) + cm2.α*(μ0 - μ_star)\n", + "\n", + "cm3 = create_cagan_model(m0=m_T1, μ_seq=μ_seq_2_cont)\n", + "π_seq_2_cont2, m_seq_2_cont2, p_seq_2_cont2 = solve(cm3, T-1-T1)\n", + "\n", + "m_seq_2_regime2 = np.concatenate((m_seq_2_path1[:T1+1], \n", + " m_seq_2_cont2))\n", + "p_seq_2_regime2 = np.concatenate((p_seq_2_path1[:T1+1],\n", + " p_seq_2_cont2))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b1221aa4", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "T_seq = range(T+2)\n", + "\n", + "# plot both regimes\n", + "fig, ax = plt.subplots(5, 1, figsize=(5, 12), dpi=200)\n", + "\n", + "# Configuration for each subplot\n", + "plot_configs = [\n", + " {'data': [(T_seq[:-1], μ_seq_2)], 'ylabel': r'$\\mu$'},\n", + " {'data': [(T_seq, π_seq_2)], 'ylabel': r'$\\pi$'},\n", + " {'data': [(T_seq, m_seq_2_regime1 - p_seq_2_regime1)], \n", + " 'ylabel': r'$m - p$'},\n", + " {'data': [(T_seq, m_seq_2_regime1, 'Smooth $m_{T_1}$'), \n", + " (T_seq, m_seq_2_regime2, 'Jumpy $m_{T_1}$')], \n", + " 'ylabel': r'$m$'},\n", + " {'data': [(T_seq, p_seq_2_regime1, 'Smooth $p_{T_1}$'), \n", + " (T_seq, p_seq_2_regime2, 'Jumpy $p_{T_1}$')], \n", + " 'ylabel': r'$p$'}\n", + "]\n", + "\n", + "def experiment_plot(plot_configs, ax):\n", + " # Loop through each subplot configuration\n", + " for axi, config in zip(ax, plot_configs):\n", + " for data in config['data']:\n", + " if len(data) == 3: # Plot with label for legend\n", + " axi.plot(data[0], data[1], label=data[2])\n", + " axi.legend()\n", + " else: # Plot without label\n", + " axi.plot(data[0], data[1])\n", + " axi.set_ylabel(config['ylabel'])\n", + " axi.set_xlabel(r'$t$')\n", + " plt.tight_layout()\n", + " plt.show()\n", + " \n", + "experiment_plot(plot_configs, ax)" + ] + }, + { + "cell_type": "markdown", + "id": "cdca3cb8", + "metadata": {}, + "source": [ + "We invite you to compare these graphs with corresponding ones for the foreseen stabilization analyzed in experiment 1 above.\n", + "\n", + "Note how the inflation graph in the second panel is now identical to the \n", + "money growth graph in the top panel, and how now the log of real balances portrayed in the third panel jumps upward at time $T_1$.\n", + "\n", + "The bottom two panels plot $m$ and $p$ under two possible ways that $m_{T_1}$ might adjust\n", + "as required by the upward jump in $m - p$ at $T_1$. \n", + "\n", + "* the orange line lets $m_{T_1}$ jump upward in order to make sure that the log price level $p_{T_1}$ does not fall.\n", + "\n", + "* the blue line lets $p_{T_1}$ fall while stopping the money supply from jumping.\n", + " \n", + "Here is a way to interpret what the government is doing when the orange line policy is in place.\n", + "\n", + "The government prints money to finance expenditure with the \"velocity dividend\" that it reaps from the increased demand for real balances brought about by the permanent decrease in the rate of growth of the money supply.\n", + "\n", + "The next code generates a multi-panel graph that includes outcomes of both experiments 1 and 2.\n", + "\n", + "That allows us to assess how important it is to understand whether the sudden permanent drop in $\\mu_t$ at $t=T_1$ is fully unanticipated, as in experiment 1, or completely\n", + "unanticipated, as in experiment 2." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "90036eb7", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "# compare foreseen vs unforeseen shock\n", + "fig, ax = plt.subplots(5, figsize=(5, 12), dpi=200)\n", + "\n", + "plot_configs = [\n", + " {'data': [(T_seq[:-1], μ_seq_2)], 'ylabel': r'$\\mu$'},\n", + " {'data': [(T_seq, π_seq_2, 'Unforeseen'), \n", + " (T_seq, π_seq_1, 'Foreseen')], 'ylabel': r'$p$'},\n", + " {'data': [(T_seq, m_seq_2_regime1 - p_seq_2_regime1, 'Unforeseen'), \n", + " (T_seq, m_seq_1 - p_seq_1, 'Foreseen')], 'ylabel': r'$m - p$'},\n", + " {'data': [(T_seq, m_seq_2_regime1, 'Unforeseen (Smooth $m_{T_1}$)'), \n", + " (T_seq, m_seq_2_regime2, 'Unforeseen ($m_{T_1}$ jumps)'),\n", + " (T_seq, m_seq_1, 'Foreseen')], 'ylabel': r'$m$'}, \n", + " {'data': [(T_seq, p_seq_2_regime1, 'Unforeseen (Smooth $m_{T_1}$)'), \n", + " (T_seq, p_seq_2_regime2, 'Unforeseen ($m_{T_1}$ jumps)'),\n", + " (T_seq, p_seq_1, 'Foreseen')], 'ylabel': r'$p$'} \n", + "]\n", + "\n", + "experiment_plot(plot_configs, ax)" + ] + }, + { + "cell_type": "markdown", + "id": "c5fdd115", + "metadata": {}, + "source": [ + "It is instructive to compare the preceding graphs with graphs of log price levels and inflation rates for data from four big inflations described in\n", + "{doc}`this lecture `.\n", + "\n", + "In particular, in the above graphs, notice how a gradual fall in inflation precedes the \"sudden stop\" when it has been anticipated long beforehand, but how\n", + "inflation instead falls abruptly when the permanent drop in money supply growth is unanticipated.\n", + "\n", + "It seems to the author team at quantecon that the drops in inflation near the ends of the four hyperinflations described in {doc}`this lecture `\n", + "more closely resemble outcomes from the experiment 2 \"unforeseen stabilization\". \n", + "\n", + "(It is fair to say that the preceding informal pattern recognition exercise should be supplemented with a more formal structural statistical analysis.)\n", + "\n", + "#### Experiment 3\n", + "\n", + "**Foreseen gradual stabilization**\n", + "\n", + "Instead of a foreseen sudden stabilization of the type studied with experiment 1,\n", + "it is also interesting to study the consequences of a foreseen gradual stabilization.\n", + "\n", + "Thus, suppose that $\\phi \\in (0,1)$, that $\\mu_0 > \\mu^*$, and that for $t = 0, \\ldots, T-1$\n", + "\n", + "$$\n", + "\\mu_t = \\phi^t \\mu_0 + (1 - \\phi^t) \\mu^* .\n", + "$$ \n", + "\n", + "Next we perform an experiment in which there is a perfectly foreseen _gradual_ decrease in the rate of growth of the money supply.\n", + "\n", + "The following code does the calculations and plots the results." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "13e2baf1", + "metadata": {}, + "outputs": [], + "source": [ + "# parameters\n", + "ϕ = 0.9\n", + "μ_seq_stab = np.array([ϕ**t * μ0 + (1-ϕ**t)*μ_star for t in range(T)])\n", + "μ_seq_stab = np.append(μ_seq_stab, μ_star)\n", + "\n", + "cm4 = create_cagan_model(μ_seq=μ_seq_stab)\n", + "\n", + "π_seq_4, m_seq_4, p_seq_4 = solve(cm4, T)\n", + "\n", + "sequences = (μ_seq_stab, π_seq_4, \n", + " m_seq_4 - p_seq_4, m_seq_4, p_seq_4)\n", + "plot_sequences(sequences, (r'$\\mu$', r'$\\pi$', \n", + " r'$m - p$', r'$m$', r'$p$'))" + ] + }, + { + "cell_type": "markdown", + "id": "8b6ee97f", + "metadata": {}, + "source": [ + "## Sequel\n", + "\n", + "Another lecture {doc}`monetarist theory of price levels with adaptive expectations ` describes an \"adaptive expectations\" version of Cagan's model.\n", + "\n", + "The dynamics become more complicated and so does the algebra.\n", + "\n", + "Nowadays, the \"rational expectations\" version of the model is more popular among central bankers and economists advising them." + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.16.1" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 235, + 239, + 243, + 257, + 261, + 282, + 323, + 335, + 339, + 352, + 488, + 525, + 562, + 585, + 606, + 636, + 650 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/cagan_ree.md b/book/_build/html/_sources/cagan_ree.md new file mode 100644 index 0000000..f0274b5 --- /dev/null +++ b/book/_build/html/_sources/cagan_ree.md @@ -0,0 +1,658 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.16.1 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# A Monetarist Theory of Price Levels + +## Overview + + +We'll use linear algebra first to explain and then do some experiments with a "monetarist theory of price levels". + +Economists call it a "monetary" or "monetarist" theory of price levels because effects on price levels occur via a central bank's decisions to print money supply. + + * a goverment's fiscal policies determine whether its _expenditures_ exceed its _tax collections_ + * if its expenditures exceed its tax collections, the government can instruct the central bank to cover the difference by _printing money_ + * that leads to effects on the price level as price level path adjusts to equate the supply of money to the demand for money + +Such a theory of price levels was described by Thomas Sargent and Neil Wallace in chapter 5 of +{cite}`sargent2013rational`, which reprints a 1981 Federal Reserve Bank of Minneapolis article entitled "Unpleasant Monetarist Arithmetic". + +Sometimes this theory is also called a "fiscal theory of price levels" to emphasize the importance of fiscal deficits in shaping changes in the money supply. + +The theory has been extended, criticized, and applied by John Cochrane {cite}`cochrane2023fiscal`. + +In another lecture {doc}`price level histories `, we described some European hyperinflations that occurred in the wake of World War I. + +Elemental forces at work in the fiscal theory of the price level help to understand those episodes. + + +According to this theory, when the government persistently spends more than it collects in taxes and prints money to finance the shortfall (the "shortfall" is called the "government deficit"), it puts upward pressure on the price level and generates +persistent inflation. + +The "monetarist" or "fiscal theory of price levels" asserts that + +* to _start_ a persistent inflation the government begins persistently to run a money-financed government deficit + +* to _stop_ a persistent inflation the government stops persistently running a money-financed government deficit + +The model in this lecture is a "rational expectations" (or "perfect foresight") version of a model that Philip Cagan {cite}`Cagan` used to study the monetary dynamics of hyperinflations. + +While Cagan didn't use that "rational expectations" version of the model, Thomas Sargent {cite}`sargent1982ends` did when he studied the Ends of Four Big Inflations in Europe after World War I. + +* this lecture {doc}`fiscal theory of the price level with adaptive expectations ` describes a version of the model that does not impose "rational expectations" but instead uses + what Cagan and his teacher Milton Friedman called "adaptive expectations" + + * a reader of both lectures will notice that the algebra is less complicated in the present rational expectations version of the model + * the difference in algebra complications can be traced to the following source: the adaptive expectations version of the model has more endogenous variables and more free parameters + +Some of our quantitative experiments with the rational expectations version of the model are designed to illustrate how the fiscal theory explains the abrupt end of those big inflations. + +In those experiments, we'll encounter an instance of a "velocity dividend" that has sometimes accompanied successful inflation stabilization programs. + +To facilitate using linear matrix algebra as our main mathematical tool, we'll use a finite horizon version of the model. + +As in the {doc}`present values ` and {doc}`consumption smoothing` lectures, our mathematical tools are matrix multiplication and matrix inversion. + + +## Structure of the model + + +The model consists of + +* a function that expresses the demand for real balances of government printed money as an inverse function of the public's expected rate of inflation + +* an exogenous sequence of rates of growth of the money supply. The money supply grows because the government prints it to pay for goods and services + +* an equilibrium condition that equates the demand for money to the supply + +* a "perfect foresight" assumption that the public's expected rate of inflation equals the actual rate of inflation. + +To represent the model formally, let + +* $ m_t $ be the log of the supply of nominal money balances; +* $\mu_t = m_{t+1} - m_t $ be the net rate of growth of nominal balances; +* $p_t $ be the log of the price level; +* $\pi_t = p_{t+1} - p_t $ be the net rate of inflation between $t$ and $ t+1$; +* $\pi_t^*$ be the public's expected rate of inflation between $t$ and $t+1$; +* $T$ the horizon -- i.e., the last period for which the model will determine $p_t$ +* $\pi_{T+1}^*$ the terminal rate of inflation between times $T$ and $T+1$. + +The demand for real balances $\exp\left(m_t^d - p_t\right)$ is governed by the following version of the Cagan demand function + +$$ +m_t^d - p_t = -\alpha \pi_t^* \: , \: \alpha > 0 ; \quad t = 0, 1, \ldots, T . +$$ (eq:caganmd) + +This equation asserts that the demand for real balances +is inversely related to the public's expected rate of inflation with sensitivity $\alpha$. + +People somehow acquire **perfect foresight** by their having solved a forecasting +problem. + +This lets us set + +$$ +\pi_t^* = \pi_t , % \forall t +$$ (eq:ree) + +while equating demand for money to supply lets us set $m_t^d = m_t$ for all $t \geq 0$. + +The preceding equations then imply + +$$ +m_t - p_t = -\alpha(p_{t+1} - p_t) +$$ (eq:cagan) + +To fill in details about what it means for private agents +to have perfect foresight, we subtract equation {eq}`eq:cagan` at time $ t $ from the same equation at $ t+1$ to get + +$$ +\mu_t - \pi_t = -\alpha \pi_{t+1} + \alpha \pi_t , +$$ + +which we rewrite as a forward-looking first-order linear difference +equation in $\pi_s$ with $\mu_s$ as a "forcing variable": + +$$ +\pi_t = \frac{\alpha}{1+\alpha} \pi_{t+1} + \frac{1}{1+\alpha} \mu_t , \quad t= 0, 1, \ldots , T +$$ + +where $ 0< \frac{\alpha}{1+\alpha} <1 $. + +Setting $\delta =\frac{\alpha}{1+\alpha}$, let's us represent the preceding equation as + +$$ +\pi_t = \delta \pi_{t+1} + (1-\delta) \mu_t , \quad t =0, 1, \ldots, T +$$ + +Write this system of $T+1$ equations as the single matrix equation + +$$ +\begin{bmatrix} 1 & -\delta & 0 & 0 & \cdots & 0 & 0 \cr + 0 & 1 & -\delta & 0 & \cdots & 0 & 0 \cr + 0 & 0 & 1 & -\delta & \cdots & 0 & 0 \cr + \vdots & \vdots & \vdots & \vdots & \vdots & -\delta & 0 \cr + 0 & 0 & 0 & 0 & \cdots & 1 & -\delta \cr + 0 & 0 & 0 & 0 & \cdots & 0 & 1 \end{bmatrix} +\begin{bmatrix} \pi_0 \cr \pi_1 \cr \pi_2 \cr \vdots \cr \pi_{T-1} \cr \pi_T +\end{bmatrix} += (1 - \delta) \begin{bmatrix} +\mu_0 \cr \mu_1 \cr \mu_2 \cr \vdots \cr \mu_{T-1} \cr \mu_T +\end{bmatrix} ++ \begin{bmatrix} +0 \cr 0 \cr 0 \cr \vdots \cr 0 \cr \delta \pi_{T+1}^* +\end{bmatrix} +$$ (eq:pieq) + +By multiplying both sides of equation {eq}`eq:pieq` by the inverse of the matrix on the left side, we can calculate + +$$ +\pi \equiv \begin{bmatrix} \pi_0 \cr \pi_1 \cr \pi_2 \cr \vdots \cr \pi_{T-1} \cr \pi_T +\end{bmatrix} +$$ + +It turns out that + +$$ +\pi_t = (1-\delta) \sum_{s=t}^T \delta^{s-t} \mu_s + \delta^{T+1-t} \pi_{T+1}^* +$$ (eq:fisctheory1) + +We can represent the equations + +$$ +m_{t+1} = m_t + \mu_t , \quad t = 0, 1, \ldots, T +$$ + +as the matrix equation + +$$ +\begin{bmatrix} +1 & 0 & 0 & \cdots & 0 & 0 \cr +-1 & 1 & 0 & \cdots & 0 & 0 \cr +0 & -1 & 1 & \cdots & 0 & 0 \cr +\vdots & \vdots & \vdots & \vdots & 0 & 0 \cr +0 & 0 & 0 & \cdots & 1 & 0 \cr +0 & 0 & 0 & \cdots & -1 & 1 +\end{bmatrix} +\begin{bmatrix} +m_1 \cr m_2 \cr m_3 \cr \vdots \cr m_T \cr m_{T+1} +\end{bmatrix} += \begin{bmatrix} +\mu_0 \cr \mu_1 \cr \mu_2 \cr \vdots \cr \mu_{T-1} \cr \mu_T +\end{bmatrix} ++ \begin{bmatrix} +m_0 \cr 0 \cr 0 \cr \vdots \cr 0 \cr 0 +\end{bmatrix} +$$ (eq:eq101) + +Multiplying both sides of equation {eq}`eq:eq101` with the inverse of the matrix on the left will give + +$$ +m_t = m_0 + \sum_{s=0}^{t-1} \mu_s, \quad t =1, \ldots, T+1 +$$ (eq:mcum) + +Equation {eq}`eq:mcum` shows that the log of the money supply at $t$ equals the log of the initial money supply $m_0$ +plus accumulation of rates of money growth between times $0$ and $T$. + +## Continuation values + +To determine the continuation inflation rate $\pi_{T+1}^*$ we shall proceed by applying the following infinite-horizon +version of equation {eq}`eq:fisctheory1` at time $t = T+1$: + +$$ +\pi_t = (1-\delta) \sum_{s=t}^\infty \delta^{s-t} \mu_s , +$$ (eq:fisctheory2) + +and by also assuming the following continuation path for $\mu_t$ beyond $T$: + +$$ +\mu_{t+1} = \gamma^* \mu_t, \quad t \geq T . +$$ + +Plugging the preceding equation into equation {eq}`eq:fisctheory2` at $t = T+1$ and rearranging we can deduce that + +$$ +\pi_{T+1}^* = \frac{1 - \delta}{1 - \delta \gamma^*} \gamma^* \mu_T +$$ (eq:piterm) + +where we require that $\vert \gamma^* \delta \vert < 1$. + +Let's implement and solve this model. + + +As usual, we'll start by importing some Python modules. + +```{code-cell} ipython3 +import numpy as np +from collections import namedtuple +import matplotlib.pyplot as plt +``` + +First, we store parameters in a `namedtuple`: + +```{code-cell} ipython3 +# Create the rational expectation version of Cagan model in finite time +CaganREE = namedtuple("CaganREE", + ["m0", # initial money supply + "μ_seq", # sequence of rate of growth + "α", # sensitivity parameter + "δ", # α/(1 + α) + "π_end" # terminal expected inflation + ]) + +def create_cagan_model(m0=1, α=5, μ_seq=None): + δ = α/(1 + α) + π_end = μ_seq[-1] # compute terminal expected inflation + return CaganREE(m0, μ_seq, α, δ, π_end) +``` + +Now we can solve the model to compute $\pi_t$, $m_t$ and $p_t$ for $t =1, \ldots, T+1$ using the matrix equation above + +```{code-cell} ipython3 +def solve(model, T): + m0, π_end, μ_seq, α, δ = (model.m0, model.π_end, + model.μ_seq, model.α, model.δ) + + # Create matrix representation above + A1 = np.eye(T+1, T+1) - δ * np.eye(T+1, T+1, k=1) + A2 = np.eye(T+1, T+1) - np.eye(T+1, T+1, k=-1) + + b1 = (1-δ) * μ_seq + np.concatenate([np.zeros(T), [δ * π_end]]) + b2 = μ_seq + np.concatenate([[m0], np.zeros(T)]) + + π_seq = np.linalg.solve(A1, b1) + m_seq = np.linalg.solve(A2, b2) + + π_seq = np.append(π_seq, π_end) + m_seq = np.append(m0, m_seq) + + p_seq = m_seq + α * π_seq + + return π_seq, m_seq, p_seq +``` + +### Some quantitative experiments + +In the experiments below, we'll use formula {eq}`eq:piterm` as our terminal condition for expected inflation. + +In devising these experiments, we'll make assumptions about $\{\mu_t\}$ that are consistent with formula +{eq}`eq:piterm`. + +We describe several such experiments. + +In all of them, + +$$ +\mu_t = \mu^* , \quad t \geq T_1 +$$ + +so that, in terms of our notation and formula for $\pi_{T+1}^*$ above, $\gamma^* = 1$. + +#### Experiment 1: Foreseen sudden stabilization + +In this experiment, we'll study how, when $\alpha >0$, a foreseen inflation stabilization has effects on inflation that proceed it. + +We'll study a situation in which the rate of growth of the money supply is $\mu_0$ +from $t=0$ to $t= T_1$ and then permanently falls to $\mu^*$ at $t=T_1$. + +Thus, let $T_1 \in (0, T)$. + +So where $\mu_0 > \mu^*$, we assume that + +$$ +\mu_{t+1} = \begin{cases} + \mu_0 , & t = 0, \ldots, T_1 -1 \\ + \mu^* , & t \geq T_1 + \end{cases} +$$ + +We'll start by executing a version of our "experiment 1" in which the government implements a _foreseen_ sudden permanent reduction in the rate of money creation at time $T_1$. + +Let's experiment with the following parameters + +```{code-cell} ipython3 +T1 = 60 +μ0 = 0.5 +μ_star = 0 +T = 80 + +μ_seq_1 = np.append(μ0*np.ones(T1+1), μ_star*np.ones(T-T1)) + +cm = create_cagan_model(μ_seq=μ_seq_1) + +# solve the model +π_seq_1, m_seq_1, p_seq_1 = solve(cm, T) +``` + +Now we use the following function to plot the result + +```{code-cell} ipython3 +def plot_sequences(sequences, labels): + fig, axs = plt.subplots(len(sequences), 1, figsize=(5, 12), dpi=200) + for ax, seq, label in zip(axs, sequences, labels): + ax.plot(range(len(seq)), seq, label=label) + ax.set_ylabel(label) + ax.set_xlabel('$t$') + ax.legend() + plt.tight_layout() + plt.show() + +sequences = (μ_seq_1, π_seq_1, m_seq_1 - p_seq_1, m_seq_1, p_seq_1) +plot_sequences(sequences, (r'$\mu$', r'$\pi$', r'$m - p$', r'$m$', r'$p$')) +``` + +The plot of the money growth rate $\mu_t$ in the top level panel portrays +a sudden reduction from $.5$ to $0$ at time $T_1 = 60$. + +This brings about a gradual reduction of the inflation rate $\pi_t$ that precedes the +money supply growth rate reduction at time $T_1$. + +Notice how the inflation rate declines smoothly (i.e., continuously) to $0$ at $T_1$ -- +unlike the money growth rate, it does not suddenly "jump" downward at $T_1$. + +This is because the reduction in $\mu$ at $T_1$ has been foreseen from the start. + +While the log money supply portrayed in the bottom panel has a kink at $T_1$, the log price level does not -- it is "smooth" -- once again a consequence of the fact that the +reduction in $\mu$ has been foreseen. + +To set the stage for our next experiment, we want to study the determinants of the price level a little more. + + +### The log price level + +We can use equations {eq}`eq:caganmd` and {eq}`eq:ree` +to discover that the log of the price level satisfies + +$$ +p_t = m_t + \alpha \pi_t +$$ (eq:pformula2) + +or, by using equation {eq}`eq:fisctheory1`, + +$$ +p_t = m_t + \alpha \left[ (1-\delta) \sum_{s=t}^T \delta^{s-t} \mu_s + \delta^{T+1-t} \pi_{T+1}^* \right] +$$ (eq:pfiscaltheory2) + +In our next experiment, we'll study a "surprise" permanent change in the money growth that beforehand +was completely unanticipated. + +At time $T_1$ when the "surprise" money growth rate change occurs, to satisfy +equation {eq}`eq:pformula2`, the log of real balances jumps +_upward_ as $\pi_t$ jumps _downward_. + +But in order for $m_t - p_t$ to jump, which variable jumps, $m_{T_1}$ or $p_{T_1}$? + +We'll study that interesting question next. + +### What jumps? + +What jumps at $T_1$? + +Is it $p_{T_1}$ or $m_{T_1}$? + +If we insist that the money supply $m_{T_1}$ is locked at its value $m_{T_1}^1$ inherited from the past, then formula {eq}`eq:pformula2` implies that the price level jumps downward at time $T_1$, to coincide with the downward jump in +$\pi_{T_1}$ + +An alternative assumption about the money supply level is that as part of the "inflation stabilization", +the government resets $m_{T_1}$ according to + +$$ +m_{T_1}^2 - m_{T_1}^1 = \alpha (\pi_{T_1}^1 - \pi_{T_1}^2), +$$ (eq:eqnmoneyjump) + +which describes how the government could reset the money supply at $T_1$ in response to the jump in expected inflation associated with monetary stabilization. + +Doing this would let the price level be continuous at $T_1$. + +By letting money jump according to equation {eq}`eq:eqnmoneyjump` the monetary authority prevents the price level from _falling_ at the moment that the unanticipated stabilization arrives. + +In various research papers about stabilizations of high inflations, the jump in the money supply described by equation {eq}`eq:eqnmoneyjump` has been called +"the velocity dividend" that a government reaps from implementing a regime change that sustains a permanently lower inflation rate. + +#### Technical details about whether $p$ or $m$ jumps at $T_1$ + +We have noted that with a constant expected forward sequence $\mu_s = \bar \mu$ for $s\geq t$, $\pi_{t} =\bar{\mu}$. + +A consequence is that at $T_1$, either $m$ or $p$ must "jump" at $T_1$. + +We'll study both cases. + +#### $m_{T_{1}}$ does not jump. + +$$ +\begin{aligned} +m_{T_{1}}&=m_{T_{1}-1}+\mu_{0}\\\pi_{T_{1}}&=\mu^{*}\\p_{T_{1}}&=m_{T_{1}}+\alpha\pi_{T_{1}} +\end{aligned} +$$ + +Simply glue the sequences $t\leq T_1$ and $t > T_1$. + +#### $m_{T_{1}}$ jumps. + +We reset $m_{T_{1}}$ so that $p_{T_{1}}=\left(m_{T_{1}-1}+\mu_{0}\right)+\alpha\mu_{0}$, with $\pi_{T_{1}}=\mu^{*}$. + +Then, + +$$ +m_{T_{1}}=p_{T_{1}}-\alpha\pi_{T_{1}}=\left(m_{T_{1}-1}+\mu_{0}\right)+\alpha\left(\mu_{0}-\mu^{*}\right) +$$ + +We then compute for the remaining $T-T_{1}$ periods with $\mu_{s}=\mu^{*},\forall s\geq T_{1}$ and the initial condition $m_{T_{1}}$ from above. + +We are now technically equipped to discuss our next experiment. + +#### Experiment 2: an unforeseen sudden stabilization + +This experiment deviates a little bit from a pure version of our "perfect foresight" +assumption by assuming that a sudden permanent reduction in $\mu_t$ like that +analyzed in experiment 1 is completely unanticipated. + +Such a completely unanticipated shock is popularly known as an "MIT shock". + +The mental experiment involves switching at time $T_1$ from an initial "continuation path" for $\{\mu_t, \pi_t\} $ to another path that involves a permanently lower inflation rate. + +**Initial Path:** $\mu_t = \mu_0$ for all $t \geq 0$. So this path is for $\{\mu_t\}_{t=0}^\infty$; the associated +path for $\pi_t$ has $\pi_t = \mu_0$. + +**Revised Continuation Path** Where $ \mu_0 > \mu^*$, we construct a continuation path $\{\mu_s\}_{s=T_1}^\infty$ +by setting $\mu_s = \mu^*$ for all $s \geq T_1$. The perfect foresight continuation path for +$\pi$ is $\pi_s = \mu^*$ + +To capture a "completely unanticipated permanent shock to the $\{\mu_t\}$ process at time $T_1$, we simply glue the $\mu_t, \pi_t$ +that emerges under path 2 for $t \geq T_1$ to the $\mu_t, \pi_t$ path that had emerged under path 1 for $ t=0, \ldots, +T_1 -1$. + +We can do the MIT shock calculations mostly by hand. + +Thus, for path 1, $\pi_t = \mu_0 $ for all $t \in [0, T_1-1]$, while for path 2, +$\mu_s = \mu^*$ for all $s \geq T_1$. + +We now move on to experiment 2, our "MIT shock", completely unforeseen +sudden stabilization. + +We set this up so that the $\{\mu_t\}$ sequences that describe the sudden stabilization +are identical to those for experiment 1, the foreseen sudden stabilization. + +The following code does the calculations and plots outcomes. + +```{code-cell} ipython3 +# path 1 +μ_seq_2_path1 = μ0 * np.ones(T+1) + +cm1 = create_cagan_model(μ_seq=μ_seq_2_path1) +π_seq_2_path1, m_seq_2_path1, p_seq_2_path1 = solve(cm1, T) + +# continuation path +μ_seq_2_cont = μ_star * np.ones(T-T1) + +cm2 = create_cagan_model(m0=m_seq_2_path1[T1+1], + μ_seq=μ_seq_2_cont) +π_seq_2_cont, m_seq_2_cont1, p_seq_2_cont1 = solve(cm2, T-1-T1) + + +# regime 1 - simply glue π_seq, μ_seq +μ_seq_2 = np.concatenate((μ_seq_2_path1[:T1+1], + μ_seq_2_cont)) +π_seq_2 = np.concatenate((π_seq_2_path1[:T1+1], + π_seq_2_cont)) +m_seq_2_regime1 = np.concatenate((m_seq_2_path1[:T1+1], + m_seq_2_cont1)) +p_seq_2_regime1 = np.concatenate((p_seq_2_path1[:T1+1], + p_seq_2_cont1)) + +# regime 2 - reset m_T1 +m_T1 = (m_seq_2_path1[T1] + μ0) + cm2.α*(μ0 - μ_star) + +cm3 = create_cagan_model(m0=m_T1, μ_seq=μ_seq_2_cont) +π_seq_2_cont2, m_seq_2_cont2, p_seq_2_cont2 = solve(cm3, T-1-T1) + +m_seq_2_regime2 = np.concatenate((m_seq_2_path1[:T1+1], + m_seq_2_cont2)) +p_seq_2_regime2 = np.concatenate((p_seq_2_path1[:T1+1], + p_seq_2_cont2)) +``` + +```{code-cell} ipython3 +:tags: [hide-input] + +T_seq = range(T+2) + +# plot both regimes +fig, ax = plt.subplots(5, 1, figsize=(5, 12), dpi=200) + +# Configuration for each subplot +plot_configs = [ + {'data': [(T_seq[:-1], μ_seq_2)], 'ylabel': r'$\mu$'}, + {'data': [(T_seq, π_seq_2)], 'ylabel': r'$\pi$'}, + {'data': [(T_seq, m_seq_2_regime1 - p_seq_2_regime1)], + 'ylabel': r'$m - p$'}, + {'data': [(T_seq, m_seq_2_regime1, 'Smooth $m_{T_1}$'), + (T_seq, m_seq_2_regime2, 'Jumpy $m_{T_1}$')], + 'ylabel': r'$m$'}, + {'data': [(T_seq, p_seq_2_regime1, 'Smooth $p_{T_1}$'), + (T_seq, p_seq_2_regime2, 'Jumpy $p_{T_1}$')], + 'ylabel': r'$p$'} +] + +def experiment_plot(plot_configs, ax): + # Loop through each subplot configuration + for axi, config in zip(ax, plot_configs): + for data in config['data']: + if len(data) == 3: # Plot with label for legend + axi.plot(data[0], data[1], label=data[2]) + axi.legend() + else: # Plot without label + axi.plot(data[0], data[1]) + axi.set_ylabel(config['ylabel']) + axi.set_xlabel(r'$t$') + plt.tight_layout() + plt.show() + +experiment_plot(plot_configs, ax) +``` + +We invite you to compare these graphs with corresponding ones for the foreseen stabilization analyzed in experiment 1 above. + +Note how the inflation graph in the second panel is now identical to the +money growth graph in the top panel, and how now the log of real balances portrayed in the third panel jumps upward at time $T_1$. + +The bottom two panels plot $m$ and $p$ under two possible ways that $m_{T_1}$ might adjust +as required by the upward jump in $m - p$ at $T_1$. + +* the orange line lets $m_{T_1}$ jump upward in order to make sure that the log price level $p_{T_1}$ does not fall. + +* the blue line lets $p_{T_1}$ fall while stopping the money supply from jumping. + +Here is a way to interpret what the government is doing when the orange line policy is in place. + +The government prints money to finance expenditure with the "velocity dividend" that it reaps from the increased demand for real balances brought about by the permanent decrease in the rate of growth of the money supply. + +The next code generates a multi-panel graph that includes outcomes of both experiments 1 and 2. + +That allows us to assess how important it is to understand whether the sudden permanent drop in $\mu_t$ at $t=T_1$ is fully unanticipated, as in experiment 1, or completely +unanticipated, as in experiment 2. + +```{code-cell} ipython3 +:tags: [hide-input] + +# compare foreseen vs unforeseen shock +fig, ax = plt.subplots(5, figsize=(5, 12), dpi=200) + +plot_configs = [ + {'data': [(T_seq[:-1], μ_seq_2)], 'ylabel': r'$\mu$'}, + {'data': [(T_seq, π_seq_2, 'Unforeseen'), + (T_seq, π_seq_1, 'Foreseen')], 'ylabel': r'$p$'}, + {'data': [(T_seq, m_seq_2_regime1 - p_seq_2_regime1, 'Unforeseen'), + (T_seq, m_seq_1 - p_seq_1, 'Foreseen')], 'ylabel': r'$m - p$'}, + {'data': [(T_seq, m_seq_2_regime1, 'Unforeseen (Smooth $m_{T_1}$)'), + (T_seq, m_seq_2_regime2, 'Unforeseen ($m_{T_1}$ jumps)'), + (T_seq, m_seq_1, 'Foreseen')], 'ylabel': r'$m$'}, + {'data': [(T_seq, p_seq_2_regime1, 'Unforeseen (Smooth $m_{T_1}$)'), + (T_seq, p_seq_2_regime2, 'Unforeseen ($m_{T_1}$ jumps)'), + (T_seq, p_seq_1, 'Foreseen')], 'ylabel': r'$p$'} +] + +experiment_plot(plot_configs, ax) +``` + +It is instructive to compare the preceding graphs with graphs of log price levels and inflation rates for data from four big inflations described in +{doc}`this lecture `. + +In particular, in the above graphs, notice how a gradual fall in inflation precedes the "sudden stop" when it has been anticipated long beforehand, but how +inflation instead falls abruptly when the permanent drop in money supply growth is unanticipated. + +It seems to the author team at quantecon that the drops in inflation near the ends of the four hyperinflations described in {doc}`this lecture ` +more closely resemble outcomes from the experiment 2 "unforeseen stabilization". + +(It is fair to say that the preceding informal pattern recognition exercise should be supplemented with a more formal structural statistical analysis.) + +#### Experiment 3 + +**Foreseen gradual stabilization** + +Instead of a foreseen sudden stabilization of the type studied with experiment 1, +it is also interesting to study the consequences of a foreseen gradual stabilization. + +Thus, suppose that $\phi \in (0,1)$, that $\mu_0 > \mu^*$, and that for $t = 0, \ldots, T-1$ + +$$ +\mu_t = \phi^t \mu_0 + (1 - \phi^t) \mu^* . +$$ + +Next we perform an experiment in which there is a perfectly foreseen _gradual_ decrease in the rate of growth of the money supply. + +The following code does the calculations and plots the results. + +```{code-cell} ipython3 +# parameters +ϕ = 0.9 +μ_seq_stab = np.array([ϕ**t * μ0 + (1-ϕ**t)*μ_star for t in range(T)]) +μ_seq_stab = np.append(μ_seq_stab, μ_star) + +cm4 = create_cagan_model(μ_seq=μ_seq_stab) + +π_seq_4, m_seq_4, p_seq_4 = solve(cm4, T) + +sequences = (μ_seq_stab, π_seq_4, + m_seq_4 - p_seq_4, m_seq_4, p_seq_4) +plot_sequences(sequences, (r'$\mu$', r'$\pi$', + r'$m - p$', r'$m$', r'$p$')) +``` + +## Sequel + +Another lecture {doc}`monetarist theory of price levels with adaptive expectations ` describes an "adaptive expectations" version of Cagan's model. + +The dynamics become more complicated and so does the algebra. + +Nowadays, the "rational expectations" version of the model is more popular among central bankers and economists advising them. diff --git a/content/lectures/cobweb.ipynb b/book/_build/html/_sources/cobweb.ipynb similarity index 86% rename from content/lectures/cobweb.ipynb rename to book/_build/html/_sources/cobweb.ipynb index 64bc44e..ea35586 100644 --- a/content/lectures/cobweb.ipynb +++ b/book/_build/html/_sources/cobweb.ipynb @@ -2,13 +2,12 @@ "cells": [ { "cell_type": "markdown", - "id": "7615683b", + "id": "51c14ade", "metadata": {}, "source": [ "(cobweb)=\n", "# The Cobweb Model\n", "\n", - "\n", "The cobweb model is a model of prices and quantities in a given market, and how they evolve over time.\n", "\n", "## Overview \n", @@ -18,7 +17,7 @@ "\n", "To give some idea of how the model operates, and why expectations matter, imagine the following scenario.\n", "\n", - "There is a market for soy beans, say, where prices and traded quantities\n", + "There is a market for soybeans, say, where prices and traded quantities\n", "depend on the choices of buyers and sellers.\n", "\n", "The buyers are represented by a demand curve --- they buy more at low prices\n", @@ -32,11 +31,11 @@ "Suppose now that the price is currently high.\n", "\n", "Seeing this high price, and perhaps expecting that the high price will remain\n", - "for some time, the farmers plant many fields with soy beans.\n", + "for some time, the farmers plant many fields with soybeans.\n", "\n", "Next period the resulting high supply floods the market, causing the price to drop.\n", "\n", - "Seeing this low price, the farmers now shift out of soy beans, restricting\n", + "Seeing this low price, the farmers now shift out of soybeans, restricting\n", "supply and causing the price to climb again.\n", "\n", "You can imagine how these dynamics could cause cycles in prices and quantities\n", @@ -46,23 +45,17 @@ "them, and to study conditions under which cycles persist (or disappear).\n", "\n", "In this lecture, we investigate and simulate the basic model under different\n", - "assumptions regarding the way that produces form expectations.\n", + "assumptions regarding the way that producers form expectations.\n", + "\n", + "Our discussion and simulations draw on [high quality lectures](https://comp-econ.org/CEF_2013/downloads/Complex%20Econ%20Systems%20Lecture%20II.pdf) by [Cars Hommes](https://www.uva.nl/en/profile/h/o/c.h.hommes/c.h.hommes.html).\n", "\n", - "Our discussion and simulations draw on [high quality lectures](https://comp-econ.org/CEF_2013/downloads/Complex%20Econ%20Systems%20Lecture%20II.pdf) by [Cars Hommes](https://www.uva.nl/en/profile/h/o/c.h.hommes/c.h.hommes.html)." - ] - }, - { - "cell_type": "markdown", - "id": "353ee1d8", - "metadata": {}, - "source": [ "We will use the following imports." ] }, { "cell_type": "code", "execution_count": null, - "id": "eb6bcc0d", + "id": "35239c06", "metadata": {}, "outputs": [], "source": [ @@ -72,14 +65,14 @@ }, { "cell_type": "markdown", - "id": "ce16e184", + "id": "43d8154d", "metadata": {}, "source": [ "## History\n", "\n", "Early papers on the cobweb cycle include {cite}`cobweb_model` and {cite}`hog_cycle`.\n", "\n", - "The paper {cite}`hog_cycle` uses the cobweb theorem to explain the prices of hog in the US over 1920--1950\n", + "The paper {cite}`hog_cycle` uses the cobweb theorem to explain the prices of hog in the US over 1920--1950.\n", "\n", "The next plot replicates part of Figure 2 from that paper, which plots the price of hogs at yearly frequency.\n", "\n", @@ -89,7 +82,7 @@ { "cell_type": "code", "execution_count": null, - "id": "adafd9b0", + "id": "f39d83c9", "metadata": {}, "outputs": [], "source": [ @@ -108,14 +101,14 @@ }, { "cell_type": "markdown", - "id": "67929476", + "id": "c5254a00", "metadata": {}, "source": [ - "## The Model\n", + "## The model\n", "\n", - "Let's return to our discussion of a hypothetical soy bean market, where price is determined by supply and demand.\n", + "Let's return to our discussion of a hypothetical soybean market, where price is determined by supply and demand.\n", "\n", - "We suppose that demand for soy beans is given by\n", + "We suppose that demand for soybeans is given by\n", "\n", "$$\n", " D(p_t) = a - b p_t\n", @@ -125,15 +118,15 @@ "\n", "($D(p_t)$ is the quantity demanded in some fixed unit, such as thousands of tons.)\n", "\n", - "Because the crop of soy beans for time $t$ is planted at $t-1$, supply of soy beans at time $t$ depends on *expected* prices at time $t$, which we denote $p^e_{t-1}$.\n", + "Because the crop of soybeans for time $t$ is planted at $t-1$, supply of soybeans at time $t$ depends on *expected* prices at time $t$, which we denote $p^e_t$.\n", "\n", "We suppose that supply is nonlinear in expected prices, and takes the form\n", "\n", "$$\n", - " S(p^e_{t-1}) = \\tanh(\\lambda(p^e_{t-1} - c)) + d\n", + " S(p^e_t) = \\tanh(\\lambda(p^e_t - c)) + d\n", "$$\n", "\n", - "where $\\lambda$ is a positive constant and $c, d \\geq 0$.\n", + "where $\\lambda$ is a positive constant, $c, d$ are nonnegative constants and $\\tanh$ is a type of [hyperbolic function](https://en.wikipedia.org/wiki/Hyperbolic_functions).\n", "\n", "Let's make a plot of supply and demand for particular choices of the parameter values.\n", "\n", @@ -143,7 +136,7 @@ { "cell_type": "code", "execution_count": null, - "id": "46b48306", + "id": "13205c87", "metadata": {}, "outputs": [], "source": [ @@ -169,7 +162,7 @@ }, { "cell_type": "markdown", - "id": "6167427e", + "id": "7d9d74c5", "metadata": {}, "source": [ "Now let's plot." @@ -178,7 +171,7 @@ { "cell_type": "code", "execution_count": null, - "id": "21a325c2", + "id": "98a6c898", "metadata": {}, "outputs": [], "source": [ @@ -187,7 +180,7 @@ "fig, ax = plt.subplots()\n", "\n", "ax.plot(p_grid, m.demand(p_grid), label=\"$D$\")\n", - "ax.plot(p_grid, m.supply(p_grid), label=\"S\")\n", + "ax.plot(p_grid, m.supply(p_grid), label=\"$S$\")\n", "ax.set_xlabel(\"price\")\n", "ax.set_ylabel(\"quantity\")\n", "ax.legend()\n", @@ -197,19 +190,19 @@ }, { "cell_type": "markdown", - "id": "7835721d", + "id": "1874274c", "metadata": {}, "source": [ "Market equilibrium requires that supply equals demand, or\n", "\n", "$$\n", - " a - b p_t = S(p^e_{t-1})\n", + " a - b p_t = S(p^e_t)\n", "$$\n", "\n", "Rewriting in terms of $p_t$ gives\n", "\n", "$$\n", - " p_t = - \\frac{1}{b} [S(p^e_{t-1}) - a]\n", + " p_t = - \\frac{1}{b} [S(p^e_t) - a]\n", "$$\n", "\n", "Finally, to complete the model, we need to describe how price expectations are formed.\n", @@ -220,7 +213,7 @@ "\n", "```{math}\n", ":label: p_et\n", - " p^e_{t-1} = f(p_{t-1}, p_{t-2})\n", + " p^e_t = f(p_{t-1}, p_{t-2})\n", "```\n", "\n", "where $f$ is some function.\n", @@ -238,8 +231,7 @@ "\n", "The price dynamics depend on the parameter values and also on the function $f$ that determines how producers form expectations.\n", "\n", - "\n", - "## Naive Expectations\n", + "## Naive expectations\n", "\n", "To go further in our analysis we need to specify the function $f$; that is, how expectations are formed.\n", "\n", @@ -247,7 +239,9 @@ "\n", "In other words,\n", "\n", - "$$ p_{t-1}^e = p_{t-1} $$\n", + "$$ \n", + "p_t^e = p_{t-1} \n", + "$$\n", "\n", "Using {eq}`price_t`, we then have\n", "\n", @@ -268,14 +262,13 @@ " g(p) = - \\frac{1}{b} [ S(p) - a]\n", "```\n", "\n", - "\n", "Here we represent the function $g$" ] }, { "cell_type": "code", "execution_count": null, - "id": "5842c03b", + "id": "12ebe7dc", "metadata": {}, "outputs": [], "source": [ @@ -291,18 +284,18 @@ }, { "cell_type": "markdown", - "id": "32fe9c96", + "id": "4fed2d19", "metadata": {}, "source": [ - "Let's try to understand how prices will evolve using a 45 degree diagram, which is a tool for studying one-dimensional dynamics.\n", + "Let's try to understand how prices will evolve using a 45-degree diagram, which is a tool for studying one-dimensional dynamics.\n", "\n", - "The function `plot45` defined below helps us draw the 45 degree diagram." + "The function `plot45` defined below helps us draw the 45-degree diagram." ] }, { "cell_type": "code", "execution_count": null, - "id": "d16435f7", + "id": "4c7c7ff8", "metadata": { "tags": [ "hide-input" @@ -341,7 +334,7 @@ "\n", " ax.plot(pgrid, g(model, pgrid), 'b-',\n", " lw=2, alpha=0.6, label='g')\n", - " ax.plot(pgrid, pgrid, lw=1, alpha=0.7, label='45')\n", + " ax.plot(pgrid, pgrid, lw=1, alpha=0.7, label='$45\\degree$')\n", "\n", " x = p0\n", " xticks = [pmin]\n", @@ -368,6 +361,8 @@ "\n", " xticks.append(pmax)\n", " xtick_labels.append(pmax)\n", + " ax.set_ylabel(r'$p_{t+1}$')\n", + " ax.set_xlabel(r'$p_t$')\n", " ax.set_xticks(xticks)\n", " ax.set_yticks(xticks)\n", " ax.set_xticklabels(xtick_labels)\n", @@ -382,16 +377,16 @@ }, { "cell_type": "markdown", - "id": "3a6910a8", + "id": "328966ce", "metadata": {}, "source": [ - "Now we can set up a market and plot the 45 degree diagram." + "Now we can set up a market and plot the 45-degree diagram." ] }, { "cell_type": "code", "execution_count": null, - "id": "7e8d03eb", + "id": "0d28181b", "metadata": {}, "outputs": [], "source": [ @@ -401,7 +396,7 @@ { "cell_type": "code", "execution_count": null, - "id": "85366335", + "id": "9909a45e", "metadata": {}, "outputs": [], "source": [ @@ -410,10 +405,10 @@ }, { "cell_type": "markdown", - "id": "528d4220", + "id": "d8cd3000", "metadata": {}, "source": [ - "The plot shows the function $g$ defined in {eq}`def_g` and the $45$ degree line.\n", + "The plot shows the function $g$ defined in {eq}`def_g` and the 45-degree line.\n", "\n", "Think of $ p_t $ as a value on the horizontal axis.\n", "\n", @@ -421,13 +416,13 @@ "\n", "Clearly,\n", "\n", - "- If $ g $ lies above the 45 degree line at $p_t$, then we have $ p_{t+1} > p_t $.\n", - "- If $ g $ lies below the 45 degree line at $p_t$, then we have $ p_{t+1} < p_t $.\n", - "- If $ g $ hits the 45 degree line at $p_t$, then we have $ p_{t+1} = p_t $, so $ p_t $ is a steady state.\n", + "- If $ g $ lies above the 45-degree line at $p_t$, then we have $ p_{t+1} > p_t $.\n", + "- If $ g $ lies below the 45-degree line at $p_t$, then we have $ p_{t+1} < p_t $.\n", + "- If $ g $ hits the 45-degree line at $p_t$, then we have $ p_{t+1} = p_t $, so $ p_t $ is a steady state.\n", "\n", "Consider the sequence of prices starting at $p_0$, as shown in the figure.\n", "\n", - "We find $p_1$ on the vertical axis and then shift it to the horizontal axis using the 45 degree line (where values on the two axes are equal).\n", + "We find $p_1$ on the vertical axis and then shift it to the horizontal axis using the 45-degree line (where values on the two axes are equal).\n", "\n", "Then from $p_1$ we obtain $p_2$ and continue.\n", "\n", @@ -439,7 +434,7 @@ { "cell_type": "code", "execution_count": null, - "id": "204328fe", + "id": "c4194ad9", "metadata": {}, "outputs": [], "source": [ @@ -473,7 +468,7 @@ { "cell_type": "code", "execution_count": null, - "id": "08dc28fa", + "id": "f169121c", "metadata": {}, "outputs": [], "source": [ @@ -482,7 +477,7 @@ }, { "cell_type": "markdown", - "id": "69406b94", + "id": "b888df1c", "metadata": {}, "source": [ "We see that a cycle has formed and the cycle is persistent.\n", @@ -497,7 +492,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a9ded11a", + "id": "834776bd", "metadata": {}, "outputs": [], "source": [ @@ -506,10 +501,10 @@ }, { "cell_type": "markdown", - "id": "9544893f", + "id": "4e91a8b6", "metadata": {}, "source": [ - "## Adaptive Expectations\n", + "## Adaptive expectations\n", "\n", "Naive expectations are quite simple and also important in driving the cycle that we found.\n", "\n", @@ -525,7 +520,7 @@ "\n", "```{math}\n", ":label: pe_adaptive\n", - "p_{t-1}^e = \\alpha p_{t-1} + (1-\\alpha) p^e_{t-2}\n", + "p_t^e = \\alpha p_{t-1} + (1-\\alpha) p^e_{t-1}\n", "\\qquad (0 \\leq \\alpha \\leq 1)\n", "```\n", "\n", @@ -533,7 +528,7 @@ "\n", "```{math}\n", ":label: pe_adaptive_2\n", - "p_{t-1}^e = p^e_{t-2} + \\alpha (p_{t-1} - p_{t-2}^e)\n", + "p_t^e = p^e_{t-1} + \\alpha (p_{t-1} - p_{t-1}^e)\n", "```\n", "\n", "This equation helps to show that expectations shift\n", @@ -544,17 +539,16 @@ "Using {eq}`pe_adaptive`, we obtain the dynamics\n", "\n", "$$\n", - " p_t = - \\frac{1}{b} [ S(\\alpha p_{t-1} + (1-\\alpha) p^e_{t-2}) - a]\n", + " p_t = - \\frac{1}{b} [ S(\\alpha p_{t-1} + (1-\\alpha) p^e_{t-1}) - a]\n", "$$\n", "\n", - "\n", "Let's try to simulate the price and observe the dynamics using different values of $\\alpha$." ] }, { "cell_type": "code", "execution_count": null, - "id": "205f383f", + "id": "b352f06e", "metadata": {}, "outputs": [], "source": [ @@ -568,7 +562,7 @@ }, { "cell_type": "markdown", - "id": "7827f4d9", + "id": "8335632f", "metadata": {}, "source": [ "The function below plots price dynamics under adaptive expectations for different values of $\\alpha$." @@ -577,7 +571,7 @@ { "cell_type": "code", "execution_count": null, - "id": "aa1032c1", + "id": "d4e9bfc7", "metadata": {}, "outputs": [], "source": [ @@ -600,18 +594,16 @@ }, { "cell_type": "markdown", - "id": "cac10b03", + "id": "c964a48f", "metadata": {}, "source": [ - "Let's call the function with prices starting at $p_0 = 5$.\n", - "\n", - "TODO does this fit well in the page, even in the pdf? If not should it be stacked vertically?" + "Let's call the function with prices starting at $p_0 = 5$." ] }, { "cell_type": "code", "execution_count": null, - "id": "4266a97a", + "id": "4e20f6a1", "metadata": {}, "outputs": [], "source": [ @@ -620,7 +612,7 @@ }, { "cell_type": "markdown", - "id": "21a92ba6", + "id": "b9a07e4f", "metadata": {}, "source": [ "Note that if $\\alpha=1$, then adaptive expectations are just naive expectation.\n", @@ -630,9 +622,6 @@ "\n", "This increased stability can be seen in the figures.\n", "\n", - "\n", - "TODO check / fix exercises\n", - "\n", "## Exercises\n", "\n", "```{exercise-start}\n", @@ -653,7 +642,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1e382dd6", + "id": "a79232f9", "metadata": {}, "outputs": [], "source": [ @@ -689,7 +678,7 @@ { "cell_type": "code", "execution_count": null, - "id": "bf7e2dcb", + "id": "1d7fb34c", "metadata": {}, "outputs": [], "source": [ @@ -699,7 +688,7 @@ }, { "cell_type": "markdown", - "id": "e4d8d771", + "id": "99fa2ab2", "metadata": {}, "source": [ "```{solution-end}\n", @@ -718,7 +707,7 @@ "\n", "```{math}\n", ":label: pe_blae\n", - "p_{t-1}^e = \\alpha p_{t-1} + (1-\\alpha) p_{t-2}\n", + "p_t^e = \\alpha p_{t-1} + (1-\\alpha) p_{t-2}\n", "```\n", "\n", "\n", @@ -735,7 +724,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f009b457", + "id": "8f464b42", "metadata": {}, "outputs": [], "source": [ @@ -750,7 +739,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ba7045ca", + "id": "64e12377", "metadata": {}, "outputs": [], "source": [ @@ -782,7 +771,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6010e78c", + "id": "c6038a57", "metadata": {}, "outputs": [], "source": [ @@ -796,29 +785,65 @@ }, { "cell_type": "markdown", - "id": "27de5499", + "id": "898768a0", "metadata": {}, "source": [ "```{solution-end}\n", "```" ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "07ae856a", - "metadata": {}, - "outputs": [], - "source": [] } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.16.2" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 12, + 60, + 63, + 75, + 87, + 117, + 136, + 140, + 152, + 225, + 234, + 240, + 313, + 317, + 321, + 323, + 347, + 375, + 377, + 387, + 389, + 431, + 438, + 442, + 458, + 462, + 464, + 489, + 519, + 522, + 553, + 562, + 588, + 595 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/cobweb.md b/book/_build/html/_sources/cobweb.md new file mode 100644 index 0000000..31d7181 --- /dev/null +++ b/book/_build/html/_sources/cobweb.md @@ -0,0 +1,598 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.16.2 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +(cobweb)= +# The Cobweb Model + +The cobweb model is a model of prices and quantities in a given market, and how they evolve over time. + +## Overview + +The cobweb model dates back to the 1930s and, while simple, it remains significant +because it shows the fundamental importance of *expectations*. + +To give some idea of how the model operates, and why expectations matter, imagine the following scenario. + +There is a market for soybeans, say, where prices and traded quantities +depend on the choices of buyers and sellers. + +The buyers are represented by a demand curve --- they buy more at low prices +and less at high prices. + +The sellers have a supply curve --- they wish to sell more at high prices and +less at low prices. + +However, the sellers (who are farmers) need time to grow their crops. + +Suppose now that the price is currently high. + +Seeing this high price, and perhaps expecting that the high price will remain +for some time, the farmers plant many fields with soybeans. + +Next period the resulting high supply floods the market, causing the price to drop. + +Seeing this low price, the farmers now shift out of soybeans, restricting +supply and causing the price to climb again. + +You can imagine how these dynamics could cause cycles in prices and quantities +that persist over time. + +The cobweb model puts these ideas into equations so we can try to quantify +them, and to study conditions under which cycles persist (or disappear). + +In this lecture, we investigate and simulate the basic model under different +assumptions regarding the way that producers form expectations. + +Our discussion and simulations draw on [high quality lectures](https://comp-econ.org/CEF_2013/downloads/Complex%20Econ%20Systems%20Lecture%20II.pdf) by [Cars Hommes](https://www.uva.nl/en/profile/h/o/c.h.hommes/c.h.hommes.html). + +We will use the following imports. + +```{code-cell} ipython3 +import numpy as np +import matplotlib.pyplot as plt +``` + +## History + +Early papers on the cobweb cycle include {cite}`cobweb_model` and {cite}`hog_cycle`. + +The paper {cite}`hog_cycle` uses the cobweb theorem to explain the prices of hog in the US over 1920--1950. + +The next plot replicates part of Figure 2 from that paper, which plots the price of hogs at yearly frequency. + +Notice the cyclical price dynamics, which match the kind of cyclical soybean price dynamics discussed above. + +```{code-cell} ipython3 +hog_prices = [55, 57, 80, 70, 60, 65, 72, 65, 51, 49, 45, 80, 85, + 78, 80, 68, 52, 65, 83, 78, 60, 62, 80, 87, 81, 70, + 69, 65, 62, 85, 87, 65, 63, 75, 80, 62] +years = np.arange(1924, 1960) +fig, ax = plt.subplots() +ax.plot(years, hog_prices, '-o', ms=4, label='hog price') +ax.set_xlabel('year') +ax.set_ylabel('dollars') +ax.legend() +ax.grid() +plt.show() +``` + +## The model + +Let's return to our discussion of a hypothetical soybean market, where price is determined by supply and demand. + +We suppose that demand for soybeans is given by + +$$ + D(p_t) = a - b p_t +$$ + +where $a, b$ are nonnegative constants and $p_t$ is the spot (i.e, current market) price at time $t$. + +($D(p_t)$ is the quantity demanded in some fixed unit, such as thousands of tons.) + +Because the crop of soybeans for time $t$ is planted at $t-1$, supply of soybeans at time $t$ depends on *expected* prices at time $t$, which we denote $p^e_t$. + +We suppose that supply is nonlinear in expected prices, and takes the form + +$$ + S(p^e_t) = \tanh(\lambda(p^e_t - c)) + d +$$ + +where $\lambda$ is a positive constant, $c, d$ are nonnegative constants and $\tanh$ is a type of [hyperbolic function](https://en.wikipedia.org/wiki/Hyperbolic_functions). + +Let's make a plot of supply and demand for particular choices of the parameter values. + +First we store the parameters in a class and define the functions above as methods. + +```{code-cell} ipython3 +class Market: + + def __init__(self, + a=8, # demand parameter + b=1, # demand parameter + c=6, # supply parameter + d=1, # supply parameter + λ=2.0): # supply parameter + self.a, self.b, self.c, self.d = a, b, c, d + self.λ = λ + + def demand(self, p): + a, b = self.a, self.b + return a - b * p + + def supply(self, p): + c, d, λ = self.c, self.d, self.λ + return np.tanh(λ * (p - c)) + d +``` + +Now let's plot. + +```{code-cell} ipython3 +p_grid = np.linspace(5, 8, 200) +m = Market() +fig, ax = plt.subplots() + +ax.plot(p_grid, m.demand(p_grid), label="$D$") +ax.plot(p_grid, m.supply(p_grid), label="$S$") +ax.set_xlabel("price") +ax.set_ylabel("quantity") +ax.legend() + +plt.show() +``` + +Market equilibrium requires that supply equals demand, or + +$$ + a - b p_t = S(p^e_t) +$$ + +Rewriting in terms of $p_t$ gives + +$$ + p_t = - \frac{1}{b} [S(p^e_t) - a] +$$ + +Finally, to complete the model, we need to describe how price expectations are formed. + +We will assume that expected prices at time $t$ depend on past prices. + +In particular, we suppose that + +```{math} +:label: p_et + p^e_t = f(p_{t-1}, p_{t-2}) +``` + +where $f$ is some function. + +Thus, we are assuming that producers expect the time-$t$ price to be some function of lagged prices, up to $2$ lags. + +(We could of course add additional lags and readers are encouraged to experiment with such cases.) + +Combining the last two equations gives the dynamics for prices: + +```{math} +:label: price_t + p_t = - \frac{1}{b} [ S(f(p_{t-1}, p_{t-2})) - a] +``` + +The price dynamics depend on the parameter values and also on the function $f$ that determines how producers form expectations. + +## Naive expectations + +To go further in our analysis we need to specify the function $f$; that is, how expectations are formed. + +Let's start with naive expectations, which refers to the case where producers expect the next period spot price to be whatever the price is in the current period. + +In other words, + +$$ +p_t^e = p_{t-1} +$$ + +Using {eq}`price_t`, we then have + +$$ + p_t = - \frac{1}{b} [ S(p_{t-1}) - a] +$$ + +We can write this as + +$$ + p_t = g(p_{t-1}) +$$ + +where $g$ is the function defined by + +```{math} +:label: def_g + g(p) = - \frac{1}{b} [ S(p) - a] +``` + +Here we represent the function $g$ + +```{code-cell} ipython3 +def g(model, current_price): + """ + Function to find the next price given the current price + and Market model + """ + a, b = model.a, model.b + next_price = - (model.supply(current_price) - a) / b + return next_price +``` + +Let's try to understand how prices will evolve using a 45-degree diagram, which is a tool for studying one-dimensional dynamics. + +The function `plot45` defined below helps us draw the 45-degree diagram. + +```{code-cell} ipython3 +:tags: [hide-input] + +def plot45(model, pmin, pmax, p0, num_arrows=5): + """ + Function to plot a 45 degree plot + + Parameters + ========== + + model: Market model + + pmin: Lower price limit + + pmax: Upper price limit + + p0: Initial value of price (needed to simulate prices) + + num_arrows: Number of simulations to plot + """ + pgrid = np.linspace(pmin, pmax, 200) + + fig, ax = plt.subplots() + ax.set_xlim(pmin, pmax) + ax.set_ylim(pmin, pmax) + + hw = (pmax - pmin) * 0.01 + hl = 2 * hw + arrow_args = dict(fc="k", ec="k", head_width=hw, + length_includes_head=True, lw=1, + alpha=0.6, head_length=hl) + + ax.plot(pgrid, g(model, pgrid), 'b-', + lw=2, alpha=0.6, label='g') + ax.plot(pgrid, pgrid, lw=1, alpha=0.7, label='$45\degree$') + + x = p0 + xticks = [pmin] + xtick_labels = [pmin] + + for i in range(num_arrows): + if i == 0: + ax.arrow(x, 0.0, 0.0, g(model, x), + **arrow_args) + else: + ax.arrow(x, x, 0.0, g(model, x) - x, + **arrow_args) + ax.plot((x, x), (0, x), ls='dotted') + + ax.arrow(x, g(model, x), + g(model, x) - x, 0, **arrow_args) + xticks.append(x) + xtick_labels.append(r'$p_{}$'.format(str(i))) + + x = g(model, x) + xticks.append(x) + xtick_labels.append(r'$p_{}$'.format(str(i+1))) + ax.plot((x, x), (0, x), '->', alpha=0.5, color='orange') + + xticks.append(pmax) + xtick_labels.append(pmax) + ax.set_ylabel(r'$p_{t+1}$') + ax.set_xlabel(r'$p_t$') + ax.set_xticks(xticks) + ax.set_yticks(xticks) + ax.set_xticklabels(xtick_labels) + ax.set_yticklabels(xtick_labels) + + bbox = (0., 1.04, 1., .104) + legend_args = {'bbox_to_anchor': bbox, 'loc': 'upper right'} + + ax.legend(ncol=2, frameon=False, **legend_args, fontsize=14) + plt.show() +``` + +Now we can set up a market and plot the 45-degree diagram. + +```{code-cell} ipython3 +m = Market() +``` + +```{code-cell} ipython3 +plot45(m, 0, 9, 2, num_arrows=3) +``` + +The plot shows the function $g$ defined in {eq}`def_g` and the 45-degree line. + +Think of $ p_t $ as a value on the horizontal axis. + +Since $p_{t+1} = g(p_t)$, we use the graph of $g$ to see $p_{t+1}$ on the vertical axis. + +Clearly, + +- If $ g $ lies above the 45-degree line at $p_t$, then we have $ p_{t+1} > p_t $. +- If $ g $ lies below the 45-degree line at $p_t$, then we have $ p_{t+1} < p_t $. +- If $ g $ hits the 45-degree line at $p_t$, then we have $ p_{t+1} = p_t $, so $ p_t $ is a steady state. + +Consider the sequence of prices starting at $p_0$, as shown in the figure. + +We find $p_1$ on the vertical axis and then shift it to the horizontal axis using the 45-degree line (where values on the two axes are equal). + +Then from $p_1$ we obtain $p_2$ and continue. + +We can see the start of a cycle. + +To confirm this, let's plot a time series. + +```{code-cell} ipython3 +def ts_plot_price(model, # Market model + p0, # Initial price + y_a=3, y_b= 12, # Controls y-axis + ts_length=10): # Length of time series + """ + Function to simulate and plot the time series of price. + + """ + fig, ax = plt.subplots() + ax.set_xlabel(r'$t$', fontsize=12) + ax.set_ylabel(r'$p_t$', fontsize=12) + p = np.empty(ts_length) + p[0] = p0 + for t in range(1, ts_length): + p[t] = g(model, p[t-1]) + ax.plot(np.arange(ts_length), + p, + 'bo-', + alpha=0.6, + lw=2, + label=r'$p_t$') + ax.legend(loc='best', fontsize=10) + ax.set_ylim(y_a, y_b) + ax.set_xticks(np.arange(ts_length)) + plt.show() +``` + +```{code-cell} ipython3 +ts_plot_price(m, 4, ts_length=15) +``` + +We see that a cycle has formed and the cycle is persistent. + +(You can confirm this by plotting over a longer time horizon.) + +The cycle is "stable", in the sense that prices converge to it from most starting conditions. + +For example, + +```{code-cell} ipython3 +ts_plot_price(m, 10, ts_length=15) +``` + +## Adaptive expectations + +Naive expectations are quite simple and also important in driving the cycle that we found. + +What if expectations are formed in a different way? + +Next we consider adaptive expectations. + +This refers to the case where producers form expectations for +the next period price as a weighted average of their last guess and the +current spot price. + +That is, + +```{math} +:label: pe_adaptive +p_t^e = \alpha p_{t-1} + (1-\alpha) p^e_{t-1} +\qquad (0 \leq \alpha \leq 1) +``` + +Another way to write this is + +```{math} +:label: pe_adaptive_2 +p_t^e = p^e_{t-1} + \alpha (p_{t-1} - p_{t-1}^e) +``` + +This equation helps to show that expectations shift + +1. up when prices last period were above expectations +1. down when prices last period were below expectations + +Using {eq}`pe_adaptive`, we obtain the dynamics + +$$ + p_t = - \frac{1}{b} [ S(\alpha p_{t-1} + (1-\alpha) p^e_{t-1}) - a] +$$ + +Let's try to simulate the price and observe the dynamics using different values of $\alpha$. + +```{code-cell} ipython3 +def find_next_price_adaptive(model, curr_price_exp): + """ + Function to find the next price given the current price expectation + and Market model + """ + return - (model.supply(curr_price_exp) - model.a) / model.b +``` + +The function below plots price dynamics under adaptive expectations for different values of $\alpha$. + +```{code-cell} ipython3 +def ts_price_plot_adaptive(model, p0, ts_length=10, α=[1.0, 0.9, 0.75]): + fig, axs = plt.subplots(1, len(α), figsize=(12, 5)) + for i_plot, a in enumerate(α): + pe_last = p0 + p_values = np.empty(ts_length) + p_values[0] = p0 + for i in range(1, ts_length): + p_values[i] = find_next_price_adaptive(model, pe_last) + pe_last = a*p_values[i] + (1 - a)*pe_last + + axs[i_plot].plot(np.arange(ts_length), p_values) + axs[i_plot].set_title(r'$\alpha={}$'.format(a)) + axs[i_plot].set_xlabel('t') + axs[i_plot].set_ylabel('price') + plt.show() +``` + +Let's call the function with prices starting at $p_0 = 5$. + +```{code-cell} ipython3 +ts_price_plot_adaptive(m, 5, ts_length=30) +``` + +Note that if $\alpha=1$, then adaptive expectations are just naive expectation. + +Decreasing the value of $\alpha$ shifts more weight to the previous +expectations, which stabilizes expected prices. + +This increased stability can be seen in the figures. + +## Exercises + +```{exercise-start} +:label: cobweb_ex1 +``` +Using the default `Market` class and naive expectations, plot a time series simulation of supply (rather than the price). + +Show, in particular, that supply also cycles. + +```{exercise-end} +``` + +```{solution-start} cobweb_ex1 +:class: dropdown +``` + +```{code-cell} ipython3 +def ts_plot_supply(model, p0, ts_length=10): + """ + Function to simulate and plot the supply function + given the initial price. + """ + pe_last = p0 + s_values = np.empty(ts_length) + for i in range(ts_length): + # store quantity + s_values[i] = model.supply(pe_last) + # update price + pe_last = - (s_values[i] - model.a) / model.b + + + fig, ax = plt.subplots() + ax.plot(np.arange(ts_length), + s_values, + 'bo-', + alpha=0.6, + lw=2, + label=r'supply') + + ax.legend(loc='best', fontsize=10) + ax.set_xticks(np.arange(ts_length)) + ax.set_xlabel("time") + ax.set_ylabel("quantity") + plt.show() +``` + +```{code-cell} ipython3 +m = Market() +ts_plot_supply(m, 5, 15) +``` + +```{solution-end} +``` + +```{exercise-start} +:label: cobweb_ex2 +``` +**Backward looking average expectations** + +Backward looking average expectations refers to the case where producers form +expectations for the next period price as a linear combination of their last +guess and the second last guess. + +That is, + +```{math} +:label: pe_blae +p_t^e = \alpha p_{t-1} + (1-\alpha) p_{t-2} +``` + + +Simulate and plot the price dynamics for $\alpha \in \{0.1, 0.3, 0.5, 0.8\}$ where $p_0=1$ and $p_1=2.5$. + +```{exercise-end} +``` + +```{solution-start} cobweb_ex2 +:class: dropdown +``` + +```{code-cell} ipython3 +def find_next_price_blae(model, curr_price_exp): + """ + Function to find the next price given the current price expectation + and Market model + """ + return - (model.supply(curr_price_exp) - model.a) / model.b +``` + +```{code-cell} ipython3 +def ts_plot_price_blae(model, p0, p1, alphas, ts_length=15): + """ + Function to simulate and plot the time series of price + using backward looking average expectations. + """ + fig, axes = plt.subplots(len(alphas), 1, figsize=(8, 16)) + + for ax, a in zip(axes.flatten(), alphas): + p = np.empty(ts_length) + p[0] = p0 + p[1] = p1 + for t in range(2, ts_length): + pe = a*p[t-1] + (1 - a)*p[t-2] + p[t] = -(model.supply(pe) - model.a) / model.b + ax.plot(np.arange(ts_length), + p, + 'o-', + alpha=0.6, + label=r'$\alpha={}$'.format(a)) + ax.legend(loc='best', fontsize=10) + ax.set_xlabel(r'$t$', fontsize=12) + ax.set_ylabel(r'$p_t$', fontsize=12) + plt.show() +``` + +```{code-cell} ipython3 +m = Market() +ts_plot_price_blae(m, + p0=5, + p1=6, + alphas=[0.1, 0.3, 0.5, 0.8], + ts_length=20) +``` + +```{solution-end} +``` \ No newline at end of file diff --git a/content/lectures/commod_price.ipynb b/book/_build/html/_sources/commod_price.ipynb similarity index 75% rename from content/lectures/commod_price.ipynb rename to book/_build/html/_sources/commod_price.ipynb index 2fc34ac..2ffa39e 100644 --- a/content/lectures/commod_price.ipynb +++ b/book/_build/html/_sources/commod_price.ipynb @@ -2,16 +2,38 @@ "cells": [ { "cell_type": "markdown", - "id": "7bb16ff2", + "id": "f5bf384a", "metadata": {}, "source": [ + "# Commodity Prices\n", + "\n", + "## Outline\n", + "\n", + "For more than half of all countries around the globe, [commodities](https://en.wikipedia.org/wiki/Commodity) account for [the majority of total exports](https://unctad.org/publication/commodities-and-development-report-2019).\n", + "\n", + "Examples of commodities include copper, diamonds, iron ore, lithium, cotton\n", + "and coffee beans.\n", + "\n", + "In this lecture we give an introduction to the theory of commodity prices.\n", + "\n", + "The lecture is quite advanced relative to other lectures in this series.\n", + "\n", + "We need to compute an equilibrium, and that equilibrium is described by a\n", + "price function.\n", + "\n", + "We will solve an equation where the price function is the unknown.\n", + "\n", + "This is harder than solving an equation for an unknown number, or vector.\n", + "\n", + "The lecture will discuss one way to solve a [functional equation](https://en.wikipedia.org/wiki/Functional_equation) (an equation where the unknown object is a function).\n", + "\n", "For this lecture we need the `yfinance` library." ] }, { "cell_type": "code", "execution_count": null, - "id": "305a3ccb", + "id": "9282e9a6", "metadata": { "tags": [ "hide-output" @@ -19,23 +41,38 @@ }, "outputs": [], "source": [ - "%pip install yfinance " + "%pip install yfinance" ] }, { "cell_type": "markdown", - "id": "5220e7d9", + "id": "d055da4e", "metadata": {}, "source": [ - "# Commodity Prices\n", - "\n", - "For more than half of all countries around the globe, [commodities](https://en.wikipedia.org/wiki/Commodity) account for [the majority of total exports](https://unctad.org/publication/commodities-and-development-report-2019).\n", - "\n", - "\n", - "Examples of commodities include copper, diamonds, iron ore, lithium, cotton\n", - "and coffee beans.\n", - "\n", - "In this lecture we give an introduction to the theory of commodity prices.\n", + "We will use the following imports" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e864be1a", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import yfinance as yf\n", + "import matplotlib.pyplot as plt\n", + "from scipy.interpolate import interp1d\n", + "from scipy.optimize import brentq\n", + "from scipy.stats import beta" + ] + }, + { + "cell_type": "markdown", + "id": "f297f038", + "metadata": {}, + "source": [ + "## Data\n", "\n", "The figure below shows the price of cotton in USD since the start of 2016." ] @@ -43,7 +80,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9bdd0c3c", + "id": "3b2a6712", "metadata": { "tags": [ "hide-input", @@ -52,15 +89,13 @@ }, "outputs": [], "source": [ - "import yfinance as yf\n", - "import matplotlib.pyplot as plt\n", - "s = yf.download('CT=F', '2016-1-1', '2023-4-1')['Adj Close']" + "s = yf.download('CT=F', '2016-1-1', '2023-4-1')['Close']" ] }, { "cell_type": "code", "execution_count": null, - "id": "a557e960", + "id": "d2cd3321", "metadata": { "tags": [ "hide-input" @@ -71,7 +106,7 @@ "fig, ax = plt.subplots()\n", "\n", "ax.plot(s, marker='o', alpha=0.5, ms=1)\n", - "ax.set_ylabel('price', fontsize=12)\n", + "ax.set_ylabel('cotton price in USD', fontsize=12)\n", "ax.set_xlabel('date', fontsize=12)\n", "\n", "plt.show()" @@ -79,27 +114,34 @@ }, { "cell_type": "markdown", - "id": "24e1b6f6", + "id": "1bc50faa", "metadata": {}, "source": [ "The figure shows surprisingly large movements in the price of cotton.\n", "\n", - "In general, prices depend on the choices and actions of suppliers, consumers and\n", - "speculators.\n", + "What causes these movements?\n", + "\n", + "In general, prices depend on the choices and actions of \n", + "\n", + "1. suppliers, \n", + "2. consumers, and\n", + "3. speculators.\n", "\n", - "Our focus will be on the interaction between these parties, viewed through the\n", - "lens of the standard competitive storage model \n", + "Our focus will be on the interaction between these parties. \n", + "\n", + "We will connect them together in a dynamic model of supply and demand, called\n", + "the *competitive storage model*.\n", "\n", "This model was developed by\n", - "{cite}`samuelson1971stochastic`, \n", + "{cite}`samuelson1971stochastic`,\n", "{cite}`wright1982economic`, {cite}`scheinkman1983simple`,\n", "{cite}`deaton1992on`, {cite}`deaton1996competitive`, and\n", "{cite}`chambers1996theory`.\n", "\n", "\n", "\n", - "## Outline\n", "\n", + "## The competitive storage model\n", "\n", "In the competitive storage model, commodities are assets that\n", "\n", @@ -114,7 +156,7 @@ "These days, goods such as basic computer chips and integrated circuits are\n", "often treated as commodities in financial markets, being highly standardized,\n", "and, for these kinds of commodities, the word \"harvest\" is not\n", - "appropriate. \n", + "appropriate.\n", "\n", "Nonetheless, we maintain it for simplicity.\n", "```\n", @@ -124,51 +166,27 @@ "It is a function of the current state (which determines\n", "current harvests and predicts future harvests).\n", "\n", - "We begin with the following imports" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "16b0569c", - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from numba import jit, vectorize\n", - "from scipy.interpolate import interp1d\n", - "from scipy.optimize import minimize_scalar, brentq\n", - "from scipy.stats import beta" - ] - }, - { - "cell_type": "markdown", - "id": "21c01171", - "metadata": {}, - "source": [ - "## The Model\n", + "\n", + "\n", + "## The model\n", "\n", "Consider a market for a single commodity, whose price is given at $t$ by\n", - "$p_t$. \n", + "$p_t$.\n", "\n", "The harvest of the commodity at time $t$ is $Z_t$.\n", "\n", - "We assume that the sequence $\\{ Z_t \\}_{t \\geq 1}$ is IID with common\n", - "density function $\\phi$. \n", - "\n", - "The harvests take values in $S$, a subset of the nonnegative numbers.\n", + "We assume that the sequence $\\{ Z_t \\}_{t \\geq 1}$ is IID with common density function $\\phi$, where $\\phi$ is nonnegative.\n", "\n", "Speculators can store the commodity between periods, with $I_t$ units\n", "purchased in the current period yielding $\\alpha I_t$ units in the next.\n", "\n", - "Here $\\alpha \\in (0,1)$ is a depreciation rate for the commodity. \n", + "Here the parameter $\\alpha \\in (0,1)$ is a depreciation rate for the commodity.\n", "\n", "For simplicity, the risk free interest rate is taken to be\n", - "zero, so expected profit on purchasing $I_t$ units is \n", + "zero, so expected profit on purchasing $I_t$ units is\n", "\n", "$$\n", - " \\mathbb{E}_t \\, p_{t+1} \\cdot \\alpha I_t - p_t I_t \n", + " \\mathbb{E}_t \\, p_{t+1} \\cdot \\alpha I_t - p_t I_t\n", " = (\\alpha \\mathbb{E}_t \\, p_{t+1} - p_t) I_t\n", "$$\n", "\n", @@ -187,7 +205,7 @@ "Speculators are assumed to be risk neutral, which means that they buy the\n", "commodity whenever expected profits are positive.\n", "\n", - "As a consequence, if expected prices are positive, then the market is not in\n", + "As a consequence, if expected profits are positive, then the market is not in\n", "equilibrium.\n", "\n", "Hence, to be in equilibrium, prices must satisfy the \"no-arbitrage\"\n", @@ -197,6 +215,7 @@ " \\alpha \\mathbb{E}_t \\, p_{t+1} - p_t \\leq 0\n", "$$ (eq:arbi)\n", "\n", + "This means that if the expected price is lower than the current price, there is no room for arbitrage.\n", "\n", "Profit maximization gives the additional condition\n", "\n", @@ -205,7 +224,7 @@ "$$ (eq:pmco)\n", "\n", "\n", - "We also require that the market clears in each period. \n", + "We also require that the market clears, with supply equaling demand in each period.\n", "\n", "We assume that consumers generate demand quantity $D(p)$ corresponding to\n", "price $p$.\n", @@ -215,15 +234,15 @@ "\n", "Regarding quantities,\n", "\n", - "* supply is the sum of carryover by speculators and the current harvest\n", - "* demand is the sum of purchases by consumers and purchases by speculators. \n", + "* supply is the sum of carryover by speculators and the current harvest, and\n", + "* demand is the sum of purchases by consumers and purchases by speculators.\n", "\n", "Mathematically,\n", "\n", - "* supply $ = X_t = \\alpha I_{t-1} + Z_t$ \n", - "* demand $ = D(p_t) + I_t$ \n", + "* supply is given by $X_t = \\alpha I_{t-1} + Z_t$, which takes values in $S := \\mathbb R_+$, while\n", + "* demand $ = D(p_t) + I_t$\n", "\n", - "Thus, the market equilibrium condition is \n", + "Thus, the market equilibrium condition is\n", "\n", "$$\n", " \\alpha I_{t-1} + Z_t = D(p_t) + I_t\n", @@ -237,14 +256,16 @@ "\n", "### An equilibrium function\n", "\n", - "Now to find an equilibrium? \n", + "How can we find an equilibrium?\n", "\n", "Our path of attack will be to seek a system of prices that depend only on the\n", "current state.\n", "\n", - "In other words, we take a function $p$ on $S$ and set $p_t = p(X_t)$ for every $t$. \n", + "(Our solution method involves using an [ansatz](https://en.wikipedia.org/wiki/Ansatz), which is an educated guess --- in this case for the price function.)\n", + "\n", + "In other words, we take a function $p$ on $S$ and set $p_t = p(X_t)$ for every $t$.\n", "\n", - "Prices and quantities then follow \n", + "Prices and quantities then follow\n", "\n", "$$\n", " p_t = p(X_t), \\quad I_t = X_t - D(p_t), \\quad X_{t+1} = \\alpha I_t + Z_{t+1}\n", @@ -257,11 +278,9 @@ "More precisely, we seek a $p$ such that [](eq:arbi) and [](eq:pmco) hold for\n", "the corresponding system [](eq:eosy).\n", "\n", - "To this end, suppose that there exists a function $p^*$ on $S$\n", - "satisfying\n", "\n", "$$\n", - " p^*(x) = \\max \n", + " p^*(x) = \\max\n", " \\left\\{\n", " \\alpha \\int_0^\\infty p^*(\\alpha I(x) + z) \\phi(z)dz, P(x)\n", " \\right\\}\n", @@ -276,14 +295,14 @@ "$$ (eq:einvf)\n", "\n", "It turns out that such a $p^*$ will suffice, in the sense that [](eq:arbi)\n", - "and [](eq:pmco) hold for the corresponding system [](eq:eosy). \n", + "and [](eq:pmco) hold for the corresponding system [](eq:eosy).\n", "\n", - "To see this, observe first that \n", + "To see this, observe first that\n", "\n", "$$\n", " \\mathbb{E}_t \\, p_{t+1}\n", - " = \\mathbb{E}_t \\, p^*(X_{t+1}) \n", - " = \\mathbb{E}_t \\, p^*(\\alpha I(X_t) + Z_{t+1}) \n", + " = \\mathbb{E}_t \\, p^*(X_{t+1})\n", + " = \\mathbb{E}_t \\, p^*(\\alpha I(X_t) + Z_{t+1})\n", " = \\int_0^\\infty p^*(\\alpha I(X_t) + z) \\phi(z)dz\n", "$$\n", "\n", @@ -292,10 +311,10 @@ "$$\n", " \\alpha \\int_0^\\infty p^*(\\alpha I(X_t) + z) \\phi(z)dz \\leq p^*(X_t)\n", "$$\n", - " \n", - "This inequality is immediate from [](eq:dopf). \n", "\n", - "Second, regarding [](eq:pmco), suppose that \n", + "This inequality is immediate from [](eq:dopf).\n", + "\n", + "Second, regarding [](eq:pmco), suppose that\n", "\n", "$$\n", " \\alpha \\int_0^\\infty p^*(\\alpha I(X_t) + z) \\phi(z)dz < p^*(X_t)\n", @@ -303,11 +322,11 @@ "\n", "Then by [](eq:dopf) we have $p^*(X_t) = P(X_t)$\n", "\n", - "But then $D(p^*(X_t)) = X_t$ and $I_t = I(X_t) = 0$. \n", + "But then $D(p^*(X_t)) = X_t$ and $I_t = I(X_t) = 0$.\n", "\n", - "As a consequence, both [](eq:arbi) and [](eq:pmco) hold. \n", + "As a consequence, both [](eq:arbi) and [](eq:pmco) hold.\n", "\n", - "We have found an equilibrium.\n", + "We have found an equilibrium, which verifies the ansatz.\n", "\n", "\n", "### Computing the equilibrium\n", @@ -336,16 +355,16 @@ "This leads us to the update rule\n", "\n", "$$\n", - " p_{k+1}(x) = \\max \n", + " p_{k+1}(x) = \\max\n", " \\left\\{\n", " \\alpha \\int_0^\\infty p_k(\\alpha ( x - D(p_{k+1}(x))) + z) \\phi(z)dz, P(x)\n", " \\right\\}\n", "$$ (eq:dopf2)\n", "\n", - "In other words, we take $p_k$ as given and, at each $x$, solve for $q$ in \n", + "In other words, we take $p_k$ as given and, at each $x$, solve for $q$ in\n", "\n", "$$\n", - " q = \\max \n", + " q = \\max\n", " \\left\\{\n", " \\alpha \\int_0^\\infty p_k(\\alpha ( x - D(q)) + z) \\phi(z)dz, P(x)\n", " \\right\\}\n", @@ -356,7 +375,7 @@ "\n", "Then we get the corresponding values $q_1, \\ldots, q_n$.\n", "\n", - "Then we compute $p_{k+1}$ as the linear interpolation of \n", + "Then we compute $p_{k+1}$ as the linear interpolation of\n", "the values $q_1, \\ldots, q_n$ over the grid $x_1, \\ldots, x_n$.\n", "\n", "Then we repeat, seeking convergence.\n", @@ -369,17 +388,17 @@ "The distribution $\\phi$ is set to a shifted Beta distribution (although many\n", "other choices are possible).\n", "\n", - "The integral in [](eq:dopf3) is computed via Monte Carlo." + "The integral in [](eq:dopf3) is computed via {ref}`Monte Carlo `." ] }, { "cell_type": "code", "execution_count": null, - "id": "f7dec601", + "id": "8b3999b5", "metadata": {}, "outputs": [], "source": [ - "α, a, c = 0.8, 1.0, 2.0 \n", + "α, a, c = 0.8, 1.0, 2.0\n", "beta_a, beta_b = 5, 5\n", "mc_draw_size = 250\n", "gridsize = 150\n", @@ -388,7 +407,7 @@ "\n", "beta_dist = beta(5, 5)\n", "Z = a + beta_dist.rvs(mc_draw_size) * c # Shock observations\n", - "D = P = lambda x: 1.0 / x \n", + "D = P = lambda x: 1.0 / x\n", "tol = 1e-4\n", "\n", "\n", @@ -397,8 +416,8 @@ " new_p = np.empty_like(p_array)\n", "\n", " # Interpolate to obtain p as a function.\n", - " p = interp1d(grid, \n", - " p_array, \n", + " p = interp1d(grid,\n", + " p_array,\n", " fill_value=(p_array[0], p_array[-1]),\n", " bounds_error=False)\n", "\n", @@ -423,14 +442,15 @@ "\n", "ax.plot(grid, price, 'k-', alpha=0.5, lw=2, label=r'$p^*$')\n", "ax.legend()\n", - "ax.set_xlabel('$x$', fontsize=12)\n", + "ax.set_xlabel('$x$')\n", + "ax.set_ylabel(\"prices\")\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "95aaa990", + "id": "8899a9b6", "metadata": {}, "source": [ "The figure above shows the inverse demand curve $P$, which is also $p_0$, as\n", @@ -443,13 +463,13 @@ { "cell_type": "code", "execution_count": null, - "id": "ab9484f0", + "id": "285e9877", "metadata": {}, "outputs": [], "source": [ "# Turn the price array into a price function\n", - "p_star = interp1d(grid, \n", - " price, \n", + "p_star = interp1d(grid,\n", + " price,\n", " fill_value=(price[0], price[-1]),\n", " bounds_error=False)\n", "\n", @@ -473,12 +493,31 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 10, + 39, + 42, + 47, + 54, + 60, + 66, + 76, + 352, + 401, + 410 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/commod_price.md b/book/_build/html/_sources/commod_price.md new file mode 100644 index 0000000..48fb38d --- /dev/null +++ b/book/_build/html/_sources/commod_price.md @@ -0,0 +1,433 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + + + + +# Commodity Prices + +## Outline + +For more than half of all countries around the globe, [commodities](https://en.wikipedia.org/wiki/Commodity) account for [the majority of total exports](https://unctad.org/publication/commodities-and-development-report-2019). + +Examples of commodities include copper, diamonds, iron ore, lithium, cotton +and coffee beans. + +In this lecture we give an introduction to the theory of commodity prices. + +The lecture is quite advanced relative to other lectures in this series. + +We need to compute an equilibrium, and that equilibrium is described by a +price function. + +We will solve an equation where the price function is the unknown. + +This is harder than solving an equation for an unknown number, or vector. + +The lecture will discuss one way to solve a [functional equation](https://en.wikipedia.org/wiki/Functional_equation) (an equation where the unknown object is a function). + +For this lecture we need the `yfinance` library. + +```{code-cell} ipython3 +:tags: [hide-output] +%pip install yfinance +``` + +We will use the following imports + + +```{code-cell} ipython3 +import numpy as np +import yfinance as yf +import matplotlib.pyplot as plt +from scipy.interpolate import interp1d +from scipy.optimize import brentq +from scipy.stats import beta +``` + +## Data + +The figure below shows the price of cotton in USD since the start of 2016. + +```{code-cell} ipython3 +:tags: [hide-input, hide-output] + +s = yf.download('CT=F', '2016-1-1', '2023-4-1')['Close'] +``` + +```{code-cell} ipython3 +:tags: [hide-input] + +fig, ax = plt.subplots() + +ax.plot(s, marker='o', alpha=0.5, ms=1) +ax.set_ylabel('cotton price in USD', fontsize=12) +ax.set_xlabel('date', fontsize=12) + +plt.show() +``` + +The figure shows surprisingly large movements in the price of cotton. + +What causes these movements? + +In general, prices depend on the choices and actions of + +1. suppliers, +2. consumers, and +3. speculators. + +Our focus will be on the interaction between these parties. + +We will connect them together in a dynamic model of supply and demand, called +the *competitive storage model*. + +This model was developed by +{cite}`samuelson1971stochastic`, +{cite}`wright1982economic`, {cite}`scheinkman1983simple`, +{cite}`deaton1992on`, {cite}`deaton1996competitive`, and +{cite}`chambers1996theory`. + + + + +## The competitive storage model + +In the competitive storage model, commodities are assets that + +1. can be traded by speculators and +1. have intrinsic value to consumers. + +Total demand is the sum of consumer demand and demand by speculators. + +Supply is exogenous, depending on "harvests". + +```{note} +These days, goods such as basic computer chips and integrated circuits are +often treated as commodities in financial markets, being highly standardized, +and, for these kinds of commodities, the word "harvest" is not +appropriate. + +Nonetheless, we maintain it for simplicity. +``` + +The equilibrium price is determined competitively. + +It is a function of the current state (which determines +current harvests and predicts future harvests). + + + +## The model + +Consider a market for a single commodity, whose price is given at $t$ by +$p_t$. + +The harvest of the commodity at time $t$ is $Z_t$. + +We assume that the sequence $\{ Z_t \}_{t \geq 1}$ is IID with common density function $\phi$, where $\phi$ is nonnegative. + +Speculators can store the commodity between periods, with $I_t$ units +purchased in the current period yielding $\alpha I_t$ units in the next. + +Here the parameter $\alpha \in (0,1)$ is a depreciation rate for the commodity. + +For simplicity, the risk free interest rate is taken to be +zero, so expected profit on purchasing $I_t$ units is + +$$ + \mathbb{E}_t \, p_{t+1} \cdot \alpha I_t - p_t I_t + = (\alpha \mathbb{E}_t \, p_{t+1} - p_t) I_t +$$ + + +Here $\mathbb{E}_t \, p_{t+1}$ is the expectation of $p_{t+1}$ taken at time +$t$. + + + +## Equilibrium + +In this section we define the equilibrium and discuss how to compute it. + +### Equilibrium conditions + +Speculators are assumed to be risk neutral, which means that they buy the +commodity whenever expected profits are positive. + +As a consequence, if expected profits are positive, then the market is not in +equilibrium. + +Hence, to be in equilibrium, prices must satisfy the "no-arbitrage" +condition + +$$ + \alpha \mathbb{E}_t \, p_{t+1} - p_t \leq 0 +$$ (eq:arbi) + +This means that if the expected price is lower than the current price, there is no room for arbitrage. + +Profit maximization gives the additional condition + +$$ + \alpha \mathbb{E}_t \, p_{t+1} - p_t < 0 \text{ implies } I_t = 0 +$$ (eq:pmco) + + +We also require that the market clears, with supply equaling demand in each period. + +We assume that consumers generate demand quantity $D(p)$ corresponding to +price $p$. + +Let $P := D^{-1}$ be the inverse demand function. + + +Regarding quantities, + +* supply is the sum of carryover by speculators and the current harvest, and +* demand is the sum of purchases by consumers and purchases by speculators. + +Mathematically, + +* supply is given by $X_t = \alpha I_{t-1} + Z_t$, which takes values in $S := \mathbb R_+$, while +* demand $ = D(p_t) + I_t$ + +Thus, the market equilibrium condition is + +$$ + \alpha I_{t-1} + Z_t = D(p_t) + I_t +$$ (eq:mkeq) + + +The initial condition $X_0 \in S$ is treated as given. + + + + +### An equilibrium function + +How can we find an equilibrium? + +Our path of attack will be to seek a system of prices that depend only on the +current state. + +(Our solution method involves using an [ansatz](https://en.wikipedia.org/wiki/Ansatz), which is an educated guess --- in this case for the price function.) + +In other words, we take a function $p$ on $S$ and set $p_t = p(X_t)$ for every $t$. + +Prices and quantities then follow + +$$ + p_t = p(X_t), \quad I_t = X_t - D(p_t), \quad X_{t+1} = \alpha I_t + Z_{t+1} +$$ (eq:eosy) + + +We choose $p$ so that these prices and quantities satisfy the equilibrium +conditions above. + +More precisely, we seek a $p$ such that [](eq:arbi) and [](eq:pmco) hold for +the corresponding system [](eq:eosy). + + +$$ + p^*(x) = \max + \left\{ + \alpha \int_0^\infty p^*(\alpha I(x) + z) \phi(z)dz, P(x) + \right\} + \qquad (x \in S) +$$ (eq:dopf) + +where + +$$ + I(x) := x - D(p^*(x)) + \qquad (x \in S) +$$ (eq:einvf) + +It turns out that such a $p^*$ will suffice, in the sense that [](eq:arbi) +and [](eq:pmco) hold for the corresponding system [](eq:eosy). + +To see this, observe first that + +$$ + \mathbb{E}_t \, p_{t+1} + = \mathbb{E}_t \, p^*(X_{t+1}) + = \mathbb{E}_t \, p^*(\alpha I(X_t) + Z_{t+1}) + = \int_0^\infty p^*(\alpha I(X_t) + z) \phi(z)dz +$$ + +Thus [](eq:arbi) requires that + +$$ + \alpha \int_0^\infty p^*(\alpha I(X_t) + z) \phi(z)dz \leq p^*(X_t) +$$ + +This inequality is immediate from [](eq:dopf). + +Second, regarding [](eq:pmco), suppose that + +$$ + \alpha \int_0^\infty p^*(\alpha I(X_t) + z) \phi(z)dz < p^*(X_t) +$$ + +Then by [](eq:dopf) we have $p^*(X_t) = P(X_t)$ + +But then $D(p^*(X_t)) = X_t$ and $I_t = I(X_t) = 0$. + +As a consequence, both [](eq:arbi) and [](eq:pmco) hold. + +We have found an equilibrium, which verifies the ansatz. + + +### Computing the equilibrium + +We now know that an equilibrium can be obtained by finding a function $p^*$ +that satisfies [](eq:dopf). + +It can be shown that, under mild conditions there is exactly one function on +$S$ satisfying [](eq:dopf). + +Moreover, we can compute this function using successive approximation. + +This means that we start with a guess of the function and then update it using +[](eq:dopf). + +This generates a sequence of functions $p_1, p_2, \ldots$ + +We continue until this process converges, in the sense that $p_k$ and +$p_{k+1}$ are very close together. + +Then we take the final $p_k$ that we computed as our approximation of $p^*$. + +To implement our update step, it is helpful if we put [](eq:dopf) and +[](eq:einvf) together. + +This leads us to the update rule + +$$ + p_{k+1}(x) = \max + \left\{ + \alpha \int_0^\infty p_k(\alpha ( x - D(p_{k+1}(x))) + z) \phi(z)dz, P(x) + \right\} +$$ (eq:dopf2) + +In other words, we take $p_k$ as given and, at each $x$, solve for $q$ in + +$$ + q = \max + \left\{ + \alpha \int_0^\infty p_k(\alpha ( x - D(q)) + z) \phi(z)dz, P(x) + \right\} +$$ (eq:dopf3) + +Actually we can't do this at every $x$, so instead we do it on a grid of +points $x_1, \ldots, x_n$. + +Then we get the corresponding values $q_1, \ldots, q_n$. + +Then we compute $p_{k+1}$ as the linear interpolation of +the values $q_1, \ldots, q_n$ over the grid $x_1, \ldots, x_n$. + +Then we repeat, seeking convergence. + + +## Code + +The code below implements this iterative process, starting from $p_0 = P$. + +The distribution $\phi$ is set to a shifted Beta distribution (although many +other choices are possible). + +The integral in [](eq:dopf3) is computed via {ref}`Monte Carlo `. + + +```{code-cell} ipython3 +α, a, c = 0.8, 1.0, 2.0 +beta_a, beta_b = 5, 5 +mc_draw_size = 250 +gridsize = 150 +grid_max = 35 +grid = np.linspace(a, grid_max, gridsize) + +beta_dist = beta(5, 5) +Z = a + beta_dist.rvs(mc_draw_size) * c # Shock observations +D = P = lambda x: 1.0 / x +tol = 1e-4 + + +def T(p_array): + + new_p = np.empty_like(p_array) + + # Interpolate to obtain p as a function. + p = interp1d(grid, + p_array, + fill_value=(p_array[0], p_array[-1]), + bounds_error=False) + + # Update + for i, x in enumerate(grid): + + h = lambda q: q - max(α * np.mean(p(α * (x - D(q)) + Z)), P(x)) + new_p[i] = brentq(h, 1e-8, 100) + + return new_p + + +fig, ax = plt.subplots() + +price = P(grid) +ax.plot(grid, price, alpha=0.5, lw=1, label="inverse demand curve") +error = tol + 1 +while error > tol: + new_price = T(price) + error = max(np.abs(new_price - price)) + price = new_price + +ax.plot(grid, price, 'k-', alpha=0.5, lw=2, label=r'$p^*$') +ax.legend() +ax.set_xlabel('$x$') +ax.set_ylabel("prices") + +plt.show() +``` + +The figure above shows the inverse demand curve $P$, which is also $p_0$, as +well as our approximation of $p^*$. + +Once we have an approximation of $p^*$, we can simulate a time series of +prices. + + +```{code-cell} ipython3 +# Turn the price array into a price function +p_star = interp1d(grid, + price, + fill_value=(price[0], price[-1]), + bounds_error=False) + +def carry_over(x): + return α * (x - D(p_star(x))) + +def generate_cp_ts(init=1, n=50): + X = np.empty(n) + X[0] = init + for t in range(n-1): + Z = a + c * beta_dist.rvs() + X[t+1] = carry_over(X[t]) + Z + return p_star(X) + +fig, ax = plt.subplots() +ax.plot(generate_cp_ts(), label="price") +ax.set_xlabel("time") +ax.legend() +plt.show() +``` diff --git a/book/_build/html/_sources/complex_and_trig.ipynb b/book/_build/html/_sources/complex_and_trig.ipynb new file mode 100644 index 0000000..7fa2620 --- /dev/null +++ b/book/_build/html/_sources/complex_and_trig.ipynb @@ -0,0 +1,665 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "283d7118", + "metadata": {}, + "source": [ + "(complex_and_trig)=\n", + "```{raw} html\n", + "
\n", + " \n", + " \"QuantEcon\"\n", + " \n", + "
\n", + "```\n", + "\n", + "```{index} single: python\n", + "```\n", + "\n", + "# Complex Numbers and Trigonometry\n", + "\n", + "## Overview\n", + "\n", + "This lecture introduces some elementary mathematics and trigonometry.\n", + "\n", + "Useful and interesting in its own right, these concepts reap substantial rewards when studying dynamics generated\n", + "by linear difference equations or linear differential equations.\n", + "\n", + "For example, these tools are keys to understanding outcomes attained by Paul\n", + "Samuelson (1939) {cite}`Samuelson1939` in his classic paper on interactions\n", + "between the investment accelerator and the Keynesian consumption function, our\n", + "topic in the lecture {doc}`Samuelson Multiplier Accelerator `.\n", + "\n", + "In addition to providing foundations for Samuelson's work and extensions of\n", + "it, this lecture can be read as a stand-alone quick reminder of key results\n", + "from elementary high school trigonometry.\n", + "\n", + "So let's dive in.\n", + "\n", + "### Complex Numbers\n", + "\n", + "A complex number has a **real part** $x$ and a purely **imaginary part** $y$.\n", + "\n", + "The Euclidean, polar, and trigonometric forms of a complex number $z$ are:\n", + "\n", + "$$\n", + "z = x + iy = re^{i\\theta} = r(\\cos{\\theta} + i \\sin{\\theta})\n", + "$$\n", + "\n", + "The second equality above is known as **Euler's formula**\n", + "\n", + "- [Euler](https://en.wikipedia.org/wiki/Leonhard_Euler) contributed many other formulas too!\n", + "\n", + "The complex conjugate $\\bar z$ of $z$ is defined as\n", + "\n", + "$$\n", + "\\bar z = x - iy = r e^{-i \\theta} = r (\\cos{\\theta} - i \\sin{\\theta} )\n", + "$$\n", + "\n", + "The value $x$ is the **real** part of $z$ and $y$ is the\n", + "**imaginary** part of $z$.\n", + "\n", + "The symbol $| z |$ = $\\sqrt{\\bar{z}\\cdot z} = r$ represents the **modulus** of $z$.\n", + "\n", + "The value $r$ is the Euclidean distance of vector $(x,y)$ from the\n", + "origin:\n", + "\n", + "$$\n", + "r = |z| = \\sqrt{x^2 + y^2}\n", + "$$\n", + "\n", + "The value $\\theta$ is the angle of $(x,y)$ with respect to the real axis.\n", + "\n", + "Evidently, the tangent of $\\theta$ is $\\left(\\frac{y}{x}\\right)$.\n", + "\n", + "Therefore,\n", + "\n", + "$$\n", + "\\theta = \\tan^{-1} \\Big( \\frac{y}{x} \\Big)\n", + "$$\n", + "\n", + "Three elementary trigonometric functions are\n", + "\n", + "$$\n", + "\\cos{\\theta} = \\frac{x}{r} = \\frac{e^{i\\theta} + e^{-i\\theta}}{2} , \\quad\n", + "\\sin{\\theta} = \\frac{y}{r} = \\frac{e^{i\\theta} - e^{-i\\theta}}{2i} , \\quad\n", + "\\tan{\\theta} = \\frac{y}{x}\n", + "$$\n", + "\n", + "We'll need the following imports:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8de56cca", + "metadata": {}, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "plt.rcParams[\"figure.figsize\"] = (11, 5) #set default figure size\n", + "import numpy as np\n", + "from sympy import (Symbol, symbols, Eq, nsolve, sqrt, cos, sin, simplify,\n", + " init_printing, integrate)" + ] + }, + { + "cell_type": "markdown", + "id": "5076b051", + "metadata": {}, + "source": [ + "### An Example\n", + "\n", + "```{prf:example}\n", + ":label: ct_ex_com\n", + "\n", + "Consider the complex number $z = 1 + \\sqrt{3} i$.\n", + "\n", + "For $z = 1 + \\sqrt{3} i$, $x = 1$, $y = \\sqrt{3}$.\n", + "\n", + "It follows that $r = 2$ and\n", + "$\\theta = \\tan^{-1}(\\sqrt{3}) = \\frac{\\pi}{3} = 60^o$.\n", + "```\n", + "\n", + "Let's use Python to plot the trigonometric form of the complex number\n", + "$z = 1 + \\sqrt{3} i$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c67cb2a4", + "metadata": {}, + "outputs": [], + "source": [ + "# Abbreviate useful values and functions\n", + "π = np.pi\n", + "\n", + "\n", + "# Set parameters\n", + "r = 2\n", + "θ = π/3\n", + "x = r * np.cos(θ)\n", + "x_range = np.linspace(0, x, 1000)\n", + "θ_range = np.linspace(0, θ, 1000)\n", + "\n", + "# Plot\n", + "fig = plt.figure(figsize=(8, 8))\n", + "ax = plt.subplot(111, projection='polar')\n", + "\n", + "ax.plot((0, θ), (0, r), marker='o', color='b') # Plot r\n", + "ax.plot(np.zeros(x_range.shape), x_range, color='b') # Plot x\n", + "ax.plot(θ_range, x / np.cos(θ_range), color='b') # Plot y\n", + "ax.plot(θ_range, np.full(θ_range.shape, 0.1), color='r') # Plot θ\n", + "\n", + "ax.margins(0) # Let the plot starts at origin\n", + "\n", + "ax.set_title(\"Trigonometry of complex numbers\", va='bottom',\n", + " fontsize='x-large')\n", + "\n", + "ax.set_rmax(2)\n", + "ax.set_rticks((0.5, 1, 1.5, 2)) # Less radial ticks\n", + "ax.set_rlabel_position(-88.5) # Get radial labels away from plotted line\n", + "\n", + "ax.text(θ, r+0.01 , r'$z = x + iy = 1 + \\sqrt{3}\\, i$') # Label z\n", + "ax.text(θ+0.2, 1 , '$r = 2$') # Label r\n", + "ax.text(0-0.2, 0.5, '$x = 1$') # Label x\n", + "ax.text(0.5, 1.2, r'$y = \\sqrt{3}$') # Label y\n", + "ax.text(0.25, 0.15, r'$\\theta = 60^o$') # Label θ\n", + "\n", + "ax.grid(True)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "8a5dd8c8", + "metadata": {}, + "source": [ + "## De Moivre's Theorem\n", + "\n", + "de Moivre's theorem states that:\n", + "\n", + "$$\n", + "(r(\\cos{\\theta} + i \\sin{\\theta}))^n =\n", + "r^n e^{in\\theta} =\n", + "r^n(\\cos{n\\theta} + i \\sin{n\\theta})\n", + "$$\n", + "\n", + "To prove de Moivre's theorem, note that\n", + "\n", + "$$\n", + "(r(\\cos{\\theta} + i \\sin{\\theta}))^n = \\big( re^{i\\theta} \\big)^n\n", + "$$\n", + "\n", + "and compute.\n", + "\n", + "## Applications of de Moivre's Theorem\n", + "\n", + "### Example 1\n", + "\n", + "We can use de Moivre's theorem to show that\n", + "$r = \\sqrt{x^2 + y^2}$.\n", + "\n", + "We have\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "1 &= e^{i\\theta} e^{-i\\theta} \\\\\n", + "&= (\\cos{\\theta} + i \\sin{\\theta})(\\cos{(\\text{-}\\theta)} + i \\sin{(\\text{-}\\theta)}) \\\\\n", + "&= (\\cos{\\theta} + i \\sin{\\theta})(\\cos{\\theta} - i \\sin{\\theta}) \\\\\n", + "&= \\cos^2{\\theta} + \\sin^2{\\theta} \\\\\n", + "&= \\frac{x^2}{r^2} + \\frac{y^2}{r^2}\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "and thus\n", + "\n", + "$$\n", + "x^2 + y^2 = r^2\n", + "$$\n", + "\n", + "We recognize this as a theorem of **Pythagoras**.\n", + "\n", + "### Example 2\n", + "\n", + "Let $z = re^{i\\theta}$ and $\\bar{z} = re^{-i\\theta}$ so that $\\bar{z}$ is the **complex conjugate** of $z$.\n", + "\n", + "$(z, \\bar z)$ form a **complex conjugate pair** of complex numbers.\n", + "\n", + "Let $a = pe^{i\\omega}$ and $\\bar{a} = pe^{-i\\omega}$ be\n", + "another complex conjugate pair.\n", + "\n", + "For each element of a sequence of integers $n = 0, 1, 2, \\ldots, $.\n", + "\n", + "To do so, we can apply de Moivre's formula.\n", + "\n", + "Thus,\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "x_n &= az^n + \\bar{a}\\bar{z}^n \\\\\n", + "&= p e^{i\\omega} (re^{i\\theta})^n + p e^{-i\\omega} (re^{-i\\theta})^n \\\\\n", + "&= pr^n e^{i (\\omega + n\\theta)} + pr^n e^{-i (\\omega + n\\theta)} \\\\\n", + "&= pr^n [\\cos{(\\omega + n\\theta)} + i \\sin{(\\omega + n\\theta)} +\n", + " \\cos{(\\omega + n\\theta)} - i \\sin{(\\omega + n\\theta)}] \\\\\n", + "&= 2 pr^n \\cos{(\\omega + n\\theta)}\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "### Example 3\n", + "\n", + "This example provides machinery that is at the heard of Samuelson's analysis of his multiplier-accelerator model {cite}`Samuelson1939`.\n", + "\n", + "Thus, consider a **second-order linear difference equation**\n", + "\n", + "$$\n", + "x_{n+2} = c_1 x_{n+1} + c_2 x_n\n", + "$$\n", + "\n", + "whose **characteristic polynomial** is\n", + "\n", + "$$\n", + "z^2 - c_1 z - c_2 = 0\n", + "$$\n", + "\n", + "or\n", + "\n", + "$$\n", + "(z^2 - c_1 z - c_2 ) = (z - z_1)(z- z_2) = 0\n", + "$$\n", + "\n", + "has roots $z_1, z_1$.\n", + "\n", + "A **solution** is a sequence $\\{x_n\\}_{n=0}^\\infty$ that satisfies\n", + "the difference equation.\n", + "\n", + "Under the following circumstances, we can apply our example 2 formula to\n", + "solve the difference equation\n", + "\n", + "- the roots $z_1, z_2$ of the characteristic polynomial of the\n", + " difference equation form a complex conjugate pair\n", + "- the values $x_0, x_1$ are given initial conditions\n", + "\n", + "To solve the difference equation, recall from example 2 that\n", + "\n", + "$$\n", + "x_n = 2 pr^n \\cos{(\\omega + n\\theta)}\n", + "$$\n", + "\n", + "where $\\omega, p$ are coefficients to be determined from\n", + "information encoded in the initial conditions $x_1, x_0$.\n", + "\n", + "Since\n", + "$x_0 = 2 p \\cos{\\omega}$ and $x_1 = 2 pr \\cos{(\\omega + \\theta)}$\n", + "the ratio of $x_1$ to $x_0$ is\n", + "\n", + "$$\n", + "\\frac{x_1}{x_0} = \\frac{r \\cos{(\\omega + \\theta)}}{\\cos{\\omega}}\n", + "$$\n", + "\n", + "We can solve this equation for $\\omega$ then solve for $p$ using $x_0 = 2 pr^0 \\cos{(\\omega + n\\theta)}$.\n", + "\n", + "With the `sympy` package in Python, we are able to solve and plot the\n", + "dynamics of $x_n$ given different values of $n$.\n", + "\n", + "In this example, we set the initial values: - $r = 0.9$ -\n", + "$\\theta = \\frac{1}{4}\\pi$ - $x_0 = 4$ -\n", + "$x_1 = r \\cdot 2\\sqrt{2} = 1.8 \\sqrt{2}$.\n", + "\n", + "We first numerically solve for $\\omega$ and $p$ using\n", + "`nsolve` in the `sympy` package based on the above initial\n", + "condition:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "43825cc5", + "metadata": {}, + "outputs": [], + "source": [ + "# Set parameters\n", + "r = 0.9\n", + "θ = π/4\n", + "x0 = 4\n", + "x1 = 2 * r * sqrt(2)\n", + "\n", + "# Define symbols to be calculated\n", + "ω, p = symbols('ω p', real=True)\n", + "\n", + "# Solve for ω\n", + "## Note: we choose the solution near 0\n", + "eq1 = Eq(x1/x0 - r * cos(ω+θ) / cos(ω), 0)\n", + "ω = nsolve(eq1, ω, 0)\n", + "ω = float(ω)\n", + "print(f'ω = {ω:1.3f}')\n", + "\n", + "# Solve for p\n", + "eq2 = Eq(x0 - 2 * p * cos(ω), 0)\n", + "p = nsolve(eq2, p, 0)\n", + "p = float(p)\n", + "print(f'p = {p:1.3f}')" + ] + }, + { + "cell_type": "markdown", + "id": "85f4ff89", + "metadata": {}, + "source": [ + "Using the code above, we compute that\n", + "$\\omega = 0$ and $p = 2$.\n", + "\n", + "Then we plug in the values we solve for $\\omega$ and $p$\n", + "and plot the dynamic." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a3b313d3", + "metadata": {}, + "outputs": [], + "source": [ + "# Define range of n\n", + "max_n = 30\n", + "n = np.arange(0, max_n+1, 0.01)\n", + "\n", + "# Define x_n\n", + "x = lambda n: 2 * p * r**n * np.cos(ω + n * θ)\n", + "\n", + "# Plot\n", + "fig, ax = plt.subplots(figsize=(12, 8))\n", + "\n", + "ax.plot(n, x(n))\n", + "ax.set(xlim=(0, max_n), ylim=(-5, 5), xlabel='$n$', ylabel='$x_n$')\n", + "\n", + "# Set x-axis in the middle of the plot\n", + "ax.spines['bottom'].set_position('center')\n", + "ax.spines['right'].set_color('none')\n", + "ax.spines['top'].set_color('none')\n", + "ax.xaxis.set_ticks_position('bottom')\n", + "ax.yaxis.set_ticks_position('left')\n", + "\n", + "ticklab = ax.xaxis.get_ticklabels()[0] # Set x-label position\n", + "trans = ticklab.get_transform()\n", + "ax.xaxis.set_label_coords(31, 0, transform=trans)\n", + "\n", + "ticklab = ax.yaxis.get_ticklabels()[0] # Set y-label position\n", + "trans = ticklab.get_transform()\n", + "ax.yaxis.set_label_coords(0, 5, transform=trans)\n", + "\n", + "ax.grid()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "b8c9bcd8", + "metadata": {}, + "source": [ + "### Trigonometric Identities\n", + "\n", + "We can obtain a complete suite of trigonometric identities by\n", + "appropriately manipulating polar forms of complex numbers.\n", + "\n", + "We'll get many of them by deducing implications of the equality\n", + "\n", + "$$\n", + "e^{i(\\omega + \\theta)} = e^{i\\omega} e^{i\\theta}\n", + "$$\n", + "\n", + "For example, we'll calculate identities for\n", + "\n", + "$\\cos{(\\omega + \\theta)}$ and $\\sin{(\\omega + \\theta)}$.\n", + "\n", + "Using the sine and cosine formulas presented at the beginning of this\n", + "lecture, we have:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "\\cos{(\\omega + \\theta)} = \\frac{e^{i(\\omega + \\theta)} + e^{-i(\\omega + \\theta)}}{2} \\\\\n", + "\\sin{(\\omega + \\theta)} = \\frac{e^{i(\\omega + \\theta)} - e^{-i(\\omega + \\theta)}}{2i}\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "We can also obtain the trigonometric identities as follows:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "\\cos{(\\omega + \\theta)} + i \\sin{(\\omega + \\theta)}\n", + "&= e^{i(\\omega + \\theta)} \\\\\n", + "&= e^{i\\omega} e^{i\\theta} \\\\\n", + "&= (\\cos{\\omega} + i \\sin{\\omega})(\\cos{\\theta} + i \\sin{\\theta}) \\\\\n", + "&= (\\cos{\\omega}\\cos{\\theta} - \\sin{\\omega}\\sin{\\theta}) +\n", + "i (\\cos{\\omega}\\sin{\\theta} + \\sin{\\omega}\\cos{\\theta})\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "Since both real and imaginary parts of the above formula should be\n", + "equal, we get:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "\\cos{(\\omega + \\theta)} = \\cos{\\omega}\\cos{\\theta} - \\sin{\\omega}\\sin{\\theta} \\\\\n", + "\\sin{(\\omega + \\theta)} = \\cos{\\omega}\\sin{\\theta} + \\sin{\\omega}\\cos{\\theta}\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "The equations above are also known as the **angle sum identities**. We\n", + "can verify the equations using the `simplify` function in the\n", + "`sympy` package:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f5f63e9f", + "metadata": {}, + "outputs": [], + "source": [ + "# Define symbols\n", + "ω, θ = symbols('ω θ', real=True)\n", + "\n", + "# Verify\n", + "print(\"cos(ω)cos(θ) - sin(ω)sin(θ) =\",\n", + " simplify(cos(ω)*cos(θ) - sin(ω) * sin(θ)))\n", + "print(\"cos(ω)sin(θ) + sin(ω)cos(θ) =\",\n", + " simplify(cos(ω)*sin(θ) + sin(ω) * cos(θ)))" + ] + }, + { + "cell_type": "markdown", + "id": "dc86dcb1", + "metadata": {}, + "source": [ + "### Trigonometric Integrals\n", + "\n", + "We can also compute the trigonometric integrals using polar forms of\n", + "complex numbers.\n", + "\n", + "For example, we want to solve the following integral:\n", + "\n", + "$$\n", + "\\int_{-\\pi}^{\\pi} \\cos(\\omega) \\sin(\\omega) \\, d\\omega\n", + "$$\n", + "\n", + "Using Euler's formula, we have:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "\\int \\cos(\\omega) \\sin(\\omega) \\, d\\omega\n", + "&=\n", + "\\int\n", + "\\frac{(e^{i\\omega} + e^{-i\\omega})}{2}\n", + "\\frac{(e^{i\\omega} - e^{-i\\omega})}{2i}\n", + "\\, d\\omega \\\\\n", + "&=\n", + "\\frac{1}{4i}\n", + "\\int\n", + "e^{2i\\omega} - e^{-2i\\omega}\n", + "\\, d\\omega \\\\\n", + "&=\n", + "\\frac{1}{4i}\n", + "\\bigg( \\frac{-i}{2} e^{2i\\omega} - \\frac{i}{2} e^{-2i\\omega} + C_1 \\bigg) \\\\\n", + "&=\n", + "-\\frac{1}{8}\n", + "\\bigg[ \\bigg(e^{i\\omega}\\bigg)^2 + \\bigg(e^{-i\\omega}\\bigg)^2 - 2 \\bigg] + C_2 \\\\\n", + "&=\n", + "-\\frac{1}{8} (e^{i\\omega} - e^{-i\\omega})^2 + C_2 \\\\\n", + "&=\n", + "\\frac{1}{2} \\bigg( \\frac{e^{i\\omega} - e^{-i\\omega}}{2i} \\bigg)^2 + C_2 \\\\\n", + "&= \\frac{1}{2} \\sin^2(\\omega) + C_2\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "and thus:\n", + "\n", + "$$\n", + "\\int_{-\\pi}^{\\pi} \\cos(\\omega) \\sin(\\omega) \\, d\\omega =\n", + "\\frac{1}{2}\\sin^2(\\pi) - \\frac{1}{2}\\sin^2(-\\pi) = 0\n", + "$$\n", + "\n", + "We can verify the analytical as well as numerical results using\n", + "`integrate` in the `sympy` package:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5811b36b", + "metadata": {}, + "outputs": [], + "source": [ + "# Set initial printing\n", + "init_printing(use_latex=\"mathjax\")\n", + "\n", + "ω = Symbol('ω')\n", + "print('The analytical solution for integral of cos(ω)sin(ω) is:')\n", + "integrate(cos(ω) * sin(ω), ω)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c6993839", + "metadata": {}, + "outputs": [], + "source": [ + "print('The numerical solution for the integral of cos(ω)sin(ω) \\\n", + "from -π to π is:')\n", + "integrate(cos(ω) * sin(ω), (ω, -π, π))" + ] + }, + { + "cell_type": "markdown", + "id": "57386dbe", + "metadata": {}, + "source": [ + "### Exercises\n", + "\n", + "```{exercise}\n", + ":label: complex_ex1\n", + "\n", + "We invite the reader to verify analytically and with the `sympy` package the following two equalities:\n", + "\n", + "$$\n", + "\\int_{-\\pi}^{\\pi} \\cos (\\omega)^2 \\, d\\omega = \\pi\n", + "$$\n", + "\n", + "$$\n", + "\\int_{-\\pi}^{\\pi} \\sin (\\omega)^2 \\, d\\omega = \\pi\n", + "$$\n", + "```\n", + "\n", + "```{solution-start} complex_ex1\n", + ":class: dropdown\n", + "```\n", + "\n", + "Let's import symbolic $\\pi$ from `sympy`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "29590374", + "metadata": {}, + "outputs": [], + "source": [ + "# Import symbolic π from sympy\n", + "from sympy import pi" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2d8629e8", + "metadata": {}, + "outputs": [], + "source": [ + "print('The analytical solution for the integral of cos(ω)**2 \\\n", + "from -π to π is:')\n", + "\n", + "integrate(cos(ω)**2, (ω, -pi, pi))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "00bedf44", + "metadata": {}, + "outputs": [], + "source": [ + "print('The analytical solution for the integral of sin(ω)**2 \\\n", + "from -π to π is:')\n", + "\n", + "integrate(sin(ω)**2, (ω, -pi, pi))" + ] + }, + { + "cell_type": "markdown", + "id": "62fd0934", + "metadata": {}, + "source": [ + "```{solution-end}\n", + "```" + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst" + } + }, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "source_map": [ + 10, + 96, + 102, + 120, + 158, + 295, + 317, + 325, + 356, + 410, + 419, + 471, + 480, + 484, + 508, + 513, + 520, + 525 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/complex_and_trig.md b/book/_build/html/_sources/complex_and_trig.md new file mode 100644 index 0000000..7f40497 --- /dev/null +++ b/book/_build/html/_sources/complex_and_trig.md @@ -0,0 +1,528 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst +kernelspec: + display_name: Python 3 + language: python + name: python3 +--- + +(complex_and_trig)= +```{raw} html + +``` + +```{index} single: python +``` + +# Complex Numbers and Trigonometry + +## Overview + +This lecture introduces some elementary mathematics and trigonometry. + +Useful and interesting in its own right, these concepts reap substantial rewards when studying dynamics generated +by linear difference equations or linear differential equations. + +For example, these tools are keys to understanding outcomes attained by Paul +Samuelson (1939) {cite}`Samuelson1939` in his classic paper on interactions +between the investment accelerator and the Keynesian consumption function, our +topic in the lecture {doc}`Samuelson Multiplier Accelerator `. + +In addition to providing foundations for Samuelson's work and extensions of +it, this lecture can be read as a stand-alone quick reminder of key results +from elementary high school trigonometry. + +So let's dive in. + +### Complex Numbers + +A complex number has a **real part** $x$ and a purely **imaginary part** $y$. + +The Euclidean, polar, and trigonometric forms of a complex number $z$ are: + +$$ +z = x + iy = re^{i\theta} = r(\cos{\theta} + i \sin{\theta}) +$$ + +The second equality above is known as **Euler's formula** + +- [Euler](https://en.wikipedia.org/wiki/Leonhard_Euler) contributed many other formulas too! + +The complex conjugate $\bar z$ of $z$ is defined as + +$$ +\bar z = x - iy = r e^{-i \theta} = r (\cos{\theta} - i \sin{\theta} ) +$$ + +The value $x$ is the **real** part of $z$ and $y$ is the +**imaginary** part of $z$. + +The symbol $| z |$ = $\sqrt{\bar{z}\cdot z} = r$ represents the **modulus** of $z$. + +The value $r$ is the Euclidean distance of vector $(x,y)$ from the +origin: + +$$ +r = |z| = \sqrt{x^2 + y^2} +$$ + +The value $\theta$ is the angle of $(x,y)$ with respect to the real axis. + +Evidently, the tangent of $\theta$ is $\left(\frac{y}{x}\right)$. + +Therefore, + +$$ +\theta = \tan^{-1} \Big( \frac{y}{x} \Big) +$$ + +Three elementary trigonometric functions are + +$$ +\cos{\theta} = \frac{x}{r} = \frac{e^{i\theta} + e^{-i\theta}}{2} , \quad +\sin{\theta} = \frac{y}{r} = \frac{e^{i\theta} - e^{-i\theta}}{2i} , \quad +\tan{\theta} = \frac{y}{x} +$$ + +We'll need the following imports: + +```{code-cell} ipython +import matplotlib.pyplot as plt +plt.rcParams["figure.figsize"] = (11, 5) #set default figure size +import numpy as np +from sympy import (Symbol, symbols, Eq, nsolve, sqrt, cos, sin, simplify, + init_printing, integrate) +``` + +### An Example + +```{prf:example} +:label: ct_ex_com + +Consider the complex number $z = 1 + \sqrt{3} i$. + +For $z = 1 + \sqrt{3} i$, $x = 1$, $y = \sqrt{3}$. + +It follows that $r = 2$ and +$\theta = \tan^{-1}(\sqrt{3}) = \frac{\pi}{3} = 60^o$. +``` + +Let's use Python to plot the trigonometric form of the complex number +$z = 1 + \sqrt{3} i$. + +```{code-cell} python3 +# Abbreviate useful values and functions +π = np.pi + + +# Set parameters +r = 2 +θ = π/3 +x = r * np.cos(θ) +x_range = np.linspace(0, x, 1000) +θ_range = np.linspace(0, θ, 1000) + +# Plot +fig = plt.figure(figsize=(8, 8)) +ax = plt.subplot(111, projection='polar') + +ax.plot((0, θ), (0, r), marker='o', color='b') # Plot r +ax.plot(np.zeros(x_range.shape), x_range, color='b') # Plot x +ax.plot(θ_range, x / np.cos(θ_range), color='b') # Plot y +ax.plot(θ_range, np.full(θ_range.shape, 0.1), color='r') # Plot θ + +ax.margins(0) # Let the plot starts at origin + +ax.set_title("Trigonometry of complex numbers", va='bottom', + fontsize='x-large') + +ax.set_rmax(2) +ax.set_rticks((0.5, 1, 1.5, 2)) # Less radial ticks +ax.set_rlabel_position(-88.5) # Get radial labels away from plotted line + +ax.text(θ, r+0.01 , r'$z = x + iy = 1 + \sqrt{3}\, i$') # Label z +ax.text(θ+0.2, 1 , '$r = 2$') # Label r +ax.text(0-0.2, 0.5, '$x = 1$') # Label x +ax.text(0.5, 1.2, r'$y = \sqrt{3}$') # Label y +ax.text(0.25, 0.15, r'$\theta = 60^o$') # Label θ + +ax.grid(True) +plt.show() +``` + +## De Moivre's Theorem + +de Moivre's theorem states that: + +$$ +(r(\cos{\theta} + i \sin{\theta}))^n = +r^n e^{in\theta} = +r^n(\cos{n\theta} + i \sin{n\theta}) +$$ + +To prove de Moivre's theorem, note that + +$$ +(r(\cos{\theta} + i \sin{\theta}))^n = \big( re^{i\theta} \big)^n +$$ + +and compute. + +## Applications of de Moivre's Theorem + +### Example 1 + +We can use de Moivre's theorem to show that +$r = \sqrt{x^2 + y^2}$. + +We have + +$$ +\begin{aligned} +1 &= e^{i\theta} e^{-i\theta} \\ +&= (\cos{\theta} + i \sin{\theta})(\cos{(\text{-}\theta)} + i \sin{(\text{-}\theta)}) \\ +&= (\cos{\theta} + i \sin{\theta})(\cos{\theta} - i \sin{\theta}) \\ +&= \cos^2{\theta} + \sin^2{\theta} \\ +&= \frac{x^2}{r^2} + \frac{y^2}{r^2} +\end{aligned} +$$ + +and thus + +$$ +x^2 + y^2 = r^2 +$$ + +We recognize this as a theorem of **Pythagoras**. + +### Example 2 + +Let $z = re^{i\theta}$ and $\bar{z} = re^{-i\theta}$ so that $\bar{z}$ is the **complex conjugate** of $z$. + +$(z, \bar z)$ form a **complex conjugate pair** of complex numbers. + +Let $a = pe^{i\omega}$ and $\bar{a} = pe^{-i\omega}$ be +another complex conjugate pair. + +For each element of a sequence of integers $n = 0, 1, 2, \ldots, $. + +To do so, we can apply de Moivre's formula. + +Thus, + +$$ +\begin{aligned} +x_n &= az^n + \bar{a}\bar{z}^n \\ +&= p e^{i\omega} (re^{i\theta})^n + p e^{-i\omega} (re^{-i\theta})^n \\ +&= pr^n e^{i (\omega + n\theta)} + pr^n e^{-i (\omega + n\theta)} \\ +&= pr^n [\cos{(\omega + n\theta)} + i \sin{(\omega + n\theta)} + + \cos{(\omega + n\theta)} - i \sin{(\omega + n\theta)}] \\ +&= 2 pr^n \cos{(\omega + n\theta)} +\end{aligned} +$$ + +### Example 3 + +This example provides machinery that is at the heard of Samuelson's analysis of his multiplier-accelerator model {cite}`Samuelson1939`. + +Thus, consider a **second-order linear difference equation** + +$$ +x_{n+2} = c_1 x_{n+1} + c_2 x_n +$$ + +whose **characteristic polynomial** is + +$$ +z^2 - c_1 z - c_2 = 0 +$$ + +or + +$$ +(z^2 - c_1 z - c_2 ) = (z - z_1)(z- z_2) = 0 +$$ + +has roots $z_1, z_1$. + +A **solution** is a sequence $\{x_n\}_{n=0}^\infty$ that satisfies +the difference equation. + +Under the following circumstances, we can apply our example 2 formula to +solve the difference equation + +- the roots $z_1, z_2$ of the characteristic polynomial of the + difference equation form a complex conjugate pair +- the values $x_0, x_1$ are given initial conditions + +To solve the difference equation, recall from example 2 that + +$$ +x_n = 2 pr^n \cos{(\omega + n\theta)} +$$ + +where $\omega, p$ are coefficients to be determined from +information encoded in the initial conditions $x_1, x_0$. + +Since +$x_0 = 2 p \cos{\omega}$ and $x_1 = 2 pr \cos{(\omega + \theta)}$ +the ratio of $x_1$ to $x_0$ is + +$$ +\frac{x_1}{x_0} = \frac{r \cos{(\omega + \theta)}}{\cos{\omega}} +$$ + +We can solve this equation for $\omega$ then solve for $p$ using $x_0 = 2 pr^0 \cos{(\omega + n\theta)}$. + +With the `sympy` package in Python, we are able to solve and plot the +dynamics of $x_n$ given different values of $n$. + +In this example, we set the initial values: - $r = 0.9$ - +$\theta = \frac{1}{4}\pi$ - $x_0 = 4$ - +$x_1 = r \cdot 2\sqrt{2} = 1.8 \sqrt{2}$. + +We first numerically solve for $\omega$ and $p$ using +`nsolve` in the `sympy` package based on the above initial +condition: + +```{code-cell} python3 +# Set parameters +r = 0.9 +θ = π/4 +x0 = 4 +x1 = 2 * r * sqrt(2) + +# Define symbols to be calculated +ω, p = symbols('ω p', real=True) + +# Solve for ω +## Note: we choose the solution near 0 +eq1 = Eq(x1/x0 - r * cos(ω+θ) / cos(ω), 0) +ω = nsolve(eq1, ω, 0) +ω = float(ω) +print(f'ω = {ω:1.3f}') + +# Solve for p +eq2 = Eq(x0 - 2 * p * cos(ω), 0) +p = nsolve(eq2, p, 0) +p = float(p) +print(f'p = {p:1.3f}') +``` + +Using the code above, we compute that +$\omega = 0$ and $p = 2$. + +Then we plug in the values we solve for $\omega$ and $p$ +and plot the dynamic. + +```{code-cell} python3 +# Define range of n +max_n = 30 +n = np.arange(0, max_n+1, 0.01) + +# Define x_n +x = lambda n: 2 * p * r**n * np.cos(ω + n * θ) + +# Plot +fig, ax = plt.subplots(figsize=(12, 8)) + +ax.plot(n, x(n)) +ax.set(xlim=(0, max_n), ylim=(-5, 5), xlabel='$n$', ylabel='$x_n$') + +# Set x-axis in the middle of the plot +ax.spines['bottom'].set_position('center') +ax.spines['right'].set_color('none') +ax.spines['top'].set_color('none') +ax.xaxis.set_ticks_position('bottom') +ax.yaxis.set_ticks_position('left') + +ticklab = ax.xaxis.get_ticklabels()[0] # Set x-label position +trans = ticklab.get_transform() +ax.xaxis.set_label_coords(31, 0, transform=trans) + +ticklab = ax.yaxis.get_ticklabels()[0] # Set y-label position +trans = ticklab.get_transform() +ax.yaxis.set_label_coords(0, 5, transform=trans) + +ax.grid() +plt.show() +``` + +### Trigonometric Identities + +We can obtain a complete suite of trigonometric identities by +appropriately manipulating polar forms of complex numbers. + +We'll get many of them by deducing implications of the equality + +$$ +e^{i(\omega + \theta)} = e^{i\omega} e^{i\theta} +$$ + +For example, we'll calculate identities for + +$\cos{(\omega + \theta)}$ and $\sin{(\omega + \theta)}$. + +Using the sine and cosine formulas presented at the beginning of this +lecture, we have: + +$$ +\begin{aligned} +\cos{(\omega + \theta)} = \frac{e^{i(\omega + \theta)} + e^{-i(\omega + \theta)}}{2} \\ +\sin{(\omega + \theta)} = \frac{e^{i(\omega + \theta)} - e^{-i(\omega + \theta)}}{2i} +\end{aligned} +$$ + +We can also obtain the trigonometric identities as follows: + +$$ +\begin{aligned} +\cos{(\omega + \theta)} + i \sin{(\omega + \theta)} +&= e^{i(\omega + \theta)} \\ +&= e^{i\omega} e^{i\theta} \\ +&= (\cos{\omega} + i \sin{\omega})(\cos{\theta} + i \sin{\theta}) \\ +&= (\cos{\omega}\cos{\theta} - \sin{\omega}\sin{\theta}) + +i (\cos{\omega}\sin{\theta} + \sin{\omega}\cos{\theta}) +\end{aligned} +$$ + +Since both real and imaginary parts of the above formula should be +equal, we get: + +$$ +\begin{aligned} +\cos{(\omega + \theta)} = \cos{\omega}\cos{\theta} - \sin{\omega}\sin{\theta} \\ +\sin{(\omega + \theta)} = \cos{\omega}\sin{\theta} + \sin{\omega}\cos{\theta} +\end{aligned} +$$ + +The equations above are also known as the **angle sum identities**. We +can verify the equations using the `simplify` function in the +`sympy` package: + +```{code-cell} python3 +# Define symbols +ω, θ = symbols('ω θ', real=True) + +# Verify +print("cos(ω)cos(θ) - sin(ω)sin(θ) =", + simplify(cos(ω)*cos(θ) - sin(ω) * sin(θ))) +print("cos(ω)sin(θ) + sin(ω)cos(θ) =", + simplify(cos(ω)*sin(θ) + sin(ω) * cos(θ))) +``` + +### Trigonometric Integrals + +We can also compute the trigonometric integrals using polar forms of +complex numbers. + +For example, we want to solve the following integral: + +$$ +\int_{-\pi}^{\pi} \cos(\omega) \sin(\omega) \, d\omega +$$ + +Using Euler's formula, we have: + +$$ +\begin{aligned} +\int \cos(\omega) \sin(\omega) \, d\omega +&= +\int +\frac{(e^{i\omega} + e^{-i\omega})}{2} +\frac{(e^{i\omega} - e^{-i\omega})}{2i} +\, d\omega \\ +&= +\frac{1}{4i} +\int +e^{2i\omega} - e^{-2i\omega} +\, d\omega \\ +&= +\frac{1}{4i} +\bigg( \frac{-i}{2} e^{2i\omega} - \frac{i}{2} e^{-2i\omega} + C_1 \bigg) \\ +&= +-\frac{1}{8} +\bigg[ \bigg(e^{i\omega}\bigg)^2 + \bigg(e^{-i\omega}\bigg)^2 - 2 \bigg] + C_2 \\ +&= +-\frac{1}{8} (e^{i\omega} - e^{-i\omega})^2 + C_2 \\ +&= +\frac{1}{2} \bigg( \frac{e^{i\omega} - e^{-i\omega}}{2i} \bigg)^2 + C_2 \\ +&= \frac{1}{2} \sin^2(\omega) + C_2 +\end{aligned} +$$ + +and thus: + +$$ +\int_{-\pi}^{\pi} \cos(\omega) \sin(\omega) \, d\omega = +\frac{1}{2}\sin^2(\pi) - \frac{1}{2}\sin^2(-\pi) = 0 +$$ + +We can verify the analytical as well as numerical results using +`integrate` in the `sympy` package: + +```{code-cell} python3 +# Set initial printing +init_printing(use_latex="mathjax") + +ω = Symbol('ω') +print('The analytical solution for integral of cos(ω)sin(ω) is:') +integrate(cos(ω) * sin(ω), ω) +``` + +```{code-cell} python3 +print('The numerical solution for the integral of cos(ω)sin(ω) \ +from -π to π is:') +integrate(cos(ω) * sin(ω), (ω, -π, π)) +``` + +### Exercises + +```{exercise} +:label: complex_ex1 + +We invite the reader to verify analytically and with the `sympy` package the following two equalities: + +$$ +\int_{-\pi}^{\pi} \cos (\omega)^2 \, d\omega = \pi +$$ + +$$ +\int_{-\pi}^{\pi} \sin (\omega)^2 \, d\omega = \pi +$$ +``` + +```{solution-start} complex_ex1 +:class: dropdown +``` + +Let's import symbolic $\pi$ from `sympy` + +```{code-cell} ipython3 +# Import symbolic π from sympy +from sympy import pi +``` + +```{code-cell} ipython3 +print('The analytical solution for the integral of cos(ω)**2 \ +from -π to π is:') + +integrate(cos(ω)**2, (ω, -pi, pi)) +``` + +```{code-cell} ipython3 +print('The analytical solution for the integral of sin(ω)**2 \ +from -π to π is:') + +integrate(sin(ω)**2, (ω, -pi, pi)) +``` + +```{solution-end} +``` diff --git a/book/_build/html/_sources/cons_smooth.ipynb b/book/_build/html/_sources/cons_smooth.ipynb new file mode 100644 index 0000000..e56b303 --- /dev/null +++ b/book/_build/html/_sources/cons_smooth.ipynb @@ -0,0 +1,1064 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "44edf43a", + "metadata": {}, + "source": [ + "# Consumption Smoothing\n", + "\n", + "## Overview\n", + "\n", + "\n", + "In this lecture, we'll study a famous model of the \"consumption function\" that Milton Friedman {cite}`Friedman1956` and Robert Hall {cite}`Hall1978`) proposed to fit some empirical data patterns that the original Keynesian consumption function described in this QuantEcon lecture {doc}`geometric series ` missed.\n", + "\n", + "In this lecture, we'll study what is often called the \"consumption-smoothing model\" using matrix multiplication and matrix inversion, the same tools that we used in this QuantEcon lecture {doc}`present values `. \n", + "\n", + "Formulas presented in {doc}`present value formulas` are at the core of the consumption-smoothing model because we shall use them to define a consumer's \"human wealth\".\n", + "\n", + "The key idea that inspired Milton Friedman was that a person's non-financial income, i.e., his or\n", + "her wages from working, could be viewed as a dividend stream from that person's ''human capital''\n", + "and that standard asset-pricing formulas could be applied to compute a person's\n", + "''non-financial wealth'' that capitalizes the earnings stream. \n", + "\n", + "```{note}\n", + "As we'll see in this QuantEcon lecture {doc}`equalizing difference model `,\n", + "Milton Friedman had used this idea in his PhD thesis at Columbia University, \n", + "eventually published as {cite}`kuznets1939incomes` and {cite}`friedman1954incomes`.\n", + "```\n", + "\n", + "It will take a while for a \"present value\" or asset price explicilty to appear in this lecture, but when it does it will be a key actor.\n", + "\n", + "\n", + "## Analysis\n", + "\n", + "As usual, we'll start by importing some Python modules." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "54a3d934", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from collections import namedtuple" + ] + }, + { + "cell_type": "markdown", + "id": "384c5c5d", + "metadata": {}, + "source": [ + "The model describes a consumer who lives from time $t=0, 1, \\ldots, T$, receives a stream $\\{y_t\\}_{t=0}^T$ of non-financial income and chooses a consumption stream $\\{c_t\\}_{t=0}^T$.\n", + "\n", + "We usually think of the non-financial income stream as coming from the person's salary from supplying labor. \n", + "\n", + "The model takes a non-financial income stream as an input, regarding it as \"exogenous\" in the sense of not being determined by the model. \n", + "\n", + "The consumer faces a gross interest rate of $R >1$ that is constant over time, at which she is free to borrow or lend, up to limits that we'll describe below.\n", + "\n", + "To set up the model, let \n", + "\n", + " * $T \\geq 2$ be a positive integer that constitutes a time-horizon. \n", + " * $y = \\{y_t\\}_{t=0}^T$ be an exogenous sequence of non-negative non-financial incomes $y_t$. \n", + " * $a = \\{a_t\\}_{t=0}^{T+1}$ be a sequence of financial wealth. \n", + " * $c = \\{c_t\\}_{t=0}^T$ be a sequence of non-negative consumption rates. \n", + " * $R \\geq 1$ be a fixed gross one period rate of return on financial assets. \n", + " * $\\beta \\in (0,1)$ be a fixed discount factor. \n", + " * $a_0$ be a given initial level of financial assets\n", + " * $a_{T+1} \\geq 0$ be a terminal condition on final assets. \n", + "\n", + "The sequence of financial wealth $a$ is to be determined by the model.\n", + "\n", + "We require it to satisfy two **boundary conditions**:\n", + "\n", + " * it must equal an exogenous value $a_0$ at time $0$ \n", + " * it must equal or exceed an exogenous value $a_{T+1}$ at time $T+1$.\n", + "\n", + "The **terminal condition** $a_{T+1} \\geq 0$ requires that the consumer not leave the model in debt.\n", + "\n", + "(We'll soon see that a utility maximizing consumer won't want to die leaving positive assets, so she'll arrange her affairs to make\n", + "$a_{T+1} = 0$.)\n", + "\n", + "The consumer faces a sequence of budget constraints that constrains sequences $(y, c, a)$\n", + "\n", + "$$\n", + "a_{t+1} = R (a_t+ y_t - c_t), \\quad t =0, 1, \\ldots T\n", + "$$ (eq:a_t)\n", + "\n", + "Equations {eq}`eq:a_t` constitute $T+1$ such budget constraints, one for each $t=0, 1, \\ldots, T$. \n", + "\n", + "Given a sequence $y$ of non-financial incomes, a large set of pairs $(a, c)$ of (financial wealth, consumption) sequences satisfy the sequence of budget constraints {eq}`eq:a_t`. \n", + "\n", + "Our model has the following logical flow.\n", + "\n", + " * start with an exogenous non-financial income sequence $y$, an initial financial wealth $a_0$, and \n", + " a candidate consumption path $c$.\n", + " \n", + " * use the system of equations {eq}`eq:a_t` for $t=0, \\ldots, T$ to compute a path $a$ of financial wealth\n", + " \n", + " * verify that $a_{T+1}$ satisfies the terminal wealth constraint $a_{T+1} \\geq 0$. \n", + " \n", + " * If it does, declare that the candidate path is **budget feasible**. \n", + " \n", + " * if the candidate consumption path is not budget feasible, propose a less greedy consumption path and start over\n", + " \n", + "Below, we'll describe how to execute these steps using linear algebra -- matrix inversion and multiplication.\n", + "\n", + "The above procedure seems like a sensible way to find \"budget-feasible\" consumption paths $c$, i.e., paths that are consistent\n", + "with the exogenous non-financial income stream $y$, the initial financial asset level $a_0$, and the terminal asset level $a_{T+1}$.\n", + "\n", + "In general, there are **many** budget feasible consumption paths $c$.\n", + "\n", + "Among all budget-feasible consumption paths, which one should a consumer want?\n", + "\n", + "\n", + "To answer this question, we shall eventually evaluate alternative budget feasible consumption paths $c$ using the following utility functional or **welfare criterion**:\n", + "\n", + "```{math}\n", + ":label: welfare\n", + "\n", + "W = \\sum_{t=0}^T \\beta^t (g_1 c_t - \\frac{g_2}{2} c_t^2 )\n", + "```\n", + "\n", + "where $g_1 > 0, g_2 > 0$. \n", + "\n", + "When $\\beta R \\approx 1$, the fact that the utility function $g_1 c_t - \\frac{g_2}{2} c_t^2$ has diminishing marginal utility imparts a preference for consumption that is very smooth. \n", + "\n", + "Indeed, we shall see that when $\\beta R = 1$ (a condition assumed by Milton Friedman {cite}`Friedman1956` and Robert Hall {cite}`Hall1978`), criterion {eq}`welfare` assigns higher welfare to smoother consumption paths.\n", + "\n", + "By **smoother** we mean as close as possible to being constant over time. \n", + "\n", + "The preference for smooth consumption paths that is built into the model gives it the name \"consumption-smoothing model\".\n", + "\n", + "Let's dive in and do some calculations that will help us understand how the model works. \n", + "\n", + "Here we use default parameters $R = 1.05$, $g_1 = 1$, $g_2 = 1/2$, and $T = 65$. \n", + "\n", + "We create a Python **namedtuple** to store these parameters with default values." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3ca5970e", + "metadata": {}, + "outputs": [], + "source": [ + "ConsumptionSmoothing = namedtuple(\"ConsumptionSmoothing\", \n", + " [\"R\", \"g1\", \"g2\", \"β_seq\", \"T\"])\n", + "\n", + "def create_consumption_smoothing_model(R=1.05, g1=1, g2=1/2, T=65):\n", + " β = 1/R\n", + " β_seq = np.array([β**i for i in range(T+1)])\n", + " return ConsumptionSmoothing(R, g1, g2, \n", + " β_seq, T)" + ] + }, + { + "cell_type": "markdown", + "id": "dff3eadf", + "metadata": {}, + "source": [ + "## Friedman-Hall consumption-smoothing model\n", + "\n", + "A key object is what Milton Friedman called \"human\" or \"non-financial\" wealth at time $0$:\n", + "\n", + "\n", + "$$\n", + "h_0 \\equiv \\sum_{t=0}^T R^{-t} y_t = \\begin{bmatrix} 1 & R^{-1} & \\cdots & R^{-T} \\end{bmatrix}\n", + "\\begin{bmatrix} y_0 \\cr y_1 \\cr \\vdots \\cr y_T \\end{bmatrix}\n", + "$$\n", + "\n", + "Human or non-financial wealth at time $0$ is evidently just the present value of the consumer's non-financial income stream $y$. \n", + "\n", + "Formally it very much resembles the asset price that we computed in this QuantEcon lecture {doc}`present values `.\n", + "\n", + "Indeed, this is why Milton Friedman called it \"human capital\". \n", + "\n", + "By iterating on equation {eq}`eq:a_t` and imposing the terminal condition \n", + "\n", + "$$\n", + "a_{T+1} = 0,\n", + "$$\n", + "\n", + "it is possible to convert a sequence of budget constraints {eq}`eq:a_t` into a single intertemporal constraint\n", + "\n", + "$$ \n", + "\\sum_{t=0}^T R^{-t} c_t = a_0 + h_0. \n", + "$$ (eq:budget_intertemp)\n", + "\n", + "Equation {eq}`eq:budget_intertemp` says that the present value of the consumption stream equals the sum of financial and non-financial (or human) wealth.\n", + "\n", + "Robert Hall {cite}`Hall1978` showed that when $\\beta R = 1$, a condition Milton Friedman had also assumed, it is \"optimal\" for a consumer to smooth consumption by setting \n", + "\n", + "$$ \n", + "c_t = c_0 \\quad t =0, 1, \\ldots, T\n", + "$$\n", + "\n", + "(Later we'll present a \"variational argument\" that shows that this constant path maximizes\n", + "criterion {eq}`welfare` when $\\beta R =1$.)\n", + "\n", + "In this case, we can use the intertemporal budget constraint to write \n", + "\n", + "$$\n", + "c_t = c_0 = \\left(\\sum_{t=0}^T R^{-t}\\right)^{-1} (a_0 + h_0), \\quad t= 0, 1, \\ldots, T.\n", + "$$ (eq:conssmoothing)\n", + "\n", + "Equation {eq}`eq:conssmoothing` is the consumption-smoothing model in a nutshell.\n", + "\n", + "\n", + "## Mechanics of consumption-smoothing model \n", + "\n", + "As promised, we'll provide step-by-step instructions on how to use linear algebra, readily implemented in Python, to compute all objects in play in the consumption-smoothing model.\n", + "\n", + "In the calculations below, we'll set default values of $R > 1$, e.g., $R = 1.05$, and $\\beta = R^{-1}$.\n", + "\n", + "### Step 1\n", + "\n", + "For a $(T+1) \\times 1$ vector $y$, use matrix algebra to compute $h_0$\n", + "\n", + "$$\n", + "h_0 = \\sum_{t=0}^T R^{-t} y_t = \\begin{bmatrix} 1 & R^{-1} & \\cdots & R^{-T} \\end{bmatrix}\n", + "\\begin{bmatrix} y_0 \\cr y_1 \\cr \\vdots \\cr y_T \\end{bmatrix}\n", + "$$\n", + "\n", + "### Step 2\n", + "\n", + "Compute an time $0$ consumption $c_0 $ :\n", + "\n", + "$$\n", + "c_t = c_0 = \\left( \\frac{1 - R^{-1}}{1 - R^{-(T+1)}} \\right) (a_0 + \\sum_{t=0}^T R^{-t} y_t ) , \\quad t = 0, 1, \\ldots, T\n", + "$$\n", + "\n", + "### Step 3\n", + "\n", + "Use the system of equations {eq}`eq:a_t` for $t=0, \\ldots, T$ to compute a path $a$ of financial wealth.\n", + "\n", + "To do this, we translate that system of difference equations into a single matrix equation as follows:\n", + "\n", + "\n", + "$$\n", + "\\begin{bmatrix} \n", + "1 & 0 & 0 & \\cdots & 0 & 0 & 0 \\cr\n", + "-R & 1 & 0 & \\cdots & 0 & 0 & 0 \\cr\n", + "0 & -R & 1 & \\cdots & 0 & 0 & 0 \\cr\n", + "\\vdots &\\vdots & \\vdots & \\cdots & \\vdots & \\vdots & \\vdots \\cr\n", + "0 & 0 & 0 & \\cdots & -R & 1 & 0 \\cr\n", + "0 & 0 & 0 & \\cdots & 0 & -R & 1\n", + "\\end{bmatrix} \n", + "\\begin{bmatrix} a_1 \\cr a_2 \\cr a_3 \\cr \\vdots \\cr a_T \\cr a_{T+1} \n", + "\\end{bmatrix}\n", + "= R \n", + "\\begin{bmatrix} y_0 + a_0 - c_0 \\cr y_1 - c_0 \\cr y_2 - c_0 \\cr \\vdots\\cr y_{T-1} - c_0 \\cr y_T - c_0\n", + "\\end{bmatrix}\n", + "$$\n", + "\n", + "Multiply both sides by the inverse of the matrix on the left side to compute\n", + "\n", + "$$\n", + " \\begin{bmatrix} a_1 \\cr a_2 \\cr a_3 \\cr \\vdots \\cr a_T \\cr a_{T+1} \\end{bmatrix}\n", + "$$\n", + "\n", + "\n", + "Because we have built into our calculations that the consumer leaves the model with exactly zero assets, just barely satisfying the\n", + "terminal condition that $a_{T+1} \\geq 0$, it should turn out that \n", + "\n", + "$$\n", + "a_{T+1} = 0.\n", + "$$\n", + " \n", + "\n", + "Let's verify this with Python code.\n", + "\n", + "First we implement the model with `compute_optimal`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "450ac0b9", + "metadata": {}, + "outputs": [], + "source": [ + "def compute_optimal(model, a0, y_seq):\n", + " R, T = model.R, model.T\n", + "\n", + " # non-financial wealth\n", + " h0 = model.β_seq @ y_seq # since β = 1/R\n", + "\n", + " # c0\n", + " c0 = (1 - 1/R) / (1 - (1/R)**(T+1)) * (a0 + h0)\n", + " c_seq = c0*np.ones(T+1)\n", + "\n", + " # verify\n", + " A = np.diag(-R*np.ones(T), k=-1) + np.eye(T+1)\n", + " b = y_seq - c_seq\n", + " b[0] = b[0] + a0\n", + "\n", + " a_seq = np.linalg.inv(A) @ b\n", + " a_seq = np.concatenate([[a0], a_seq])\n", + "\n", + " return c_seq, a_seq, h0" + ] + }, + { + "cell_type": "markdown", + "id": "1bf3db2e", + "metadata": {}, + "source": [ + "We use an example where the consumer inherits $a_0<0$.\n", + "\n", + "This can be interpreted as a student debt.\n", + "\n", + "The non-financial process $\\{y_t\\}_{t=0}^{T}$ is constant and positive up to $t=45$ and then becomes zero afterward.\n", + "\n", + "The drop in non-financial income late in life reflects retirement from work." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "446fc6a3", + "metadata": {}, + "outputs": [], + "source": [ + "# Financial wealth\n", + "a0 = -2 # such as \"student debt\"\n", + "\n", + "# non-financial Income process\n", + "y_seq = np.concatenate([np.ones(46), np.zeros(20)])\n", + "\n", + "cs_model = create_consumption_smoothing_model()\n", + "c_seq, a_seq, h0 = compute_optimal(cs_model, a0, y_seq)\n", + "\n", + "print('check a_T+1=0:', \n", + " np.abs(a_seq[-1] - 0) <= 1e-8)" + ] + }, + { + "cell_type": "markdown", + "id": "dc48ad3d", + "metadata": {}, + "source": [ + "The graphs below show paths of non-financial income, consumption, and financial assets." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9a91219f", + "metadata": {}, + "outputs": [], + "source": [ + "# Sequence Length\n", + "T = cs_model.T\n", + "\n", + "plt.plot(range(T+1), y_seq, label='non-financial income')\n", + "plt.plot(range(T+1), c_seq, label='consumption')\n", + "plt.plot(range(T+2), a_seq, label='financial wealth')\n", + "plt.plot(range(T+2), np.zeros(T+2), '--')\n", + "\n", + "plt.legend()\n", + "plt.xlabel(r'$t$')\n", + "plt.ylabel(r'$c_t,y_t,a_t$')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "81a5b72e", + "metadata": {}, + "source": [ + "Note that $a_{T+1} = 0$, as anticipated.\n", + "\n", + "We can evaluate welfare criterion {eq}`welfare`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e3bb4b4c", + "metadata": {}, + "outputs": [], + "source": [ + "def welfare(model, c_seq):\n", + " β_seq, g1, g2 = model.β_seq, model.g1, model.g2\n", + "\n", + " u_seq = g1 * c_seq - g2/2 * c_seq**2\n", + " return β_seq @ u_seq\n", + "\n", + "print('Welfare:', welfare(cs_model, c_seq))" + ] + }, + { + "cell_type": "markdown", + "id": "14a6a07e", + "metadata": {}, + "source": [ + "### Experiments\n", + "\n", + "In this section we describe how a consumption sequence would optimally respond to different sequences sequences of non-financial income.\n", + "\n", + "First we create a function `plot_cs` that generates graphs for different instances of the consumption-smoothing model `cs_model`.\n", + "\n", + "This will help us avoid rewriting code to plot outcomes for different non-financial income sequences." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ad68f886", + "metadata": {}, + "outputs": [], + "source": [ + "def plot_cs(model, # consumption-smoothing model \n", + " a0, # initial financial wealth\n", + " y_seq # non-financial income process\n", + " ):\n", + " \n", + " # Compute optimal consumption\n", + " c_seq, a_seq, h0 = compute_optimal(model, a0, y_seq)\n", + " \n", + " # Sequence length\n", + " T = cs_model.T\n", + " \n", + " # Generate plot\n", + " plt.plot(range(T+1), y_seq, label='non-financial income')\n", + " plt.plot(range(T+1), c_seq, label='consumption')\n", + " plt.plot(range(T+2), a_seq, label='financial wealth')\n", + " plt.plot(range(T+2), np.zeros(T+2), '--')\n", + " \n", + " plt.legend()\n", + " plt.xlabel(r'$t$')\n", + " plt.ylabel(r'$c_t,y_t,a_t$')\n", + " plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "37df1d34", + "metadata": {}, + "source": [ + "In the experiments below, please study how consumption and financial asset sequences vary across different sequences for non-financial income.\n", + "\n", + "#### Experiment 1: one-time gain/loss\n", + "\n", + "We first assume a one-time windfall of $W_0$ in year 21 of the income sequence $y$. \n", + "\n", + "We'll make $W_0$ big - positive to indicate a one-time windfall, and negative to indicate a one-time \"disaster\"." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d0a87fa7", + "metadata": {}, + "outputs": [], + "source": [ + "# Windfall W_0 = 2.5\n", + "y_seq_pos = np.concatenate([np.ones(21), np.array([2.5]), np.ones(24), np.zeros(20)])\n", + "\n", + "plot_cs(cs_model, a0, y_seq_pos)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ded293e0", + "metadata": {}, + "outputs": [], + "source": [ + "# Disaster W_0 = -2.5\n", + "y_seq_neg = np.concatenate([np.ones(21), np.array([-2.5]), np.ones(24), np.zeros(20)])\n", + "\n", + "plot_cs(cs_model, a0, y_seq_neg)" + ] + }, + { + "cell_type": "markdown", + "id": "872538c7", + "metadata": {}, + "source": [ + "#### Experiment 2: permanent wage gain/loss\n", + "\n", + "Now we assume a permanent increase in income of $W$ in year 21 of the $y$-sequence.\n", + "\n", + "Again we can study positive and negative cases" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "95901c46", + "metadata": {}, + "outputs": [], + "source": [ + "# Positive permanent income change W = 0.5 when t >= 21\n", + "y_seq_pos = np.concatenate(\n", + " [np.ones(21), 1.5*np.ones(25), np.zeros(20)])\n", + "\n", + "plot_cs(cs_model, a0, y_seq_pos)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4b0081a4", + "metadata": {}, + "outputs": [], + "source": [ + "# Negative permanent income change W = -0.5 when t >= 21\n", + "y_seq_neg = np.concatenate(\n", + " [np.ones(21), .5*np.ones(25), np.zeros(20)])\n", + "\n", + "plot_cs(cs_model, a0, y_seq_neg)" + ] + }, + { + "cell_type": "markdown", + "id": "fa00569d", + "metadata": {}, + "source": [ + "#### Experiment 3: a late starter\n", + "\n", + "Now we simulate a $y$ sequence in which a person gets zero for 46 years, and then works and gets 1 for the last 20 years of life (a \"late starter\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "963f1feb", + "metadata": {}, + "outputs": [], + "source": [ + "# Late starter\n", + "y_seq_late = np.concatenate(\n", + " [np.zeros(46), np.ones(20)])\n", + "\n", + "plot_cs(cs_model, a0, y_seq_late)" + ] + }, + { + "cell_type": "markdown", + "id": "6846935b", + "metadata": {}, + "source": [ + "#### Experiment 4: geometric earner\n", + "\n", + "Now we simulate a geometric $y$ sequence in which a person gets $y_t = \\lambda^t y_0$ in first 46 years.\n", + "\n", + "We first experiment with $\\lambda = 1.05$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1de99b8f", + "metadata": {}, + "outputs": [], + "source": [ + "# Geometric earner parameters where λ = 1.05\n", + "λ = 1.05\n", + "y_0 = 1\n", + "t_max = 46\n", + "\n", + "# Generate geometric y sequence\n", + "geo_seq = λ ** np.arange(t_max) * y_0 \n", + "y_seq_geo = np.concatenate(\n", + " [geo_seq, np.zeros(20)])\n", + "\n", + "plot_cs(cs_model, a0, y_seq_geo)" + ] + }, + { + "cell_type": "markdown", + "id": "b8e6b1d8", + "metadata": {}, + "source": [ + "Now we show the behavior when $\\lambda = 0.95$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "939e957d", + "metadata": {}, + "outputs": [], + "source": [ + "λ = 0.95\n", + "\n", + "geo_seq = λ ** np.arange(t_max) * y_0 \n", + "y_seq_geo = np.concatenate(\n", + " [geo_seq, np.zeros(20)])\n", + "\n", + "plot_cs(cs_model, a0, y_seq_geo)" + ] + }, + { + "cell_type": "markdown", + "id": "b613028a", + "metadata": {}, + "source": [ + "What happens when $\\lambda$ is negative" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fa5c335d", + "metadata": {}, + "outputs": [], + "source": [ + "λ = -0.95\n", + "\n", + "geo_seq = λ ** np.arange(t_max) * y_0 \n", + "y_seq_geo = np.concatenate(\n", + " [geo_seq, np.zeros(20)])\n", + "\n", + "plot_cs(cs_model, a0, y_seq_geo)" + ] + }, + { + "cell_type": "markdown", + "id": "84ff0098", + "metadata": {}, + "source": [ + "### Feasible consumption variations\n", + "\n", + "We promised to justify our claim that a constant consumption play $c_t = c_0$ for all\n", + "$t$ is optimal. \n", + "\n", + "Let's do that now.\n", + "\n", + "The approach we'll take is an elementary example of the \"calculus of variations\". \n", + "\n", + "Let's dive in and see what the key idea is. \n", + "\n", + "To explore what types of consumption paths are welfare-improving, we shall create an **admissible consumption path variation sequence** $\\{v_t\\}_{t=0}^T$\n", + "that satisfies\n", + "\n", + "$$\n", + "\\sum_{t=0}^T R^{-t} v_t = 0\n", + "$$\n", + "\n", + "This equation says that the **present value** of admissible consumption path variations must be zero.\n", + "\n", + "So once again, we encounter a formula for the present value of an \"asset\":\n", + "\n", + " * we require that the present value of consumption path variations be zero.\n", + "\n", + "Here we'll restrict ourselves to a two-parameter class of admissible consumption path variations\n", + "of the form\n", + "\n", + "$$\n", + "v_t = \\xi_1 \\phi^t - \\xi_0\n", + "$$\n", + "\n", + "We say two and not three-parameter class because $\\xi_0$ will be a function of $(\\phi, \\xi_1; R)$ that guarantees that the variation sequence is feasible. \n", + "\n", + "Let's compute that function.\n", + "\n", + "We require\n", + "\n", + "$$\n", + "\\sum_{t=0}^T R^{-t}\\left[ \\xi_1 \\phi^t - \\xi_0 \\right] = 0\n", + "$$\n", + "\n", + "which implies that\n", + "\n", + "$$\n", + "\\xi_1 \\sum_{t=0}^T \\phi_t R^{-t} - \\xi_0 \\sum_{t=0}^T R^{-t} = 0\n", + "$$\n", + "\n", + "which implies that\n", + "\n", + "$$\n", + "\\xi_1 \\frac{1 - (\\phi R^{-1})^{T+1}}{1 - \\phi R^{-1}} - \\xi_0 \\frac{1 - R^{-(T+1)}}{1-R^{-1} } =0\n", + "$$\n", + "\n", + "which implies that\n", + "\n", + "$$\n", + "\\xi_0 = \\xi_0(\\phi, \\xi_1; R) = \\xi_1 \\left(\\frac{1 - R^{-1}}{1 - R^{-(T+1)}}\\right) \\left(\\frac{1 - (\\phi R^{-1})^{T+1}}{1 - \\phi R^{-1}}\\right)\n", + "$$ \n", + "\n", + "This is our formula for $\\xi_0$. \n", + "\n", + "**Key Idea:** if $c^o$ is a budget-feasible consumption path, then so is $c^o + v$,\n", + "where $v$ is a budget-feasible variation.\n", + "\n", + "Given $R$, we thus have a two parameter class of budget feasible variations $v$ that we can use\n", + "to compute alternative consumption paths, then evaluate their welfare.\n", + "\n", + "Now let's compute and plot consumption path variations" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c40c7a92", + "metadata": {}, + "outputs": [], + "source": [ + "def compute_variation(model, ξ1, ϕ, a0, y_seq, verbose=1):\n", + " R, T, β_seq = model.R, model.T, model.β_seq\n", + "\n", + " ξ0 = ξ1*((1 - 1/R) / (1 - (1/R)**(T+1))) * ((1 - (ϕ/R)**(T+1)) / (1 - ϕ/R))\n", + " v_seq = np.array([(ξ1*ϕ**t - ξ0) for t in range(T+1)])\n", + " \n", + " if verbose == 1:\n", + " print('check feasible:', np.isclose(β_seq @ v_seq, 0)) # since β = 1/R\n", + "\n", + " c_opt, _, _ = compute_optimal(model, a0, y_seq)\n", + " cvar_seq = c_opt + v_seq\n", + "\n", + " return cvar_seq" + ] + }, + { + "cell_type": "markdown", + "id": "4b10e183", + "metadata": {}, + "source": [ + "We visualize variations for $\\xi_1 \\in \\{.01, .05\\}$ and $\\phi \\in \\{.95, 1.02\\}$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "730ce577", + "metadata": {}, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "\n", + "ξ1s = [.01, .05]\n", + "ϕs= [.95, 1.02]\n", + "colors = {.01: 'tab:blue', .05: 'tab:green'}\n", + "\n", + "params = np.array(np.meshgrid(ξ1s, ϕs)).T.reshape(-1, 2)\n", + "\n", + "for i, param in enumerate(params):\n", + " ξ1, ϕ = param\n", + " print(f'variation {i}: ξ1={ξ1}, ϕ={ϕ}')\n", + " cvar_seq = compute_variation(model=cs_model, \n", + " ξ1=ξ1, ϕ=ϕ, a0=a0, \n", + " y_seq=y_seq)\n", + " print(f'welfare={welfare(cs_model, cvar_seq)}')\n", + " print('-'*64)\n", + " if i % 2 == 0:\n", + " ls = '-.'\n", + " else: \n", + " ls = '-' \n", + " ax.plot(range(T+1), cvar_seq, ls=ls, \n", + " color=colors[ξ1], \n", + " label=fr'$\\xi_1 = {ξ1}, \\phi = {ϕ}$')\n", + "\n", + "plt.plot(range(T+1), c_seq, \n", + " color='orange', label=r'Optimal $\\vec{c}$ ')\n", + "\n", + "plt.legend()\n", + "plt.xlabel(r'$t$')\n", + "plt.ylabel(r'$c_t$')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "a17172c0", + "metadata": {}, + "source": [ + "We can even use the Python `np.gradient` command to compute derivatives of welfare with respect to our two parameters. \n", + "\n", + "We are teaching the key idea beneath the **calculus of variations**.\n", + "\n", + "First, we define the welfare with respect to $\\xi_1$ and $\\phi$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d0b98755", + "metadata": {}, + "outputs": [], + "source": [ + "def welfare_rel(ξ1, ϕ):\n", + " \"\"\"\n", + " Compute welfare of variation sequence \n", + " for given ϕ, ξ1 with a consumption-smoothing model\n", + " \"\"\"\n", + " \n", + " cvar_seq = compute_variation(cs_model, ξ1=ξ1, \n", + " ϕ=ϕ, a0=a0, \n", + " y_seq=y_seq, \n", + " verbose=0)\n", + " return welfare(cs_model, cvar_seq)\n", + "\n", + "# Vectorize the function to allow array input\n", + "welfare_vec = np.vectorize(welfare_rel)" + ] + }, + { + "cell_type": "markdown", + "id": "54e92816", + "metadata": {}, + "source": [ + "Then we can visualize the relationship between welfare and $\\xi_1$ and compute its derivatives" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d83ab1eb", + "metadata": {}, + "outputs": [], + "source": [ + "ξ1_arr = np.linspace(-0.5, 0.5, 20)\n", + "\n", + "plt.plot(ξ1_arr, welfare_vec(ξ1_arr, 1.02))\n", + "plt.ylabel('welfare')\n", + "plt.xlabel(r'$\\xi_1$')\n", + "plt.show()\n", + "\n", + "welfare_grad = welfare_vec(ξ1_arr, 1.02)\n", + "welfare_grad = np.gradient(welfare_grad)\n", + "plt.plot(ξ1_arr, welfare_grad)\n", + "plt.ylabel('derivative of welfare')\n", + "plt.xlabel(r'$\\xi_1$')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "48eee396", + "metadata": {}, + "source": [ + "The same can be done on $\\phi$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5acbc447", + "metadata": {}, + "outputs": [], + "source": [ + "ϕ_arr = np.linspace(-0.5, 0.5, 20)\n", + "\n", + "plt.plot(ξ1_arr, welfare_vec(0.05, ϕ_arr))\n", + "plt.ylabel('welfare')\n", + "plt.xlabel(r'$\\phi$')\n", + "plt.show()\n", + "\n", + "welfare_grad = welfare_vec(0.05, ϕ_arr)\n", + "welfare_grad = np.gradient(welfare_grad)\n", + "plt.plot(ξ1_arr, welfare_grad)\n", + "plt.ylabel('derivative of welfare')\n", + "plt.xlabel(r'$\\phi$')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "06411588", + "metadata": {}, + "source": [ + "## Wrapping up the consumption-smoothing model\n", + "\n", + "The consumption-smoothing model of Milton Friedman {cite}`Friedman1956` and Robert Hall {cite}`Hall1978`) is a cornerstone of modern macro that has important ramifications for the size of the Keynesian \"fiscal policy multiplier\" described briefly in\n", + "QuantEcon lecture {doc}`geometric series `. \n", + "\n", + "In particular, it **lowers** the government expenditure multiplier relative to one implied by\n", + "the original Keynesian consumption function presented in {doc}`geometric series `.\n", + "\n", + "Friedman's work opened the door to an enlightening literature on the aggregate consumption function and associated government expenditure multipliers that\n", + "remains active today. \n", + "\n", + "\n", + "## Appendix: solving difference equations with linear algebra\n", + "\n", + "In the preceding sections we have used linear algebra to solve a consumption-smoothing model. \n", + "\n", + "The same tools from linear algebra -- matrix multiplication and matrix inversion -- can be used to study many other dynamic models.\n", + "\n", + "We'll conclude this lecture by giving a couple of examples.\n", + "\n", + "We'll describe a useful way of representing and \"solving\" linear difference equations. \n", + "\n", + "To generate some $y$ vectors, we'll just write down a linear difference equation\n", + "with appropriate initial conditions and then use linear algebra to solve it.\n", + "\n", + "### First-order difference equation\n", + "\n", + "We'll start with a first-order linear difference equation for $\\{y_t\\}_{t=0}^T$:\n", + "\n", + "$$\n", + "y_{t} = \\lambda y_{t-1}, \\quad t = 1, 2, \\ldots, T\n", + "$$\n", + "\n", + "where $y_0$ is a given initial condition.\n", + "\n", + "\n", + "We can cast this set of $T$ equations as a single matrix equation\n", + "\n", + "$$\n", + "\\begin{bmatrix} \n", + "1 & 0 & 0 & \\cdots & 0 & 0 \\cr\n", + "-\\lambda & 1 & 0 & \\cdots & 0 & 0 \\cr\n", + "0 & -\\lambda & 1 & \\cdots & 0 & 0 \\cr\n", + " \\vdots & \\vdots & \\vdots & \\cdots & \\vdots & \\vdots \\cr\n", + "0 & 0 & 0 & \\cdots & -\\lambda & 1 \n", + "\\end{bmatrix} \n", + "\\begin{bmatrix}\n", + "y_1 \\cr y_2 \\cr y_3 \\cr \\vdots \\cr y_T \n", + "\\end{bmatrix}\n", + "= \n", + "\\begin{bmatrix} \n", + "\\lambda y_0 \\cr 0 \\cr 0 \\cr \\vdots \\cr 0 \n", + "\\end{bmatrix}\n", + "$$ (eq:first_order_lin_diff)\n", + "\n", + "\n", + "Multiplying both sides of {eq}`eq:first_order_lin_diff` by the inverse of the matrix on the left provides the solution\n", + "\n", + "```{math}\n", + ":label: fst_ord_inverse\n", + "\n", + "\\begin{bmatrix} \n", + "y_1 \\cr y_2 \\cr y_3 \\cr \\vdots \\cr y_T \n", + "\\end{bmatrix} \n", + "= \n", + "\\begin{bmatrix} \n", + "1 & 0 & 0 & \\cdots & 0 & 0 \\cr\n", + "\\lambda & 1 & 0 & \\cdots & 0 & 0 \\cr\n", + "\\lambda^2 & \\lambda & 1 & \\cdots & 0 & 0 \\cr\n", + " \\vdots & \\vdots & \\vdots & \\cdots & \\vdots & \\vdots \\cr\n", + "\\lambda^{T-1} & \\lambda^{T-2} & \\lambda^{T-3} & \\cdots & \\lambda & 1 \n", + "\\end{bmatrix}\n", + "\\begin{bmatrix} \n", + "\\lambda y_0 \\cr 0 \\cr 0 \\cr \\vdots \\cr 0 \n", + "\\end{bmatrix}\n", + "```\n", + "\n", + "```{exercise}\n", + ":label: consmooth_ex1\n", + "\n", + "To get {eq}`fst_ord_inverse`, we multiplied both sides of {eq}`eq:first_order_lin_diff` by the inverse of the matrix $A$. Please confirm that \n", + "\n", + "$$\n", + "\\begin{bmatrix} \n", + "1 & 0 & 0 & \\cdots & 0 & 0 \\cr\n", + "\\lambda & 1 & 0 & \\cdots & 0 & 0 \\cr\n", + "\\lambda^2 & \\lambda & 1 & \\cdots & 0 & 0 \\cr\n", + " \\vdots & \\vdots & \\vdots & \\cdots & \\vdots & \\vdots \\cr\n", + "\\lambda^{T-1} & \\lambda^{T-2} & \\lambda^{T-3} & \\cdots & \\lambda & 1 \n", + "\\end{bmatrix}\n", + "$$\n", + "\n", + "is the inverse of $A$ and check that $A A^{-1} = I$\n", + "\n", + "```\n", + "\n", + "### Second-order difference equation\n", + "\n", + "A second-order linear difference equation for $\\{y_t\\}_{t=0}^T$ is\n", + "\n", + "$$\n", + "y_{t} = \\lambda_1 y_{t-1} + \\lambda_2 y_{t-2}, \\quad t = 1, 2, \\ldots, T\n", + "$$\n", + "\n", + "where now $y_0$ and $y_{-1}$ are two given initial equations determined outside the model. \n", + "\n", + "As we did with the first-order difference equation, we can cast this set of $T$ equations as a single matrix equation\n", + "\n", + "$$\n", + "\\begin{bmatrix} \n", + "1 & 0 & 0 & \\cdots & 0 & 0 & 0 \\cr\n", + "-\\lambda_1 & 1 & 0 & \\cdots & 0 & 0 & 0 \\cr\n", + "-\\lambda_2 & -\\lambda_1 & 1 & \\cdots & 0 & 0 & 0 \\cr\n", + " \\vdots & \\vdots & \\vdots & \\cdots & \\vdots & \\vdots \\cr\n", + "0 & 0 & 0 & \\cdots & -\\lambda_2 & -\\lambda_1 & 1 \n", + "\\end{bmatrix} \n", + "\\begin{bmatrix} \n", + "y_1 \\cr y_2 \\cr y_3 \\cr \\vdots \\cr y_T \n", + "\\end{bmatrix}\n", + "= \n", + "\\begin{bmatrix} \n", + "\\lambda_1 y_0 + \\lambda_2 y_{-1} \\cr \\lambda_2 y_0 \\cr 0 \\cr \\vdots \\cr 0 \n", + "\\end{bmatrix}\n", + "$$\n", + "\n", + "Multiplying both sides by inverse of the matrix on the left again provides the solution.\n", + "\n", + "```{exercise}\n", + ":label: consmooth_ex2\n", + "\n", + "As an exercise, we ask you to represent and solve a **third-order linear difference equation**.\n", + "How many initial conditions must you specify?\n", + "```" + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.16.1" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 44, + 48, + 139, + 148, + 264, + 284, + 294, + 306, + 310, + 323, + 329, + 337, + 347, + 369, + 379, + 386, + 391, + 399, + 407, + 413, + 419, + 425, + 433, + 445, + 449, + 457, + 461, + 469, + 541, + 555, + 560, + 592, + 601, + 616, + 621, + 635, + 640, + 654 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/cons_smooth.md b/book/_build/html/_sources/cons_smooth.md new file mode 100644 index 0000000..2719baa --- /dev/null +++ b/book/_build/html/_sources/cons_smooth.md @@ -0,0 +1,788 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.16.1 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + + +# Consumption Smoothing + +## Overview + + +In this lecture, we'll study a famous model of the "consumption function" that Milton Friedman {cite}`Friedman1956` and Robert Hall {cite}`Hall1978`) proposed to fit some empirical data patterns that the original Keynesian consumption function described in this QuantEcon lecture {doc}`geometric series ` missed. + +In this lecture, we'll study what is often called the "consumption-smoothing model" using matrix multiplication and matrix inversion, the same tools that we used in this QuantEcon lecture {doc}`present values `. + +Formulas presented in {doc}`present value formulas` are at the core of the consumption-smoothing model because we shall use them to define a consumer's "human wealth". + +The key idea that inspired Milton Friedman was that a person's non-financial income, i.e., his or +her wages from working, could be viewed as a dividend stream from that person's ''human capital'' +and that standard asset-pricing formulas could be applied to compute a person's +''non-financial wealth'' that capitalizes the earnings stream. + +```{note} +As we'll see in this QuantEcon lecture {doc}`equalizing difference model `, +Milton Friedman had used this idea in his PhD thesis at Columbia University, +eventually published as {cite}`kuznets1939incomes` and {cite}`friedman1954incomes`. +``` + +It will take a while for a "present value" or asset price explicilty to appear in this lecture, but when it does it will be a key actor. + + +## Analysis + +As usual, we'll start by importing some Python modules. + +```{code-cell} ipython3 +import numpy as np +import matplotlib.pyplot as plt +from collections import namedtuple +``` + + +The model describes a consumer who lives from time $t=0, 1, \ldots, T$, receives a stream $\{y_t\}_{t=0}^T$ of non-financial income and chooses a consumption stream $\{c_t\}_{t=0}^T$. + +We usually think of the non-financial income stream as coming from the person's salary from supplying labor. + +The model takes a non-financial income stream as an input, regarding it as "exogenous" in the sense of not being determined by the model. + +The consumer faces a gross interest rate of $R >1$ that is constant over time, at which she is free to borrow or lend, up to limits that we'll describe below. + +To set up the model, let + + * $T \geq 2$ be a positive integer that constitutes a time-horizon. + * $y = \{y_t\}_{t=0}^T$ be an exogenous sequence of non-negative non-financial incomes $y_t$. + * $a = \{a_t\}_{t=0}^{T+1}$ be a sequence of financial wealth. + * $c = \{c_t\}_{t=0}^T$ be a sequence of non-negative consumption rates. + * $R \geq 1$ be a fixed gross one period rate of return on financial assets. + * $\beta \in (0,1)$ be a fixed discount factor. + * $a_0$ be a given initial level of financial assets + * $a_{T+1} \geq 0$ be a terminal condition on final assets. + +The sequence of financial wealth $a$ is to be determined by the model. + +We require it to satisfy two **boundary conditions**: + + * it must equal an exogenous value $a_0$ at time $0$ + * it must equal or exceed an exogenous value $a_{T+1}$ at time $T+1$. + +The **terminal condition** $a_{T+1} \geq 0$ requires that the consumer not leave the model in debt. + +(We'll soon see that a utility maximizing consumer won't want to die leaving positive assets, so she'll arrange her affairs to make +$a_{T+1} = 0$.) + +The consumer faces a sequence of budget constraints that constrains sequences $(y, c, a)$ + +$$ +a_{t+1} = R (a_t+ y_t - c_t), \quad t =0, 1, \ldots T +$$ (eq:a_t) + +Equations {eq}`eq:a_t` constitute $T+1$ such budget constraints, one for each $t=0, 1, \ldots, T$. + +Given a sequence $y$ of non-financial incomes, a large set of pairs $(a, c)$ of (financial wealth, consumption) sequences satisfy the sequence of budget constraints {eq}`eq:a_t`. + +Our model has the following logical flow. + + * start with an exogenous non-financial income sequence $y$, an initial financial wealth $a_0$, and + a candidate consumption path $c$. + + * use the system of equations {eq}`eq:a_t` for $t=0, \ldots, T$ to compute a path $a$ of financial wealth + + * verify that $a_{T+1}$ satisfies the terminal wealth constraint $a_{T+1} \geq 0$. + + * If it does, declare that the candidate path is **budget feasible**. + + * if the candidate consumption path is not budget feasible, propose a less greedy consumption path and start over + +Below, we'll describe how to execute these steps using linear algebra -- matrix inversion and multiplication. + +The above procedure seems like a sensible way to find "budget-feasible" consumption paths $c$, i.e., paths that are consistent +with the exogenous non-financial income stream $y$, the initial financial asset level $a_0$, and the terminal asset level $a_{T+1}$. + +In general, there are **many** budget feasible consumption paths $c$. + +Among all budget-feasible consumption paths, which one should a consumer want? + + +To answer this question, we shall eventually evaluate alternative budget feasible consumption paths $c$ using the following utility functional or **welfare criterion**: + +```{math} +:label: welfare + +W = \sum_{t=0}^T \beta^t (g_1 c_t - \frac{g_2}{2} c_t^2 ) +``` + +where $g_1 > 0, g_2 > 0$. + +When $\beta R \approx 1$, the fact that the utility function $g_1 c_t - \frac{g_2}{2} c_t^2$ has diminishing marginal utility imparts a preference for consumption that is very smooth. + +Indeed, we shall see that when $\beta R = 1$ (a condition assumed by Milton Friedman {cite}`Friedman1956` and Robert Hall {cite}`Hall1978`), criterion {eq}`welfare` assigns higher welfare to smoother consumption paths. + +By **smoother** we mean as close as possible to being constant over time. + +The preference for smooth consumption paths that is built into the model gives it the name "consumption-smoothing model". + +Let's dive in and do some calculations that will help us understand how the model works. + +Here we use default parameters $R = 1.05$, $g_1 = 1$, $g_2 = 1/2$, and $T = 65$. + +We create a Python **namedtuple** to store these parameters with default values. + +```{code-cell} ipython3 +ConsumptionSmoothing = namedtuple("ConsumptionSmoothing", + ["R", "g1", "g2", "β_seq", "T"]) + +def create_consumption_smoothing_model(R=1.05, g1=1, g2=1/2, T=65): + β = 1/R + β_seq = np.array([β**i for i in range(T+1)]) + return ConsumptionSmoothing(R, g1, g2, + β_seq, T) +``` + + +## Friedman-Hall consumption-smoothing model + +A key object is what Milton Friedman called "human" or "non-financial" wealth at time $0$: + + +$$ +h_0 \equiv \sum_{t=0}^T R^{-t} y_t = \begin{bmatrix} 1 & R^{-1} & \cdots & R^{-T} \end{bmatrix} +\begin{bmatrix} y_0 \cr y_1 \cr \vdots \cr y_T \end{bmatrix} +$$ + +Human or non-financial wealth at time $0$ is evidently just the present value of the consumer's non-financial income stream $y$. + +Formally it very much resembles the asset price that we computed in this QuantEcon lecture {doc}`present values `. + +Indeed, this is why Milton Friedman called it "human capital". + +By iterating on equation {eq}`eq:a_t` and imposing the terminal condition + +$$ +a_{T+1} = 0, +$$ + +it is possible to convert a sequence of budget constraints {eq}`eq:a_t` into a single intertemporal constraint + +$$ +\sum_{t=0}^T R^{-t} c_t = a_0 + h_0. +$$ (eq:budget_intertemp) + +Equation {eq}`eq:budget_intertemp` says that the present value of the consumption stream equals the sum of financial and non-financial (or human) wealth. + +Robert Hall {cite}`Hall1978` showed that when $\beta R = 1$, a condition Milton Friedman had also assumed, it is "optimal" for a consumer to smooth consumption by setting + +$$ +c_t = c_0 \quad t =0, 1, \ldots, T +$$ + +(Later we'll present a "variational argument" that shows that this constant path maximizes +criterion {eq}`welfare` when $\beta R =1$.) + +In this case, we can use the intertemporal budget constraint to write + +$$ +c_t = c_0 = \left(\sum_{t=0}^T R^{-t}\right)^{-1} (a_0 + h_0), \quad t= 0, 1, \ldots, T. +$$ (eq:conssmoothing) + +Equation {eq}`eq:conssmoothing` is the consumption-smoothing model in a nutshell. + + +## Mechanics of consumption-smoothing model + +As promised, we'll provide step-by-step instructions on how to use linear algebra, readily implemented in Python, to compute all objects in play in the consumption-smoothing model. + +In the calculations below, we'll set default values of $R > 1$, e.g., $R = 1.05$, and $\beta = R^{-1}$. + +### Step 1 + +For a $(T+1) \times 1$ vector $y$, use matrix algebra to compute $h_0$ + +$$ +h_0 = \sum_{t=0}^T R^{-t} y_t = \begin{bmatrix} 1 & R^{-1} & \cdots & R^{-T} \end{bmatrix} +\begin{bmatrix} y_0 \cr y_1 \cr \vdots \cr y_T \end{bmatrix} +$$ + +### Step 2 + +Compute an time $0$ consumption $c_0 $ : + +$$ +c_t = c_0 = \left( \frac{1 - R^{-1}}{1 - R^{-(T+1)}} \right) (a_0 + \sum_{t=0}^T R^{-t} y_t ) , \quad t = 0, 1, \ldots, T +$$ + +### Step 3 + +Use the system of equations {eq}`eq:a_t` for $t=0, \ldots, T$ to compute a path $a$ of financial wealth. + +To do this, we translate that system of difference equations into a single matrix equation as follows: + + +$$ +\begin{bmatrix} +1 & 0 & 0 & \cdots & 0 & 0 & 0 \cr +-R & 1 & 0 & \cdots & 0 & 0 & 0 \cr +0 & -R & 1 & \cdots & 0 & 0 & 0 \cr +\vdots &\vdots & \vdots & \cdots & \vdots & \vdots & \vdots \cr +0 & 0 & 0 & \cdots & -R & 1 & 0 \cr +0 & 0 & 0 & \cdots & 0 & -R & 1 +\end{bmatrix} +\begin{bmatrix} a_1 \cr a_2 \cr a_3 \cr \vdots \cr a_T \cr a_{T+1} +\end{bmatrix} += R +\begin{bmatrix} y_0 + a_0 - c_0 \cr y_1 - c_0 \cr y_2 - c_0 \cr \vdots\cr y_{T-1} - c_0 \cr y_T - c_0 +\end{bmatrix} +$$ + +Multiply both sides by the inverse of the matrix on the left side to compute + +$$ + \begin{bmatrix} a_1 \cr a_2 \cr a_3 \cr \vdots \cr a_T \cr a_{T+1} \end{bmatrix} +$$ + + +Because we have built into our calculations that the consumer leaves the model with exactly zero assets, just barely satisfying the +terminal condition that $a_{T+1} \geq 0$, it should turn out that + +$$ +a_{T+1} = 0. +$$ + + +Let's verify this with Python code. + +First we implement the model with `compute_optimal` + +```{code-cell} ipython3 +def compute_optimal(model, a0, y_seq): + R, T = model.R, model.T + + # non-financial wealth + h0 = model.β_seq @ y_seq # since β = 1/R + + # c0 + c0 = (1 - 1/R) / (1 - (1/R)**(T+1)) * (a0 + h0) + c_seq = c0*np.ones(T+1) + + # verify + A = np.diag(-R*np.ones(T), k=-1) + np.eye(T+1) + b = y_seq - c_seq + b[0] = b[0] + a0 + + a_seq = np.linalg.inv(A) @ b + a_seq = np.concatenate([[a0], a_seq]) + + return c_seq, a_seq, h0 +``` + +We use an example where the consumer inherits $a_0<0$. + +This can be interpreted as a student debt. + +The non-financial process $\{y_t\}_{t=0}^{T}$ is constant and positive up to $t=45$ and then becomes zero afterward. + +The drop in non-financial income late in life reflects retirement from work. + +```{code-cell} ipython3 +# Financial wealth +a0 = -2 # such as "student debt" + +# non-financial Income process +y_seq = np.concatenate([np.ones(46), np.zeros(20)]) + +cs_model = create_consumption_smoothing_model() +c_seq, a_seq, h0 = compute_optimal(cs_model, a0, y_seq) + +print('check a_T+1=0:', + np.abs(a_seq[-1] - 0) <= 1e-8) +``` + +The graphs below show paths of non-financial income, consumption, and financial assets. + +```{code-cell} ipython3 +# Sequence Length +T = cs_model.T + +plt.plot(range(T+1), y_seq, label='non-financial income') +plt.plot(range(T+1), c_seq, label='consumption') +plt.plot(range(T+2), a_seq, label='financial wealth') +plt.plot(range(T+2), np.zeros(T+2), '--') + +plt.legend() +plt.xlabel(r'$t$') +plt.ylabel(r'$c_t,y_t,a_t$') +plt.show() +``` + +Note that $a_{T+1} = 0$, as anticipated. + +We can evaluate welfare criterion {eq}`welfare` + +```{code-cell} ipython3 +def welfare(model, c_seq): + β_seq, g1, g2 = model.β_seq, model.g1, model.g2 + + u_seq = g1 * c_seq - g2/2 * c_seq**2 + return β_seq @ u_seq + +print('Welfare:', welfare(cs_model, c_seq)) +``` + +### Experiments + +In this section we describe how a consumption sequence would optimally respond to different sequences sequences of non-financial income. + +First we create a function `plot_cs` that generates graphs for different instances of the consumption-smoothing model `cs_model`. + +This will help us avoid rewriting code to plot outcomes for different non-financial income sequences. + +```{code-cell} ipython3 +def plot_cs(model, # consumption-smoothing model + a0, # initial financial wealth + y_seq # non-financial income process + ): + + # Compute optimal consumption + c_seq, a_seq, h0 = compute_optimal(model, a0, y_seq) + + # Sequence length + T = cs_model.T + + # Generate plot + plt.plot(range(T+1), y_seq, label='non-financial income') + plt.plot(range(T+1), c_seq, label='consumption') + plt.plot(range(T+2), a_seq, label='financial wealth') + plt.plot(range(T+2), np.zeros(T+2), '--') + + plt.legend() + plt.xlabel(r'$t$') + plt.ylabel(r'$c_t,y_t,a_t$') + plt.show() +``` + +In the experiments below, please study how consumption and financial asset sequences vary across different sequences for non-financial income. + +#### Experiment 1: one-time gain/loss + +We first assume a one-time windfall of $W_0$ in year 21 of the income sequence $y$. + +We'll make $W_0$ big - positive to indicate a one-time windfall, and negative to indicate a one-time "disaster". + +```{code-cell} ipython3 +# Windfall W_0 = 2.5 +y_seq_pos = np.concatenate([np.ones(21), np.array([2.5]), np.ones(24), np.zeros(20)]) + +plot_cs(cs_model, a0, y_seq_pos) +``` + +```{code-cell} ipython3 +# Disaster W_0 = -2.5 +y_seq_neg = np.concatenate([np.ones(21), np.array([-2.5]), np.ones(24), np.zeros(20)]) + +plot_cs(cs_model, a0, y_seq_neg) +``` + +#### Experiment 2: permanent wage gain/loss + +Now we assume a permanent increase in income of $W$ in year 21 of the $y$-sequence. + +Again we can study positive and negative cases + +```{code-cell} ipython3 +# Positive permanent income change W = 0.5 when t >= 21 +y_seq_pos = np.concatenate( + [np.ones(21), 1.5*np.ones(25), np.zeros(20)]) + +plot_cs(cs_model, a0, y_seq_pos) +``` + +```{code-cell} ipython3 +# Negative permanent income change W = -0.5 when t >= 21 +y_seq_neg = np.concatenate( + [np.ones(21), .5*np.ones(25), np.zeros(20)]) + +plot_cs(cs_model, a0, y_seq_neg) +``` + +#### Experiment 3: a late starter + +Now we simulate a $y$ sequence in which a person gets zero for 46 years, and then works and gets 1 for the last 20 years of life (a "late starter") + +```{code-cell} ipython3 +# Late starter +y_seq_late = np.concatenate( + [np.zeros(46), np.ones(20)]) + +plot_cs(cs_model, a0, y_seq_late) +``` + +#### Experiment 4: geometric earner + +Now we simulate a geometric $y$ sequence in which a person gets $y_t = \lambda^t y_0$ in first 46 years. + +We first experiment with $\lambda = 1.05$ + +```{code-cell} ipython3 +# Geometric earner parameters where λ = 1.05 +λ = 1.05 +y_0 = 1 +t_max = 46 + +# Generate geometric y sequence +geo_seq = λ ** np.arange(t_max) * y_0 +y_seq_geo = np.concatenate( + [geo_seq, np.zeros(20)]) + +plot_cs(cs_model, a0, y_seq_geo) +``` + +Now we show the behavior when $\lambda = 0.95$ + +```{code-cell} ipython3 +λ = 0.95 + +geo_seq = λ ** np.arange(t_max) * y_0 +y_seq_geo = np.concatenate( + [geo_seq, np.zeros(20)]) + +plot_cs(cs_model, a0, y_seq_geo) +``` + +What happens when $\lambda$ is negative + +```{code-cell} ipython3 +λ = -0.95 + +geo_seq = λ ** np.arange(t_max) * y_0 +y_seq_geo = np.concatenate( + [geo_seq, np.zeros(20)]) + +plot_cs(cs_model, a0, y_seq_geo) +``` + + +### Feasible consumption variations + +We promised to justify our claim that a constant consumption play $c_t = c_0$ for all +$t$ is optimal. + +Let's do that now. + +The approach we'll take is an elementary example of the "calculus of variations". + +Let's dive in and see what the key idea is. + +To explore what types of consumption paths are welfare-improving, we shall create an **admissible consumption path variation sequence** $\{v_t\}_{t=0}^T$ +that satisfies + +$$ +\sum_{t=0}^T R^{-t} v_t = 0 +$$ + +This equation says that the **present value** of admissible consumption path variations must be zero. + +So once again, we encounter a formula for the present value of an "asset": + + * we require that the present value of consumption path variations be zero. + +Here we'll restrict ourselves to a two-parameter class of admissible consumption path variations +of the form + +$$ +v_t = \xi_1 \phi^t - \xi_0 +$$ + +We say two and not three-parameter class because $\xi_0$ will be a function of $(\phi, \xi_1; R)$ that guarantees that the variation sequence is feasible. + +Let's compute that function. + +We require + +$$ +\sum_{t=0}^T R^{-t}\left[ \xi_1 \phi^t - \xi_0 \right] = 0 +$$ + +which implies that + +$$ +\xi_1 \sum_{t=0}^T \phi_t R^{-t} - \xi_0 \sum_{t=0}^T R^{-t} = 0 +$$ + +which implies that + +$$ +\xi_1 \frac{1 - (\phi R^{-1})^{T+1}}{1 - \phi R^{-1}} - \xi_0 \frac{1 - R^{-(T+1)}}{1-R^{-1} } =0 +$$ + +which implies that + +$$ +\xi_0 = \xi_0(\phi, \xi_1; R) = \xi_1 \left(\frac{1 - R^{-1}}{1 - R^{-(T+1)}}\right) \left(\frac{1 - (\phi R^{-1})^{T+1}}{1 - \phi R^{-1}}\right) +$$ + +This is our formula for $\xi_0$. + +**Key Idea:** if $c^o$ is a budget-feasible consumption path, then so is $c^o + v$, +where $v$ is a budget-feasible variation. + +Given $R$, we thus have a two parameter class of budget feasible variations $v$ that we can use +to compute alternative consumption paths, then evaluate their welfare. + +Now let's compute and plot consumption path variations + +```{code-cell} ipython3 +def compute_variation(model, ξ1, ϕ, a0, y_seq, verbose=1): + R, T, β_seq = model.R, model.T, model.β_seq + + ξ0 = ξ1*((1 - 1/R) / (1 - (1/R)**(T+1))) * ((1 - (ϕ/R)**(T+1)) / (1 - ϕ/R)) + v_seq = np.array([(ξ1*ϕ**t - ξ0) for t in range(T+1)]) + + if verbose == 1: + print('check feasible:', np.isclose(β_seq @ v_seq, 0)) # since β = 1/R + + c_opt, _, _ = compute_optimal(model, a0, y_seq) + cvar_seq = c_opt + v_seq + + return cvar_seq +``` + + +We visualize variations for $\xi_1 \in \{.01, .05\}$ and $\phi \in \{.95, 1.02\}$ + +```{code-cell} ipython3 +fig, ax = plt.subplots() + +ξ1s = [.01, .05] +ϕs= [.95, 1.02] +colors = {.01: 'tab:blue', .05: 'tab:green'} + +params = np.array(np.meshgrid(ξ1s, ϕs)).T.reshape(-1, 2) + +for i, param in enumerate(params): + ξ1, ϕ = param + print(f'variation {i}: ξ1={ξ1}, ϕ={ϕ}') + cvar_seq = compute_variation(model=cs_model, + ξ1=ξ1, ϕ=ϕ, a0=a0, + y_seq=y_seq) + print(f'welfare={welfare(cs_model, cvar_seq)}') + print('-'*64) + if i % 2 == 0: + ls = '-.' + else: + ls = '-' + ax.plot(range(T+1), cvar_seq, ls=ls, + color=colors[ξ1], + label=fr'$\xi_1 = {ξ1}, \phi = {ϕ}$') + +plt.plot(range(T+1), c_seq, + color='orange', label=r'Optimal $\vec{c}$ ') + +plt.legend() +plt.xlabel(r'$t$') +plt.ylabel(r'$c_t$') +plt.show() +``` + + +We can even use the Python `np.gradient` command to compute derivatives of welfare with respect to our two parameters. + +We are teaching the key idea beneath the **calculus of variations**. + +First, we define the welfare with respect to $\xi_1$ and $\phi$ + +```{code-cell} ipython3 +def welfare_rel(ξ1, ϕ): + """ + Compute welfare of variation sequence + for given ϕ, ξ1 with a consumption-smoothing model + """ + + cvar_seq = compute_variation(cs_model, ξ1=ξ1, + ϕ=ϕ, a0=a0, + y_seq=y_seq, + verbose=0) + return welfare(cs_model, cvar_seq) + +# Vectorize the function to allow array input +welfare_vec = np.vectorize(welfare_rel) +``` + + +Then we can visualize the relationship between welfare and $\xi_1$ and compute its derivatives + +```{code-cell} ipython3 +ξ1_arr = np.linspace(-0.5, 0.5, 20) + +plt.plot(ξ1_arr, welfare_vec(ξ1_arr, 1.02)) +plt.ylabel('welfare') +plt.xlabel(r'$\xi_1$') +plt.show() + +welfare_grad = welfare_vec(ξ1_arr, 1.02) +welfare_grad = np.gradient(welfare_grad) +plt.plot(ξ1_arr, welfare_grad) +plt.ylabel('derivative of welfare') +plt.xlabel(r'$\xi_1$') +plt.show() +``` + + +The same can be done on $\phi$ + +```{code-cell} ipython3 +ϕ_arr = np.linspace(-0.5, 0.5, 20) + +plt.plot(ξ1_arr, welfare_vec(0.05, ϕ_arr)) +plt.ylabel('welfare') +plt.xlabel(r'$\phi$') +plt.show() + +welfare_grad = welfare_vec(0.05, ϕ_arr) +welfare_grad = np.gradient(welfare_grad) +plt.plot(ξ1_arr, welfare_grad) +plt.ylabel('derivative of welfare') +plt.xlabel(r'$\phi$') +plt.show() +``` + +## Wrapping up the consumption-smoothing model + +The consumption-smoothing model of Milton Friedman {cite}`Friedman1956` and Robert Hall {cite}`Hall1978`) is a cornerstone of modern macro that has important ramifications for the size of the Keynesian "fiscal policy multiplier" described briefly in +QuantEcon lecture {doc}`geometric series `. + +In particular, it **lowers** the government expenditure multiplier relative to one implied by +the original Keynesian consumption function presented in {doc}`geometric series `. + +Friedman's work opened the door to an enlightening literature on the aggregate consumption function and associated government expenditure multipliers that +remains active today. + + +## Appendix: solving difference equations with linear algebra + +In the preceding sections we have used linear algebra to solve a consumption-smoothing model. + +The same tools from linear algebra -- matrix multiplication and matrix inversion -- can be used to study many other dynamic models. + +We'll conclude this lecture by giving a couple of examples. + +We'll describe a useful way of representing and "solving" linear difference equations. + +To generate some $y$ vectors, we'll just write down a linear difference equation +with appropriate initial conditions and then use linear algebra to solve it. + +### First-order difference equation + +We'll start with a first-order linear difference equation for $\{y_t\}_{t=0}^T$: + +$$ +y_{t} = \lambda y_{t-1}, \quad t = 1, 2, \ldots, T +$$ + +where $y_0$ is a given initial condition. + + +We can cast this set of $T$ equations as a single matrix equation + +$$ +\begin{bmatrix} +1 & 0 & 0 & \cdots & 0 & 0 \cr +-\lambda & 1 & 0 & \cdots & 0 & 0 \cr +0 & -\lambda & 1 & \cdots & 0 & 0 \cr + \vdots & \vdots & \vdots & \cdots & \vdots & \vdots \cr +0 & 0 & 0 & \cdots & -\lambda & 1 +\end{bmatrix} +\begin{bmatrix} +y_1 \cr y_2 \cr y_3 \cr \vdots \cr y_T +\end{bmatrix} += +\begin{bmatrix} +\lambda y_0 \cr 0 \cr 0 \cr \vdots \cr 0 +\end{bmatrix} +$$ (eq:first_order_lin_diff) + + +Multiplying both sides of {eq}`eq:first_order_lin_diff` by the inverse of the matrix on the left provides the solution + +```{math} +:label: fst_ord_inverse + +\begin{bmatrix} +y_1 \cr y_2 \cr y_3 \cr \vdots \cr y_T +\end{bmatrix} += +\begin{bmatrix} +1 & 0 & 0 & \cdots & 0 & 0 \cr +\lambda & 1 & 0 & \cdots & 0 & 0 \cr +\lambda^2 & \lambda & 1 & \cdots & 0 & 0 \cr + \vdots & \vdots & \vdots & \cdots & \vdots & \vdots \cr +\lambda^{T-1} & \lambda^{T-2} & \lambda^{T-3} & \cdots & \lambda & 1 +\end{bmatrix} +\begin{bmatrix} +\lambda y_0 \cr 0 \cr 0 \cr \vdots \cr 0 +\end{bmatrix} +``` + +```{exercise} +:label: consmooth_ex1 + +To get {eq}`fst_ord_inverse`, we multiplied both sides of {eq}`eq:first_order_lin_diff` by the inverse of the matrix $A$. Please confirm that + +$$ +\begin{bmatrix} +1 & 0 & 0 & \cdots & 0 & 0 \cr +\lambda & 1 & 0 & \cdots & 0 & 0 \cr +\lambda^2 & \lambda & 1 & \cdots & 0 & 0 \cr + \vdots & \vdots & \vdots & \cdots & \vdots & \vdots \cr +\lambda^{T-1} & \lambda^{T-2} & \lambda^{T-3} & \cdots & \lambda & 1 +\end{bmatrix} +$$ + +is the inverse of $A$ and check that $A A^{-1} = I$ + +``` + +### Second-order difference equation + +A second-order linear difference equation for $\{y_t\}_{t=0}^T$ is + +$$ +y_{t} = \lambda_1 y_{t-1} + \lambda_2 y_{t-2}, \quad t = 1, 2, \ldots, T +$$ + +where now $y_0$ and $y_{-1}$ are two given initial equations determined outside the model. + +As we did with the first-order difference equation, we can cast this set of $T$ equations as a single matrix equation + +$$ +\begin{bmatrix} +1 & 0 & 0 & \cdots & 0 & 0 & 0 \cr +-\lambda_1 & 1 & 0 & \cdots & 0 & 0 & 0 \cr +-\lambda_2 & -\lambda_1 & 1 & \cdots & 0 & 0 & 0 \cr + \vdots & \vdots & \vdots & \cdots & \vdots & \vdots \cr +0 & 0 & 0 & \cdots & -\lambda_2 & -\lambda_1 & 1 +\end{bmatrix} +\begin{bmatrix} +y_1 \cr y_2 \cr y_3 \cr \vdots \cr y_T +\end{bmatrix} += +\begin{bmatrix} +\lambda_1 y_0 + \lambda_2 y_{-1} \cr \lambda_2 y_0 \cr 0 \cr \vdots \cr 0 +\end{bmatrix} +$$ + +Multiplying both sides by inverse of the matrix on the left again provides the solution. + +```{exercise} +:label: consmooth_ex2 + +As an exercise, we ask you to represent and solve a **third-order linear difference equation**. +How many initial conditions must you specify? +``` diff --git a/content/lectures/eigen_I.ipynb b/book/_build/html/_sources/eigen_I.ipynb similarity index 68% rename from content/lectures/eigen_I.ipynb rename to book/_build/html/_sources/eigen_I.ipynb index 21b9468..4cf9ce0 100644 --- a/content/lectures/eigen_I.ipynb +++ b/book/_build/html/_sources/eigen_I.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "d6cbeebc", + "id": "db81524a", "metadata": { "user_expressions": [] }, @@ -13,14 +13,9 @@ "```{index} single: Eigenvalues and Eigenvectors\n", "```\n", "\n", - "```{contents} Contents\n", - ":depth: 2\n", - "```\n", - "\n", "## Overview\n", "\n", - "Eigenvalues and eigenvectors are a somewhat advanced topic in linear and\n", - "matrix algebra.\n", + "Eigenvalues and eigenvectors are a relatively advanced topic in linear algebra.\n", "\n", "At the same time, these concepts are extremely useful for \n", "\n", @@ -30,17 +25,10 @@ "* machine learning\n", "* and many other fields of science.\n", "\n", - "In this lecture we explain the basics of eigenvalues and eigenvectors, and\n", - "state two very important results from linear algebra.\n", - "\n", - "The first is called the Neumann series theorem and the second is called the\n", - "Perron-Frobenius theorem.\n", + "In this lecture we explain the basics of eigenvalues and eigenvectors and introduce the Neumann Series Lemma.\n", "\n", - "We will explain what these theorems tell us and how we can use them to\n", - "understand the predictions of economic models.\n", - "\n", - "We assume in this lecture that students are familiar with matrices and\n", - "understand the basics of matrix algebra.\n", + "We assume in this lecture that students are familiar with matrices\n", + " and understand {doc}`the basics of matrix algebra`.\n", "\n", "We will use the following imports:" ] @@ -48,39 +36,35 @@ { "cell_type": "code", "execution_count": null, - "id": "5928f6e3", + "id": "8b155d43", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "from numpy.linalg import matrix_power\n", - "from matplotlib import cm\n", "from matplotlib.lines import Line2D\n", - "from mpl_toolkits.mplot3d import Axes3D\n", "from matplotlib.patches import FancyArrowPatch\n", "from mpl_toolkits.mplot3d import proj3d" ] }, { "cell_type": "markdown", - "id": "94449a82", - "metadata": { - "user_expressions": [] - }, + "id": "6f681f6e", + "metadata": {}, "source": [ "(matrices_as_transformation)=\n", "## Matrices as transformations\n", "\n", "Let's start by discussing an important concept concerning matrices.\n", "\n", - "### Mapping vectors into vectors\n", + "### Mapping vectors to vectors\n", "\n", - "One way to think about a given matrix is as a rectangular collection of\n", + "One way to think about a matrix is as a rectangular collection of\n", "numbers.\n", "\n", - "Another way to think about a matrix is as a **map** (i.e., as a function) that\n", - "transforms vectors into new vectors.\n", + "Another way to think about a matrix is as a *map* (i.e., as a function) that\n", + "transforms vectors to new vectors.\n", "\n", "To understand the second point of view, suppose we multiply an $n \\times m$\n", "matrix $A$ with an $m \\times 1$ column vector $x$ to obtain an $n \\times 1$\n", @@ -91,26 +75,27 @@ "$$\n", "\n", "If we fix $A$ and consider different choices of $x$, we can understand $A$ as\n", - "a map transforming $x$ into $Ax$.\n", + "a map transforming $x$ to $Ax$.\n", "\n", - "Because $A$ is $n \\times m$, it transforms $m$-vectors into $n$-vectors.\n", + "Because $A$ is $n \\times m$, it transforms $m$-vectors to $n$-vectors.\n", "\n", - "We can write this formally as $A \\colon \\mathbb{R}^m \\rightarrow \\mathbb{R}^n$ \n", + "We can write this formally as $A \\colon \\mathbb{R}^m \\rightarrow \\mathbb{R}^n$.\n", "\n", - "(You might argue that if $A$ is a function then we should write \n", - "$A(x) = y$ rather than $Ax = y$ but the second notation is more conventional.)\n", + "You might argue that if $A$ is a function then we should write \n", + "$A(x) = y$ rather than $Ax = y$ but the second notation is more conventional.\n", "\n", "### Square matrices\n", "\n", "Let's restrict our discussion to square matrices.\n", "\n", - "In the above discussion, this means that $m=n$ and $A$ maps $\\mathbb R^n$ into\n", + "In the above discussion, this means that $m=n$ and $A$ maps $\\mathbb R^n$ to\n", "itself.\n", "\n", - "To repeat, $A$ is an $n \\times n$ matrix that maps (or \"transforms\") a vector\n", - "$x$ in $\\mathbb{R}^n$ into a new vector $y=Ax$ also in $\\mathbb{R}^n$.\n", + "This means $A$ is an $n \\times n$ matrix that maps (or \"transforms\") a vector\n", + "$x$ in $\\mathbb{R}^n$ to a new vector $y=Ax$ also in $\\mathbb{R}^n$.\n", "\n", - "Here's one example:\n", + "```{prf:example}\n", + ":label: eigen1_ex_sq\n", "\n", "$$\n", " \\begin{bmatrix}\n", @@ -136,8 +121,9 @@ " \\end{bmatrix}\n", "$$\n", "\n", - "transforms the vector $x = \\begin{bmatrix} 1 \\\\ 3 \\end{bmatrix}$ into the vector\n", + "transforms the vector $x = \\begin{bmatrix} 1 \\\\ 3 \\end{bmatrix}$ to the vector\n", "$y = \\begin{bmatrix} 5 \\\\ 2 \\end{bmatrix}$.\n", + "```\n", "\n", "Let's visualize this using Python:" ] @@ -145,18 +131,18 @@ { "cell_type": "code", "execution_count": null, - "id": "e9e5f08e", + "id": "56adfb2d", "metadata": {}, "outputs": [], "source": [ - "A = np.array([[2, 1], \n", + "A = np.array([[2, 1],\n", " [-1, 1]])" ] }, { "cell_type": "code", "execution_count": null, - "id": "8229460b", + "id": "a4114d91", "metadata": {}, "outputs": [], "source": [ @@ -172,43 +158,44 @@ "\n", "ax.set(xlim=(-2, 6), ylim=(-2, 4), aspect=1)\n", "\n", - "vecs = ((1, 3),(5, 2))\n", - "c = ['r','black']\n", + "vecs = ((1, 3), (5, 2))\n", + "c = ['r', 'black']\n", "for i, v in enumerate(vecs):\n", " ax.annotate('', xy=v, xytext=(0, 0),\n", " arrowprops=dict(color=c[i],\n", " shrink=0,\n", " alpha=0.7,\n", " width=0.5))\n", - " \n", - "ax.text(0.2 + 1 , 0.2 + 3, 'x=$(1,3)$')\n", - "ax.text(0.2 + 5 , 0.2 + 2, 'Ax=$(5,2)$')\n", - " \n", - "ax.annotate('', xy=(sqrt(10/29)* 5, sqrt(10/29) *2), xytext=(0, 0),\n", - " arrowprops=dict(color='purple',\n", - " shrink=0,\n", - " alpha=0.7,\n", - " width=0.5))\n", "\n", - "ax.annotate('',xy=(1,2/5),xytext=(1/3, 1),\n", - " arrowprops={'arrowstyle':'->', 'connectionstyle':'arc3,rad=-0.3'}\n", - " ,horizontalalignment='center')\n", - "ax.text(0.8,0.8, f'θ',fontsize =14)\n", + "ax.text(0.2 + 1, 0.2 + 3, 'x=$(1,3)$')\n", + "ax.text(0.2 + 5, 0.2 + 2, 'Ax=$(5,2)$')\n", + "\n", + "ax.annotate('', xy=(sqrt(10/29) * 5, sqrt(10/29) * 2), xytext=(0, 0),\n", + " arrowprops=dict(color='purple',\n", + " shrink=0,\n", + " alpha=0.7,\n", + " width=0.5))\n", + "\n", + "ax.annotate('', xy=(1, 2/5), xytext=(1/3, 1),\n", + " arrowprops={'arrowstyle': '->',\n", + " 'connectionstyle': 'arc3,rad=-0.3'},\n", + " horizontalalignment='center')\n", + "ax.text(0.8, 0.8, f'θ', fontsize=14)\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "8542f1bd", + "id": "6c349d5b", "metadata": { "user_expressions": [] }, "source": [ "One way to understand this transformation is that $A$ \n", "\n", - "* first rotates $x$ by some angle $\\theta$ \n", - "* and then scales it by some scalar $\\gamma$ to obtain the image $y$ of $x$.\n", + "* first rotates $x$ by some angle $\\theta$ and\n", + "* then scales it by some scalar $\\gamma$ to obtain the image $y$ of $x$.\n", "\n", "\n", "\n", @@ -222,17 +209,17 @@ "We consider how a given matrix transforms \n", "\n", "* a grid of points and \n", - "* a set of points located on the unit circle in $\\mathbb{R}^2$\n", + "* a set of points located on the unit circle in $\\mathbb{R}^2$.\n", "\n", "To build the transformations we will use two functions, called `grid_transform` and `circle_transform`.\n", "\n", - "Each of these functions visualizes the action of a given $2 \\times 2$ matrix $A$." + "Each of these functions visualizes the actions of a given $2 \\times 2$ matrix $A$." ] }, { "cell_type": "code", "execution_count": null, - "id": "049b1d5a", + "id": "da8eb89d", "metadata": { "tags": [ "hide-input" @@ -246,16 +233,17 @@ " b = 1/4 + x/16\n", " return (r, g, b)\n", "\n", - "def grid_transform(A = np.array([[1, -1], [1, 1]])):\n", + "\n", + "def grid_transform(A=np.array([[1, -1], [1, 1]])):\n", " xvals = np.linspace(-4, 4, 9)\n", " yvals = np.linspace(-3, 3, 7)\n", " xygrid = np.column_stack([[x, y] for x in xvals for y in yvals])\n", " uvgrid = A @ xygrid\n", - " \n", + "\n", " colors = list(map(colorizer, xygrid[0], xygrid[1]))\n", - " \n", - " figure, ax = plt.subplots(1,2, figsize = (10,5))\n", - " \n", + "\n", + " fig, ax = plt.subplots(1, 2, figsize=(10, 5))\n", + "\n", " for axes in ax:\n", " axes.set(xlim=(-11, 11), ylim=(-11, 11))\n", " axes.set_xticks([])\n", @@ -264,25 +252,26 @@ " axes.spines[spine].set_position('zero')\n", " for spine in ['right', 'top']:\n", " axes.spines[spine].set_color('none')\n", - " \n", + "\n", " # Plot x-y grid points\n", " ax[0].scatter(xygrid[0], xygrid[1], s=36, c=colors, edgecolor=\"none\")\n", - " #ax[0].grid(True)\n", - " #ax[0].axis(\"equal\")\n", + " # ax[0].grid(True)\n", + " # ax[0].axis(\"equal\")\n", " ax[0].set_title(\"points $x_1, x_2, \\cdots, x_k$\")\n", - " \n", + "\n", " # Plot transformed grid points\n", " ax[1].scatter(uvgrid[0], uvgrid[1], s=36, c=colors, edgecolor=\"none\")\n", - " #ax[1].grid(True)\n", - " #ax[1].axis(\"equal\")\n", + " # ax[1].grid(True)\n", + " # ax[1].axis(\"equal\")\n", " ax[1].set_title(\"points $Ax_1, Ax_2, \\cdots, Ax_k$\")\n", - " \n", + "\n", " plt.show()\n", "\n", - "def circle_transform(A = np.array([[-1, 2], [0, 1]])):\n", - " \n", - " figure, ax = plt.subplots(1,2, figsize = (10,5))\n", - " \n", + "\n", + "def circle_transform(A=np.array([[-1, 2], [0, 1]])):\n", + "\n", + " fig, ax = plt.subplots(1, 2, figsize=(10, 5))\n", + "\n", " for axes in ax:\n", " axes.set(xlim=(-4, 4), ylim=(-4, 4))\n", " axes.set_xticks([])\n", @@ -291,41 +280,44 @@ " axes.spines[spine].set_position('zero')\n", " for spine in ['right', 'top']:\n", " axes.spines[spine].set_color('none')\n", - " \n", - " θ = np.linspace( 0 , 2 * np.pi , 150) \n", + "\n", + " θ = np.linspace(0, 2 * np.pi, 150)\n", " r = 1\n", - " \n", + "\n", " θ_1 = np.empty(12)\n", " for i in range(12):\n", " θ_1[i] = 2 * np.pi * (i/12)\n", - " \n", - " x = r * np.cos(θ) \n", + "\n", + " x = r * np.cos(θ)\n", " y = r * np.sin(θ)\n", " a = r * np.cos(θ_1)\n", " b = r * np.sin(θ_1)\n", - " a_1 = a.reshape(1,-1)\n", - " b_1 = b.reshape(1,-1)\n", + " a_1 = a.reshape(1, -1)\n", + " b_1 = b.reshape(1, -1)\n", " colors = list(map(colorizer, a, b))\n", - " ax[0].plot(x, y, color = 'black', zorder=1)\n", - " ax[0].scatter(a_1,b_1, c = colors, alpha = 1, s = 60, edgecolors = 'black', zorder =2)\n", + " ax[0].plot(x, y, color='black', zorder=1)\n", + " ax[0].scatter(a_1, b_1, c=colors, alpha=1, s=60,\n", + " edgecolors='black', zorder=2)\n", " ax[0].set_title(\"unit circle in $\\mathbb{R}^2$\")\n", - " \n", - " x1= x.reshape(1,-1)\n", + "\n", + " x1 = x.reshape(1, -1)\n", " y1 = y.reshape(1, -1)\n", - " ab = np.concatenate((a_1,b_1), axis=0)\n", + " ab = np.concatenate((a_1, b_1), axis=0)\n", " transformed_ab = A @ ab\n", - " transformed_circle_input = np.concatenate((x1,y1), axis=0)\n", + " transformed_circle_input = np.concatenate((x1, y1), axis=0)\n", " transformed_circle = A @ transformed_circle_input\n", - " ax[1].plot(transformed_circle[0,:], transformed_circle[1,:], color = 'black', zorder= 1) \n", - " ax[1].scatter(transformed_ab[0,:],transformed_ab[1:,], color = colors, alpha = 1, s = 60, edgecolors = 'black', zorder =2)\n", + " ax[1].plot(transformed_circle[0, :],\n", + " transformed_circle[1, :], color='black', zorder=1)\n", + " ax[1].scatter(transformed_ab[0, :], transformed_ab[1:,],\n", + " color=colors, alpha=1, s=60, edgecolors='black', zorder=2)\n", " ax[1].set_title(\"transformed circle\")\n", - " \n", + "\n", " plt.show()" ] }, { "cell_type": "markdown", - "id": "8b2cd59e", + "id": "84158333", "metadata": { "user_expressions": [] }, @@ -350,11 +342,11 @@ { "cell_type": "code", "execution_count": null, - "id": "16cb774a", + "id": "7960b7af", "metadata": {}, "outputs": [], "source": [ - "A = np.array([[3 ,0], #scaling by 3 in both directions\n", + "A = np.array([[3, 0], # scaling by 3 in both directions\n", " [0, 3]])\n", "grid_transform(A)\n", "circle_transform(A)" @@ -362,7 +354,7 @@ }, { "cell_type": "markdown", - "id": "be179291", + "id": "32285232", "metadata": { "user_expressions": [] }, @@ -385,7 +377,7 @@ { "cell_type": "code", "execution_count": null, - "id": "476cd58a", + "id": "27f88a7f", "metadata": {}, "outputs": [], "source": [ @@ -397,7 +389,7 @@ }, { "cell_type": "markdown", - "id": "e1a80b86", + "id": "9de1d252", "metadata": { "user_expressions": [] }, @@ -420,11 +412,11 @@ { "cell_type": "code", "execution_count": null, - "id": "6faf4397", + "id": "1418c1a3", "metadata": {}, "outputs": [], "source": [ - "θ = np.pi/4 #45 degree clockwise rotation\n", + "θ = np.pi/4 # 45 degree clockwise rotation\n", "A = np.array([[np.cos(θ), np.sin(θ)],\n", " [-np.sin(θ), np.cos(θ)]])\n", "grid_transform(A)" @@ -432,7 +424,7 @@ }, { "cell_type": "markdown", - "id": "e3ee61c8", + "id": "604a12d3", "metadata": { "user_expressions": [] }, @@ -453,7 +445,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4abddde1", + "id": "b6de4fc7", "metadata": {}, "outputs": [], "source": [ @@ -463,7 +455,7 @@ }, { "cell_type": "markdown", - "id": "824b2d9f", + "id": "ecd244dd", "metadata": { "user_expressions": [] }, @@ -584,10 +576,10 @@ "\n", "Thus the matrix product $AB$ is the\n", "[composition](https://en.wikipedia.org/wiki/Function_composition) of the\n", - "matrix transformations $A$ and $B$.\n", + "matrix transformations $A$ and $B$\n", "\n", - "(To compose the transformations, first apply transformation $B$ and then\n", - "transformation $A$.)\n", + "This means first apply transformation $B$ and then\n", + "transformation $A$.\n", "\n", "When we matrix multiply an $n \\times m$ matrix $A$ with an $m \\times k$ matrix\n", "$B$ the obtained matrix product is an $n \\times k$ matrix $AB$.\n", @@ -597,7 +589,7 @@ "transforms $\\mathbb{R}^k$ to $\\mathbb{R}^n$.\n", "\n", "Viewing matrix multiplication as composition of maps helps us\n", - "understand why, under matrix multiplication, $AB$ is not generally equal to $BA$.\n", + "understand why, under matrix multiplication, $AB$ is generally not equal to $BA$.\n", "\n", "(After all, when we compose functions, the order usually matters.)\n", "\n", @@ -614,7 +606,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8815b4ca", + "id": "af0b0d1b", "metadata": { "tags": [ "hide-input" @@ -622,17 +614,18 @@ }, "outputs": [], "source": [ - "def grid_composition_transform(A = np.array([[1, -1], [1, 1]]), B = np.array([[1, -1], [1, 1]])):\n", + "def grid_composition_transform(A=np.array([[1, -1], [1, 1]]),\n", + " B=np.array([[1, -1], [1, 1]])):\n", " xvals = np.linspace(-4, 4, 9)\n", " yvals = np.linspace(-3, 3, 7)\n", " xygrid = np.column_stack([[x, y] for x in xvals for y in yvals])\n", " uvgrid = B @ xygrid\n", " abgrid = A @ uvgrid\n", - " \n", + "\n", " colors = list(map(colorizer, xygrid[0], xygrid[1]))\n", - " \n", - " figure, ax = plt.subplots(1,3, figsize = (15,5))\n", - " \n", + "\n", + " fig, ax = plt.subplots(1, 3, figsize=(15, 5))\n", + "\n", " for axes in ax:\n", " axes.set(xlim=(-12, 12), ylim=(-12, 12))\n", " axes.set_xticks([])\n", @@ -641,16 +634,16 @@ " axes.spines[spine].set_position('zero')\n", " for spine in ['right', 'top']:\n", " axes.spines[spine].set_color('none')\n", - " \n", + "\n", " # Plot grid points\n", " ax[0].scatter(xygrid[0], xygrid[1], s=36, c=colors, edgecolor=\"none\")\n", " ax[0].set_title(\"points $x_1, x_2, \\cdots, x_k$\")\n", - " \n", + "\n", " # Plot intermediate grid points\n", " ax[1].scatter(uvgrid[0], uvgrid[1], s=36, c=colors, edgecolor=\"none\")\n", " ax[1].set_title(\"points $Bx_1, Bx_2, \\cdots, Bx_k$\")\n", - " \n", - " #Plot transformed grid points\n", + "\n", + " # Plot transformed grid points\n", " ax[2].scatter(abgrid[0], abgrid[1], s=36, c=colors, edgecolor=\"none\")\n", " ax[2].set_title(\"points $ABx_1, ABx_2, \\cdots, ABx_k$\")\n", "\n", @@ -660,13 +653,10 @@ { "cell_type": "code", "execution_count": null, - "id": "6c98392e", + "id": "e050bf20", "metadata": {}, "outputs": [], "source": [ - "θ = np.pi/2 \n", - "#B = np.array([[np.cos(θ), np.sin(θ)],\n", - "# [-np.sin(θ), np.cos(θ)]])\n", "A = np.array([[0, 1], # 90 degree clockwise rotation\n", " [-1, 0]])\n", "B = np.array([[1, 2], # shear along x-axis\n", @@ -675,7 +665,7 @@ }, { "cell_type": "markdown", - "id": "4bfe7abf", + "id": "6ce0a196", "metadata": { "user_expressions": [] }, @@ -686,16 +676,16 @@ { "cell_type": "code", "execution_count": null, - "id": "3d3dae0b", + "id": "b26383d3", "metadata": {}, "outputs": [], "source": [ - "grid_composition_transform(A,B) #transformation AB" + "grid_composition_transform(A, B) # transformation AB" ] }, { "cell_type": "markdown", - "id": "feaeb751", + "id": "8abaf846", "metadata": { "user_expressions": [] }, @@ -706,25 +696,25 @@ { "cell_type": "code", "execution_count": null, - "id": "601e19c4", + "id": "7f1a2ed9", "metadata": {}, "outputs": [], "source": [ - "grid_composition_transform(B,A) #transformation BA" + "grid_composition_transform(B,A) # transformation BA" ] }, { "cell_type": "markdown", - "id": "dadc8c0d", + "id": "66de6985", "metadata": { "user_expressions": [] }, "source": [ - "It is quite evident that the transformation $AB$ is not the same as the transformation $BA$.\n", + "It is evident that the transformation $AB$ is not the same as the transformation $BA$.\n", "\n", "## Iterating on a fixed map\n", "\n", - "In economics (and especially in dynamic modeling), we often are interested in\n", + "In economics (and especially in dynamic modeling), we are often interested in\n", "analyzing behavior where we repeatedly apply a fixed matrix.\n", "\n", "For example, given a vector $v$ and a matrix $A$, we are interested in\n", @@ -733,7 +723,7 @@ "$$ \n", " v, \\quad\n", " Av, \\quad\n", - " AAv = A^2v, \\ldots\n", + " AAv = A^2v, \\quad \\ldots\n", "$$\n", "\n", "Let's first see examples of a sequence of iterates $(A^k v)_{k \\geq 0}$ under\n", @@ -745,17 +735,17 @@ { "cell_type": "code", "execution_count": null, - "id": "f71edda3", + "id": "23fcc0a7", "metadata": {}, "outputs": [], "source": [ - "def plot_series(B, v, n):\n", - " \n", - " A = np.array([[1, -1],\n", + "def plot_series(A, v, n):\n", + "\n", + " B = np.array([[1, -1],\n", " [1, 0]])\n", - " \n", - " figure, ax = plt.subplots()\n", - " \n", + "\n", + " fig, ax = plt.subplots()\n", + "\n", " ax.set(xlim=(-4, 4), ylim=(-4, 4))\n", " ax.set_xticks([])\n", " ax.set_yticks([])\n", @@ -763,54 +753,55 @@ " ax.spines[spine].set_position('zero')\n", " for spine in ['right', 'top']:\n", " ax.spines[spine].set_color('none')\n", - " \n", - " θ = np.linspace( 0 , 2 * np.pi , 150) \n", + "\n", + " θ = np.linspace(0, 2 * np.pi, 150)\n", " r = 2.5\n", - " x = r * np.cos(θ) \n", + " x = r * np.cos(θ)\n", " y = r * np.sin(θ)\n", - " x1 = x.reshape(1,-1)\n", + " x1 = x.reshape(1, -1)\n", " y1 = y.reshape(1, -1)\n", - " xy = np.concatenate((x1,y1), axis=0)\n", - " \n", - " ellipse = A @ xy\n", - " ax.plot(ellipse[0,:], ellipse[1,:], color = 'black', linestyle = (0, (5,10)), linewidth = 0.5)\n", - " \n", - " colors = plt.cm.rainbow(np.linspace(0,1,20))# Initialize holder for trajectories\n", - " \n", + " xy = np.concatenate((x1, y1), axis=0)\n", + "\n", + " ellipse = B @ xy\n", + " ax.plot(ellipse[0, :], ellipse[1, :], color='black',\n", + " linestyle=(0, (5, 10)), linewidth=0.5)\n", + "\n", + " # Initialize holder for trajectories\n", + " colors = plt.cm.rainbow(np.linspace(0, 1, 20))\n", + "\n", " for i in range(n):\n", - " iteration = matrix_power(B, i) @ v\n", + " iteration = matrix_power(A, i) @ v\n", " v1 = iteration[0]\n", " v2 = iteration[1]\n", " ax.scatter(v1, v2, color=colors[i])\n", " if i == 0:\n", " ax.text(v1+0.25, v2, f'$v$')\n", - " if i == 1:\n", + " elif i == 1:\n", " ax.text(v1+0.25, v2, f'$Av$')\n", - " if 1< i < 4:\n", + " elif 1 < i < 4:\n", " ax.text(v1+0.25, v2, f'$A^{i}v$')\n", - " \n", " plt.show()" ] }, { "cell_type": "code", "execution_count": null, - "id": "4cd1a08b", + "id": "c0b488c5", "metadata": {}, "outputs": [], "source": [ - "B = np.array([[sqrt(3) + 1, -2],\n", + "A = np.array([[sqrt(3) + 1, -2],\n", " [1, sqrt(3) - 1]])\n", - "B = (1/(2*sqrt(2))) * B\n", + "A = (1/(2*sqrt(2))) * A\n", "v = (-3, -3)\n", "n = 12\n", "\n", - "plot_series(B, v, n)" + "plot_series(A, v, n)" ] }, { "cell_type": "markdown", - "id": "f4c53250", + "id": "f79030ad", "metadata": { "user_expressions": [] }, @@ -823,7 +814,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e469f1a2", + "id": "6778314c", "metadata": {}, "outputs": [], "source": [ @@ -838,7 +829,7 @@ }, { "cell_type": "markdown", - "id": "5323eca7", + "id": "fbc39ab7", "metadata": { "user_expressions": [] }, @@ -852,7 +843,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ad8a5f31", + "id": "c4bf654b", "metadata": {}, "outputs": [], "source": [ @@ -867,7 +858,7 @@ }, { "cell_type": "markdown", - "id": "72f7f91b", + "id": "293868d7", "metadata": { "user_expressions": [] }, @@ -893,13 +884,14 @@ "\n", "Let $A$ be an $n \\times n$ square matrix.\n", "\n", - "If $\\lambda$ is scalar and $v$ is a non-zero $n$-vector such that\n", + "If $\\lambda$ is scalar and $v$ is a non-zero $n$-vector such that\n", "\n", "$$\n", - "A v = \\lambda v\n", + "A v = \\lambda v.\n", "$$\n", "\n", - "then we say that $\\lambda$ is an *eigenvalue* of $A$, and $v$ is an *eigenvector*.\n", + "\n", + "Then we say that $\\lambda$ is an *eigenvalue* of $A$, and $v$ is the corresponding *eigenvector*.\n", "\n", "Thus, an eigenvector of $A$ is a nonzero vector $v$ such that when the map $A$ is\n", "applied, $v$ is merely scaled.\n", @@ -913,7 +905,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b4848301", + "id": "3121fb59", "metadata": { "tags": [ "output_scroll" @@ -935,7 +927,7 @@ " ax.spines[spine].set_position('zero')\n", "for spine in ['right', 'top']:\n", " ax.spines[spine].set_color('none')\n", - "#ax.grid(alpha=0.4)\n", + "# ax.grid(alpha=0.4)\n", "\n", "xmin, xmax = -3, 3\n", "ymin, ymax = -3, 3\n", @@ -969,7 +961,7 @@ }, { "cell_type": "markdown", - "id": "a3d9234f", + "id": "d7ca6652", "metadata": { "user_expressions": [] }, @@ -978,7 +970,7 @@ "\n", "So far our definition of eigenvalues and eigenvectors seems straightforward.\n", "\n", - "There is, however, one complication we haven't mentioned yet:\n", + "There is one complication we haven't mentioned yet:\n", "\n", "When solving $Av = \\lambda v$, \n", "\n", @@ -987,7 +979,6 @@ "\n", "We will see some examples below.\n", "\n", - "\n", "### Some mathematical details\n", "\n", "We note some mathematical details for more advanced readers.\n", @@ -998,7 +989,7 @@ "\n", "This equation has a nonzero solution $v$ only when the columns of $A - \\lambda I$ are linearly dependent.\n", "\n", - "This in turn is equivalent to stating that the determinant is zero.\n", + "This in turn is equivalent to stating the determinant is zero.\n", "\n", "Hence, to find all eigenvalues, we can look for $\\lambda$ such that the\n", "determinant of $A - \\lambda I$ is zero.\n", @@ -1009,18 +1000,16 @@ "This in turn implies the existence of $n$ solutions in the complex\n", "plane, although some might be repeated.\n", "\n", - "\n", - "\n", "### Facts \n", "\n", "Some nice facts about the eigenvalues of a square matrix $A$ are as follows:\n", "\n", - "1. The determinant of $A$ equals the product of the eigenvalues.\n", - "1. The trace of $A$ (the sum of the elements on the principal diagonal) equals the sum of the eigenvalues.\n", - "1. If $A$ is symmetric, then all of its eigenvalues are real.\n", - "1. If $A$ is invertible and $\\lambda_1, \\ldots, \\lambda_n$ are its eigenvalues, then the eigenvalues of $A^{-1}$ are $1/\\lambda_1, \\ldots, 1/\\lambda_n$.\n", + "1. the determinant of $A$ equals the product of the eigenvalues\n", + "2. the trace of $A$ (the sum of the elements on the principal diagonal) equals the sum of the eigenvalues\n", + "3. if $A$ is symmetric, then all of its eigenvalues are real\n", + "4. if $A$ is invertible and $\\lambda_1, \\ldots, \\lambda_n$ are its eigenvalues, then the eigenvalues of $A^{-1}$ are $1/\\lambda_1, \\ldots, 1/\\lambda_n$.\n", "\n", - "A corollary of the first statement is that a matrix is invertible if and only if all its eigenvalues are nonzero.\n", + "A corollary of the last statement is that a matrix is invertible if and only if all its eigenvalues are nonzero.\n", "\n", "### Computation\n", "\n", @@ -1030,7 +1019,7 @@ { "cell_type": "code", "execution_count": null, - "id": "06cbbfa3", + "id": "460d0227", "metadata": {}, "outputs": [], "source": [ @@ -1041,22 +1030,22 @@ "\n", "A = np.array(A)\n", "evals, evecs = eig(A)\n", - "evals #eigenvalues" + "evals # eigenvalues" ] }, { "cell_type": "code", "execution_count": null, - "id": "4fc232f8", + "id": "66d0c66e", "metadata": {}, "outputs": [], "source": [ - "evecs #eigenvectors" + "evecs # eigenvectors" ] }, { "cell_type": "markdown", - "id": "4dfdceac", + "id": "1fb3bb32", "metadata": { "user_expressions": [] }, @@ -1064,19 +1053,179 @@ "Note that the *columns* of `evecs` are the eigenvectors.\n", "\n", "Since any scalar multiple of an eigenvector is an eigenvector with the same\n", - "eigenvalue (check it), the eig routine normalizes the length of each eigenvector\n", + "eigenvalue (which can be verified), the `eig` routine normalizes the length of each eigenvector\n", "to one.\n", "\n", "The eigenvectors and eigenvalues of a map $A$ determine how a vector $v$ is transformed when we repeatedly multiply by $A$.\n", "\n", "This is discussed further later.\n", "\n", + "\n", + "(la_neumann)=\n", + "## The Neumann Series Lemma\n", + "\n", + "```{index} single: Neumann's Lemma\n", + "```\n", + "\n", + "In this section we present a famous result about series of matrices that has\n", + "many applications in economics.\n", + "\n", + "### Scalar series\n", + "\n", + "Here's a fundamental result about series:\n", + "\n", + "If $a$ is a number and $|a| < 1$, then\n", + "\n", + "```{math}\n", + ":label: gp_sum\n", + "\n", + " \\sum_{k=0}^{\\infty} a^k =\\frac{1}{1-a} = (1 - a)^{-1}\n", + "\n", + "```\n", + "\n", + "For a one-dimensional linear equation $x = ax + b$ where x is unknown we can thus conclude that the solution $x^{*}$ is given by:\n", + "\n", + "$$\n", + " x^{*} = \\frac{b}{1-a} = \\sum_{k=0}^{\\infty} a^k b\n", + "$$\n", + "\n", + "### Matrix series\n", + "\n", + "A generalization of this idea exists in the matrix setting.\n", + "\n", + "Consider the system of equations $x = Ax + b$ where $A$ is an $n \\times n$\n", + "square matrix and $x$ and $b$ are both column vectors in $\\mathbb{R}^n$.\n", + "\n", + "Using matrix algebra we can conclude that the solution to this system of equations will be given by:\n", + "\n", + "```{math}\n", + ":label: neumann_eqn\n", + "\n", + " x^{*} = (I-A)^{-1}b\n", + "\n", + "```\n", + "\n", + "What guarantees the existence of a unique vector $x^{*}$ that satisfies\n", + "{eq}`neumann_eqn`?\n", + "\n", + "The following is a fundamental result in functional analysis that generalizes\n", + "{eq}`gp_sum` to a multivariate case.\n", + "\n", + "(neumann_series_lemma)=\n", + "```{prf:Theorem} Neumann Series Lemma\n", + ":label: neumann_series_lemma\n", + "\n", + "Let $A$ be a square matrix and let $A^k$ be the $k$-th power of $A$.\n", + "\n", + "Let $r(A)$ be the **spectral radius** of $A$, defined as $\\max_i |\\lambda_i|$, where\n", + "\n", + "* $\\{\\lambda_i\\}_i$ is the set of eigenvalues of $A$ and\n", + "* $|\\lambda_i|$ is the modulus of the complex number $\\lambda_i$\n", + "\n", + "Neumann's Theorem states the following: If $r(A) < 1$, then $I - A$ is invertible, and\n", + "\n", + "$$\n", + "(I - A)^{-1} = \\sum_{k=0}^{\\infty} A^k\n", + "$$\n", + "```\n", + "\n", + "We can see the Neumann Series Lemma in action in the following example." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ea8cd4b6", + "metadata": {}, + "outputs": [], + "source": [ + "A = np.array([[0.4, 0.1],\n", + " [0.7, 0.2]])\n", + "\n", + "evals, evecs = eig(A) # finding eigenvalues and eigenvectors\n", + "\n", + "r = max(abs(λ) for λ in evals) # compute spectral radius\n", + "print(r)" + ] + }, + { + "cell_type": "markdown", + "id": "3bd12c26", + "metadata": {}, + "source": [ + "The spectral radius $r(A)$ obtained is less than 1.\n", + "\n", + "Thus, we can apply the Neumann Series Lemma to find $(I-A)^{-1}$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bbcdd0cb", + "metadata": {}, + "outputs": [], + "source": [ + "I = np.identity(2) # 2 x 2 identity matrix\n", + "B = I - A" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "793f781e", + "metadata": {}, + "outputs": [], + "source": [ + "B_inverse = np.linalg.inv(B) # direct inverse method" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "89dace47", + "metadata": {}, + "outputs": [], + "source": [ + "A_sum = np.zeros((2, 2)) # power series sum of A\n", + "A_power = I\n", + "for i in range(50):\n", + " A_sum += A_power\n", + " A_power = A_power @ A" + ] + }, + { + "cell_type": "markdown", + "id": "129d3b89", + "metadata": {}, + "source": [ + "Let's check equality between the sum and the inverse methods." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7c55b918", + "metadata": {}, + "outputs": [], + "source": [ + "np.allclose(A_sum, B_inverse)" + ] + }, + { + "cell_type": "markdown", + "id": "59779409", + "metadata": {}, + "source": [ + "Although we truncate the infinite sum at $k = 50$, both methods give us the same\n", + "result which illustrates the result of the Neumann Series Lemma.\n", + "\n", + "\n", "## Exercises\n", "\n", "```{exercise}\n", ":label: eig1_ex1\n", "\n", - "Power iteration is a method for finding the largest absolute eigenvalue of a diagonalizable matrix.\n", + "Power iteration is a method for finding the greatest absolute eigenvalue of a diagonalizable matrix.\n", "\n", "The method starts with a random vector $b_0$ and repeatedly applies the matrix $A$ to it\n", "\n", @@ -1086,9 +1235,9 @@ "\n", "A thorough discussion of the method can be found [here](https://pythonnumericalmethods.berkeley.edu/notebooks/chapter15.02-The-Power-Method.html).\n", "\n", - "In this exercise, implement the power iteration method and use it to find the largest eigenvalue and its corresponding eigenvector.\n", + "In this exercise, first implement the power iteration method and use it to find the greatest absolute eigenvalue and its corresponding eigenvector.\n", "\n", - "Visualize the convergence.\n", + "Then visualize the convergence.\n", "```\n", "\n", "```{solution-start} eig1_ex1\n", @@ -1103,7 +1252,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a67c6ef0", + "id": "7d3b19ac", "metadata": { "mystnb": { "figure": { @@ -1115,8 +1264,8 @@ "outputs": [], "source": [ "# Define a matrix A\n", - "A = np.array([[1, 0, 3], \n", - " [0, 2, 0], \n", + "A = np.array([[1, 0, 3],\n", + " [0, 2, 0],\n", " [3, 0, 1]])\n", "\n", "num_iters = 20\n", @@ -1127,7 +1276,7 @@ "# Get the leading eigenvector of matrix A\n", "eigenvector = np.linalg.eig(A)[1][:, 0]\n", "\n", - "norm_ls = []\n", + "errors = []\n", "res = []\n", "\n", "# Power iteration loop\n", @@ -1138,35 +1287,36 @@ " b = b / np.linalg.norm(b)\n", " # Append b to the list of eigenvector approximations\n", " res.append(b)\n", - " norm = np.linalg.norm(np.array(b) \n", - " - eigenvector)\n", - " norm_ls.append(norm)\n", + " err = np.linalg.norm(np.array(b)\n", + " - eigenvector)\n", + " errors.append(err)\n", "\n", - "dominant_eigenvalue = np.dot(A @ b, b) / np.dot(b, b)\n", - "print(f'The approximated dominant eigenvalue is {dominant_eigenvalue:.2f}')\n", + "greatest_eigenvalue = np.dot(A @ b, b) / np.dot(b, b)\n", + "print(f'The approximated greatest absolute eigenvalue is \\\n", + " {greatest_eigenvalue:.2f}')\n", "print('The real eigenvalue is', np.linalg.eig(A)[0])\n", "\n", "# Plot the eigenvector approximations for each iteration\n", "plt.figure(figsize=(10, 6))\n", "plt.xlabel('iterations')\n", - "plt.ylabel('Norm')\n", - "_ = plt.plot(norm_ls)" + "plt.ylabel('error')\n", + "_ = plt.plot(errors)" ] }, { "cell_type": "markdown", - "id": "743b95f2", + "id": "c5a64023", "metadata": { "user_expressions": [] }, "source": [ - "Then we can look at the trajectory of the eigenvector approximation" + "Then we can look at the trajectory of the eigenvector approximation." ] }, { "cell_type": "code", "execution_count": null, - "id": "b6743c4b", + "id": "5bd57327", "metadata": { "mystnb": { "figure": { @@ -1182,35 +1332,34 @@ "ax = fig.add_subplot(111, projection='3d')\n", "\n", "# Plot the eigenvectors\n", - "ax.scatter(eigenvector[0], \n", - " eigenvector[1], \n", - " eigenvector[2], \n", - " color='r', s = 80)\n", + "ax.scatter(eigenvector[0],\n", + " eigenvector[1],\n", + " eigenvector[2],\n", + " color='r', s=80)\n", "\n", "for i, vec in enumerate(res):\n", - " ax.scatter(vec[0], vec[1], vec[2], \n", - " color='b', \n", - " alpha=(i+1)/(num_iters+1), \n", - " s = 80)\n", + " ax.scatter(vec[0], vec[1], vec[2],\n", + " color='b',\n", + " alpha=(i+1)/(num_iters+1),\n", + " s=80)\n", "\n", "ax.set_xlabel('x')\n", "ax.set_ylabel('y')\n", "ax.set_zlabel('z')\n", "ax.tick_params(axis='both', which='major', labelsize=7)\n", "\n", - "points = [plt.Line2D([0], [0], linestyle='none', \n", + "points = [plt.Line2D([0], [0], linestyle='none',\n", " c=i, marker='o') for i in ['r', 'b']]\n", - "ax.legend(points, ['actual eigenvector', \n", + "ax.legend(points, ['actual eigenvector',\n", " r'approximated eigenvector ($b_k$)'])\n", "ax.set_box_aspect(aspect=None, zoom=0.8)\n", "\n", - "# Show the plot\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "853ed760", + "id": "42e34a0c", "metadata": { "user_expressions": [] }, @@ -1237,11 +1386,11 @@ { "cell_type": "code", "execution_count": null, - "id": "b537065d", + "id": "9d7e0a99", "metadata": {}, "outputs": [], "source": [ - "A = np.array([[1, 2], \n", + "A = np.array([[1, 2],\n", " [1, 1]])\n", "v = (0.4, -0.4)\n", "n = 11\n", @@ -1249,28 +1398,30 @@ "# Compute eigenvectors and eigenvalues\n", "eigenvalues, eigenvectors = np.linalg.eig(A)\n", "\n", - "print(f\"eigenvalues:\\n {eigenvalues}\")\n", - "print(f\"eigenvectors:\\n {eigenvectors}\")\n", + "print(f'eigenvalues:\\n {eigenvalues}')\n", + "print(f'eigenvectors:\\n {eigenvectors}')\n", "\n", "plot_series(A, v, n)" ] }, { "cell_type": "markdown", - "id": "bb434517", + "id": "8fac07a1", "metadata": { "user_expressions": [] }, "source": [ "The result seems to converge to the eigenvector of $A$ with the largest eigenvalue.\n", "\n", - "Let's use a vector field to visualize the transformation brought by A." + "Let's use a [vector field](https://en.wikipedia.org/wiki/Vector_field) to visualize the transformation brought by A.\n", + "\n", + "(This is a more advanced topic in linear algebra, please step ahead if you are comfortable with the math.)" ] }, { "cell_type": "code", "execution_count": null, - "id": "a21574a2", + "id": "299137cd", "metadata": { "mystnb": { "figure": { @@ -1282,32 +1433,33 @@ "outputs": [], "source": [ "# Create a grid of points\n", - "x, y = np.meshgrid(np.linspace(-5, 5, 15), \n", - " np.linspace(-5, 5, 20))\n", + "x, y = np.meshgrid(np.linspace(-5, 5, 15),\n", + " np.linspace(-5, 5, 20))\n", "\n", "# Apply the matrix A to each point in the vector field\n", "vec_field = np.stack([x, y])\n", "u, v = np.tensordot(A, vec_field, axes=1)\n", "\n", "# Plot the transformed vector field\n", - "c = plt.streamplot(x, y, u - x, v - y, \n", - " density=1, linewidth=None, color='#A23BEC')\n", + "c = plt.streamplot(x, y, u - x, v - y,\n", + " density=1, linewidth=None, color='#A23BEC')\n", "c.lines.set_alpha(0.5)\n", "c.arrows.set_alpha(0.5)\n", "\n", "# Draw eigenvectors\n", "origin = np.zeros((2, len(eigenvectors)))\n", - "parameters = {'color':['b', 'g'], 'angles':'xy', \n", - " 'scale_units':'xy', 'scale':0.1, 'width':0.01}\n", - "plt.quiver(*origin, eigenvectors[0], \n", - " eigenvectors[1], **parameters)\n", - "plt.quiver(*origin, - eigenvectors[0], \n", - " - eigenvectors[1], **parameters)\n", + "parameters = {'color': ['b', 'g'], 'angles': 'xy',\n", + " 'scale_units': 'xy', 'scale': 0.1, 'width': 0.01}\n", + "plt.quiver(*origin, eigenvectors[0],\n", + " eigenvectors[1], **parameters)\n", + "plt.quiver(*origin, - eigenvectors[0],\n", + " - eigenvectors[1], **parameters)\n", "\n", "colors = ['b', 'g']\n", "lines = [Line2D([0], [0], color=c, linewidth=3) for c in colors]\n", "labels = [\"2.4 eigenspace\", \"0.4 eigenspace\"]\n", - "plt.legend(lines, labels,loc='center left', bbox_to_anchor=(1, 0.5))\n", + "plt.legend(lines, labels, loc='center left',\n", + " bbox_to_anchor=(1, 0.5))\n", "\n", "plt.xlabel(\"x\")\n", "plt.ylabel(\"y\")\n", @@ -1318,7 +1470,7 @@ }, { "cell_type": "markdown", - "id": "83367402", + "id": "f9e3d9bb", "metadata": { "user_expressions": [] }, @@ -1354,7 +1506,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4a9a5d99", + "id": "cf30f874", "metadata": { "mystnb": { "figure": { @@ -1365,7 +1517,7 @@ }, "outputs": [], "source": [ - "figure, ax = plt.subplots(1,3, figsize = (15, 5))\n", + "figure, ax = plt.subplots(1, 3, figsize=(15, 5))\n", "A = np.array([[sqrt(3) + 1, -2],\n", " [1, sqrt(3) - 1]])\n", "A = (1/(2*sqrt(2))) * A\n", @@ -1393,30 +1545,30 @@ " eigenvectors_real = eigenvectors.real\n", "\n", " # Create a grid of points\n", - " x, y = np.meshgrid(np.linspace(-20, 20, 15), \n", - " np.linspace(-20, 20, 20))\n", + " x, y = np.meshgrid(np.linspace(-20, 20, 15),\n", + " np.linspace(-20, 20, 20))\n", "\n", " # Apply the matrix A to each point in the vector field\n", " vec_field = np.stack([x, y])\n", " u, v = np.tensordot(M, vec_field, axes=1)\n", "\n", " # Plot the transformed vector field\n", - " c = ax[i].streamplot(x, y, u - x, v - y,\n", - " density=1, linewidth=None, color='#A23BEC')\n", + " c = ax[i].streamplot(x, y, u - x, v - y, density=1,\n", + " linewidth=None, color='#A23BEC')\n", " c.lines.set_alpha(0.5)\n", " c.arrows.set_alpha(0.5)\n", - " \n", + "\n", " # Draw eigenvectors\n", - " parameters = {'color':['b', 'g'], 'angles':'xy', \n", - " 'scale_units':'xy', 'scale':1, \n", - " 'width':0.01, 'alpha':0.5}\n", + " parameters = {'color': ['b', 'g'], 'angles': 'xy',\n", + " 'scale_units': 'xy', 'scale': 1,\n", + " 'width': 0.01, 'alpha': 0.5}\n", " origin = np.zeros((2, len(eigenvectors)))\n", - " ax[i].quiver(*origin, eigenvectors_real[0], \n", - " eigenvectors_real[1], **parameters)\n", - " ax[i].quiver(*origin, \n", - " - eigenvectors_real[0], \n", - " - eigenvectors_real[1], \n", - " **parameters)\n", + " ax[i].quiver(*origin, eigenvectors_real[0],\n", + " eigenvectors_real[1], **parameters)\n", + " ax[i].quiver(*origin,\n", + " - eigenvectors_real[0],\n", + " - eigenvectors_real[1],\n", + " **parameters)\n", "\n", " ax[i].set_xlabel(\"x-axis\")\n", " ax[i].set_ylabel(\"y-axis\")\n", @@ -1428,7 +1580,7 @@ }, { "cell_type": "markdown", - "id": "8ca7f153", + "id": "f5873491", "metadata": { "user_expressions": [] }, @@ -1437,13 +1589,13 @@ "\n", "The pattern demonstrated here is because we have complex eigenvalues and eigenvectors.\n", "\n", - "We can plot the complex plane for one of the matrices using `Arrow3D` class retrieved from [stackoverflow](https://stackoverflow.com/questions/22867620/putting-arrowheads-on-vectors-in-matplotlibs-3d-plot)." + "We can plot the complex plane for one of the matrices using `Arrow3D` class retrieved from [stackoverflow](https://stackoverflow.com/questions/22867620/putting-arrowheads-on-vectors-in-a-3d-plot)." ] }, { "cell_type": "code", "execution_count": null, - "id": "2063cbf6", + "id": "be19e81c", "metadata": { "mystnb": { "figure": { @@ -1456,20 +1608,23 @@ "source": [ "class Arrow3D(FancyArrowPatch):\n", " def __init__(self, xs, ys, zs, *args, **kwargs):\n", - " super().__init__((0,0), (0,0), *args, **kwargs)\n", + " super().__init__((0, 0), (0, 0), *args, **kwargs)\n", " self._verts3d = xs, ys, zs\n", "\n", - " def do_3d_projection(self, renderer=None):\n", + " def do_3d_projection(self):\n", " xs3d, ys3d, zs3d = self._verts3d\n", - " xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, self.axes.M)\n", - " self.set_positions((0.1*xs[0],0.1*ys[0]),(0.1*xs[1],0.1*ys[1]))\n", + " xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d,\n", + " self.axes.M)\n", + " self.set_positions((0.1*xs[0], 0.1*ys[0]),\n", + " (0.1*xs[1], 0.1*ys[1]))\n", "\n", " return np.min(zs)\n", "\n", + "\n", "eigenvalues, eigenvectors = np.linalg.eig(A)\n", "\n", "# Create meshgrid for vector field\n", - "x, y = np.meshgrid(np.linspace(-2, 2, 15), \n", + "x, y = np.meshgrid(np.linspace(-2, 2, 15),\n", " np.linspace(-2, 2, 15))\n", "\n", "# Calculate vector field (real and imaginary parts)\n", @@ -1482,18 +1637,18 @@ "fig = plt.figure()\n", "ax = fig.add_subplot(111, projection='3d')\n", "vlength = np.linalg.norm(eigenvectors)\n", - "ax.quiver(x, y, u_imag, u_real-x, v_real-y, v_imag-u_imag, \n", - " colors = 'b', alpha=0.3, length = .2, \n", - " arrow_length_ratio = 0.01)\n", + "ax.quiver(x, y, u_imag, u_real-x, v_real-y, v_imag-u_imag,\n", + " colors='b', alpha=0.3, length=.2,\n", + " arrow_length_ratio=0.01)\n", "\n", - "arrow_prop_dict = dict(mutation_scale=5, \n", - " arrowstyle='-|>', shrinkA=0, shrinkB=0)\n", + "arrow_prop_dict = dict(mutation_scale=5,\n", + " arrowstyle='-|>', shrinkA=0, shrinkB=0)\n", "\n", "# Plot 3D eigenvectors\n", "for c, i in zip(['b', 'g'], [0, 1]):\n", - " a = Arrow3D([0, eigenvectors[0][i].real], \n", - " [0, eigenvectors[1][i].real], \n", - " [0, eigenvectors[1][i].imag], \n", + " a = Arrow3D([0, eigenvectors[0][i].real],\n", + " [0, eigenvectors[1][i].real],\n", + " [0, eigenvectors[1][i].imag],\n", " color=c, **arrow_prop_dict)\n", " ax.add_artist(a)\n", "\n", @@ -1509,7 +1664,7 @@ }, { "cell_type": "markdown", - "id": "fc6d09ac", + "id": "6ea65314", "metadata": { "user_expressions": [] }, @@ -1520,12 +1675,77 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.5" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 14, + 41, + 48, + 124, + 129, + 169, + 194, + 285, + 303, + 310, + 326, + 333, + 349, + 356, + 370, + 375, + 519, + 558, + 565, + 569, + 573, + 577, + 581, + 604, + 649, + 659, + 665, + 675, + 682, + 692, + 732, + 781, + 832, + 843, + 847, + 930, + 938, + 944, + 949, + 953, + 959, + 963, + 965, + 999, + 1046, + 1050, + 1087, + 1107, + 1122, + 1130, + 1173, + 1202, + 1270, + 1278, + 1341 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/eigen_I.md b/book/_build/html/_sources/eigen_I.md new file mode 100644 index 0000000..948b2f0 --- /dev/null +++ b/book/_build/html/_sources/eigen_I.md @@ -0,0 +1,1344 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.5 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + ++++ {"user_expressions": []} + +(eigen)= +# Eigenvalues and Eigenvectors + +```{index} single: Eigenvalues and Eigenvectors +``` + +## Overview + +Eigenvalues and eigenvectors are a relatively advanced topic in linear algebra. + +At the same time, these concepts are extremely useful for + +* economic modeling (especially dynamics!) +* statistics +* some parts of applied mathematics +* machine learning +* and many other fields of science. + +In this lecture we explain the basics of eigenvalues and eigenvectors and introduce the Neumann Series Lemma. + +We assume in this lecture that students are familiar with matrices + and understand {doc}`the basics of matrix algebra`. + +We will use the following imports: + +```{code-cell} ipython3 +import matplotlib.pyplot as plt +import numpy as np +from numpy.linalg import matrix_power +from matplotlib.lines import Line2D +from matplotlib.patches import FancyArrowPatch +from mpl_toolkits.mplot3d import proj3d +``` + +(matrices_as_transformation)= +## Matrices as transformations + +Let's start by discussing an important concept concerning matrices. + +### Mapping vectors to vectors + +One way to think about a matrix is as a rectangular collection of +numbers. + +Another way to think about a matrix is as a *map* (i.e., as a function) that +transforms vectors to new vectors. + +To understand the second point of view, suppose we multiply an $n \times m$ +matrix $A$ with an $m \times 1$ column vector $x$ to obtain an $n \times 1$ +column vector $y$: + +$$ + Ax = y +$$ + +If we fix $A$ and consider different choices of $x$, we can understand $A$ as +a map transforming $x$ to $Ax$. + +Because $A$ is $n \times m$, it transforms $m$-vectors to $n$-vectors. + +We can write this formally as $A \colon \mathbb{R}^m \rightarrow \mathbb{R}^n$. + +You might argue that if $A$ is a function then we should write +$A(x) = y$ rather than $Ax = y$ but the second notation is more conventional. + +### Square matrices + +Let's restrict our discussion to square matrices. + +In the above discussion, this means that $m=n$ and $A$ maps $\mathbb R^n$ to +itself. + +This means $A$ is an $n \times n$ matrix that maps (or "transforms") a vector +$x$ in $\mathbb{R}^n$ to a new vector $y=Ax$ also in $\mathbb{R}^n$. + +```{prf:example} +:label: eigen1_ex_sq + +$$ + \begin{bmatrix} + 2 & 1 \\ + -1 & 1 + \end{bmatrix} + \begin{bmatrix} + 1 \\ + 3 + \end{bmatrix} + = + \begin{bmatrix} + 5 \\ + 2 + \end{bmatrix} +$$ + +Here, the matrix + +$$ + A = \begin{bmatrix} 2 & 1 \\ + -1 & 1 + \end{bmatrix} +$$ + +transforms the vector $x = \begin{bmatrix} 1 \\ 3 \end{bmatrix}$ to the vector +$y = \begin{bmatrix} 5 \\ 2 \end{bmatrix}$. +``` + +Let's visualize this using Python: + +```{code-cell} ipython3 +A = np.array([[2, 1], + [-1, 1]]) +``` + +```{code-cell} ipython3 +from math import sqrt + +fig, ax = plt.subplots() +# Set the axes through the origin + +for spine in ['left', 'bottom']: + ax.spines[spine].set_position('zero') +for spine in ['right', 'top']: + ax.spines[spine].set_color('none') + +ax.set(xlim=(-2, 6), ylim=(-2, 4), aspect=1) + +vecs = ((1, 3), (5, 2)) +c = ['r', 'black'] +for i, v in enumerate(vecs): + ax.annotate('', xy=v, xytext=(0, 0), + arrowprops=dict(color=c[i], + shrink=0, + alpha=0.7, + width=0.5)) + +ax.text(0.2 + 1, 0.2 + 3, 'x=$(1,3)$') +ax.text(0.2 + 5, 0.2 + 2, 'Ax=$(5,2)$') + +ax.annotate('', xy=(sqrt(10/29) * 5, sqrt(10/29) * 2), xytext=(0, 0), + arrowprops=dict(color='purple', + shrink=0, + alpha=0.7, + width=0.5)) + +ax.annotate('', xy=(1, 2/5), xytext=(1/3, 1), + arrowprops={'arrowstyle': '->', + 'connectionstyle': 'arc3,rad=-0.3'}, + horizontalalignment='center') +ax.text(0.8, 0.8, f'θ', fontsize=14) + +plt.show() +``` + ++++ {"user_expressions": []} + +One way to understand this transformation is that $A$ + +* first rotates $x$ by some angle $\theta$ and +* then scales it by some scalar $\gamma$ to obtain the image $y$ of $x$. + + + +## Types of transformations + +Let's examine some standard transformations we can perform with matrices. + +Below we visualize transformations by thinking of vectors as points +instead of arrows. + +We consider how a given matrix transforms + +* a grid of points and +* a set of points located on the unit circle in $\mathbb{R}^2$. + +To build the transformations we will use two functions, called `grid_transform` and `circle_transform`. + +Each of these functions visualizes the actions of a given $2 \times 2$ matrix $A$. + +```{code-cell} ipython3 +:tags: [hide-input] + +def colorizer(x, y): + r = min(1, 1-y/3) + g = min(1, 1+y/3) + b = 1/4 + x/16 + return (r, g, b) + + +def grid_transform(A=np.array([[1, -1], [1, 1]])): + xvals = np.linspace(-4, 4, 9) + yvals = np.linspace(-3, 3, 7) + xygrid = np.column_stack([[x, y] for x in xvals for y in yvals]) + uvgrid = A @ xygrid + + colors = list(map(colorizer, xygrid[0], xygrid[1])) + + fig, ax = plt.subplots(1, 2, figsize=(10, 5)) + + for axes in ax: + axes.set(xlim=(-11, 11), ylim=(-11, 11)) + axes.set_xticks([]) + axes.set_yticks([]) + for spine in ['left', 'bottom']: + axes.spines[spine].set_position('zero') + for spine in ['right', 'top']: + axes.spines[spine].set_color('none') + + # Plot x-y grid points + ax[0].scatter(xygrid[0], xygrid[1], s=36, c=colors, edgecolor="none") + # ax[0].grid(True) + # ax[0].axis("equal") + ax[0].set_title("points $x_1, x_2, \cdots, x_k$") + + # Plot transformed grid points + ax[1].scatter(uvgrid[0], uvgrid[1], s=36, c=colors, edgecolor="none") + # ax[1].grid(True) + # ax[1].axis("equal") + ax[1].set_title("points $Ax_1, Ax_2, \cdots, Ax_k$") + + plt.show() + + +def circle_transform(A=np.array([[-1, 2], [0, 1]])): + + fig, ax = plt.subplots(1, 2, figsize=(10, 5)) + + for axes in ax: + axes.set(xlim=(-4, 4), ylim=(-4, 4)) + axes.set_xticks([]) + axes.set_yticks([]) + for spine in ['left', 'bottom']: + axes.spines[spine].set_position('zero') + for spine in ['right', 'top']: + axes.spines[spine].set_color('none') + + θ = np.linspace(0, 2 * np.pi, 150) + r = 1 + + θ_1 = np.empty(12) + for i in range(12): + θ_1[i] = 2 * np.pi * (i/12) + + x = r * np.cos(θ) + y = r * np.sin(θ) + a = r * np.cos(θ_1) + b = r * np.sin(θ_1) + a_1 = a.reshape(1, -1) + b_1 = b.reshape(1, -1) + colors = list(map(colorizer, a, b)) + ax[0].plot(x, y, color='black', zorder=1) + ax[0].scatter(a_1, b_1, c=colors, alpha=1, s=60, + edgecolors='black', zorder=2) + ax[0].set_title("unit circle in $\mathbb{R}^2$") + + x1 = x.reshape(1, -1) + y1 = y.reshape(1, -1) + ab = np.concatenate((a_1, b_1), axis=0) + transformed_ab = A @ ab + transformed_circle_input = np.concatenate((x1, y1), axis=0) + transformed_circle = A @ transformed_circle_input + ax[1].plot(transformed_circle[0, :], + transformed_circle[1, :], color='black', zorder=1) + ax[1].scatter(transformed_ab[0, :], transformed_ab[1:,], + color=colors, alpha=1, s=60, edgecolors='black', zorder=2) + ax[1].set_title("transformed circle") + + plt.show() +``` + ++++ {"user_expressions": []} + +### Scaling + +A matrix of the form + +$$ + \begin{bmatrix} + \alpha & 0 + \\ 0 & \beta + \end{bmatrix} +$$ + +scales vectors across the x-axis by a factor $\alpha$ and along the y-axis by +a factor $\beta$. + +Here we illustrate a simple example where $\alpha = \beta = 3$. + +```{code-cell} ipython3 +A = np.array([[3, 0], # scaling by 3 in both directions + [0, 3]]) +grid_transform(A) +circle_transform(A) +``` + ++++ {"user_expressions": []} + +### Shearing + +A "shear" matrix of the form + +$$ + \begin{bmatrix} + 1 & \lambda \\ + 0 & 1 + \end{bmatrix} +$$ + +stretches vectors along the x-axis by an amount proportional to the +y-coordinate of a point. + +```{code-cell} ipython3 +A = np.array([[1, 2], # shear along x-axis + [0, 1]]) +grid_transform(A) +circle_transform(A) +``` + ++++ {"user_expressions": []} + +### Rotation + +A matrix of the form + +$$ + \begin{bmatrix} + \cos \theta & \sin \theta + \\ - \sin \theta & \cos \theta + \end{bmatrix} +$$ +is called a _rotation matrix_. + +This matrix rotates vectors clockwise by an angle $\theta$. + +```{code-cell} ipython3 +θ = np.pi/4 # 45 degree clockwise rotation +A = np.array([[np.cos(θ), np.sin(θ)], + [-np.sin(θ), np.cos(θ)]]) +grid_transform(A) +``` + ++++ {"user_expressions": []} + +### Permutation + +The permutation matrix + +$$ + \begin{bmatrix} + 0 & 1 \\ + 1 & 0 + \end{bmatrix} +$$ +interchanges the coordinates of a vector. + +```{code-cell} ipython3 +A = np.column_stack([[0, 1], [1, 0]]) +grid_transform(A) +``` + ++++ {"user_expressions": []} + +More examples of common transition matrices can be found [here](https://en.wikipedia.org/wiki/Transformation_matrix#Examples_in_2_dimensions). + +## Matrix multiplication as composition + +Since matrices act as functions that transform one vector to another, we can +apply the concept of function composition to matrices as well. + + +### Linear compositions + +Consider the two matrices + +$$ + A = + \begin{bmatrix} + 0 & 1 \\ + -1 & 0 + \end{bmatrix} + \quad \text{and} \quad + B = + \begin{bmatrix} + 1 & 2 \\ + 0 & 1 + \end{bmatrix} +$$ + +What will the output be when we try to obtain $ABx$ for some $2 \times 1$ +vector $x$? + +$$ +\color{red}{\underbrace{ + \color{black}{\begin{bmatrix} + 0 & 1 \\ + -1 & 0 + \end{bmatrix}} +}_{\textstyle A} } +\color{red}{\underbrace{ + \color{black}{\begin{bmatrix} + 1 & 2 \\ + 0 & 1 + \end{bmatrix}} +}_{\textstyle B}} +\color{red}{\overbrace{ + \color{black}{\begin{bmatrix} + 1 \\ + 3 + \end{bmatrix}} +}^{\textstyle x}} +\rightarrow +\color{red}{\underbrace{ + \color{black}{\begin{bmatrix} + 0 & 1 \\ + -1 & -2 + \end{bmatrix}} +}_{\textstyle AB}} +\color{red}{\overbrace{ + \color{black}{\begin{bmatrix} + 1 \\ + 3 + \end{bmatrix}} +}^{\textstyle x}} +\rightarrow +\color{red}{\overbrace{ + \color{black}{\begin{bmatrix} + 3 \\ + -7 + \end{bmatrix}} +}^{\textstyle y}} +$$ + +$$ +\color{red}{\underbrace{ + \color{black}{\begin{bmatrix} + 0 & 1 \\ + -1 & 0 + \end{bmatrix}} +}_{\textstyle A} } +\color{red}{\underbrace{ + \color{black}{\begin{bmatrix} + 1 & 2 \\ + 0 & 1 + \end{bmatrix}} +}_{\textstyle B}} +\color{red}{\overbrace{ + \color{black}{\begin{bmatrix} + 1 \\ + 3 + \end{bmatrix}} +}^{\textstyle x}} +\rightarrow +\color{red}{\underbrace{ + \color{black}{\begin{bmatrix} + 0 & 1 \\ + -1 & 0 + \end{bmatrix}} +}_{\textstyle A}} +\color{red}{\overbrace{ + \color{black}{\begin{bmatrix} + 7 \\ + 3 + \end{bmatrix}} +}^{\textstyle Bx}} +\rightarrow +\color{red}{\overbrace{ + \color{black}{\begin{bmatrix} + 3 \\ + -7 + \end{bmatrix}} +}^{\textstyle y}} +$$ + +We can observe that applying the transformation $AB$ on the vector $x$ is the +same as first applying $B$ on $x$ and then applying $A$ on the vector $Bx$. + +Thus the matrix product $AB$ is the +[composition](https://en.wikipedia.org/wiki/Function_composition) of the +matrix transformations $A$ and $B$ + +This means first apply transformation $B$ and then +transformation $A$. + +When we matrix multiply an $n \times m$ matrix $A$ with an $m \times k$ matrix +$B$ the obtained matrix product is an $n \times k$ matrix $AB$. + +Thus, if $A$ and $B$ are transformations such that $A \colon \mathbb{R}^m \to +\mathbb{R}^n$ and $B \colon \mathbb{R}^k \to \mathbb{R}^m$, then $AB$ +transforms $\mathbb{R}^k$ to $\mathbb{R}^n$. + +Viewing matrix multiplication as composition of maps helps us +understand why, under matrix multiplication, $AB$ is generally not equal to $BA$. + +(After all, when we compose functions, the order usually matters.) + +### Examples + +Let $A$ be the $90^{\circ}$ clockwise rotation matrix given by +$\begin{bmatrix} 0 & 1 \\ -1 & 0 \end{bmatrix}$ and let $B$ be a shear matrix +along the x-axis given by $\begin{bmatrix} 1 & 2 \\ 0 & 1 \end{bmatrix}$. + +We will visualize how a grid of points changes when we apply the +transformation $AB$ and then compare it with the transformation $BA$. + +```{code-cell} ipython3 +:tags: [hide-input] + +def grid_composition_transform(A=np.array([[1, -1], [1, 1]]), + B=np.array([[1, -1], [1, 1]])): + xvals = np.linspace(-4, 4, 9) + yvals = np.linspace(-3, 3, 7) + xygrid = np.column_stack([[x, y] for x in xvals for y in yvals]) + uvgrid = B @ xygrid + abgrid = A @ uvgrid + + colors = list(map(colorizer, xygrid[0], xygrid[1])) + + fig, ax = plt.subplots(1, 3, figsize=(15, 5)) + + for axes in ax: + axes.set(xlim=(-12, 12), ylim=(-12, 12)) + axes.set_xticks([]) + axes.set_yticks([]) + for spine in ['left', 'bottom']: + axes.spines[spine].set_position('zero') + for spine in ['right', 'top']: + axes.spines[spine].set_color('none') + + # Plot grid points + ax[0].scatter(xygrid[0], xygrid[1], s=36, c=colors, edgecolor="none") + ax[0].set_title("points $x_1, x_2, \cdots, x_k$") + + # Plot intermediate grid points + ax[1].scatter(uvgrid[0], uvgrid[1], s=36, c=colors, edgecolor="none") + ax[1].set_title("points $Bx_1, Bx_2, \cdots, Bx_k$") + + # Plot transformed grid points + ax[2].scatter(abgrid[0], abgrid[1], s=36, c=colors, edgecolor="none") + ax[2].set_title("points $ABx_1, ABx_2, \cdots, ABx_k$") + + plt.show() +``` + +```{code-cell} ipython3 +A = np.array([[0, 1], # 90 degree clockwise rotation + [-1, 0]]) +B = np.array([[1, 2], # shear along x-axis + [0, 1]]) +``` + ++++ {"user_expressions": []} + +#### Shear then rotate + +```{code-cell} ipython3 +grid_composition_transform(A, B) # transformation AB +``` + ++++ {"user_expressions": []} + +#### Rotate then shear + +```{code-cell} ipython3 +grid_composition_transform(B,A) # transformation BA +``` + ++++ {"user_expressions": []} + +It is evident that the transformation $AB$ is not the same as the transformation $BA$. + +## Iterating on a fixed map + +In economics (and especially in dynamic modeling), we are often interested in +analyzing behavior where we repeatedly apply a fixed matrix. + +For example, given a vector $v$ and a matrix $A$, we are interested in +studying the sequence + +$$ + v, \quad + Av, \quad + AAv = A^2v, \quad \ldots +$$ + +Let's first see examples of a sequence of iterates $(A^k v)_{k \geq 0}$ under +different maps $A$. + +(plot_series)= + +```{code-cell} ipython3 +def plot_series(A, v, n): + + B = np.array([[1, -1], + [1, 0]]) + + fig, ax = plt.subplots() + + ax.set(xlim=(-4, 4), ylim=(-4, 4)) + ax.set_xticks([]) + ax.set_yticks([]) + for spine in ['left', 'bottom']: + ax.spines[spine].set_position('zero') + for spine in ['right', 'top']: + ax.spines[spine].set_color('none') + + θ = np.linspace(0, 2 * np.pi, 150) + r = 2.5 + x = r * np.cos(θ) + y = r * np.sin(θ) + x1 = x.reshape(1, -1) + y1 = y.reshape(1, -1) + xy = np.concatenate((x1, y1), axis=0) + + ellipse = B @ xy + ax.plot(ellipse[0, :], ellipse[1, :], color='black', + linestyle=(0, (5, 10)), linewidth=0.5) + + # Initialize holder for trajectories + colors = plt.cm.rainbow(np.linspace(0, 1, 20)) + + for i in range(n): + iteration = matrix_power(A, i) @ v + v1 = iteration[0] + v2 = iteration[1] + ax.scatter(v1, v2, color=colors[i]) + if i == 0: + ax.text(v1+0.25, v2, f'$v$') + elif i == 1: + ax.text(v1+0.25, v2, f'$Av$') + elif 1 < i < 4: + ax.text(v1+0.25, v2, f'$A^{i}v$') + plt.show() +``` + +```{code-cell} ipython3 +A = np.array([[sqrt(3) + 1, -2], + [1, sqrt(3) - 1]]) +A = (1/(2*sqrt(2))) * A +v = (-3, -3) +n = 12 + +plot_series(A, v, n) +``` + ++++ {"user_expressions": []} + +Here with each iteration the vectors get shorter, i.e., move closer to the origin. + +In this case, repeatedly multiplying a vector by $A$ makes the vector "spiral in". + +```{code-cell} ipython3 +B = np.array([[sqrt(3) + 1, -2], + [1, sqrt(3) - 1]]) +B = (1/2) * B +v = (2.5, 0) +n = 12 + +plot_series(B, v, n) +``` + ++++ {"user_expressions": []} + +Here with each iteration vectors do not tend to get longer or shorter. + +In this case, repeatedly multiplying a vector by $A$ simply "rotates it around +an ellipse". + +```{code-cell} ipython3 +B = np.array([[sqrt(3) + 1, -2], + [1, sqrt(3) - 1]]) +B = (1/sqrt(2)) * B +v = (-1, -0.25) +n = 6 + +plot_series(B, v, n) +``` + ++++ {"user_expressions": []} + +Here with each iteration vectors tend to get longer, i.e., farther from the +origin. + +In this case, repeatedly multiplying a vector by $A$ makes the vector "spiral out". + +We thus observe that the sequence $(A^kv)_{k \geq 0}$ behaves differently depending on the map $A$ itself. + +We now discuss the property of A that determines this behavior. + +(la_eigenvalues)= +## Eigenvalues + +```{index} single: Linear Algebra; Eigenvalues +``` + +In this section we introduce the notions of eigenvalues and eigenvectors. + +### Definitions + +Let $A$ be an $n \times n$ square matrix. + +If $\lambda$ is scalar and $v$ is a non-zero $n$-vector such that + +$$ +A v = \lambda v. +$$ + + +Then we say that $\lambda$ is an *eigenvalue* of $A$, and $v$ is the corresponding *eigenvector*. + +Thus, an eigenvector of $A$ is a nonzero vector $v$ such that when the map $A$ is +applied, $v$ is merely scaled. + +The next figure shows two eigenvectors (blue arrows) and their images under +$A$ (red arrows). + +As expected, the image $Av$ of each $v$ is just a scaled version of the original + +```{code-cell} ipython3 +:tags: [output_scroll] + +from numpy.linalg import eig + +A = [[1, 2], + [2, 1]] +A = np.array(A) +evals, evecs = eig(A) +evecs = evecs[:, 0], evecs[:, 1] + +fig, ax = plt.subplots(figsize=(10, 8)) +# Set the axes through the origin +for spine in ['left', 'bottom']: + ax.spines[spine].set_position('zero') +for spine in ['right', 'top']: + ax.spines[spine].set_color('none') +# ax.grid(alpha=0.4) + +xmin, xmax = -3, 3 +ymin, ymax = -3, 3 +ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax)) + +# Plot each eigenvector +for v in evecs: + ax.annotate('', xy=v, xytext=(0, 0), + arrowprops=dict(facecolor='blue', + shrink=0, + alpha=0.6, + width=0.5)) + +# Plot the image of each eigenvector +for v in evecs: + v = A @ v + ax.annotate('', xy=v, xytext=(0, 0), + arrowprops=dict(facecolor='red', + shrink=0, + alpha=0.6, + width=0.5)) + +# Plot the lines they run through +x = np.linspace(xmin, xmax, 3) +for v in evecs: + a = v[1] / v[0] + ax.plot(x, a * x, 'b-', lw=0.4) + +plt.show() +``` + ++++ {"user_expressions": []} + +### Complex values + +So far our definition of eigenvalues and eigenvectors seems straightforward. + +There is one complication we haven't mentioned yet: + +When solving $Av = \lambda v$, + +* $\lambda$ is allowed to be a complex number and +* $v$ is allowed to be an $n$-vector of complex numbers. + +We will see some examples below. + +### Some mathematical details + +We note some mathematical details for more advanced readers. + +(Other readers can skip to the next section.) + +The eigenvalue equation is equivalent to $(A - \lambda I) v = 0$. + +This equation has a nonzero solution $v$ only when the columns of $A - \lambda I$ are linearly dependent. + +This in turn is equivalent to stating the determinant is zero. + +Hence, to find all eigenvalues, we can look for $\lambda$ such that the +determinant of $A - \lambda I$ is zero. + +This problem can be expressed as one of solving for the roots of a polynomial +in $\lambda$ of degree $n$. + +This in turn implies the existence of $n$ solutions in the complex +plane, although some might be repeated. + +### Facts + +Some nice facts about the eigenvalues of a square matrix $A$ are as follows: + +1. the determinant of $A$ equals the product of the eigenvalues +2. the trace of $A$ (the sum of the elements on the principal diagonal) equals the sum of the eigenvalues +3. if $A$ is symmetric, then all of its eigenvalues are real +4. if $A$ is invertible and $\lambda_1, \ldots, \lambda_n$ are its eigenvalues, then the eigenvalues of $A^{-1}$ are $1/\lambda_1, \ldots, 1/\lambda_n$. + +A corollary of the last statement is that a matrix is invertible if and only if all its eigenvalues are nonzero. + +### Computation + +Using NumPy, we can solve for the eigenvalues and eigenvectors of a matrix as follows + +```{code-cell} ipython3 +from numpy.linalg import eig + +A = ((1, 2), + (2, 1)) + +A = np.array(A) +evals, evecs = eig(A) +evals # eigenvalues +``` + +```{code-cell} ipython3 +evecs # eigenvectors +``` + ++++ {"user_expressions": []} + +Note that the *columns* of `evecs` are the eigenvectors. + +Since any scalar multiple of an eigenvector is an eigenvector with the same +eigenvalue (which can be verified), the `eig` routine normalizes the length of each eigenvector +to one. + +The eigenvectors and eigenvalues of a map $A$ determine how a vector $v$ is transformed when we repeatedly multiply by $A$. + +This is discussed further later. + + +(la_neumann)= +## The Neumann Series Lemma + +```{index} single: Neumann's Lemma +``` + +In this section we present a famous result about series of matrices that has +many applications in economics. + +### Scalar series + +Here's a fundamental result about series: + +If $a$ is a number and $|a| < 1$, then + +```{math} +:label: gp_sum + + \sum_{k=0}^{\infty} a^k =\frac{1}{1-a} = (1 - a)^{-1} + +``` + +For a one-dimensional linear equation $x = ax + b$ where x is unknown we can thus conclude that the solution $x^{*}$ is given by: + +$$ + x^{*} = \frac{b}{1-a} = \sum_{k=0}^{\infty} a^k b +$$ + +### Matrix series + +A generalization of this idea exists in the matrix setting. + +Consider the system of equations $x = Ax + b$ where $A$ is an $n \times n$ +square matrix and $x$ and $b$ are both column vectors in $\mathbb{R}^n$. + +Using matrix algebra we can conclude that the solution to this system of equations will be given by: + +```{math} +:label: neumann_eqn + + x^{*} = (I-A)^{-1}b + +``` + +What guarantees the existence of a unique vector $x^{*}$ that satisfies +{eq}`neumann_eqn`? + +The following is a fundamental result in functional analysis that generalizes +{eq}`gp_sum` to a multivariate case. + +(neumann_series_lemma)= +```{prf:Theorem} Neumann Series Lemma +:label: neumann_series_lemma + +Let $A$ be a square matrix and let $A^k$ be the $k$-th power of $A$. + +Let $r(A)$ be the **spectral radius** of $A$, defined as $\max_i |\lambda_i|$, where + +* $\{\lambda_i\}_i$ is the set of eigenvalues of $A$ and +* $|\lambda_i|$ is the modulus of the complex number $\lambda_i$ + +Neumann's Theorem states the following: If $r(A) < 1$, then $I - A$ is invertible, and + +$$ +(I - A)^{-1} = \sum_{k=0}^{\infty} A^k +$$ +``` + +We can see the Neumann Series Lemma in action in the following example. + +```{code-cell} ipython3 +A = np.array([[0.4, 0.1], + [0.7, 0.2]]) + +evals, evecs = eig(A) # finding eigenvalues and eigenvectors + +r = max(abs(λ) for λ in evals) # compute spectral radius +print(r) +``` + +The spectral radius $r(A)$ obtained is less than 1. + +Thus, we can apply the Neumann Series Lemma to find $(I-A)^{-1}$. + +```{code-cell} ipython3 +I = np.identity(2) # 2 x 2 identity matrix +B = I - A +``` + +```{code-cell} ipython3 +B_inverse = np.linalg.inv(B) # direct inverse method +``` + +```{code-cell} ipython3 +A_sum = np.zeros((2, 2)) # power series sum of A +A_power = I +for i in range(50): + A_sum += A_power + A_power = A_power @ A +``` + +Let's check equality between the sum and the inverse methods. + +```{code-cell} ipython3 +np.allclose(A_sum, B_inverse) +``` + +Although we truncate the infinite sum at $k = 50$, both methods give us the same +result which illustrates the result of the Neumann Series Lemma. + + +## Exercises + +```{exercise} +:label: eig1_ex1 + +Power iteration is a method for finding the greatest absolute eigenvalue of a diagonalizable matrix. + +The method starts with a random vector $b_0$ and repeatedly applies the matrix $A$ to it + +$$ +b_{k+1}=\frac{A b_k}{\left\|A b_k\right\|} +$$ + +A thorough discussion of the method can be found [here](https://pythonnumericalmethods.berkeley.edu/notebooks/chapter15.02-The-Power-Method.html). + +In this exercise, first implement the power iteration method and use it to find the greatest absolute eigenvalue and its corresponding eigenvector. + +Then visualize the convergence. +``` + +```{solution-start} eig1_ex1 +:class: dropdown +``` + +Here is one solution. + +We start by looking into the distance between the eigenvector approximation and the true eigenvector. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Power iteration + name: pow-dist +--- +# Define a matrix A +A = np.array([[1, 0, 3], + [0, 2, 0], + [3, 0, 1]]) + +num_iters = 20 + +# Define a random starting vector b +b = np.random.rand(A.shape[1]) + +# Get the leading eigenvector of matrix A +eigenvector = np.linalg.eig(A)[1][:, 0] + +errors = [] +res = [] + +# Power iteration loop +for i in range(num_iters): + # Multiply b by A + b = A @ b + # Normalize b + b = b / np.linalg.norm(b) + # Append b to the list of eigenvector approximations + res.append(b) + err = np.linalg.norm(np.array(b) + - eigenvector) + errors.append(err) + +greatest_eigenvalue = np.dot(A @ b, b) / np.dot(b, b) +print(f'The approximated greatest absolute eigenvalue is \ + {greatest_eigenvalue:.2f}') +print('The real eigenvalue is', np.linalg.eig(A)[0]) + +# Plot the eigenvector approximations for each iteration +plt.figure(figsize=(10, 6)) +plt.xlabel('iterations') +plt.ylabel('error') +_ = plt.plot(errors) +``` + ++++ {"user_expressions": []} + +Then we can look at the trajectory of the eigenvector approximation. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Power iteration trajectory + name: pow-trajectory +--- +# Set up the figure and axis for 3D plot +fig = plt.figure() +ax = fig.add_subplot(111, projection='3d') + +# Plot the eigenvectors +ax.scatter(eigenvector[0], + eigenvector[1], + eigenvector[2], + color='r', s=80) + +for i, vec in enumerate(res): + ax.scatter(vec[0], vec[1], vec[2], + color='b', + alpha=(i+1)/(num_iters+1), + s=80) + +ax.set_xlabel('x') +ax.set_ylabel('y') +ax.set_zlabel('z') +ax.tick_params(axis='both', which='major', labelsize=7) + +points = [plt.Line2D([0], [0], linestyle='none', + c=i, marker='o') for i in ['r', 'b']] +ax.legend(points, ['actual eigenvector', + r'approximated eigenvector ($b_k$)']) +ax.set_box_aspect(aspect=None, zoom=0.8) + +plt.show() +``` + ++++ {"user_expressions": []} + +```{solution-end} +``` + +```{exercise} +:label: eig1_ex2 + +We have discussed the trajectory of the vector $v$ after being transformed by $A$. + +Consider the matrix $A = \begin{bmatrix} 1 & 2 \\ 1 & 1 \end{bmatrix}$ and the vector $v = \begin{bmatrix} 2 \\ -2 \end{bmatrix}$. + +Try to compute the trajectory of $v$ after being transformed by $A$ for $n=4$ iterations and plot the result. + +``` + +```{solution-start} eig1_ex2 +:class: dropdown +``` + +```{code-cell} ipython3 +A = np.array([[1, 2], + [1, 1]]) +v = (0.4, -0.4) +n = 11 + +# Compute eigenvectors and eigenvalues +eigenvalues, eigenvectors = np.linalg.eig(A) + +print(f'eigenvalues:\n {eigenvalues}') +print(f'eigenvectors:\n {eigenvectors}') + +plot_series(A, v, n) +``` + ++++ {"user_expressions": []} + +The result seems to converge to the eigenvector of $A$ with the largest eigenvalue. + +Let's use a [vector field](https://en.wikipedia.org/wiki/Vector_field) to visualize the transformation brought by A. + +(This is a more advanced topic in linear algebra, please step ahead if you are comfortable with the math.) + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Convergence towards eigenvectors + name: eigen-conv +--- +# Create a grid of points +x, y = np.meshgrid(np.linspace(-5, 5, 15), + np.linspace(-5, 5, 20)) + +# Apply the matrix A to each point in the vector field +vec_field = np.stack([x, y]) +u, v = np.tensordot(A, vec_field, axes=1) + +# Plot the transformed vector field +c = plt.streamplot(x, y, u - x, v - y, + density=1, linewidth=None, color='#A23BEC') +c.lines.set_alpha(0.5) +c.arrows.set_alpha(0.5) + +# Draw eigenvectors +origin = np.zeros((2, len(eigenvectors))) +parameters = {'color': ['b', 'g'], 'angles': 'xy', + 'scale_units': 'xy', 'scale': 0.1, 'width': 0.01} +plt.quiver(*origin, eigenvectors[0], + eigenvectors[1], **parameters) +plt.quiver(*origin, - eigenvectors[0], + - eigenvectors[1], **parameters) + +colors = ['b', 'g'] +lines = [Line2D([0], [0], color=c, linewidth=3) for c in colors] +labels = ["2.4 eigenspace", "0.4 eigenspace"] +plt.legend(lines, labels, loc='center left', + bbox_to_anchor=(1, 0.5)) + +plt.xlabel("x") +plt.ylabel("y") +plt.grid() +plt.gca().set_aspect('equal', adjustable='box') +plt.show() +``` + ++++ {"user_expressions": []} + +Note that the vector field converges to the eigenvector of $A$ with the largest eigenvalue and diverges from the eigenvector of $A$ with the smallest eigenvalue. + +In fact, the eigenvectors are also the directions in which the matrix $A$ stretches or shrinks the space. + +Specifically, the eigenvector with the largest eigenvalue is the direction in which the matrix $A$ stretches the space the most. + +We will see more intriguing examples in the following exercise. + +```{solution-end} +``` + +```{exercise} +:label: eig1_ex3 + +{ref}`Previously `, we demonstrated the trajectory of the vector $v$ after being transformed by $A$ for three different matrices. + +Use the visualization in the previous exercise to explain the trajectory of the vector $v$ after being transformed by $A$ for the three different matrices. + +``` + + +```{solution-start} eig1_ex3 +:class: dropdown +``` + +Here is one solution + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Vector fields of the three matrices + name: vector-field +--- +figure, ax = plt.subplots(1, 3, figsize=(15, 5)) +A = np.array([[sqrt(3) + 1, -2], + [1, sqrt(3) - 1]]) +A = (1/(2*sqrt(2))) * A + +B = np.array([[sqrt(3) + 1, -2], + [1, sqrt(3) - 1]]) +B = (1/2) * B + +C = np.array([[sqrt(3) + 1, -2], + [1, sqrt(3) - 1]]) +C = (1/sqrt(2)) * C + +examples = [A, B, C] + +for i, example in enumerate(examples): + M = example + + # Compute right eigenvectors and eigenvalues + eigenvalues, eigenvectors = np.linalg.eig(M) + print(f'Example {i+1}:\n') + print(f'eigenvalues:\n {eigenvalues}') + print(f'eigenvectors:\n {eigenvectors}\n') + + eigenvalues_real = eigenvalues.real + eigenvectors_real = eigenvectors.real + + # Create a grid of points + x, y = np.meshgrid(np.linspace(-20, 20, 15), + np.linspace(-20, 20, 20)) + + # Apply the matrix A to each point in the vector field + vec_field = np.stack([x, y]) + u, v = np.tensordot(M, vec_field, axes=1) + + # Plot the transformed vector field + c = ax[i].streamplot(x, y, u - x, v - y, density=1, + linewidth=None, color='#A23BEC') + c.lines.set_alpha(0.5) + c.arrows.set_alpha(0.5) + + # Draw eigenvectors + parameters = {'color': ['b', 'g'], 'angles': 'xy', + 'scale_units': 'xy', 'scale': 1, + 'width': 0.01, 'alpha': 0.5} + origin = np.zeros((2, len(eigenvectors))) + ax[i].quiver(*origin, eigenvectors_real[0], + eigenvectors_real[1], **parameters) + ax[i].quiver(*origin, + - eigenvectors_real[0], + - eigenvectors_real[1], + **parameters) + + ax[i].set_xlabel("x-axis") + ax[i].set_ylabel("y-axis") + ax[i].grid() + ax[i].set_aspect('equal', adjustable='box') + +plt.show() +``` + ++++ {"user_expressions": []} + +The vector fields explain why we observed the trajectories of the vector $v$ multiplied by $A$ iteratively before. + +The pattern demonstrated here is because we have complex eigenvalues and eigenvectors. + +We can plot the complex plane for one of the matrices using `Arrow3D` class retrieved from [stackoverflow](https://stackoverflow.com/questions/22867620/putting-arrowheads-on-vectors-in-a-3d-plot). + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: 3D plot of the vector field + name: 3d-vector-field +--- +class Arrow3D(FancyArrowPatch): + def __init__(self, xs, ys, zs, *args, **kwargs): + super().__init__((0, 0), (0, 0), *args, **kwargs) + self._verts3d = xs, ys, zs + + def do_3d_projection(self): + xs3d, ys3d, zs3d = self._verts3d + xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, + self.axes.M) + self.set_positions((0.1*xs[0], 0.1*ys[0]), + (0.1*xs[1], 0.1*ys[1])) + + return np.min(zs) + + +eigenvalues, eigenvectors = np.linalg.eig(A) + +# Create meshgrid for vector field +x, y = np.meshgrid(np.linspace(-2, 2, 15), + np.linspace(-2, 2, 15)) + +# Calculate vector field (real and imaginary parts) +u_real = A[0][0] * x + A[0][1] * y +v_real = A[1][0] * x + A[1][1] * y +u_imag = np.zeros_like(x) +v_imag = np.zeros_like(y) + +# Create 3D figure +fig = plt.figure() +ax = fig.add_subplot(111, projection='3d') +vlength = np.linalg.norm(eigenvectors) +ax.quiver(x, y, u_imag, u_real-x, v_real-y, v_imag-u_imag, + colors='b', alpha=0.3, length=.2, + arrow_length_ratio=0.01) + +arrow_prop_dict = dict(mutation_scale=5, + arrowstyle='-|>', shrinkA=0, shrinkB=0) + +# Plot 3D eigenvectors +for c, i in zip(['b', 'g'], [0, 1]): + a = Arrow3D([0, eigenvectors[0][i].real], + [0, eigenvectors[1][i].real], + [0, eigenvectors[1][i].imag], + color=c, **arrow_prop_dict) + ax.add_artist(a) + +# Set axis labels and title +ax.set_xlabel('x') +ax.set_ylabel('y') +ax.set_zlabel('Im') +ax.set_box_aspect(aspect=None, zoom=0.8) + +plt.draw() +plt.show() +``` + ++++ {"user_expressions": []} + +```{solution-end} +``` diff --git a/content/lectures/eigen_II.ipynb b/book/_build/html/_sources/eigen_II.ipynb similarity index 59% rename from content/lectures/eigen_II.ipynb rename to book/_build/html/_sources/eigen_II.ipynb index c272af1..5e01680 100644 --- a/content/lectures/eigen_II.ipynb +++ b/book/_build/html/_sources/eigen_II.ipynb @@ -2,18 +2,12 @@ "cells": [ { "cell_type": "markdown", - "id": "cdd061a2", - "metadata": { - "user_expressions": [] - }, + "id": "db831433", + "metadata": {}, "source": [ - "# Spectral Theory\n", + "# The Perron-Frobenius Theorem\n", "\n", - "```{index} single: Spectral Theory\n", - "```\n", - "\n", - "```{contents} Contents\n", - ":depth: 2\n", + "```{index} single: The Perron-Frobenius Theorem\n", "```\n", "\n", "In addition to what's in Anaconda, this lecture will need the following libraries:" @@ -22,7 +16,7 @@ { "cell_type": "code", "execution_count": null, - "id": "49e26923", + "id": "e75946f7", "metadata": { "tags": [ "hide-output" @@ -30,24 +24,17 @@ }, "outputs": [], "source": [ - "%pip install graphviz quantecon" + "%pip install quantecon" ] }, { "cell_type": "markdown", - "id": "7e9441fc", + "id": "d984f84b", "metadata": {}, "source": [ - "```{admonition} graphviz\n", - ":class: warning\n", - "If you are running this lecture locally it requires [graphviz](https://www.graphviz.org)\n", - "to be installed on your computer. Installation instructions for graphviz can be found\n", - "[here](https://www.graphviz.org/download/) \n", - "```\n", - "\n", "In this lecture we will begin with the foundational concepts in spectral theory.\n", "\n", - "Then we will explore the Perron-Frobenius Theorem and the Neumann Series Lemma, and connect them to applications in Markov chains and networks. \n", + "Then we will explore the Perron-Frobenius theorem and connect it to applications in Markov chains and networks.\n", "\n", "We will use the following imports:" ] @@ -55,21 +42,19 @@ { "cell_type": "code", "execution_count": null, - "id": "81ce3eee", + "id": "11f5c183", "metadata": {}, "outputs": [], "source": [ - "import matplotlib.pyplot as plt\n", "import numpy as np\n", "from numpy.linalg import eig\n", "import scipy as sp\n", - "import graphviz as gv\n", "import quantecon as qe" ] }, { "cell_type": "markdown", - "id": "4164bdc6", + "id": "5f3c4b8d", "metadata": {}, "source": [ "## Nonnegative matrices\n", @@ -78,11 +63,9 @@ "\n", "Nonnegative matrices have several special and useful properties.\n", "\n", - "In this section we discuss some of them --- in particular, the connection\n", + "In this section we will discuss some of them --- in particular, the connection\n", "between nonnegativity and eigenvalues.\n", "\n", - "Let $a^{k}_{ij}$ be element $(i,j)$ of $A^k$.\n", - "\n", "An $n \\times m$ matrix $A$ is called **nonnegative** if every element of $A$\n", "is nonnegative, i.e., $a_{ij} \\geq 0$ for every $i,j$.\n", "\n", @@ -91,50 +74,70 @@ "(irreducible)=\n", "### Irreducible matrices\n", "\n", - "We have (informally) introduced irreducible matrices in the Markov chain lecture (TODO: link to Markov chain lecture).\n", + "We introduced irreducible matrices in the [Markov chain lecture](mc_irreducible).\n", "\n", - "Here we will introduce this concept formally.\n", + "Here we generalize this concept:\n", "\n", - "$A$ is called **irreducible** if for *each* $(i,j)$ there is an integer $k \\geq 0$ such that $a^{k}_{ij} > 0$.\n", + "Let $a^{k}_{ij}$ be element $(i,j)$ of $A^k$.\n", "\n", - "A matrix $A$ that is not irreducible is called reducible.\n", + "An $n \\times n$ nonnegative matrix $A$ is called irreducible if $A + A^2 + A^3 + \\cdots \\gg 0$, where $\\gg 0$ indicates that every element in $A$ is strictly positive.\n", "\n", - "Here are some examples to illustrate this further.\n", + "In other words, for each $i,j$ with $1 \\leq i, j \\leq n$, there exists a $k \\geq 0$ such that $a^{k}_{ij} > 0$.\n", "\n", - "1. $A = \\begin{bmatrix} 0.5 & 0.1 \\\\ 0.2 & 0.2 \\end{bmatrix}$ is irreducible since $a_{ij}>0$ for all $(i,j)$.\n", + "```{prf:example}\n", + ":label: eigen2_ex_irr\n", "\n", - "2. $A = \\begin{bmatrix} 0 & 1 \\\\ 1 & 0 \\end{bmatrix}$ is irreducible since $a_{12},a_{21} >0$ and $a^{2}_{11},a^{2}_{22} >0$.\n", + "Here are some examples to illustrate this further:\n", "\n", - "3. $A = \\begin{bmatrix} 1 & 0 \\\\ 0 & 1 \\end{bmatrix}$ is reducible since $A^k = A$ for all $k \\geq 0$ and thus\n", - " $a^{k}_{12},a^{k}_{21} = 0$ for all $k \\geq 0$.\n", + "$$\n", + "A = \\begin{bmatrix} 0.5 & 0.1 \\\\ \n", + " 0.2 & 0.2 \n", + "\\end{bmatrix}\n", + "$$\n", "\n", - "### Primitive matrices\n", + "$A$ is irreducible since $a_{ij}>0$ for all $(i,j)$.\n", "\n", - "Let $A$ be a square nonnegative matrix and let $A^k$ be the $k^{th}$ power of $A$.\n", + "$$\n", + "B = \\begin{bmatrix} 0 & 1 \\\\ \n", + " 1 & 0 \n", + "\\end{bmatrix}\n", + ", \\quad\n", + "B^2 = \\begin{bmatrix} 1 & 0 \\\\ \n", + " 0 & 1\n", + "\\end{bmatrix}\n", + "$$\n", "\n", - "A matrix is considered **primitive** if there exists a $k \\in \\mathbb{N}$ such that $A^k$ is everywhere positive.\n", + "$B$ is irreducible since $B + B^2$ is a matrix of ones.\n", "\n", - "It means that $A$ is called primitive if there is an integer $k \\geq 0$ such that $a^{k}_{ij} > 0$ for *all* $(i,j)$.\n", + "$$\n", + "C = \\begin{bmatrix} 1 & 0 \\\\ \n", + " 0 & 1 \n", + "\\end{bmatrix}\n", + "$$\n", "\n", - "We can see that if a matrix is primitive, then it implies the matrix is irreducible.\n", + "$C$ is not irreducible since $C^k = C$ for all $k \\geq 0$ and thus\n", + " $c^{k}_{12},c^{k}_{21} = 0$ for all $k \\geq 0$.\n", + "```\n", "\n", - "This is because if there exists an $A^k$ such that $a^{k}_{ij} > 0$ for all $(i,j)$, then it guarantees the same property for ${k+1}^th, {k+2}^th ... {k+n}^th$ iterations.\n", + "### Left eigenvectors\n", "\n", - "In other words, a primitive matrix is both irreducible and aperiodic as aperiodicity requires a state to be visited with a guarantee of returning to itself after a certain amount of iterations.\n", + "Recall that we previously discussed eigenvectors in {ref}`Eigenvalues and Eigenvectors `.\n", "\n", - "### Left eigenvectors\n", + "In particular, $\\lambda$ is an eigenvalue of $A$ and $v$ is an eigenvector of $A$ if $v$ is nonzero and satisfy\n", + "\n", + "$$\n", + "Av = \\lambda v.\n", + "$$\n", "\n", - "We have previously discussed right (ordinary) eigenvectors $Av = \\lambda v$.\n", + "In this section we introduce left eigenvectors.\n", "\n", - "Here we introduce left eigenvectors.\n", + "To avoid confusion, what we previously referred to as \"eigenvectors\" will be called \"right eigenvectors\".\n", "\n", "Left eigenvectors will play important roles in what follows, including that of stochastic steady states for dynamic models under a Markov assumption.\n", "\n", - "We will talk more about this later, but for now, let's define left eigenvectors.\n", - "\n", - "A vector $w$ is called a left eigenvector of $A$ if $w$ is an eigenvector of $A^T$.\n", + "A vector $w$ is called a left eigenvector of $A$ if $w$ is a right eigenvector of $A^\\top$.\n", "\n", - "In other words, if $w$ is a left eigenvector of matrix A, then $A^T w = \\lambda w$, where $\\lambda$ is the eigenvalue associated with the left eigenvector $v$.\n", + "In other words, if $w$ is a left eigenvector of matrix $A$, then $A^\\top w = \\lambda w$, where $\\lambda$ is the eigenvalue associated with the left eigenvector $v$.\n", "\n", "This hints at how to compute left eigenvectors" ] @@ -142,83 +145,77 @@ { "cell_type": "code", "execution_count": null, - "id": "d8b97125", + "id": "763169b2", "metadata": {}, "outputs": [], "source": [ - "A = np.array([[3, 2], \n", + "A = np.array([[3, 2],\n", " [1, 4]])\n", "\n", - "# Compute right eigenvectors and eigenvalues\n", - "λ_r, v = eig(A)\n", + "# Compute eigenvalues and right eigenvectors\n", + "λ, v = eig(A)\n", "\n", - "# Compute left eigenvectors and eigenvalues\n", - "λ_l, w = eig(A.T)\n", + "# Compute eigenvalues and left eigenvectors\n", + "λ, w = eig(A.T)\n", "\n", - "print(\"Right Eigenvalues:\")\n", - "print(λ_r)\n", - "print(\"\\nRight Eigenvectors:\")\n", - "print(v)\n", - "print(\"\\nLeft Eigenvalues:\")\n", - "print(λ_l)\n", - "print(\"\\nLeft Eigenvectors:\")\n", - "print(w)" + "# Keep 5 decimals\n", + "np.set_printoptions(precision=5)\n", + "\n", + "print(f\"The eigenvalues of A are:\\n {λ}\\n\")\n", + "print(f\"The corresponding right eigenvectors are: \\n {v[:,0]} and {-v[:,1]}\\n\")\n", + "print(f\"The corresponding left eigenvectors are: \\n {w[:,0]} and {-w[:,1]}\\n\")" ] }, { "cell_type": "markdown", - "id": "b9ea57bb", + "id": "5bf945bc", "metadata": {}, "source": [ - "We can use `scipy.linalg.eig` with argument `left=True` to find left eigenvectors directly" + "We can also use `scipy.linalg.eig` with argument `left=True` to find left eigenvectors directly" ] }, { "cell_type": "code", "execution_count": null, - "id": "cbfde1c1", + "id": "88671da4", "metadata": {}, "outputs": [], "source": [ "eigenvals, ε, e = sp.linalg.eig(A, left=True)\n", "\n", - "print(\"Right Eigenvalues:\")\n", - "print(λ_r)\n", - "print(\"\\nRight Eigenvectors:\")\n", - "print(v)\n", - "print(\"\\nLeft Eigenvalues:\")\n", - "print(λ_l)\n", - "print(\"\\nLeft Eigenvectors:\")\n", - "print(w)" + "print(f\"The eigenvalues of A are:\\n {eigenvals.real}\\n\")\n", + "print(f\"The corresponding right eigenvectors are: \\n {e[:,0]} and {-e[:,1]}\\n\")\n", + "print(f\"The corresponding left eigenvectors are: \\n {ε[:,0]} and {-ε[:,1]}\\n\")" ] }, { "cell_type": "markdown", - "id": "91429576", + "id": "18adb7ee", "metadata": {}, "source": [ - "Note that the eigenvalues for both left and right eigenvectors are the same, but the eigenvectors themselves are different.\n", + "The eigenvalues are the same while the eigenvectors themselves are different.\n", + "\n", + "(Also note that we are taking the nonnegative value of the eigenvector of {ref}`dominant eigenvalue `, this is because `eig` automatically normalizes the eigenvectors.)\n", "\n", - "We can then take transpose to obtain $A^T w = \\lambda w$ and obtain $w^T A= \\lambda w^T$.\n", + "We can then take transpose to obtain $A^\\top w = \\lambda w$ and obtain $w^\\top A= \\lambda w^\\top$.\n", "\n", "This is a more common expression and where the name left eigenvectors originates.\n", "\n", "(perron-frobe)=\n", - "### The Perron-Frobenius Theorem\n", + "### The Perron-Frobenius theorem\n", "\n", - "For a nonnegative matrix $A$ the behavior of $A^k$ as $k \\to \\infty$ is controlled by the eigenvalue with the largest\n", + "For a square nonnegative matrix $A$, the behavior of $A^k$ as $k \\to \\infty$ is controlled by the eigenvalue with the largest\n", "absolute value, often called the **dominant eigenvalue**.\n", "\n", - "For a matrix $A$, the Perron-Frobenius Theorem characterizes certain\n", - "properties of the dominant eigenvalue and its corresponding eigenvector when\n", - "$A$ is a nonnegative square matrix.\n", + "For any such matrix $A$, the Perron-Frobenius theorem characterizes certain\n", + "properties of the dominant eigenvalue and its corresponding eigenvector.\n", "\n", "```{prf:Theorem} Perron-Frobenius Theorem\n", ":label: perron-frobenius\n", "\n", "If a matrix $A \\geq 0$ then,\n", "\n", - "1. the dominant eigenvalue of $A$, $r(A)$, is real-valued and nonnegative. \n", + "1. the dominant eigenvalue of $A$, $r(A)$, is real-valued and nonnegative.\n", "2. for any other eigenvalue (possibly complex) $\\lambda$ of $A$, $|\\lambda| \\leq r(A)$.\n", "3. we can find a nonnegative and nonzero eigenvector $v$ such that $Av = r(A)v$.\n", "\n", @@ -227,11 +224,7 @@ "4. the eigenvector $v$ associated with the eigenvalue $r(A)$ is strictly positive.\n", "5. there exists no other positive eigenvector $v$ (except scalar multiples of $v$) associated with $r(A)$.\n", "\n", - "If $A$ is primitive then,\n", - "\n", - "6. the inequality $|\\lambda| \\leq r(A)$ is **strict** for all eigenvalues $\\lambda$ of $A$ distinct from $r(A)$, and\n", - "7. with $v$ and $w$ normalized so that the inner product of $w$ and $v = 1$, we have\n", - "$ r(A)^{-m} A^m$ converges to $v w^{\\top}$ when $m \\rightarrow \\infty$. $v w^{\\top}$ is called the **Perron projection** of $A$.\n", + "(More of the Perron-Frobenius theorem about primitive matrices will be introduced {ref}`below `.)\n", "```\n", "\n", "(This is a relatively simple version of the theorem --- for more details see\n", @@ -243,26 +236,26 @@ "\n", "Now let's consider examples for each case.\n", "\n", - "#### Example 1: irreducible matrix\n", + "#### Example: irreducible matrix\n", "\n", - "Consider the following irreducible matrix A:" + "Consider the following irreducible matrix $A$:" ] }, { "cell_type": "code", "execution_count": null, - "id": "4ed1be06", + "id": "24135c2f", "metadata": {}, "outputs": [], "source": [ - "A = np.array([[0, 1, 0], \n", - " [.5, 0, .5], \n", + "A = np.array([[0, 1, 0],\n", + " [.5, 0, .5],\n", " [0, 1, 0]])" ] }, { "cell_type": "markdown", - "id": "ac576dd9", + "id": "ab825569", "metadata": {}, "source": [ "We can compute the dominant eigenvalue and the corresponding eigenvector" @@ -271,7 +264,7 @@ { "cell_type": "code", "execution_count": null, - "id": "100f9d99", + "id": "451e5efa", "metadata": {}, "outputs": [], "source": [ @@ -280,10 +273,10 @@ }, { "cell_type": "markdown", - "id": "91159750", + "id": "8320a0cc", "metadata": {}, "source": [ - "Now we can go through our checklist to verify the claims of the Perron-Frobenius Theorem for the irreducible matrix A:\n", + "Now we can see the claims of the Perron-Frobenius theorem holds for the irreducible matrix $A$:\n", "\n", "1. The dominant eigenvalue is real-valued and non-negative.\n", "2. All other eigenvalues have absolute values less than or equal to the dominant eigenvalue.\n", @@ -291,20 +284,71 @@ "4. As the matrix is irreducible, the eigenvector associated with the dominant eigenvalue is strictly positive.\n", "5. There exists no other positive eigenvector associated with the dominant eigenvalue.\n", "\n", - "#### Example 2: primitive matrix\n", + "(prim_matrices)=\n", + "### Primitive matrices\n", + "\n", + "We know that in real world situations it's hard for a matrix to be everywhere positive (although they have nice properties).\n", + "\n", + "The primitive matrices, however, can still give us helpful properties with looser definitions.\n", + "\n", + "Let $A$ be a square nonnegative matrix and let $A^k$ be the $k^{th}$ power of $A$.\n", + "\n", + "A matrix is called **primitive** if there exists a $k \\in \\mathbb{N}$ such that $A^k$ is everywhere positive.\n", + "\n", + "```{prf:example}\n", + ":label: eigen2_ex_prim\n", + "\n", + "Recall the examples given in irreducible matrices:\n", + "\n", + "$$\n", + "A = \\begin{bmatrix} 0.5 & 0.1 \\\\ \n", + " 0.2 & 0.2 \n", + "\\end{bmatrix}\n", + "$$\n", + "\n", + "$A$ here is also a primitive matrix since $A^k$ is everywhere nonnegative for $k \\in \\mathbb{N}$.\n", + "\n", + "$$\n", + "B = \\begin{bmatrix} 0 & 1 \\\\ \n", + " 1 & 0 \n", + "\\end{bmatrix}\n", + ", \\quad\n", + "B^2 = \\begin{bmatrix} 1 & 0 \\\\ \n", + " 0 & 1\n", + "\\end{bmatrix}\n", + "$$\n", + "\n", + "$B$ is irreducible but not primitive since there are always zeros in either principal diagonal or secondary diagonal.\n", + "```\n", + "\n", + "We can see that if a matrix is primitive, then it implies the matrix is irreducible but not vice versa.\n", + "\n", + "Now let's step back to the primitive matrices part of the Perron-Frobenius theorem\n", "\n", - "Consider the following primitive matrix B:" + "```{prf:Theorem} Continous of Perron-Frobenius Theorem\n", + ":label: con-perron-frobenius\n", + "\n", + "If $A$ is primitive then,\n", + "\n", + "6. the inequality $|\\lambda| \\leq r(A)$ is **strict** for all eigenvalues $\\lambda$ of $A$ distinct from $r(A)$, and\n", + "7. with $v$ and $w$ normalized so that the inner product of $w$ and $v = 1$, we have\n", + "$ r(A)^{-m} A^m$ converges to $v w^{\\top}$ when $m \\rightarrow \\infty$. The matrix $v w^{\\top}$ is called the **Perron projection** of $A$.\n", + "```\n", + "\n", + "#### Example 1: primitive matrix\n", + "\n", + "Consider the following primitive matrix $B$:" ] }, { "cell_type": "code", "execution_count": null, - "id": "f0a62d44", + "id": "9714b55b", "metadata": {}, "outputs": [], "source": [ - "B = np.array([[0, 1, 1], \n", - " [1, 0, 1], \n", + "B = np.array([[0, 1, 1],\n", + " [1, 0, 1],\n", " [1, 1, 0]])\n", "\n", "np.linalg.matrix_power(B, 2)" @@ -312,34 +356,16 @@ }, { "cell_type": "markdown", - "id": "c9ee1018", + "id": "47ab156b", "metadata": {}, "source": [ - "We can compute the dominant eigenvalue and the corresponding eigenvector using the power iteration method as discussed {ref}`earlier`:" + "We compute the dominant eigenvalue and the corresponding eigenvector" ] }, { "cell_type": "code", "execution_count": null, - "id": "8ad957e0", - "metadata": {}, - "outputs": [], - "source": [ - "num_iters = 20\n", - "b = np.random.rand(B.shape[1])\n", - "\n", - "for i in range(num_iters):\n", - " b = B @ b\n", - " b = b / np.linalg.norm(b)\n", - "\n", - "dominant_eigenvalue = np.dot(B @ b, b) / np.dot(b, b)\n", - "np.round(dominant_eigenvalue, 2)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6430d7cb", + "id": "e1f7e578", "metadata": {}, "outputs": [], "source": [ @@ -348,12 +374,10 @@ }, { "cell_type": "markdown", - "id": "54bca13e", - "metadata": { - "user_expressions": [] - }, + "id": "2d7f5a59", + "metadata": {}, "source": [ - "Now let's verify the claims of the Perron-Frobenius Theorem for the primitive matrix B:\n", + "Now let's give some examples to see if the claims of the Perron-Frobenius theorem hold for the primitive matrix $B$:\n", "\n", "1. The dominant eigenvalue is real-valued and non-negative.\n", "2. All other eigenvalues have absolute values strictly less than the dominant eigenvalue.\n", @@ -368,7 +392,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b804c73e", + "id": "01f2acd0", "metadata": {}, "outputs": [], "source": [ @@ -403,7 +427,7 @@ " n_list = [1, 10, 100, 1000, 10000]\n", "\n", " for n in n_list:\n", - " \n", + "\n", " # Compute (A/r)^n\n", " M_n = np.linalg.matrix_power(M/r, n)\n", "\n", @@ -412,15 +436,15 @@ "\n", " # Calculate the norm of the difference matrix\n", " diff_norm = np.linalg.norm(diff, 'fro')\n", - " print(f\"n = {n}, norm of the difference: {diff_norm:.10f}\")\n", + " print(f\"n = {n}, error = {diff_norm:.10f}\")\n", "\n", "\n", "A1 = np.array([[1, 2],\n", " [1, 4]])\n", "\n", - "A2 = np.array([[0, 1, 1], \n", - " [1, 0, 1], \n", - " [1, 1, 0]])\n", + "A2 = np.array([[0, 1, 1],\n", + " [1, 0, 1],\n", + " [1, 1, 0]])\n", "\n", "A3 = np.array([[0.971, 0.029, 0.1, 1],\n", " [0.145, 0.778, 0.077, 0.59],\n", @@ -438,7 +462,7 @@ }, { "cell_type": "markdown", - "id": "29d8653a", + "id": "e6d81194", "metadata": {}, "source": [ "The convergence is not observed in cases of non-primitive matrices.\n", @@ -449,12 +473,12 @@ { "cell_type": "code", "execution_count": null, - "id": "3b6a21c5", + "id": "d7f2a270", "metadata": {}, "outputs": [], "source": [ - "B = np.array([[0, 1, 1], \n", - " [1, 0, 0], \n", + "B = np.array([[0, 1, 1],\n", + " [1, 0, 0],\n", " [1, 0, 0]])\n", "\n", "# This shows that the matrix is not primitive\n", @@ -468,29 +492,29 @@ }, { "cell_type": "markdown", - "id": "827923e0", + "id": "34251903", "metadata": {}, "source": [ "The result shows that the matrix is not primitive as it is not everywhere positive.\n", "\n", - "These examples show how the Perron-Frobenius Theorem relates to the eigenvalues and eigenvectors of positive matrices and the convergence of the power of matrices.\n", + "These examples show how the Perron-Frobenius theorem relates to the eigenvalues and eigenvectors of positive matrices and the convergence of the power of matrices.\n", "\n", - "In fact we have already seen the theorem in action before in {ref}`the markov chain lecture `.\n", + "In fact we have already seen the theorem in action before in {ref}`the Markov chain lecture `.\n", "\n", "(spec_markov)=\n", - "#### Example 3: Connection to Markov chains\n", + "#### Example 2: connection to Markov chains\n", "\n", - "We are now prepared to bridge the languages spoken in the two lectures. \n", + "We are now prepared to bridge the languages spoken in the two lectures.\n", "\n", - "A primitive matrix is both irreducible (or strongly connected in the language of graph) and aperiodic.\n", + "A primitive matrix is both irreducible and aperiodic.\n", "\n", - "So Perron-Frobenius Theorem explains why both Imam and Temple matrix and Hamilton matrix converge to a stationary distribution, which is the Perron projection of the two matrices" + "So Perron-Frobenius theorem explains why both {ref}`Imam and Temple matrix ` and [Hamilton matrix](https://en.wikipedia.org/wiki/Hamiltonian_matrix) converge to a stationary distribution, which is the Perron projection of the two matrices" ] }, { "cell_type": "code", "execution_count": null, - "id": "6976ad2e", + "id": "46125208", "metadata": {}, "outputs": [], "source": [ @@ -504,7 +528,7 @@ { "cell_type": "code", "execution_count": null, - "id": "dc21fb53", + "id": "a81e3800", "metadata": {}, "outputs": [], "source": [ @@ -516,7 +540,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4e5ffd17", + "id": "c3581cf4", "metadata": {}, "outputs": [], "source": [ @@ -530,7 +554,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c0fc7937", + "id": "1d8a6e2e", "metadata": {}, "outputs": [], "source": [ @@ -541,7 +565,7 @@ }, { "cell_type": "markdown", - "id": "8cc07782", + "id": "fb16f381", "metadata": {}, "source": [ "We can also verify other properties hinted by Perron-Frobenius in these stochastic matrices." @@ -549,7 +573,7 @@ }, { "cell_type": "markdown", - "id": "072e6b79", + "id": "55599735", "metadata": {}, "source": [ "Another example is the relationship between convergence gap and convergence rate.\n", @@ -558,6 +582,8 @@ "\n", "This can be proven using what we have learned here.\n", "\n", + "Please note that we use $\\mathbb{1}$ for a vector of ones in this lecture.\n", + "\n", "With Markov model $M$ with state space $S$ and transition matrix $P$, we can write $P^t$ as\n", "\n", "$$\n", @@ -566,7 +592,7 @@ "\n", "This is proven in {cite}`sargent2023economic` and a nice discussion can be found [here](https://math.stackexchange.com/questions/2433997/can-all-matrices-be-decomposed-as-product-of-right-and-left-eigenvector).\n", "\n", - "In the formula $\\lambda_i$ is an eigenvalue of $P$ and $v_i$ and $w_i$ are the right and left eigenvectors corresponding to $\\lambda_i$. \n", + "In this formula $\\lambda_i$ is an eigenvalue of $P$ with corresponding right and left eigenvectors $v_i$ and $w_i$ .\n", "\n", "Premultiplying $P^t$ by arbitrary $\\psi \\in \\mathscr{D}(S)$ and rearranging now gives\n", "\n", @@ -574,15 +600,14 @@ "\\psi P^t-\\psi^*=\\sum_{i=1}^{n-1} \\lambda_i^t \\psi v_i w_i^{\\top}\n", "$$\n", "\n", - "Recall that eigenvalues are ordered from smallest to largest from $i = 1 ... n$. \n", + "Recall that eigenvalues are ordered from smallest to largest from $i = 1 ... n$.\n", "\n", "As we have seen, the largest eigenvalue for a primitive stochastic matrix is one.\n", "\n", - "This can be proven using [Gershgorin Circle Theorem](https://en.wikipedia.org/wiki/Gershgorin_circle_theorem), \n", + "This can be proven using [Gershgorin Circle Theorem](https://en.wikipedia.org/wiki/Gershgorin_circle_theorem),\n", "but it is out of the scope of this lecture.\n", "\n", - "So by the statement (6) of Perron-Frobenius Theorem, $\\lambda_i<1$ for all $i` to find the solution $x^{*}$ if it exists.\n", "\n", "```{exercise-end}\n", "```\n", @@ -827,7 +694,7 @@ { "cell_type": "code", "execution_count": null, - "id": "bfcc3219", + "id": "862b0677", "metadata": {}, "outputs": [], "source": [ @@ -843,16 +710,16 @@ }, { "cell_type": "markdown", - "id": "fc509d3d", + "id": "75dc1fa0", "metadata": {}, "source": [ - "Since we have $r(A) < 1$ we can thus find the solution using the Neumann Series lemma." + "Since we have $r(A) < 1$ we can thus find the solution using the Neumann Series Lemma." ] }, { "cell_type": "code", "execution_count": null, - "id": "60c4ec99", + "id": "dc46d4f1", "metadata": {}, "outputs": [], "source": [ @@ -869,7 +736,7 @@ }, { "cell_type": "markdown", - "id": "c3622489", + "id": "ad8f99ca", "metadata": {}, "source": [ "```{solution-end}\n", @@ -878,12 +745,53 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.4" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 12, + 21, + 25, + 33, + 38, + 124, + 140, + 144, + 150, + 199, + 203, + 207, + 209, + 274, + 280, + 284, + 286, + 299, + 362, + 368, + 380, + 397, + 405, + 411, + 419, + 423, + 427, + 543, + 552, + 556, + 566 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/eigen_II.md b/book/_build/html/_sources/eigen_II.md new file mode 100644 index 0000000..3d8c31a --- /dev/null +++ b/book/_build/html/_sources/eigen_II.md @@ -0,0 +1,569 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.4 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# The Perron-Frobenius Theorem + +```{index} single: The Perron-Frobenius Theorem +``` + +In addition to what's in Anaconda, this lecture will need the following libraries: + +```{code-cell} ipython3 +:tags: [hide-output] + +%pip install quantecon +``` + +In this lecture we will begin with the foundational concepts in spectral theory. + +Then we will explore the Perron-Frobenius theorem and connect it to applications in Markov chains and networks. + +We will use the following imports: + +```{code-cell} ipython3 +import numpy as np +from numpy.linalg import eig +import scipy as sp +import quantecon as qe +``` + +## Nonnegative matrices + +Often, in economics, the matrix that we are dealing with is nonnegative. + +Nonnegative matrices have several special and useful properties. + +In this section we will discuss some of them --- in particular, the connection +between nonnegativity and eigenvalues. + +An $n \times m$ matrix $A$ is called **nonnegative** if every element of $A$ +is nonnegative, i.e., $a_{ij} \geq 0$ for every $i,j$. + +We denote this as $A \geq 0$. + +(irreducible)= +### Irreducible matrices + +We introduced irreducible matrices in the [Markov chain lecture](mc_irreducible). + +Here we generalize this concept: + +Let $a^{k}_{ij}$ be element $(i,j)$ of $A^k$. + +An $n \times n$ nonnegative matrix $A$ is called irreducible if $A + A^2 + A^3 + \cdots \gg 0$, where $\gg 0$ indicates that every element in $A$ is strictly positive. + +In other words, for each $i,j$ with $1 \leq i, j \leq n$, there exists a $k \geq 0$ such that $a^{k}_{ij} > 0$. + +```{prf:example} +:label: eigen2_ex_irr + +Here are some examples to illustrate this further: + +$$ +A = \begin{bmatrix} 0.5 & 0.1 \\ + 0.2 & 0.2 +\end{bmatrix} +$$ + +$A$ is irreducible since $a_{ij}>0$ for all $(i,j)$. + +$$ +B = \begin{bmatrix} 0 & 1 \\ + 1 & 0 +\end{bmatrix} +, \quad +B^2 = \begin{bmatrix} 1 & 0 \\ + 0 & 1 +\end{bmatrix} +$$ + +$B$ is irreducible since $B + B^2$ is a matrix of ones. + +$$ +C = \begin{bmatrix} 1 & 0 \\ + 0 & 1 +\end{bmatrix} +$$ + +$C$ is not irreducible since $C^k = C$ for all $k \geq 0$ and thus + $c^{k}_{12},c^{k}_{21} = 0$ for all $k \geq 0$. +``` + +### Left eigenvectors + +Recall that we previously discussed eigenvectors in {ref}`Eigenvalues and Eigenvectors `. + +In particular, $\lambda$ is an eigenvalue of $A$ and $v$ is an eigenvector of $A$ if $v$ is nonzero and satisfy + +$$ +Av = \lambda v. +$$ + +In this section we introduce left eigenvectors. + +To avoid confusion, what we previously referred to as "eigenvectors" will be called "right eigenvectors". + +Left eigenvectors will play important roles in what follows, including that of stochastic steady states for dynamic models under a Markov assumption. + +A vector $w$ is called a left eigenvector of $A$ if $w$ is a right eigenvector of $A^\top$. + +In other words, if $w$ is a left eigenvector of matrix $A$, then $A^\top w = \lambda w$, where $\lambda$ is the eigenvalue associated with the left eigenvector $v$. + +This hints at how to compute left eigenvectors + +```{code-cell} ipython3 +A = np.array([[3, 2], + [1, 4]]) + +# Compute eigenvalues and right eigenvectors +λ, v = eig(A) + +# Compute eigenvalues and left eigenvectors +λ, w = eig(A.T) + +# Keep 5 decimals +np.set_printoptions(precision=5) + +print(f"The eigenvalues of A are:\n {λ}\n") +print(f"The corresponding right eigenvectors are: \n {v[:,0]} and {-v[:,1]}\n") +print(f"The corresponding left eigenvectors are: \n {w[:,0]} and {-w[:,1]}\n") +``` + +We can also use `scipy.linalg.eig` with argument `left=True` to find left eigenvectors directly + +```{code-cell} ipython3 +eigenvals, ε, e = sp.linalg.eig(A, left=True) + +print(f"The eigenvalues of A are:\n {eigenvals.real}\n") +print(f"The corresponding right eigenvectors are: \n {e[:,0]} and {-e[:,1]}\n") +print(f"The corresponding left eigenvectors are: \n {ε[:,0]} and {-ε[:,1]}\n") +``` + +The eigenvalues are the same while the eigenvectors themselves are different. + +(Also note that we are taking the nonnegative value of the eigenvector of {ref}`dominant eigenvalue `, this is because `eig` automatically normalizes the eigenvectors.) + +We can then take transpose to obtain $A^\top w = \lambda w$ and obtain $w^\top A= \lambda w^\top$. + +This is a more common expression and where the name left eigenvectors originates. + +(perron-frobe)= +### The Perron-Frobenius theorem + +For a square nonnegative matrix $A$, the behavior of $A^k$ as $k \to \infty$ is controlled by the eigenvalue with the largest +absolute value, often called the **dominant eigenvalue**. + +For any such matrix $A$, the Perron-Frobenius theorem characterizes certain +properties of the dominant eigenvalue and its corresponding eigenvector. + +```{prf:Theorem} Perron-Frobenius Theorem +:label: perron-frobenius + +If a matrix $A \geq 0$ then, + +1. the dominant eigenvalue of $A$, $r(A)$, is real-valued and nonnegative. +2. for any other eigenvalue (possibly complex) $\lambda$ of $A$, $|\lambda| \leq r(A)$. +3. we can find a nonnegative and nonzero eigenvector $v$ such that $Av = r(A)v$. + +Moreover if $A$ is also irreducible then, + +4. the eigenvector $v$ associated with the eigenvalue $r(A)$ is strictly positive. +5. there exists no other positive eigenvector $v$ (except scalar multiples of $v$) associated with $r(A)$. + +(More of the Perron-Frobenius theorem about primitive matrices will be introduced {ref}`below `.) +``` + +(This is a relatively simple version of the theorem --- for more details see +[here](https://en.wikipedia.org/wiki/Perron%E2%80%93Frobenius_theorem)). + +We will see applications of the theorem below. + +Let's build our intuition for the theorem using a simple example we have seen [before](mc_eg1). + +Now let's consider examples for each case. + +#### Example: irreducible matrix + +Consider the following irreducible matrix $A$: + +```{code-cell} ipython3 +A = np.array([[0, 1, 0], + [.5, 0, .5], + [0, 1, 0]]) +``` + +We can compute the dominant eigenvalue and the corresponding eigenvector + +```{code-cell} ipython3 +eig(A) +``` + +Now we can see the claims of the Perron-Frobenius theorem holds for the irreducible matrix $A$: + +1. The dominant eigenvalue is real-valued and non-negative. +2. All other eigenvalues have absolute values less than or equal to the dominant eigenvalue. +3. A non-negative and nonzero eigenvector is associated with the dominant eigenvalue. +4. As the matrix is irreducible, the eigenvector associated with the dominant eigenvalue is strictly positive. +5. There exists no other positive eigenvector associated with the dominant eigenvalue. + +(prim_matrices)= +### Primitive matrices + +We know that in real world situations it's hard for a matrix to be everywhere positive (although they have nice properties). + +The primitive matrices, however, can still give us helpful properties with looser definitions. + +Let $A$ be a square nonnegative matrix and let $A^k$ be the $k^{th}$ power of $A$. + +A matrix is called **primitive** if there exists a $k \in \mathbb{N}$ such that $A^k$ is everywhere positive. + +```{prf:example} +:label: eigen2_ex_prim + +Recall the examples given in irreducible matrices: + +$$ +A = \begin{bmatrix} 0.5 & 0.1 \\ + 0.2 & 0.2 +\end{bmatrix} +$$ + +$A$ here is also a primitive matrix since $A^k$ is everywhere nonnegative for $k \in \mathbb{N}$. + +$$ +B = \begin{bmatrix} 0 & 1 \\ + 1 & 0 +\end{bmatrix} +, \quad +B^2 = \begin{bmatrix} 1 & 0 \\ + 0 & 1 +\end{bmatrix} +$$ + +$B$ is irreducible but not primitive since there are always zeros in either principal diagonal or secondary diagonal. +``` + +We can see that if a matrix is primitive, then it implies the matrix is irreducible but not vice versa. + +Now let's step back to the primitive matrices part of the Perron-Frobenius theorem + +```{prf:Theorem} Continous of Perron-Frobenius Theorem +:label: con-perron-frobenius + +If $A$ is primitive then, + +6. the inequality $|\lambda| \leq r(A)$ is **strict** for all eigenvalues $\lambda$ of $A$ distinct from $r(A)$, and +7. with $v$ and $w$ normalized so that the inner product of $w$ and $v = 1$, we have +$ r(A)^{-m} A^m$ converges to $v w^{\top}$ when $m \rightarrow \infty$. The matrix $v w^{\top}$ is called the **Perron projection** of $A$. +``` + +#### Example 1: primitive matrix + +Consider the following primitive matrix $B$: + +```{code-cell} ipython3 +B = np.array([[0, 1, 1], + [1, 0, 1], + [1, 1, 0]]) + +np.linalg.matrix_power(B, 2) +``` + +We compute the dominant eigenvalue and the corresponding eigenvector + +```{code-cell} ipython3 +eig(B) +``` + +Now let's give some examples to see if the claims of the Perron-Frobenius theorem hold for the primitive matrix $B$: + +1. The dominant eigenvalue is real-valued and non-negative. +2. All other eigenvalues have absolute values strictly less than the dominant eigenvalue. +3. A non-negative and nonzero eigenvector is associated with the dominant eigenvalue. +4. The eigenvector associated with the dominant eigenvalue is strictly positive. +5. There exists no other positive eigenvector associated with the dominant eigenvalue. +6. The inequality $|\lambda| < r(B)$ holds for all eigenvalues $\lambda$ of $B$ distinct from the dominant eigenvalue. + +Furthermore, we can verify the convergence property (7) of the theorem on the following examples: + +```{code-cell} ipython3 +def compute_perron_projection(M): + + eigval, v = eig(M) + eigval, w = eig(M.T) + + r = np.max(eigval) + + # Find the index of the dominant (Perron) eigenvalue + i = np.argmax(eigval) + + # Get the Perron eigenvectors + v_P = v[:, i].reshape(-1, 1) + w_P = w[:, i].reshape(-1, 1) + + # Normalize the left and right eigenvectors + norm_factor = w_P.T @ v_P + v_norm = v_P / norm_factor + + # Compute the Perron projection matrix + P = v_norm @ w_P.T + return P, r + +def check_convergence(M): + P, r = compute_perron_projection(M) + print("Perron projection:") + print(P) + + # Define a list of values for n + n_list = [1, 10, 100, 1000, 10000] + + for n in n_list: + + # Compute (A/r)^n + M_n = np.linalg.matrix_power(M/r, n) + + # Compute the difference between A^n / r^n and the Perron projection + diff = np.abs(M_n - P) + + # Calculate the norm of the difference matrix + diff_norm = np.linalg.norm(diff, 'fro') + print(f"n = {n}, error = {diff_norm:.10f}") + + +A1 = np.array([[1, 2], + [1, 4]]) + +A2 = np.array([[0, 1, 1], + [1, 0, 1], + [1, 1, 0]]) + +A3 = np.array([[0.971, 0.029, 0.1, 1], + [0.145, 0.778, 0.077, 0.59], + [0.1, 0.508, 0.492, 1.12], + [0.2, 0.8, 0.71, 0.95]]) + +for M in A1, A2, A3: + print("Matrix:") + print(M) + check_convergence(M) + print() + print("-"*36) + print() +``` + +The convergence is not observed in cases of non-primitive matrices. + +Let's go through an example + +```{code-cell} ipython3 +B = np.array([[0, 1, 1], + [1, 0, 0], + [1, 0, 0]]) + +# This shows that the matrix is not primitive +print("Matrix:") +print(B) +print("100th power of matrix B:") +print(np.linalg.matrix_power(B, 100)) + +check_convergence(B) +``` + +The result shows that the matrix is not primitive as it is not everywhere positive. + +These examples show how the Perron-Frobenius theorem relates to the eigenvalues and eigenvectors of positive matrices and the convergence of the power of matrices. + +In fact we have already seen the theorem in action before in {ref}`the Markov chain lecture `. + +(spec_markov)= +#### Example 2: connection to Markov chains + +We are now prepared to bridge the languages spoken in the two lectures. + +A primitive matrix is both irreducible and aperiodic. + +So Perron-Frobenius theorem explains why both {ref}`Imam and Temple matrix ` and [Hamilton matrix](https://en.wikipedia.org/wiki/Hamiltonian_matrix) converge to a stationary distribution, which is the Perron projection of the two matrices + +```{code-cell} ipython3 +P = np.array([[0.68, 0.12, 0.20], + [0.50, 0.24, 0.26], + [0.36, 0.18, 0.46]]) + +print(compute_perron_projection(P)[0]) +``` + +```{code-cell} ipython3 +mc = qe.MarkovChain(P) +ψ_star = mc.stationary_distributions[0] +ψ_star +``` + +```{code-cell} ipython3 +P_hamilton = np.array([[0.971, 0.029, 0.000], + [0.145, 0.778, 0.077], + [0.000, 0.508, 0.492]]) + +print(compute_perron_projection(P_hamilton)[0]) +``` + +```{code-cell} ipython3 +mc = qe.MarkovChain(P_hamilton) +ψ_star = mc.stationary_distributions[0] +ψ_star +``` + +We can also verify other properties hinted by Perron-Frobenius in these stochastic matrices. + ++++ + +Another example is the relationship between convergence gap and convergence rate. + +In the {ref}`exercise`, we stated that the convergence rate is determined by the spectral gap, the difference between the largest and the second largest eigenvalue. + +This can be proven using what we have learned here. + +Please note that we use $\mathbb{1}$ for a vector of ones in this lecture. + +With Markov model $M$ with state space $S$ and transition matrix $P$, we can write $P^t$ as + +$$ +P^t=\sum_{i=1}^{n-1} \lambda_i^t v_i w_i^{\top}+\mathbb{1} \psi^*, +$$ + +This is proven in {cite}`sargent2023economic` and a nice discussion can be found [here](https://math.stackexchange.com/questions/2433997/can-all-matrices-be-decomposed-as-product-of-right-and-left-eigenvector). + +In this formula $\lambda_i$ is an eigenvalue of $P$ with corresponding right and left eigenvectors $v_i$ and $w_i$ . + +Premultiplying $P^t$ by arbitrary $\psi \in \mathscr{D}(S)$ and rearranging now gives + +$$ +\psi P^t-\psi^*=\sum_{i=1}^{n-1} \lambda_i^t \psi v_i w_i^{\top} +$$ + +Recall that eigenvalues are ordered from smallest to largest from $i = 1 ... n$. + +As we have seen, the largest eigenvalue for a primitive stochastic matrix is one. + +This can be proven using [Gershgorin Circle Theorem](https://en.wikipedia.org/wiki/Gershgorin_circle_theorem), +but it is out of the scope of this lecture. + +So by the statement (6) of Perron-Frobenius theorem, $\lambda_i<1$ for all $i` to find the solution $x^{*}$ if it exists. + +```{exercise-end} +``` + +```{solution-start} eig_ex1 +:class: dropdown +``` + +```{code-cell} ipython3 +A = np.array([[0.3, 0.2, 0.3], + [0.2, 0.4, 0.3], + [0.2, 0.5, 0.1]]) + +evals, evecs = eig(A) + +r = max(abs(λ) for λ in evals) #dominant eigenvalue/spectral radius +print(r) +``` + +Since we have $r(A) < 1$ we can thus find the solution using the Neumann Series Lemma. + +```{code-cell} ipython3 +I = np.identity(3) +B = I - A + +d = np.array([4, 5, 12]) +d.shape = (3,1) + +B_inv = np.linalg.inv(B) +x_star = B_inv @ d +print(x_star) +``` + +```{solution-end} +``` diff --git a/book/_build/html/_sources/equalizing_difference.ipynb b/book/_build/html/_sources/equalizing_difference.ipynb new file mode 100644 index 0000000..b6bb479 --- /dev/null +++ b/book/_build/html/_sources/equalizing_difference.ipynb @@ -0,0 +1,830 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "824e704a", + "metadata": {}, + "source": [ + "# Equalizing Difference Model\n", + "\n", + "## Overview\n", + "\n", + "This lecture presents a model of the college-high-school wage gap in which the\n", + "\"time to build\" a college graduate plays a key role.\n", + "\n", + "\n", + "Milton Friedman invented the model to study whether differences in earnings of US dentists and doctors were outcomes of competitive labor markets or whether\n", + "they reflected entry barriers imposed by governments working in conjunction with doctors' professional organizations. \n", + "\n", + "Chapter 4 of Jennifer Burns {cite}`Burns_2023` describes Milton Friedman's joint work with Simon Kuznets that eventually led to the publication of {cite}`kuznets1939incomes` and {cite}`friedman1954incomes`.\n", + "\n", + "To map Friedman's application into our model, think of our high school students as Friedman's dentists and our college graduates as Friedman's doctors. \n", + "\n", + "\n", + "Our presentation is \"incomplete\" in the sense that it is based on a single equation that would be part of set equilibrium conditions of a more fully articulated model.\n", + "\n", + "This ''equalizing difference'' equation determines a college-high-school wage ratio that equalizes present values of a high school educated worker and a college educated worker.\n", + "\n", + "The idea is that lifetime earnings somehow adjust to make a new high school worker indifferent between going to college and not going to college but instead going to work immediately.\n", + "\n", + "(The job of the \"other equations\" in a more complete model would be to describe what adjusts to bring about this outcome.)\n", + "\n", + "Our model is just one example of an \"equalizing difference\" theory of relative wage rates, a class of theories dating back at least to Adam Smith's **Wealth of Nations** {cite}`smith2010wealth`. \n", + "\n", + "For most of this lecture, the only mathematical tools that we'll use are from linear algebra, in particular, matrix multiplication and matrix inversion.\n", + "\n", + "However, near the end of the lecture, we'll use calculus just in case readers want to see how computing partial derivatives could let us present some findings more concisely. \n", + "\n", + "And doing that will let illustrate how good Python is at doing calculus!\n", + "\n", + "But if you don't know calculus, our tools from linear algebra are certainly enough.\n", + "\n", + "As usual, we'll start by importing some Python modules." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8fea8ed2", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from collections import namedtuple\n", + "from sympy import Symbol, Lambda, symbols" + ] + }, + { + "cell_type": "markdown", + "id": "b65ab7e0", + "metadata": {}, + "source": [ + "## The indifference condition\n", + "\n", + "The key idea is that the entry level college wage premium has to adjust to make a representative worker indifferent between going to college and not going to college.\n", + "\n", + "Let\n", + "\n", + " * $R > 1$ be the gross rate of return on a one-period bond\n", + "\n", + " * $t = 0, 1, 2, \\ldots T$ denote the years that a person either works or attends college\n", + " \n", + " * $0$ denote the first period after high school that a person can work if he does not go to college\n", + " \n", + " * $T$ denote the last period that a person works\n", + " \n", + " * $w_t^h$ be the wage at time $t$ of a high school graduate\n", + " \n", + " * $w_t^c$ be the wage at time $t$ of a college graduate\n", + " \n", + " * $\\gamma_h > 1$ be the (gross) rate of growth of wages of a high school graduate, so that\n", + " $ w_t^h = w_0^h \\gamma_h^t$\n", + " \n", + " * $\\gamma_c > 1$ be the (gross) rate of growth of wages of a college graduate, so that\n", + " $ w_t^c = w_0^c \\gamma_c^t$\n", + "\n", + " * $D$ be the upfront monetary costs of going to college\n", + "\n", + "We now compute present values that a new high school graduate earns if\n", + "\n", + " * he goes to work immediately and earns wages paid to someone without a college education\n", + " * he goes to college for four years and after graduating earns wages paid to a college graduate\n", + "\n", + "### Present value of a high school educated worker\n", + "\n", + "If someone goes to work immediately after high school and works for the $T+1$ years $t=0, 1, 2, \\ldots, T$, she earns present value\n", + "\n", + "$$\n", + "h_0 = \\sum_{t=0}^T R^{-t} w_t^h = w_0^h \\left[ \\frac{1 - (R^{-1} \\gamma_h)^{T+1} }{1 - R^{-1} \\gamma_h } \\right] \\equiv w_0^h A_h \n", + "$$\n", + "\n", + "where \n", + "\n", + "$$\n", + "A_h = \\left[ \\frac{1 - (R^{-1} \\gamma_h)^{T+1} }{1 - R^{-1} \\gamma_h } \\right].\n", + "$$\n", + "\n", + "The present value $h_0$ is the \"human wealth\" at the beginning of time $0$ of someone who chooses not to attend college but instead to go to work immediately at the wage of a high school graduate.\n", + "\n", + "### Present value of a college-bound new high school graduate\n", + "\n", + "\n", + "If someone goes to college for the four years $t=0, 1, 2, 3$ during which she earns $0$, but then goes to work immediately after college and works for the $T-3$ years $t=4, 5, \\ldots ,T$, she earns present value\n", + "\n", + "$$\n", + "c_0 = \\sum_{t=4}^T R^{-t} w_t^c = w_0^c (R^{-1} \\gamma_c)^4 \\left[ \\frac{1 - (R^{-1} \\gamma_c)^{T-3} }{1 - R^{-1} \\gamma_c } \\right] \\equiv w_0^c A_c\n", + "$$\n", + "\n", + "where\n", + "\n", + "$$\n", + "A_c = (R^{-1} \\gamma_c)^4 \\left[ \\frac{1 - (R^{-1} \\gamma_c)^{T-3} }{1 - R^{-1} \\gamma_c } \\right] .\n", + "$$ \n", + "\n", + "The present value $c_0$ is the \"human wealth\" at the beginning of time $0$ of someone who chooses to attend college for four years and then start to work at time $t=4$ at the wage of a college graduate.\n", + "\n", + "\n", + "Assume that college tuition plus four years of room and board amount to $D$ and must be paid at time $0$.\n", + "\n", + "So net of monetary cost of college, the present value of attending college as of the first period after high school is\n", + "\n", + "$$ \n", + "c_0 - D\n", + "$$\n", + "\n", + "We now formulate a pure **equalizing difference** model of the initial college-high school wage gap $\\phi$ that verifies \n", + "\n", + "$$\n", + "w_0^c = \\phi w_0^h \n", + "$$\n", + "\n", + "We suppose that $R, \\gamma_h, \\gamma_c, T$ and also $w_0^h$ are fixed parameters. \n", + "\n", + "We start by noting that the pure equalizing difference model asserts that the college-high-school wage gap $\\phi$ solves an \n", + "\"equalizing\" equation that sets the present value not going to college equal to the present value of going to college:\n", + "\n", + "\n", + "$$\n", + "h_0 = c_0 - D\n", + "$$ \n", + "\n", + "or\n", + "\n", + "$$ \n", + "w_0^h A_h = \\phi w_0^h A_c - D .\n", + "$$ (eq:equalize)\n", + "\n", + "This \"indifference condition\" is the heart of the model.\n", + "\n", + "Solving equation {eq}`eq:equalize` for the college wage premium $\\phi$ we obtain\n", + "\n", + "$$\n", + "\\phi = \\frac{A_h}{A_c} + \\frac{D}{w_0^h A_c} .\n", + "$$ (eq:wagepremium)\n", + "\n", + "In a **free college** special case $D =0$.\n", + "\n", + "Here the only cost of going to college is the forgone earnings from being a high school educated worker. \n", + "\n", + "In that case,\n", + "\n", + "$$\n", + "\\phi = \\frac{A_h}{A_c} . \n", + "$$\n", + "\n", + "In the next section we'll write Python code to compute $\\phi$ and plot it as a function of its determinants.\n", + "\n", + "## Computations\n", + "\n", + "\n", + "We can have some fun with examples that tweak various parameters,\n", + "prominently including $\\gamma_h, \\gamma_c, R$.\n", + "\n", + "Now let's write some Python code to compute $\\phi$ and plot it as a function of some of its determinants." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9a2065e5", + "metadata": {}, + "outputs": [], + "source": [ + "# Define the namedtuple for the equalizing difference model\n", + "EqDiffModel = namedtuple('EqDiffModel', 'R T γ_h γ_c w_h0 D')\n", + "\n", + "def create_edm(R=1.05, # gross rate of return\n", + " T=40, # time horizon\n", + " γ_h=1.01, # high-school wage growth\n", + " γ_c=1.01, # college wage growth\n", + " w_h0=1, # initial wage (high school)\n", + " D=10, # cost for college\n", + " ):\n", + " \n", + " return EqDiffModel(R, T, γ_h, γ_c, w_h0, D)\n", + "\n", + "def compute_gap(model):\n", + " R, T, γ_h, γ_c, w_h0, D = model\n", + " \n", + " A_h = (1 - (γ_h/R)**(T+1)) / (1 - γ_h/R)\n", + " A_c = (1 - (γ_c/R)**(T-3)) / (1 - γ_c/R) * (γ_c/R)**4\n", + " ϕ = A_h / A_c + D / (w_h0 * A_c)\n", + " \n", + " return ϕ" + ] + }, + { + "cell_type": "markdown", + "id": "6489235f", + "metadata": {}, + "source": [ + "Using vectorization instead of loops,\n", + "we build some functions to help do comparative statics .\n", + "\n", + "For a given instance of the class, we want to recompute $\\phi$ when one parameter changes and others remain fixed.\n", + "\n", + "Let's do an example." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "97097bae", + "metadata": {}, + "outputs": [], + "source": [ + "ex1 = create_edm()\n", + "gap1 = compute_gap(ex1)\n", + "\n", + "gap1" + ] + }, + { + "cell_type": "markdown", + "id": "b21ee803", + "metadata": {}, + "source": [ + "Let's not charge for college and recompute $\\phi$.\n", + "\n", + "The initial college wage premium should go down." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cc006ad6", + "metadata": {}, + "outputs": [], + "source": [ + "# free college\n", + "ex2 = create_edm(D=0)\n", + "gap2 = compute_gap(ex2)\n", + "gap2" + ] + }, + { + "cell_type": "markdown", + "id": "a6eb2a63", + "metadata": {}, + "source": [ + "Let us construct some graphs that show us how the initial college-high-school wage ratio $\\phi$ would change if one of its determinants were to change. \n", + "\n", + "Let's start with the gross interest rate $R$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "be443049", + "metadata": {}, + "outputs": [], + "source": [ + "R_arr = np.linspace(1, 1.2, 50)\n", + "models = [create_edm(R=r) for r in R_arr]\n", + "gaps = [compute_gap(model) for model in models]\n", + "\n", + "plt.plot(R_arr, gaps)\n", + "plt.xlabel(r'$R$')\n", + "plt.ylabel(r'wage gap')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "4371836f", + "metadata": {}, + "source": [ + "Evidently, the initial wage ratio $\\phi$ must rise to compensate a prospective high school student for **waiting** to start receiving income -- remember that while she is earning nothing in years $t=0, 1, 2, 3$, the high school worker is earning a salary.\n", + "\n", + "Not let's study what happens to the initial wage ratio $\\phi$ if the rate of growth of college wages rises, holding constant other \n", + "determinants of $\\phi$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5919447d", + "metadata": {}, + "outputs": [], + "source": [ + "γc_arr = np.linspace(1, 1.2, 50)\n", + "models = [create_edm(γ_c=γ_c) for γ_c in γc_arr]\n", + "gaps = [compute_gap(model) for model in models]\n", + "\n", + "plt.plot(γc_arr, gaps)\n", + "plt.xlabel(r'$\\gamma_c$')\n", + "plt.ylabel(r'wage gap')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "60f07bf4", + "metadata": {}, + "source": [ + "Notice how the initial wage gap falls when the rate of growth $\\gamma_c$ of college wages rises. \n", + "\n", + "The wage gap falls to \"equalize\" the present values of the two types of career, one as a high school worker, the other as a college worker.\n", + "\n", + "Can you guess what happens to the initial wage ratio $\\phi$ when next we vary the rate of growth of high school wages, holding all other determinants of $\\phi$ constant? \n", + "\n", + "The following graph shows what happens." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f07f9f61", + "metadata": {}, + "outputs": [], + "source": [ + "γh_arr = np.linspace(1, 1.1, 50)\n", + "models = [create_edm(γ_h=γ_h) for γ_h in γh_arr]\n", + "gaps = [compute_gap(model) for model in models]\n", + "\n", + "plt.plot(γh_arr, gaps)\n", + "plt.xlabel(r'$\\gamma_h$')\n", + "plt.ylabel(r'wage gap')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "1652c808", + "metadata": {}, + "source": [ + "## Entrepreneur-worker interpretation\n", + "\n", + "We can add a parameter and reinterpret variables to get a model of entrepreneurs versus workers.\n", + "\n", + "We now let $h$ be the present value of a \"worker\".\n", + "\n", + "We define the present value of an entrepreneur to be\n", + "\n", + "$$\n", + "c_0 = \\pi \\sum_{t=4}^T R^{-t} w_t^c\n", + "$$\n", + "\n", + "where $\\pi \\in (0,1) $ is the probability that an entrepreneur's \"project\" succeeds.\n", + "\n", + "For our model of workers and firms, we'll interpret $D$ as the cost of becoming an entrepreneur. \n", + "\n", + "This cost might include costs of hiring workers, office space, and lawyers. \n", + "\n", + "What we used to call the college, high school wage gap $\\phi$ now becomes the ratio\n", + "of a successful entrepreneur's earnings to a worker's earnings. \n", + "\n", + "We'll find that as $\\pi$ decreases, $\\phi$ increases, indicating that the riskier it is to\n", + "be an entrepreneur, the higher must be the reward for a successful project. \n", + "\n", + "Now let's adopt the entrepreneur-worker interpretation of our model" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7f403910", + "metadata": {}, + "outputs": [], + "source": [ + "# Define a model of entrepreneur-worker interpretation\n", + "EqDiffModel = namedtuple('EqDiffModel', 'R T γ_h γ_c w_h0 D π')\n", + "\n", + "def create_edm_π(R=1.05, # gross rate of return\n", + " T=40, # time horizon\n", + " γ_h=1.01, # high-school wage growth\n", + " γ_c=1.01, # college wage growth\n", + " w_h0=1, # initial wage (high school)\n", + " D=10, # cost for college\n", + " π=0 # chance of business success\n", + " ):\n", + " \n", + " return EqDiffModel(R, T, γ_h, γ_c, w_h0, D, π)\n", + "\n", + "\n", + "def compute_gap(model):\n", + " R, T, γ_h, γ_c, w_h0, D, π = model\n", + " \n", + " A_h = (1 - (γ_h/R)**(T+1)) / (1 - γ_h/R)\n", + " A_c = (1 - (γ_c/R)**(T-3)) / (1 - γ_c/R) * (γ_c/R)**4\n", + " \n", + " # Incorprate chance of success\n", + " A_c = π * A_c\n", + " \n", + " ϕ = A_h / A_c + D / (w_h0 * A_c)\n", + " return ϕ" + ] + }, + { + "cell_type": "markdown", + "id": "276b9594", + "metadata": {}, + "source": [ + "If the probability that a new business succeeds is $0.2$, let's compute the initial wage premium for successful entrepreneurs." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c1bd81e1", + "metadata": {}, + "outputs": [], + "source": [ + "ex3 = create_edm_π(π=0.2)\n", + "gap3 = compute_gap(ex3)\n", + "\n", + "gap3" + ] + }, + { + "cell_type": "markdown", + "id": "0630d0cd", + "metadata": {}, + "source": [ + "Now let's study how the initial wage premium for successful entrepreneurs depend on the success probability." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5556bf89", + "metadata": {}, + "outputs": [], + "source": [ + "π_arr = np.linspace(0.2, 1, 50)\n", + "models = [create_edm_π(π=π) for π in π_arr]\n", + "gaps = [compute_gap(model) for model in models]\n", + "\n", + "plt.plot(π_arr, gaps)\n", + "plt.ylabel(r'wage gap')\n", + "plt.xlabel(r'$\\pi$')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "df3b826c", + "metadata": {}, + "source": [ + "Does the graph make sense to you?\n", + "\n", + "\n", + "\n", + "## An application of calculus\n", + "\n", + "So far, we have used only linear algebra and it has been a good enough tool for us to figure out how our model works.\n", + "\n", + "However, someone who knows calculus might want us just to take partial derivatives.\n", + "\n", + "We'll do that now.\n", + "\n", + "A reader who doesn't know calculus could read no further and feel confident that applying linear algebra has taught us the main properties of the model.\n", + "\n", + "But for a reader interested in how we can get Python to do all the hard work involved in computing partial derivatives, we'll say a few things about that now. \n", + "\n", + "We'll use the Python module 'sympy' to compute partial derivatives of $\\phi$ with respect to the parameters that determine it.\n", + "\n", + "Define symbols" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "41cd9aba", + "metadata": {}, + "outputs": [], + "source": [ + "γ_h, γ_c, w_h0, D = symbols('\\gamma_h, \\gamma_c, w_0^h, D', real=True)\n", + "R, T = Symbol('R', real=True), Symbol('T', integer=True)" + ] + }, + { + "cell_type": "markdown", + "id": "77340f46", + "metadata": {}, + "source": [ + "Define function $A_h$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "237fee51", + "metadata": {}, + "outputs": [], + "source": [ + "A_h = Lambda((γ_h, R, T), (1 - (γ_h/R)**(T+1)) / (1 - γ_h/R))\n", + "A_h" + ] + }, + { + "cell_type": "markdown", + "id": "ee96b107", + "metadata": {}, + "source": [ + "Define function $A_c$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bb20ac3c", + "metadata": {}, + "outputs": [], + "source": [ + "A_c = Lambda((γ_c, R, T), (1 - (γ_c/R)**(T-3)) / (1 - γ_c/R) * (γ_c/R)**4)\n", + "A_c" + ] + }, + { + "cell_type": "markdown", + "id": "9c3504e9", + "metadata": {}, + "source": [ + "Now, define $\\phi$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f98bb420", + "metadata": {}, + "outputs": [], + "source": [ + "ϕ = Lambda((D, γ_h, γ_c, R, T, w_h0), A_h(γ_h, R, T)/A_c(γ_c, R, T) + D/(w_h0*A_c(γ_c, R, T)))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4c9e7af1", + "metadata": {}, + "outputs": [], + "source": [ + "ϕ" + ] + }, + { + "cell_type": "markdown", + "id": "f3319e10", + "metadata": {}, + "source": [ + "We begin by setting default parameter values." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fc0f873e", + "metadata": {}, + "outputs": [], + "source": [ + "R_value = 1.05\n", + "T_value = 40\n", + "γ_h_value, γ_c_value = 1.01, 1.01\n", + "w_h0_value = 1\n", + "D_value = 10" + ] + }, + { + "cell_type": "markdown", + "id": "d6ab1db2", + "metadata": {}, + "source": [ + "Now let's compute $\\frac{\\partial \\phi}{\\partial D}$ and then evaluate it at the default values" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7488e8a0", + "metadata": {}, + "outputs": [], + "source": [ + "ϕ_D = ϕ(D, γ_h, γ_c, R, T, w_h0).diff(D)\n", + "ϕ_D" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "69fc651f", + "metadata": {}, + "outputs": [], + "source": [ + "# Numerical value at default parameters\n", + "ϕ_D_func = Lambda((D, γ_h, γ_c, R, T, w_h0), ϕ_D)\n", + "ϕ_D_func(D_value, γ_h_value, γ_c_value, R_value, T_value, w_h0_value)" + ] + }, + { + "cell_type": "markdown", + "id": "d2cf56f1", + "metadata": {}, + "source": [ + "Thus, as with our earlier graph, we find that raising $R$ increases the initial college wage premium $\\phi$.\n", + "\n", + "Compute $\\frac{\\partial \\phi}{\\partial T}$ and evaluate it at default parameters" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d45623b4", + "metadata": {}, + "outputs": [], + "source": [ + "ϕ_T = ϕ(D, γ_h, γ_c, R, T, w_h0).diff(T)\n", + "ϕ_T" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "23d70d6a", + "metadata": {}, + "outputs": [], + "source": [ + "# Numerical value at default parameters\n", + "ϕ_T_func = Lambda((D, γ_h, γ_c, R, T, w_h0), ϕ_T)\n", + "ϕ_T_func(D_value, γ_h_value, γ_c_value, R_value, T_value, w_h0_value)" + ] + }, + { + "cell_type": "markdown", + "id": "e8f6d2dc", + "metadata": {}, + "source": [ + "We find that raising $T$ decreases the initial college wage premium $\\phi$. \n", + "\n", + "This is because college graduates now have longer career lengths to \"pay off\" the time and other costs they paid to go to college\n", + "\n", + "Let's compute $\\frac{\\partial \\phi}{\\partial γ_h}$ and evaluate it at default parameters." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6b234daa", + "metadata": {}, + "outputs": [], + "source": [ + "ϕ_γ_h = ϕ(D, γ_h, γ_c, R, T, w_h0).diff(γ_h)\n", + "ϕ_γ_h" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ac8401bf", + "metadata": {}, + "outputs": [], + "source": [ + "# Numerical value at default parameters\n", + "ϕ_γ_h_func = Lambda((D, γ_h, γ_c, R, T, w_h0), ϕ_γ_h)\n", + "ϕ_γ_h_func(D_value, γ_h_value, γ_c_value, R_value, T_value, w_h0_value)" + ] + }, + { + "cell_type": "markdown", + "id": "fb4f99c8", + "metadata": {}, + "source": [ + "We find that raising $\\gamma_h$ increases the initial college wage premium $\\phi$, in line with our earlier graphical analysis.\n", + "\n", + "Compute $\\frac{\\partial \\phi}{\\partial γ_c}$ and evaluate it numerically at default parameter values" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3af4a76e", + "metadata": {}, + "outputs": [], + "source": [ + "ϕ_γ_c = ϕ(D, γ_h, γ_c, R, T, w_h0).diff(γ_c)\n", + "ϕ_γ_c" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dfe9afbc", + "metadata": {}, + "outputs": [], + "source": [ + "# Numerical value at default parameters\n", + "ϕ_γ_c_func = Lambda((D, γ_h, γ_c, R, T, w_h0), ϕ_γ_c)\n", + "ϕ_γ_c_func(D_value, γ_h_value, γ_c_value, R_value, T_value, w_h0_value)" + ] + }, + { + "cell_type": "markdown", + "id": "a5c43b2d", + "metadata": {}, + "source": [ + "We find that raising $\\gamma_c$ decreases the initial college wage premium $\\phi$, in line with our earlier graphical analysis.\n", + "\n", + "Let's compute $\\frac{\\partial \\phi}{\\partial R}$ and evaluate it numerically at default parameter values" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b5d35e7c", + "metadata": {}, + "outputs": [], + "source": [ + "ϕ_R = ϕ(D, γ_h, γ_c, R, T, w_h0).diff(R)\n", + "ϕ_R" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "84ea1fcd", + "metadata": {}, + "outputs": [], + "source": [ + "# Numerical value at default parameters\n", + "ϕ_R_func = Lambda((D, γ_h, γ_c, R, T, w_h0), ϕ_R)\n", + "ϕ_R_func(D_value, γ_h_value, γ_c_value, R_value, T_value, w_h0_value)" + ] + }, + { + "cell_type": "markdown", + "id": "52f87e22", + "metadata": {}, + "source": [ + "We find that raising the gross interest rate $R$ increases the initial college wage premium $\\phi$, in line with our earlier graphical analysis." + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.16.1" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 50, + 55, + 180, + 202, + 211, + 216, + 222, + 227, + 233, + 242, + 249, + 258, + 268, + 277, + 305, + 332, + 336, + 341, + 345, + 354, + 376, + 379, + 383, + 386, + 390, + 393, + 397, + 401, + 403, + 407, + 413, + 417, + 422, + 426, + 432, + 437, + 441, + 449, + 454, + 458, + 464, + 469, + 473, + 479, + 484, + 488 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/equalizing_difference.md b/book/_build/html/_sources/equalizing_difference.md new file mode 100644 index 0000000..c65bbf9 --- /dev/null +++ b/book/_build/html/_sources/equalizing_difference.md @@ -0,0 +1,490 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.16.1 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Equalizing Difference Model + +## Overview + +This lecture presents a model of the college-high-school wage gap in which the +"time to build" a college graduate plays a key role. + + +Milton Friedman invented the model to study whether differences in earnings of US dentists and doctors were outcomes of competitive labor markets or whether +they reflected entry barriers imposed by governments working in conjunction with doctors' professional organizations. + +Chapter 4 of Jennifer Burns {cite}`Burns_2023` describes Milton Friedman's joint work with Simon Kuznets that eventually led to the publication of {cite}`kuznets1939incomes` and {cite}`friedman1954incomes`. + +To map Friedman's application into our model, think of our high school students as Friedman's dentists and our college graduates as Friedman's doctors. + + +Our presentation is "incomplete" in the sense that it is based on a single equation that would be part of set equilibrium conditions of a more fully articulated model. + +This ''equalizing difference'' equation determines a college-high-school wage ratio that equalizes present values of a high school educated worker and a college educated worker. + +The idea is that lifetime earnings somehow adjust to make a new high school worker indifferent between going to college and not going to college but instead going to work immediately. + +(The job of the "other equations" in a more complete model would be to describe what adjusts to bring about this outcome.) + +Our model is just one example of an "equalizing difference" theory of relative wage rates, a class of theories dating back at least to Adam Smith's **Wealth of Nations** {cite}`smith2010wealth`. + +For most of this lecture, the only mathematical tools that we'll use are from linear algebra, in particular, matrix multiplication and matrix inversion. + +However, near the end of the lecture, we'll use calculus just in case readers want to see how computing partial derivatives could let us present some findings more concisely. + +And doing that will let illustrate how good Python is at doing calculus! + +But if you don't know calculus, our tools from linear algebra are certainly enough. + +As usual, we'll start by importing some Python modules. + +```{code-cell} ipython3 +import numpy as np +import matplotlib.pyplot as plt +from collections import namedtuple +from sympy import Symbol, Lambda, symbols +``` + +## The indifference condition + +The key idea is that the entry level college wage premium has to adjust to make a representative worker indifferent between going to college and not going to college. + +Let + + * $R > 1$ be the gross rate of return on a one-period bond + + * $t = 0, 1, 2, \ldots T$ denote the years that a person either works or attends college + + * $0$ denote the first period after high school that a person can work if he does not go to college + + * $T$ denote the last period that a person works + + * $w_t^h$ be the wage at time $t$ of a high school graduate + + * $w_t^c$ be the wage at time $t$ of a college graduate + + * $\gamma_h > 1$ be the (gross) rate of growth of wages of a high school graduate, so that + $ w_t^h = w_0^h \gamma_h^t$ + + * $\gamma_c > 1$ be the (gross) rate of growth of wages of a college graduate, so that + $ w_t^c = w_0^c \gamma_c^t$ + + * $D$ be the upfront monetary costs of going to college + +We now compute present values that a new high school graduate earns if + + * he goes to work immediately and earns wages paid to someone without a college education + * he goes to college for four years and after graduating earns wages paid to a college graduate + +### Present value of a high school educated worker + +If someone goes to work immediately after high school and works for the $T+1$ years $t=0, 1, 2, \ldots, T$, she earns present value + +$$ +h_0 = \sum_{t=0}^T R^{-t} w_t^h = w_0^h \left[ \frac{1 - (R^{-1} \gamma_h)^{T+1} }{1 - R^{-1} \gamma_h } \right] \equiv w_0^h A_h +$$ + +where + +$$ +A_h = \left[ \frac{1 - (R^{-1} \gamma_h)^{T+1} }{1 - R^{-1} \gamma_h } \right]. +$$ + +The present value $h_0$ is the "human wealth" at the beginning of time $0$ of someone who chooses not to attend college but instead to go to work immediately at the wage of a high school graduate. + +### Present value of a college-bound new high school graduate + + +If someone goes to college for the four years $t=0, 1, 2, 3$ during which she earns $0$, but then goes to work immediately after college and works for the $T-3$ years $t=4, 5, \ldots ,T$, she earns present value + +$$ +c_0 = \sum_{t=4}^T R^{-t} w_t^c = w_0^c (R^{-1} \gamma_c)^4 \left[ \frac{1 - (R^{-1} \gamma_c)^{T-3} }{1 - R^{-1} \gamma_c } \right] \equiv w_0^c A_c +$$ + +where + +$$ +A_c = (R^{-1} \gamma_c)^4 \left[ \frac{1 - (R^{-1} \gamma_c)^{T-3} }{1 - R^{-1} \gamma_c } \right] . +$$ + +The present value $c_0$ is the "human wealth" at the beginning of time $0$ of someone who chooses to attend college for four years and then start to work at time $t=4$ at the wage of a college graduate. + + +Assume that college tuition plus four years of room and board amount to $D$ and must be paid at time $0$. + +So net of monetary cost of college, the present value of attending college as of the first period after high school is + +$$ +c_0 - D +$$ + +We now formulate a pure **equalizing difference** model of the initial college-high school wage gap $\phi$ that verifies + +$$ +w_0^c = \phi w_0^h +$$ + +We suppose that $R, \gamma_h, \gamma_c, T$ and also $w_0^h$ are fixed parameters. + +We start by noting that the pure equalizing difference model asserts that the college-high-school wage gap $\phi$ solves an +"equalizing" equation that sets the present value not going to college equal to the present value of going to college: + + +$$ +h_0 = c_0 - D +$$ + +or + +$$ +w_0^h A_h = \phi w_0^h A_c - D . +$$ (eq:equalize) + +This "indifference condition" is the heart of the model. + +Solving equation {eq}`eq:equalize` for the college wage premium $\phi$ we obtain + +$$ +\phi = \frac{A_h}{A_c} + \frac{D}{w_0^h A_c} . +$$ (eq:wagepremium) + +In a **free college** special case $D =0$. + +Here the only cost of going to college is the forgone earnings from being a high school educated worker. + +In that case, + +$$ +\phi = \frac{A_h}{A_c} . +$$ + +In the next section we'll write Python code to compute $\phi$ and plot it as a function of its determinants. + +## Computations + + +We can have some fun with examples that tweak various parameters, +prominently including $\gamma_h, \gamma_c, R$. + +Now let's write some Python code to compute $\phi$ and plot it as a function of some of its determinants. + +```{code-cell} ipython3 +# Define the namedtuple for the equalizing difference model +EqDiffModel = namedtuple('EqDiffModel', 'R T γ_h γ_c w_h0 D') + +def create_edm(R=1.05, # gross rate of return + T=40, # time horizon + γ_h=1.01, # high-school wage growth + γ_c=1.01, # college wage growth + w_h0=1, # initial wage (high school) + D=10, # cost for college + ): + + return EqDiffModel(R, T, γ_h, γ_c, w_h0, D) + +def compute_gap(model): + R, T, γ_h, γ_c, w_h0, D = model + + A_h = (1 - (γ_h/R)**(T+1)) / (1 - γ_h/R) + A_c = (1 - (γ_c/R)**(T-3)) / (1 - γ_c/R) * (γ_c/R)**4 + ϕ = A_h / A_c + D / (w_h0 * A_c) + + return ϕ +``` + +Using vectorization instead of loops, +we build some functions to help do comparative statics . + +For a given instance of the class, we want to recompute $\phi$ when one parameter changes and others remain fixed. + +Let's do an example. + +```{code-cell} ipython3 +ex1 = create_edm() +gap1 = compute_gap(ex1) + +gap1 +``` + +Let's not charge for college and recompute $\phi$. + +The initial college wage premium should go down. + +```{code-cell} ipython3 +# free college +ex2 = create_edm(D=0) +gap2 = compute_gap(ex2) +gap2 +``` + +Let us construct some graphs that show us how the initial college-high-school wage ratio $\phi$ would change if one of its determinants were to change. + +Let's start with the gross interest rate $R$. + +```{code-cell} ipython3 +R_arr = np.linspace(1, 1.2, 50) +models = [create_edm(R=r) for r in R_arr] +gaps = [compute_gap(model) for model in models] + +plt.plot(R_arr, gaps) +plt.xlabel(r'$R$') +plt.ylabel(r'wage gap') +plt.show() +``` + +Evidently, the initial wage ratio $\phi$ must rise to compensate a prospective high school student for **waiting** to start receiving income -- remember that while she is earning nothing in years $t=0, 1, 2, 3$, the high school worker is earning a salary. + +Not let's study what happens to the initial wage ratio $\phi$ if the rate of growth of college wages rises, holding constant other +determinants of $\phi$. + +```{code-cell} ipython3 +γc_arr = np.linspace(1, 1.2, 50) +models = [create_edm(γ_c=γ_c) for γ_c in γc_arr] +gaps = [compute_gap(model) for model in models] + +plt.plot(γc_arr, gaps) +plt.xlabel(r'$\gamma_c$') +plt.ylabel(r'wage gap') +plt.show() +``` + +Notice how the initial wage gap falls when the rate of growth $\gamma_c$ of college wages rises. + +The wage gap falls to "equalize" the present values of the two types of career, one as a high school worker, the other as a college worker. + +Can you guess what happens to the initial wage ratio $\phi$ when next we vary the rate of growth of high school wages, holding all other determinants of $\phi$ constant? + +The following graph shows what happens. + +```{code-cell} ipython3 +γh_arr = np.linspace(1, 1.1, 50) +models = [create_edm(γ_h=γ_h) for γ_h in γh_arr] +gaps = [compute_gap(model) for model in models] + +plt.plot(γh_arr, gaps) +plt.xlabel(r'$\gamma_h$') +plt.ylabel(r'wage gap') +plt.show() +``` + +## Entrepreneur-worker interpretation + +We can add a parameter and reinterpret variables to get a model of entrepreneurs versus workers. + +We now let $h$ be the present value of a "worker". + +We define the present value of an entrepreneur to be + +$$ +c_0 = \pi \sum_{t=4}^T R^{-t} w_t^c +$$ + +where $\pi \in (0,1) $ is the probability that an entrepreneur's "project" succeeds. + +For our model of workers and firms, we'll interpret $D$ as the cost of becoming an entrepreneur. + +This cost might include costs of hiring workers, office space, and lawyers. + +What we used to call the college, high school wage gap $\phi$ now becomes the ratio +of a successful entrepreneur's earnings to a worker's earnings. + +We'll find that as $\pi$ decreases, $\phi$ increases, indicating that the riskier it is to +be an entrepreneur, the higher must be the reward for a successful project. + +Now let's adopt the entrepreneur-worker interpretation of our model + +```{code-cell} ipython3 +# Define a model of entrepreneur-worker interpretation +EqDiffModel = namedtuple('EqDiffModel', 'R T γ_h γ_c w_h0 D π') + +def create_edm_π(R=1.05, # gross rate of return + T=40, # time horizon + γ_h=1.01, # high-school wage growth + γ_c=1.01, # college wage growth + w_h0=1, # initial wage (high school) + D=10, # cost for college + π=0 # chance of business success + ): + + return EqDiffModel(R, T, γ_h, γ_c, w_h0, D, π) + + +def compute_gap(model): + R, T, γ_h, γ_c, w_h0, D, π = model + + A_h = (1 - (γ_h/R)**(T+1)) / (1 - γ_h/R) + A_c = (1 - (γ_c/R)**(T-3)) / (1 - γ_c/R) * (γ_c/R)**4 + + # Incorprate chance of success + A_c = π * A_c + + ϕ = A_h / A_c + D / (w_h0 * A_c) + return ϕ +``` + +If the probability that a new business succeeds is $0.2$, let's compute the initial wage premium for successful entrepreneurs. + +```{code-cell} ipython3 +ex3 = create_edm_π(π=0.2) +gap3 = compute_gap(ex3) + +gap3 +``` + +Now let's study how the initial wage premium for successful entrepreneurs depend on the success probability. + +```{code-cell} ipython3 +π_arr = np.linspace(0.2, 1, 50) +models = [create_edm_π(π=π) for π in π_arr] +gaps = [compute_gap(model) for model in models] + +plt.plot(π_arr, gaps) +plt.ylabel(r'wage gap') +plt.xlabel(r'$\pi$') +plt.show() +``` + +Does the graph make sense to you? + + + +## An application of calculus + +So far, we have used only linear algebra and it has been a good enough tool for us to figure out how our model works. + +However, someone who knows calculus might want us just to take partial derivatives. + +We'll do that now. + +A reader who doesn't know calculus could read no further and feel confident that applying linear algebra has taught us the main properties of the model. + +But for a reader interested in how we can get Python to do all the hard work involved in computing partial derivatives, we'll say a few things about that now. + +We'll use the Python module 'sympy' to compute partial derivatives of $\phi$ with respect to the parameters that determine it. + +Define symbols + +```{code-cell} ipython3 +γ_h, γ_c, w_h0, D = symbols('\gamma_h, \gamma_c, w_0^h, D', real=True) +R, T = Symbol('R', real=True), Symbol('T', integer=True) +``` + +Define function $A_h$ + +```{code-cell} ipython3 +A_h = Lambda((γ_h, R, T), (1 - (γ_h/R)**(T+1)) / (1 - γ_h/R)) +A_h +``` + +Define function $A_c$ + +```{code-cell} ipython3 +A_c = Lambda((γ_c, R, T), (1 - (γ_c/R)**(T-3)) / (1 - γ_c/R) * (γ_c/R)**4) +A_c +``` + +Now, define $\phi$ + +```{code-cell} ipython3 +ϕ = Lambda((D, γ_h, γ_c, R, T, w_h0), A_h(γ_h, R, T)/A_c(γ_c, R, T) + D/(w_h0*A_c(γ_c, R, T))) +``` + +```{code-cell} ipython3 +ϕ +``` + +We begin by setting default parameter values. + +```{code-cell} ipython3 +R_value = 1.05 +T_value = 40 +γ_h_value, γ_c_value = 1.01, 1.01 +w_h0_value = 1 +D_value = 10 +``` + +Now let's compute $\frac{\partial \phi}{\partial D}$ and then evaluate it at the default values + +```{code-cell} ipython3 +ϕ_D = ϕ(D, γ_h, γ_c, R, T, w_h0).diff(D) +ϕ_D +``` + +```{code-cell} ipython3 +# Numerical value at default parameters +ϕ_D_func = Lambda((D, γ_h, γ_c, R, T, w_h0), ϕ_D) +ϕ_D_func(D_value, γ_h_value, γ_c_value, R_value, T_value, w_h0_value) +``` + +Thus, as with our earlier graph, we find that raising $R$ increases the initial college wage premium $\phi$. + +Compute $\frac{\partial \phi}{\partial T}$ and evaluate it at default parameters + +```{code-cell} ipython3 +ϕ_T = ϕ(D, γ_h, γ_c, R, T, w_h0).diff(T) +ϕ_T +``` + +```{code-cell} ipython3 +# Numerical value at default parameters +ϕ_T_func = Lambda((D, γ_h, γ_c, R, T, w_h0), ϕ_T) +ϕ_T_func(D_value, γ_h_value, γ_c_value, R_value, T_value, w_h0_value) +``` + +We find that raising $T$ decreases the initial college wage premium $\phi$. + +This is because college graduates now have longer career lengths to "pay off" the time and other costs they paid to go to college + +Let's compute $\frac{\partial \phi}{\partial γ_h}$ and evaluate it at default parameters. + +```{code-cell} ipython3 +ϕ_γ_h = ϕ(D, γ_h, γ_c, R, T, w_h0).diff(γ_h) +ϕ_γ_h +``` + +```{code-cell} ipython3 +# Numerical value at default parameters +ϕ_γ_h_func = Lambda((D, γ_h, γ_c, R, T, w_h0), ϕ_γ_h) +ϕ_γ_h_func(D_value, γ_h_value, γ_c_value, R_value, T_value, w_h0_value) +``` + +We find that raising $\gamma_h$ increases the initial college wage premium $\phi$, in line with our earlier graphical analysis. + +Compute $\frac{\partial \phi}{\partial γ_c}$ and evaluate it numerically at default parameter values + +```{code-cell} ipython3 +ϕ_γ_c = ϕ(D, γ_h, γ_c, R, T, w_h0).diff(γ_c) +ϕ_γ_c +``` + +```{code-cell} ipython3 +# Numerical value at default parameters +ϕ_γ_c_func = Lambda((D, γ_h, γ_c, R, T, w_h0), ϕ_γ_c) +ϕ_γ_c_func(D_value, γ_h_value, γ_c_value, R_value, T_value, w_h0_value) +``` + +We find that raising $\gamma_c$ decreases the initial college wage premium $\phi$, in line with our earlier graphical analysis. + +Let's compute $\frac{\partial \phi}{\partial R}$ and evaluate it numerically at default parameter values + +```{code-cell} ipython3 +ϕ_R = ϕ(D, γ_h, γ_c, R, T, w_h0).diff(R) +ϕ_R +``` + +```{code-cell} ipython3 +# Numerical value at default parameters +ϕ_R_func = Lambda((D, γ_h, γ_c, R, T, w_h0), ϕ_R) +ϕ_R_func(D_value, γ_h_value, γ_c_value, R_value, T_value, w_h0_value) +``` + +We find that raising the gross interest rate $R$ increases the initial college wage premium $\phi$, in line with our earlier graphical analysis. diff --git a/book/_build/html/_sources/french_rev.ipynb b/book/_build/html/_sources/french_rev.ipynb new file mode 100644 index 0000000..dca0bb6 --- /dev/null +++ b/book/_build/html/_sources/french_rev.ipynb @@ -0,0 +1,1282 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "a30afd14", + "metadata": {}, + "source": [ + "# Inflation During French Revolution \n", + "\n", + "\n", + "## Overview \n", + "\n", + "This lecture describes some of the monetary and fiscal features of the French Revolution (1789-1799) described by {cite}`sargent_velde1995`.\n", + "\n", + "To finance public expenditures and service its debts, \n", + "the French government embarked on policy experiments.\n", + "\n", + "The authors of these experiments had in mind theories about how government monetary and fiscal policies affected economic outcomes.\n", + "\n", + "Some of those theories about monetary and fiscal policies still interest us today.\n", + "\n", + "* a **tax-smoothing** model like Robert Barro's {cite}`Barro1979`\n", + "\n", + " * this normative (i.e., prescriptive model) advises a government to finance temporary war-time surges in expenditures mostly by issuing government debt, raising taxes by just enough to service the additional debt issued during the wary; then, after the war, to roll over whatever debt the government had accumulated during the war; and to increase taxes after the war permanently by just enough to finance interest payments on that post-war government debt\n", + "\n", + "* **unpleasant monetarist arithmetic** like that described in this quanteon lecture {doc}`unpleasant`\n", + " \n", + " * mathematics involving compound interest governed French government debt dynamics in the decades preceding 1789; according to leading historians, that arithmetic set the stage for the French Revolution \n", + "\n", + "* a *real bills* theory of the effects of government open market operations in which the government *backs* new issues of paper money with government holdings of valuable real property or financial assets that holders of money can purchase from the government in exchange for their money.\n", + "\n", + " * The Revolutionaries learned about this theory from Adam Smith's 1776 book The Wealth of Nations\n", + " {cite}`smith2010wealth` and other contemporary sources\n", + "\n", + " * It shaped how the Revolutionaries issued a paper money called **assignats** from 1789 to 1791 \n", + "\n", + "* a classical **gold** or **silver standard**\n", + " \n", + " * Napoleon Bonaparte became head of the French government in 1799. He used this theory to guide his monetary and fiscal policies\n", + "\n", + "* a classical **inflation-tax** theory of inflation in which Philip Cagan's ({cite}`Cagan`) demand for money studied in this lecture {doc}`cagan_ree` is a key component\n", + "\n", + " * This theory helps explain French price level and money supply data from 1794 to 1797 \n", + "\n", + "* a **legal restrictions** or **financial repression** theory of the demand for real balances \n", + " \n", + " * The Twelve Members comprising the Committee of Public Safety who adminstered the Terror from June 1793 to July 1794 used this theory to shape their monetary policy \n", + "\n", + "We use matplotlib to replicate several of the graphs with which {cite}`sargent_velde1995` portrayed outcomes of these experiments \n", + "\n", + "## Data Sources\n", + "\n", + "This lecture uses data from three spreadsheets assembled by {cite}`sargent_velde1995`:\n", + " * [datasets/fig_3.xlsx](https://github.com/QuantEcon/lecture-python-intro/blob/main/lectures/datasets/fig_3.xlsx)\n", + " * [datasets/dette.xlsx](https://github.com/QuantEcon/lecture-python-intro/blob/main/lectures/datasets/dette.xlsx)\n", + " * [datasets/assignat.xlsx](https://github.com/QuantEcon/lecture-python-intro/blob/main/lectures/datasets/assignat.xlsx)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "384e63b5", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "plt.rcParams.update({'font.size': 12})\n", + "\n", + "base_url = 'https://github.com/QuantEcon/lecture-python-intro/raw/'\\\n", + " + 'main/lectures/datasets/'\n", + "\n", + "fig_3_url = f'{base_url}fig_3.xlsx'\n", + "dette_url = f'{base_url}dette.xlsx'\n", + "assignat_url = f'{base_url}assignat.xlsx'" + ] + }, + { + "cell_type": "markdown", + "id": "9e71678d", + "metadata": {}, + "source": [ + "## Government Expenditures and Taxes Collected\n", + "\n", + "\n", + "\n", + "We'll start by using `matplotlib` to construct several graphs that will provide important historical context.\n", + "\n", + "These graphs are versions of ones that appear in {cite}`sargent_velde1995`.\n", + "\n", + "These graphs show that during the 18th century\n", + "\n", + " * government expenditures in France and Great Britain both surged during four big wars, and by comparable amounts\n", + " * In Britain, tax revenues were approximately equal to government expenditures during peace times,\n", + " but were substantially less than government expenditures during wars\n", + " * In France, even in peace time, tax revenues were substantially less than government expenditures" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7b8d7640", + "metadata": { + "mystnb": { + "figure": { + "caption": "Military Spending in Britain and France", + "name": "fr_fig4" + } + } + }, + "outputs": [], + "source": [ + "# Read the data from Excel file\n", + "data2 = pd.read_excel(dette_url, \n", + " sheet_name='Militspe', usecols='M:X', \n", + " skiprows=7, nrows=102, header=None)\n", + "\n", + "# French military spending, 1685-1789, in 1726 livres\n", + "data4 = pd.read_excel(dette_url, \n", + " sheet_name='Militspe', usecols='D', \n", + " skiprows=3, nrows=105, header=None).squeeze()\n", + " \n", + "years = range(1685, 1790)\n", + "\n", + "plt.figure()\n", + "plt.plot(years, data4, '*-', linewidth=0.8)\n", + "\n", + "plt.plot(range(1689, 1791), data2.iloc[:, 4], linewidth=0.8)\n", + "\n", + "plt.gca().spines['top'].set_visible(False)\n", + "plt.gca().spines['right'].set_visible(False)\n", + "plt.gca().tick_params(labelsize=12)\n", + "plt.xlim([1689, 1790])\n", + "plt.xlabel('*: France')\n", + "plt.ylabel('Millions of livres')\n", + "plt.ylim([0, 475])\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "e1dda9e5", + "metadata": {}, + "source": [ + "During the 18th century, Britain and France fought four large wars.\n", + "\n", + "Britain won the first three wars and lost the fourth.\n", + "\n", + "Each of those wars produced surges in both countries' government expenditures that each country somehow had to finance.\n", + "\n", + "Figure {numref}`fr_fig4` shows surges in military expenditures in France (in blue) and Great Britain.\n", + "during those four wars. \n", + "\n", + "A remarkable aspect of figure {numref}`fr_fig4` is that despite having a population less than half of France's, Britain was able to finance military expenses of about the same amounts as France's.\n", + "\n", + "This testifies to Britain's having created state institutions that could sustain high tax collections, government spending , and government borrowing. See {cite}`north1989`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "128cdc35", + "metadata": { + "mystnb": { + "figure": { + "caption": "Government Expenditures and Tax Revenues in Britain", + "name": "fr_fig2" + } + } + }, + "outputs": [], + "source": [ + "# Read the data from Excel file\n", + "data2 = pd.read_excel(dette_url, sheet_name='Militspe', usecols='M:X', \n", + " skiprows=7, nrows=102, header=None)\n", + "\n", + "# Plot the data\n", + "plt.figure()\n", + "plt.plot(range(1689, 1791), data2.iloc[:, 5], linewidth=0.8)\n", + "plt.plot(range(1689, 1791), data2.iloc[:, 11], linewidth=0.8, color='red')\n", + "plt.plot(range(1689, 1791), data2.iloc[:, 9], linewidth=0.8, color='orange')\n", + "plt.plot(range(1689, 1791), data2.iloc[:, 8], 'o-', \n", + " markerfacecolor='none', linewidth=0.8, color='purple')\n", + "\n", + "# Customize the plot\n", + "plt.gca().spines['top'].set_visible(False)\n", + "plt.gca().spines['right'].set_visible(False)\n", + "plt.gca().tick_params(labelsize=12)\n", + "plt.xlim([1689, 1790])\n", + "plt.ylabel('millions of pounds', fontsize=12)\n", + "\n", + "# Add text annotations\n", + "plt.text(1765, 1.5, 'civil', fontsize=10)\n", + "plt.text(1760, 4.2, 'civil plus debt service', fontsize=10)\n", + "plt.text(1708, 15.5, 'total govt spending', fontsize=10)\n", + "plt.text(1759, 7.3, 'revenues', fontsize=10)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "71bbd6db", + "metadata": {}, + "source": [ + "Figures {numref}`fr_fig2` and {numref}`fr_fig3` summarize British and French government fiscal policies during the century before the start of the French Revolution in 1789.\n", + "\n", + "\n", + "Before 1789, progressive forces in France admired how Britain had financed its government expenditures and wanted to redesign French fiscal arrangements to make them more like Britain's.\n", + "\n", + "Figure {numref}`fr_fig2` shows government expenditures and how it was distributed among expenditures for \n", + "\n", + " * civil (non-military) activities\n", + " * debt service, i.e., interest payments \n", + " * military expenditures (the yellow line minus the red line) \n", + "\n", + "Figure {numref}`fr_fig2` also plots total government revenues from tax collections (the purple circled line)\n", + "\n", + "Notice the surges in total government expenditures associated with surges in military expenditures\n", + "in these four wars\n", + "\n", + " * Wars against France's King Louis XIV early in the 18th century\n", + " * The War of the Austrian Succession in the 1740s\n", + " * The French and Indian War in the 1750's and 1760s\n", + " * The American War for Independence from 1775 to 1783\n", + "\n", + "Figure {numref}`fr_fig2` indicates that\n", + "\n", + " * during times of peace, government expenditures approximately equal taxes and debt service payments neither grow nor decline over time\n", + " * during times of wars, government expenditures exceed tax revenues\n", + " * the government finances the deficit of revenues relative to expenditures by issuing debt\n", + " * after a war is over, the government's tax revenues exceed its non-interest expenditures by just enough to service the debt that the government issued to finance earlier deficits\n", + " * thus, after a war, the government does *not* raise taxes by enough to pay off its debt\n", + " * instead, it just rolls over whatever debt it inherits, raising taxes by just enough to service the interest payments on that debt\n", + "\n", + "Eighteenth-century British fiscal policy portrayed Figure {numref}`fr_fig2` thus looks very much like a text-book example of a *tax-smoothing* model like Robert Barro's {cite}`Barro1979`. \n", + "\n", + "A striking feature of the graph is what we'll label a *law of gravity* between tax collections and government expenditures. \n", + "\n", + " * levels of government expenditures at taxes attract each other\n", + " * while they can temporarily differ -- as they do during wars -- they come back together when peace returns\n", + "\n", + "\n", + "\n", + "Next we'll plot data on debt service costs as fractions of government revenues in Great Britain and France during the 18th century." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a772e670", + "metadata": { + "mystnb": { + "figure": { + "caption": "Ratio of debt service to taxes, Britain and France", + "name": "fr_fig1" + } + } + }, + "outputs": [], + "source": [ + "# Read the data from the Excel file\n", + "data1 = pd.read_excel(dette_url, sheet_name='Debt', \n", + " usecols='R:S', skiprows=5, nrows=99, header=None)\n", + "data1a = pd.read_excel(dette_url, sheet_name='Debt', \n", + " usecols='P', skiprows=89, nrows=15, header=None)\n", + "\n", + "# Plot the data\n", + "plt.figure()\n", + "plt.plot(range(1690, 1789), 100 * data1.iloc[:, 1], linewidth=0.8)\n", + "\n", + "date = np.arange(1690, 1789)\n", + "index = (date < 1774) & (data1.iloc[:, 0] > 0)\n", + "plt.plot(date[index], 100 * data1[index].iloc[:, 0], \n", + " '*:', color='r', linewidth=0.8)\n", + "\n", + "# Plot the additional data\n", + "plt.plot(range(1774, 1789), 100 * data1a, '*:', color='orange')\n", + "\n", + "# Note about the data\n", + "# The French data before 1720 don't match up with the published version\n", + "# Set the plot properties\n", + "plt.gca().spines['top'].set_visible(False)\n", + "plt.gca().spines['right'].set_visible(False)\n", + "plt.gca().set_facecolor('white')\n", + "plt.gca().set_xlim([1688, 1788])\n", + "plt.ylabel('% of Taxes')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "816ae813", + "metadata": {}, + "source": [ + "Figure {numref}`fr_fig1` shows that interest payments on government debt (i.e., so-called ''debt service'') were high fractions of government tax revenues in both Great Britain and France. \n", + "\n", + "{numref}`fr_fig2` showed us that in peace times Britain managed to balance its budget despite those large interest costs. \n", + "\n", + "But as we'll see in our next graph, on the eve of the French Revolution in 1788, the fiscal *law of gravity* that worked so well in Britain did not working very well in France." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c5548306", + "metadata": {}, + "outputs": [], + "source": [ + "# Read the data from the Excel file\n", + "data1 = pd.read_excel(fig_3_url, sheet_name='Sheet1', \n", + " usecols='C:F', skiprows=5, nrows=30, header=None)\n", + "\n", + "data1.replace(0, np.nan, inplace=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ccfd0f38", + "metadata": { + "mystnb": { + "figure": { + "caption": "Government Spending and Tax Revenues in France", + "name": "fr_fig3" + } + } + }, + "outputs": [], + "source": [ + "# Plot the data\n", + "plt.figure()\n", + "\n", + "plt.plot(range(1759, 1789, 1), data1.iloc[:, 0], '-x', linewidth=0.8)\n", + "plt.plot(range(1759, 1789, 1), data1.iloc[:, 1], '--*', linewidth=0.8)\n", + "plt.plot(range(1759, 1789, 1), data1.iloc[:, 2], \n", + " '-o', linewidth=0.8, markerfacecolor='none')\n", + "plt.plot(range(1759, 1789, 1), data1.iloc[:, 3], '-*', linewidth=0.8)\n", + "\n", + "plt.text(1775, 610, 'total spending', fontsize=10)\n", + "plt.text(1773, 325, 'military', fontsize=10)\n", + "plt.text(1773, 220, 'civil plus debt service', fontsize=10)\n", + "plt.text(1773, 80, 'debt service', fontsize=10)\n", + "plt.text(1785, 500, 'revenues', fontsize=10)\n", + "\n", + "plt.gca().spines['top'].set_visible(False)\n", + "plt.gca().spines['right'].set_visible(False)\n", + "plt.ylim([0, 700])\n", + "plt.ylabel('millions of livres')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "13c76c45", + "metadata": {}, + "source": [ + "{numref}`fr_fig3` shows that on the eve of the French Revolution in 1788, government expenditures exceeded tax revenues. \n", + "\n", + "\n", + "Especially during and after France's expenditures to help the Americans in their War of Independence from Great Britain, growing government debt service (i.e., interest payments) \n", + "contributed to this situation. \n", + "\n", + "This was partly a consequence of the unfolding of the debt dynamics that underlies the Unpleasant Arithmetic discussed in this quantecon lecture {doc}`unpleasant`. \n", + "\n", + "\n", + "{cite}`sargent_velde1995` describe how the Ancient Regime that until 1788 had governed France had stable institutional features that made it difficult for the government to balance its budget.\n", + "\n", + "Powerful contending interests had prevented from the government from closing the gap between its\n", + "total expenditures and its tax revenues by either\n", + "\n", + " * raising taxes, or\n", + " * lowering government's non-debt service (i.e., non-interest) expenditures, or \n", + " * lowering debt service (i.e., interest) costs by rescheduling, i.e., defaulting on some debts\n", + "\n", + "Precedents and prevailing French arrangements had empowered three constituencies to block adjustments to components of the government budget constraint that they cared especially about\n", + "\n", + "* tax payers\n", + "* beneficiaries of government expenditures\n", + "* government creditors (i.e., owners of government bonds)\n", + "\n", + "When the French government had confronted a similar situation around 1720 after King Louis XIV's\n", + "Wars had left it with a debt crisis, it had sacrificed the interests of \n", + "government creditors, i.e., by defaulting enough of its debt to bring reduce interest payments down enough to balance the budget.\n", + "\n", + "Somehow, in 1789, creditors of the French government were more powerful than they had been in 1720.\n", + "\n", + "Therefore, King Louis XVI convened the Estates General together to ask them to redesign the French constitution in a way that would lower government expenditures or increase taxes, thereby\n", + "allowing him to balance the budget while also honoring his promises to creditors of the French government. \n", + "\n", + "The King called the Estates General together in an effort to promote the reforms that would\n", + "would bring sustained budget balance. \n", + "\n", + "{cite}`sargent_velde1995` describe how the French Revolutionaries set out to accomplish that.\n", + "\n", + "## Nationalization, Privatization, Debt Reduction \n", + "\n", + "In 1789, the Revolutionaries quickly reorganized the Estates General into a National Assembly.\n", + "\n", + "A first piece of business was to address the fiscal crisis, the situation that had motivated the King to convene the Estates General.\n", + "\n", + "The Revolutionaries were not socialists or communists.\n", + "\n", + "To the contrary, they respected private property and knew state-of-the-art economics. \n", + "\n", + "They knew that to honor government debts, they would have to raise new revenues or reduce expenditures.\n", + "\n", + "A coincidence was that the Catholic Church owned vast income-producing properties. \n", + "\n", + "Indeed, the capitalized value of those income streams put estimates of the value of church lands at \n", + "about the same amount as the entire French government debt. \n", + "\n", + "This coincidence fostered a three step plan for servicing the French government debt\n", + "\n", + " * nationalize the church lands -- i.e., sequester or confiscate it without paying for it\n", + " * sell the church lands \n", + " * use the proceeds from those sales to service or even retire French government debt\n", + "\n", + "The monetary theory underlying this plan had been set out by Adam Smith in his analysis of what he called *real bills* in his 1776 book\n", + "**The Wealth of Nations** {cite}`smith2010wealth`, which many of the revolutionaries had read.\n", + "\n", + "Adam Smith defined a *real bill* as a paper money note that is backed by a claims on a real asset like productive capital or inventories. \n", + "\n", + "The National Assembly put together an ingenious institutional arrangement to implement this plan.\n", + "\n", + "In response to a motion by Catholic Bishop Talleyrand (an atheist),\n", + "the National Assembly confiscated and nationalized Church lands. \n", + "\n", + "The National Assembly intended to use earnings from Church lands to service its national debt.\n", + "\n", + "To do this, it began to implement a ''privatization plan'' that would let it service its debt while\n", + "not raising taxes.\n", + "\n", + "Their plan involved issuing paper notes called ''assignats'' that entitled bearers to use them to purchase state lands. \n", + "\n", + "These paper notes would be ''as good as silver coins'' in the sense that both were acceptable means of payment in exchange for those (formerly) church lands. \n", + "\n", + "Finance Minister Necker and the Constituents of the National Assembly thus planned\n", + "to solve the privatization problem *and* the debt problem simultaneously\n", + "by creating a new currency. \n", + "\n", + "They devised a scheme to raise revenues by auctioning\n", + "the confiscated lands, thereby withdrawing paper notes issued on the security of\n", + "the lands sold by the government.\n", + "\n", + " This ''tax-backed money'' scheme propelled the National Assembly into the domains of then modern monetary theories.\n", + " \n", + "Records of debates show\n", + "how members of the Assembly marshaled theory and evidence to assess the likely\n", + "effects of their innovation. \n", + "\n", + " * Members of the National Assembly quoted David Hume and Adam Smith\n", + " * They cited John Law's System of 1720 and the American experiences with paper money fifteen years\n", + "earlier as examples of how paper money schemes can go awry\n", + " * Knowing pitfalls, they set out to avoid them\n", + "\n", + "They succeeded for two or three years.\n", + "\n", + "But after that, France entered a big War that disrupted the plan in ways that completely altered the character of France's paper money. {cite}`sargent_velde1995` describe what happened.\n", + "\n", + "## Remaking the tax code and tax administration\n", + "\n", + "In 1789 the French Revolutionaries formed a National Assembly and set out to remake French\n", + "fiscal policy.\n", + "\n", + "They wanted to honor government debts -- interests of French government creditors were well represented in the National Assembly.\n", + "\n", + "But they set out to remake the French tax code and the administrative machinery for collecting taxes.\n", + "\n", + " * they abolished many taxes\n", + " * they abolished the Ancient Regimes scheme for *tax farming*\n", + " * tax farming meant that the government had privatized tax collection by hiring private citizens -- so-called tax farmers to collect taxes, while retaining a fraction of them as payment for their services\n", + " * the great chemist Lavoisier was also a tax farmer, one of the reasons that the Committee for Public Safety sent him to the guillotine in 1794\n", + "\n", + "As a consequence of these tax reforms, government tax revenues declined\n", + "\n", + "The next figure shows this" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e3ab0cb3", + "metadata": { + "mystnb": { + "figure": { + "caption": "Index of real per capital revenues, France", + "name": "fr_fig5" + } + } + }, + "outputs": [], + "source": [ + "# Read data from Excel file\n", + "data5 = pd.read_excel(dette_url, sheet_name='Debt', usecols='K', \n", + " skiprows=41, nrows=120, header=None)\n", + "\n", + "# Plot the data\n", + "plt.figure()\n", + "plt.plot(range(1726, 1846), data5.iloc[:, 0], linewidth=0.8)\n", + "\n", + "plt.gca().spines['top'].set_visible(False)\n", + "plt.gca().spines['right'].set_visible(False)\n", + "plt.gca().set_facecolor('white')\n", + "plt.gca().tick_params(labelsize=12)\n", + "plt.xlim([1726, 1845])\n", + "plt.ylabel('1726 = 1', fontsize=12)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "87cf3c9c", + "metadata": {}, + "source": [ + "According to {numref}`fr_fig5`, tax revenues per capita did not rise to their pre 1789 levels\n", + "until after 1815, when Napoleon Bonaparte was exiled to St Helena and King Louis XVIII was restored to the French Crown.\n", + "\n", + " * from 1799 to 1814, Napoleon Bonaparte had other sources of revenues -- booty and reparations from provinces and nations that he defeated in war\n", + "\n", + " * from 1789 to 1799, the French Revolutionaries turned to another source to raise resources to pay for government purchases of goods and services and to service French government debt. \n", + "\n", + "And as the next figure shows, government expenditures exceeded tax revenues by substantial\n", + "amounts during the period form 1789 to 1799." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "63b7bbcb", + "metadata": { + "mystnb": { + "figure": { + "caption": "Spending (blue) and Revenues (orange), (real values)", + "name": "fr_fig11" + } + } + }, + "outputs": [], + "source": [ + "# Read data from Excel file\n", + "data11 = pd.read_excel(assignat_url, sheet_name='Budgets',\n", + " usecols='J:K', skiprows=22, nrows=52, header=None)\n", + "\n", + "# Prepare the x-axis data\n", + "x_data = np.concatenate([\n", + " np.arange(1791, 1794 + 8/12, 1/12),\n", + " np.arange(1794 + 9/12, 1795 + 3/12, 1/12)\n", + "])\n", + "\n", + "# Remove NaN values from the data\n", + "data11_clean = data11.dropna()\n", + "\n", + "# Plot the data\n", + "plt.figure()\n", + "h = plt.plot(x_data, data11_clean.values[:, 0], linewidth=0.8)\n", + "h = plt.plot(x_data, data11_clean.values[:, 1], '--', linewidth=0.8)\n", + "\n", + "# Set plot properties\n", + "plt.gca().spines['top'].set_visible(False)\n", + "plt.gca().spines['right'].set_visible(False)\n", + "plt.gca().set_facecolor('white')\n", + "plt.gca().tick_params(axis='both', which='major', labelsize=12)\n", + "plt.xlim([1791, 1795 + 3/12])\n", + "plt.xticks(np.arange(1791, 1796))\n", + "plt.yticks(np.arange(0, 201, 20))\n", + "\n", + "# Set the y-axis label\n", + "plt.ylabel('millions of livres', fontsize=12)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "9ec3dfae", + "metadata": {}, + "source": [ + "To cover the discrepancies between government expenditures and tax revenues revealed in {numref}`fr_fig11`, the French revolutionaries printed paper money and spent it. \n", + "\n", + "The next figure shows that by printing money, they were able to finance substantial purchases \n", + "of goods and services, including military goods and soldiers' pay." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0c557a46", + "metadata": { + "mystnb": { + "figure": { + "caption": "Revenues raised by printing paper money notes", + "name": "fr_fig24" + } + } + }, + "outputs": [], + "source": [ + "# Read data from Excel file\n", + "data12 = pd.read_excel(assignat_url, sheet_name='seignor', \n", + " usecols='F', skiprows=6, nrows=75, header=None).squeeze()\n", + "\n", + "# Create a figure and plot the data\n", + "plt.figure()\n", + "plt.plot(pd.date_range(start='1790', periods=len(data12), freq='M'),\n", + " data12, linewidth=0.8)\n", + "\n", + "plt.gca().spines['top'].set_visible(False)\n", + "plt.gca().spines['right'].set_visible(False)\n", + "\n", + "plt.axhline(y=472.42/12, color='r', linestyle=':')\n", + "plt.xticks(ticks=pd.date_range(start='1790', \n", + " end='1796', freq='AS'), labels=range(1790, 1797))\n", + "plt.xlim(pd.Timestamp('1791'),\n", + " pd.Timestamp('1796-02') + pd.DateOffset(months=2))\n", + "plt.ylabel('millions of livres', fontsize=12)\n", + "plt.text(pd.Timestamp('1793-11'), 39.5, 'revenues in 1788', \n", + " verticalalignment='top', fontsize=12)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "0f1e72f9", + "metadata": {}, + "source": [ + "{numref}`fr_fig24` compares the revenues raised by printing money from 1789 to 1796 with tax revenues that the Ancient Regime had raised in 1788.\n", + "\n", + "Measured in goods, revenues raised at time $t$ by printing new money equal\n", + "\n", + "$$\n", + "\\frac{M_{t+1} - M_t}{p_t}\n", + "$$\n", + "\n", + "where \n", + "\n", + "* $M_t$ is the stock of paper money at time $t$ measured in livres\n", + "* $p_t$ is the price level at time $t$ measured in units of goods per livre at time $t$\n", + "* $M_{t+1} - M_t$ is the amount of new money printed at time $t$\n", + "\n", + "Notice the 1793-1794 surge in revenues raised by printing money. \n", + "\n", + "* This reflects extraordinary measures that the Committee for Public Safety adopted to force citizens to accept paper money, or else.\n", + "\n", + "Also note the abrupt fall off in revenues raised by 1797 and the absence of further observations after 1797. \n", + "\n", + "* This reflects the end of using the printing press to raise revenues.\n", + "\n", + "What French paper money entitled its holders to changed over time in interesting ways.\n", + "\n", + "These led to outcomes that vary over time and that illustrate the playing out in practice of theories that guided the Revolutionaries' monetary policy decisions.\n", + "\n", + "\n", + "The next figure shows the price level in France during the time that the Revolutionaries used paper money to finance parts of their expenditures.\n", + "\n", + "Note that we use a log scale because the price level rose so much." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7172e0a7", + "metadata": { + "mystnb": { + "figure": { + "caption": "Price Level and Price of Gold (log scale)", + "name": "fr_fig9" + } + } + }, + "outputs": [], + "source": [ + "# Read the data from Excel file\n", + "data7 = pd.read_excel(assignat_url, sheet_name='Data', \n", + " usecols='P:Q', skiprows=4, nrows=80, header=None)\n", + "data7a = pd.read_excel(assignat_url, sheet_name='Data', \n", + " usecols='L', skiprows=4, nrows=80, header=None)\n", + "# Create the figure and plot\n", + "plt.figure()\n", + "x = np.arange(1789 + 10/12, 1796 + 5/12, 1/12)\n", + "h, = plt.plot(x, 1. / data7.iloc[:, 0], linestyle='--')\n", + "h, = plt.plot(x, 1. / data7.iloc[:, 1], color='r')\n", + "\n", + "# Set properties of the plot\n", + "plt.gca().tick_params(labelsize=12)\n", + "plt.yscale('log')\n", + "plt.xlim([1789 + 10/12, 1796 + 5/12])\n", + "plt.gca().spines['top'].set_visible(False)\n", + "plt.gca().spines['right'].set_visible(False)\n", + "\n", + "# Add vertical lines\n", + "plt.axvline(x=1793 + 6.5/12, linestyle='-', linewidth=0.8, color='orange')\n", + "plt.axvline(x=1794 + 6.5/12, linestyle='-', linewidth=0.8, color='purple')\n", + "\n", + "# Add text\n", + "plt.text(1793.75, 120, 'Terror', fontsize=12)\n", + "plt.text(1795, 2.8, 'price level', fontsize=12)\n", + "plt.text(1794.9, 40, 'gold', fontsize=12)\n", + "\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "389e6e44", + "metadata": {}, + "source": [ + "We have partioned {numref}`fr_fig9` that shows the log of the price level and {numref}`fr_fig8`\n", + "below that plots real balances $\\frac{M_t}{p_t}$ into three periods that correspond to different monetary experiments or *regimes*. \n", + "\n", + "The first period ends in the late summer of 1793, and is characterized\n", + "by growing real balances and moderate inflation. \n", + "\n", + "The second period begins and ends\n", + "with the Terror. It is marked by high real balances, around 2,500 million, and\n", + "roughly stable prices. The fall of Robespierre in late July 1794 begins the third\n", + "of our episodes, in which real balances decline and prices rise rapidly.\n", + "\n", + "We interpret\n", + "these three episodes in terms of distinct theories\n", + "\n", + "* a *backing* or *real bills* theory (the classic text for this theory is Adam Smith {cite}`smith2010wealth`)\n", + "* a legal restrictions theory ( {cite}`keynes1940pay`, {cite}`bryant1984price` )\n", + "* a classical hyperinflation theory ({cite}`Cagan`)\n", + "* \n", + "```{note}\n", + "According to the empirical definition of hyperinflation adopted by {cite}`Cagan`,\n", + "beginning in the month that inflation exceeds 50 percent\n", + "per month and ending in the month before inflation drops below 50 percent per month\n", + "for at least a year, the *assignat* experienced a hyperinflation from May to December\n", + "1795.\n", + "```\n", + "We view these\n", + "theories not as competitors but as alternative collections of ''if-then''\n", + "statements about government note issues, each of which finds its conditions more\n", + "nearly met in one of these episodes than in the other two." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6dacee24", + "metadata": { + "mystnb": { + "figure": { + "caption": "Real balances of assignats (in gold and goods)", + "name": "fr_fig8" + } + } + }, + "outputs": [], + "source": [ + "# Read the data from Excel file\n", + "data7 = pd.read_excel(assignat_url, sheet_name='Data', \n", + " usecols='P:Q', skiprows=4, nrows=80, header=None)\n", + "data7a = pd.read_excel(assignat_url, sheet_name='Data', \n", + " usecols='L', skiprows=4, nrows=80, header=None)\n", + "\n", + "# Create the figure and plot\n", + "plt.figure()\n", + "h = plt.plot(pd.date_range(start='1789-11-01', periods=len(data7), freq='M'), \n", + " (data7a.values * [1, 1]) * data7.values, linewidth=1.)\n", + "plt.setp(h[1], linestyle='--', color='red')\n", + "\n", + "plt.vlines([pd.Timestamp('1793-07-15'), pd.Timestamp('1793-07-15')], \n", + " 0, 3000, linewidth=0.8, color='orange')\n", + "plt.vlines([pd.Timestamp('1794-07-15'), pd.Timestamp('1794-07-15')], \n", + " 0, 3000, linewidth=0.8, color='purple')\n", + "\n", + "plt.ylim([0, 3000])\n", + "\n", + "# Set properties of the plot\n", + "plt.gca().spines['top'].set_visible(False)\n", + "plt.gca().spines['right'].set_visible(False)\n", + "plt.gca().set_facecolor('white')\n", + "plt.gca().tick_params(labelsize=12)\n", + "plt.xlim(pd.Timestamp('1789-11-01'), pd.Timestamp('1796-06-01'))\n", + "plt.ylabel('millions of livres', fontsize=12)\n", + "\n", + "# Add text annotations\n", + "plt.text(pd.Timestamp('1793-09-01'), 200, 'Terror', fontsize=12)\n", + "plt.text(pd.Timestamp('1791-05-01'), 750, 'gold value', fontsize=12)\n", + "plt.text(pd.Timestamp('1794-10-01'), 2500, 'real value', fontsize=12)\n", + "\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "8a100368", + "metadata": {}, + "source": [ + "The three clouds of points in Figure\n", + "{numref}`fr_fig104`\n", + " depict different real balance-inflation relationships. \n", + " \n", + "Only the cloud for the\n", + "third period has the inverse relationship familiar to us now from twentieth-century\n", + "hyperinflations.\n", + "\n", + "\n", + "\n", + "\n", + "* subperiod 1: (\"*real bills* period): January 1791 to July 1793\n", + "\n", + "* subperiod 2: (\"terror\"): August 1793 - July 1794\n", + "\n", + "* subperiod 3: (\"classic Cagan hyperinflation\"): August 1794 - March 1796" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "03b15f1c", + "metadata": {}, + "outputs": [], + "source": [ + "def fit(x, y):\n", + "\n", + " b = np.cov(x, y)[0, 1] / np.var(x)\n", + " a = y.mean() - b * x.mean()\n", + "\n", + " return a, b" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "adeec6ec", + "metadata": {}, + "outputs": [], + "source": [ + "# Load data\n", + "caron = np.load('datasets/caron.npy')\n", + "nom_balances = np.load('datasets/nom_balances.npy')\n", + "\n", + "infl = np.concatenate(([np.nan], \n", + " -np.log(caron[1:63, 1] / caron[0:62, 1])))\n", + "bal = nom_balances[14:77, 1] * caron[:, 1] / 1000" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d3acc6d1", + "metadata": {}, + "outputs": [], + "source": [ + "# Regress y on x for three periods\n", + "a1, b1 = fit(bal[1:31], infl[1:31])\n", + "a2, b2 = fit(bal[31:44], infl[31:44])\n", + "a3, b3 = fit(bal[44:63], infl[44:63])\n", + "\n", + "# Regress x on y for three periods\n", + "a1_rev, b1_rev = fit(infl[1:31], bal[1:31])\n", + "a2_rev, b2_rev = fit(infl[31:44], bal[31:44])\n", + "a3_rev, b3_rev = fit(infl[44:63], bal[44:63])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dbfd74fb", + "metadata": { + "mystnb": { + "figure": { + "caption": "Inflation and Real Balances", + "name": "fr_fig104" + } + } + }, + "outputs": [], + "source": [ + "plt.figure()\n", + "plt.gca().spines['top'].set_visible(False)\n", + "plt.gca().spines['right'].set_visible(False)\n", + "\n", + "# First subsample\n", + "plt.plot(bal[1:31], infl[1:31], 'o', markerfacecolor='none', \n", + " color='blue', label='real bills period')\n", + "\n", + "# Second subsample\n", + "plt.plot(bal[31:44], infl[31:44], '+', color='red', label='terror')\n", + "\n", + "# Third subsample\n", + "plt.plot(bal[44:63], infl[44:63], '*', \n", + " color='orange', label='classic Cagan hyperinflation')\n", + "\n", + "plt.xlabel('real balances')\n", + "plt.ylabel('inflation')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "693fca73", + "metadata": {}, + "source": [ + "The three clouds of points in {numref}`fr_fig104` evidently \n", + " depict different real balance-inflation relationships. \n", + "\n", + "Only the cloud for the\n", + "third period has the inverse relationship familiar to us now from twentieth-century\n", + "hyperinflations.\n", + "\n", + " To bring this out, we'll use linear regressions to draw straight lines that compress the \n", + " inflation-real balance relationship for our three sub-periods. \n", + "\n", + " Before we do that, we'll drop some of the early observations during the terror period \n", + " to obtain the following graph." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4307ce7d", + "metadata": {}, + "outputs": [], + "source": [ + "# Regress y on x for three periods\n", + "a1, b1 = fit(bal[1:31], infl[1:31])\n", + "a2, b2 = fit(bal[31:44], infl[31:44])\n", + "a3, b3 = fit(bal[44:63], infl[44:63])\n", + "\n", + "# Regress x on y for three periods\n", + "a1_rev, b1_rev = fit(infl[1:31], bal[1:31])\n", + "a2_rev, b2_rev = fit(infl[31:44], bal[31:44])\n", + "a3_rev, b3_rev = fit(infl[44:63], bal[44:63])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f39e161f", + "metadata": { + "mystnb": { + "figure": { + "caption": "Inflation and Real Balances", + "name": "fr_fig104b" + } + } + }, + "outputs": [], + "source": [ + "plt.figure()\n", + "plt.gca().spines['top'].set_visible(False)\n", + "plt.gca().spines['right'].set_visible(False)\n", + "\n", + "# First subsample\n", + "plt.plot(bal[1:31], infl[1:31], 'o', markerfacecolor='none', color='blue', label='real bills period')\n", + "\n", + "# Second subsample\n", + "plt.plot(bal[34:44], infl[34:44], '+', color='red', label='terror')\n", + "\n", + "# Third subsample\n", + "plt.plot(bal[44:63], infl[44:63], '*', color='orange', label='classic Cagan hyperinflation')\n", + "\n", + "plt.xlabel('real balances')\n", + "plt.ylabel('inflation')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "db7f3d32", + "metadata": {}, + "source": [ + "Now let's regress inflation on real balances during the *real bills* period and plot the regression\n", + "line." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "25fd1ba5", + "metadata": { + "mystnb": { + "figure": { + "caption": "Inflation and Real Balances", + "name": "fr_fig104c" + } + } + }, + "outputs": [], + "source": [ + "plt.figure()\n", + "plt.gca().spines['top'].set_visible(False)\n", + "plt.gca().spines['right'].set_visible(False)\n", + "\n", + "# First subsample\n", + "plt.plot(bal[1:31], infl[1:31], 'o', markerfacecolor='none', \n", + " color='blue', label='real bills period')\n", + "plt.plot(bal[1:31], a1 + bal[1:31] * b1, color='blue')\n", + "\n", + "# Second subsample\n", + "plt.plot(bal[31:44], infl[31:44], '+', color='red', label='terror')\n", + "\n", + "# Third subsample\n", + "plt.plot(bal[44:63], infl[44:63], '*', \n", + " color='orange', label='classic Cagan hyperinflation')\n", + "\n", + "plt.xlabel('real balances')\n", + "plt.ylabel('inflation')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "f68ca701", + "metadata": {}, + "source": [ + "The regression line in {numref}`fr_fig104c` shows that large increases in real balances of\n", + "assignats (paper money) were accompanied by only modest rises in the price level, an outcome in line\n", + "with the *real bills* theory. \n", + "\n", + "During this period, assignats were claims on church lands. \n", + "\n", + "But towards the end of this period, the price level started to rise and real balances to fall\n", + "as the government continued to print money but stopped selling church land. \n", + "\n", + "To get people to hold that paper money, the government forced people to hold it by using legal restrictions.\n", + "\n", + "Now let's regress real balances on inflation during the terror and plot the regression\n", + "line." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "53868900", + "metadata": { + "mystnb": { + "figure": { + "caption": "Inflation and Real Balances", + "name": "fr_fig104d" + } + } + }, + "outputs": [], + "source": [ + "plt.figure()\n", + "plt.gca().spines['top'].set_visible(False)\n", + "plt.gca().spines['right'].set_visible(False)\n", + "\n", + "# First subsample\n", + "plt.plot(bal[1:31], infl[1:31], 'o', markerfacecolor='none', \n", + " color='blue', label='real bills period')\n", + "\n", + "# Second subsample\n", + "plt.plot(bal[31:44], infl[31:44], '+', color='red', label='terror')\n", + "plt.plot(a2_rev + b2_rev * infl[31:44], infl[31:44], color='red')\n", + "\n", + "# Third subsample\n", + "plt.plot(bal[44:63], infl[44:63], '*', \n", + " color='orange', label='classic Cagan hyperinflation')\n", + "\n", + "plt.xlabel('real balances')\n", + "plt.ylabel('inflation')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "1a4410a8", + "metadata": {}, + "source": [ + "The regression line in {numref}`fr_fig104d` shows that large increases in real balances of\n", + "assignats (paper money) were accompanied by little upward price level pressure, even some declines in prices. \n", + "\n", + "This reflects how well legal restrictions -- financial repression -- was working during the period of the Terror. \n", + "\n", + "But the Terror ended in July 1794. That unleashed a big inflation as people tried to find other ways to transact and store values. \n", + "\n", + "The following two graphs are for the classical hyperinflation period.\n", + "\n", + "One regresses inflation on real balances, the other regresses real balances on inflation.\n", + "\n", + "Both show a prounced inverse relationship that is the hallmark of the hyperinflations studied by \n", + "Cagan {cite}`Cagan`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1d8ee890", + "metadata": { + "mystnb": { + "figure": { + "caption": "Inflation and Real Balances", + "name": "fr_fig104e" + } + } + }, + "outputs": [], + "source": [ + "plt.figure()\n", + "plt.gca().spines['top'].set_visible(False)\n", + "plt.gca().spines['right'].set_visible(False)\n", + "\n", + "# First subsample\n", + "plt.plot(bal[1:31], infl[1:31], 'o', markerfacecolor='none', \n", + " color='blue', label='real bills period')\n", + "\n", + "# Second subsample\n", + "plt.plot(bal[31:44], infl[31:44], '+', color='red', label='terror')\n", + "\n", + "# Third subsample\n", + "plt.plot(bal[44:63], infl[44:63], '*', \n", + " color='orange', label='classic Cagan hyperinflation')\n", + "plt.plot(bal[44:63], a3 + bal[44:63] * b3, color='orange')\n", + "\n", + "plt.xlabel('real balances')\n", + "plt.ylabel('inflation')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "a71aff81", + "metadata": {}, + "source": [ + "{numref}`fr_fig104e` shows the results of regressing inflation on real balances during the\n", + "period of the hyperinflation." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "50cc150a", + "metadata": { + "mystnb": { + "figure": { + "caption": "Inflation and Real Balances", + "name": "fr_fig104f" + } + } + }, + "outputs": [], + "source": [ + "plt.figure()\n", + "plt.gca().spines['top'].set_visible(False)\n", + "plt.gca().spines['right'].set_visible(False)\n", + "\n", + "# First subsample\n", + "plt.plot(bal[1:31], infl[1:31], 'o', \n", + " markerfacecolor='none', color='blue', label='real bills period')\n", + "\n", + "# Second subsample\n", + "plt.plot(bal[31:44], infl[31:44], '+', color='red', label='terror')\n", + "\n", + "# Third subsample\n", + "plt.plot(bal[44:63], infl[44:63], '*', \n", + " color='orange', label='classic Cagan hyperinflation')\n", + "plt.plot(a3_rev + b3_rev * infl[44:63], infl[44:63], color='orange')\n", + "\n", + "plt.xlabel('real balances')\n", + "plt.ylabel('inflation')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "4dbc6470", + "metadata": {}, + "source": [ + "{numref}`fr_fig104e` shows the results of regressing real money balances on inflation during the\n", + "period of the hyperinflation.\n", + "\n", + "## Hyperinflation Ends\n", + "\n", + "{cite}`sargent_velde1995` tell how in 1797 the Revolutionary government abruptly ended the inflation by \n", + "\n", + " * repudiating 2/3 of the national debt, and thereby\n", + " * eliminating the net-of-interest government defict\n", + " * no longer printing money, but instead\n", + " * using gold and silver coins as money\n", + "\n", + "In 1799, Napoleon Bonaparte became first consul and for the next 15 years used resources confiscated from conquered territories to help pay for French government expenditures.\n", + "\n", + "## Underlying Theories\n", + "\n", + "This lecture sets the stage for studying theories of inflation and the government monetary and fiscal policies that bring it about.\n", + "\n", + "A *monetarist theory of the price level* is described in this quantecon lecture {doc}`cagan_ree`.\n", + "\n", + "That lecture sets the stage for these quantecon lectures {doc}`money_inflation` and {doc}`unpleasant`." + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.16.2" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 64, + 76, + 95, + 129, + 144, + 179, + 223, + 260, + 269, + 277, + 306, + 429, + 453, + 465, + 504, + 511, + 541, + 574, + 611, + 643, + 685, + 704, + 713, + 723, + 735, + 763, + 778, + 790, + 816, + 821, + 850, + 866, + 895, + 911, + 940, + 945, + 974 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/french_rev.md b/book/_build/html/_sources/french_rev.md new file mode 100644 index 0000000..1f5aec0 --- /dev/null +++ b/book/_build/html/_sources/french_rev.md @@ -0,0 +1,996 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.16.2 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Inflation During French Revolution + + +## Overview + +This lecture describes some of the monetary and fiscal features of the French Revolution (1789-1799) described by {cite}`sargent_velde1995`. + +To finance public expenditures and service its debts, +the French government embarked on policy experiments. + +The authors of these experiments had in mind theories about how government monetary and fiscal policies affected economic outcomes. + +Some of those theories about monetary and fiscal policies still interest us today. + +* a **tax-smoothing** model like Robert Barro's {cite}`Barro1979` + + * this normative (i.e., prescriptive model) advises a government to finance temporary war-time surges in expenditures mostly by issuing government debt, raising taxes by just enough to service the additional debt issued during the wary; then, after the war, to roll over whatever debt the government had accumulated during the war; and to increase taxes after the war permanently by just enough to finance interest payments on that post-war government debt + +* **unpleasant monetarist arithmetic** like that described in this quanteon lecture {doc}`unpleasant` + + * mathematics involving compound interest governed French government debt dynamics in the decades preceding 1789; according to leading historians, that arithmetic set the stage for the French Revolution + +* a *real bills* theory of the effects of government open market operations in which the government *backs* new issues of paper money with government holdings of valuable real property or financial assets that holders of money can purchase from the government in exchange for their money. + + * The Revolutionaries learned about this theory from Adam Smith's 1776 book The Wealth of Nations + {cite}`smith2010wealth` and other contemporary sources + + * It shaped how the Revolutionaries issued a paper money called **assignats** from 1789 to 1791 + +* a classical **gold** or **silver standard** + + * Napoleon Bonaparte became head of the French government in 1799. He used this theory to guide his monetary and fiscal policies + +* a classical **inflation-tax** theory of inflation in which Philip Cagan's ({cite}`Cagan`) demand for money studied in this lecture {doc}`cagan_ree` is a key component + + * This theory helps explain French price level and money supply data from 1794 to 1797 + +* a **legal restrictions** or **financial repression** theory of the demand for real balances + + * The Twelve Members comprising the Committee of Public Safety who adminstered the Terror from June 1793 to July 1794 used this theory to shape their monetary policy + +We use matplotlib to replicate several of the graphs with which {cite}`sargent_velde1995` portrayed outcomes of these experiments + +## Data Sources + +This lecture uses data from three spreadsheets assembled by {cite}`sargent_velde1995`: + * [datasets/fig_3.xlsx](https://github.com/QuantEcon/lecture-python-intro/blob/main/lectures/datasets/fig_3.xlsx) + * [datasets/dette.xlsx](https://github.com/QuantEcon/lecture-python-intro/blob/main/lectures/datasets/dette.xlsx) + * [datasets/assignat.xlsx](https://github.com/QuantEcon/lecture-python-intro/blob/main/lectures/datasets/assignat.xlsx) + +```{code-cell} ipython3 +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +plt.rcParams.update({'font.size': 12}) + +base_url = 'https://github.com/QuantEcon/lecture-python-intro/raw/'\ + + 'main/lectures/datasets/' + +fig_3_url = f'{base_url}fig_3.xlsx' +dette_url = f'{base_url}dette.xlsx' +assignat_url = f'{base_url}assignat.xlsx' +``` + +## Government Expenditures and Taxes Collected + + + +We'll start by using `matplotlib` to construct several graphs that will provide important historical context. + +These graphs are versions of ones that appear in {cite}`sargent_velde1995`. + +These graphs show that during the 18th century + + * government expenditures in France and Great Britain both surged during four big wars, and by comparable amounts + * In Britain, tax revenues were approximately equal to government expenditures during peace times, + but were substantially less than government expenditures during wars + * In France, even in peace time, tax revenues were substantially less than government expenditures + + + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Military Spending in Britain and France" + name: fr_fig4 +--- +# Read the data from Excel file +data2 = pd.read_excel(dette_url, + sheet_name='Militspe', usecols='M:X', + skiprows=7, nrows=102, header=None) + +# French military spending, 1685-1789, in 1726 livres +data4 = pd.read_excel(dette_url, + sheet_name='Militspe', usecols='D', + skiprows=3, nrows=105, header=None).squeeze() + +years = range(1685, 1790) + +plt.figure() +plt.plot(years, data4, '*-', linewidth=0.8) + +plt.plot(range(1689, 1791), data2.iloc[:, 4], linewidth=0.8) + +plt.gca().spines['top'].set_visible(False) +plt.gca().spines['right'].set_visible(False) +plt.gca().tick_params(labelsize=12) +plt.xlim([1689, 1790]) +plt.xlabel('*: France') +plt.ylabel('Millions of livres') +plt.ylim([0, 475]) + +plt.tight_layout() +plt.show() +``` + +During the 18th century, Britain and France fought four large wars. + +Britain won the first three wars and lost the fourth. + +Each of those wars produced surges in both countries' government expenditures that each country somehow had to finance. + +Figure {numref}`fr_fig4` shows surges in military expenditures in France (in blue) and Great Britain. +during those four wars. + +A remarkable aspect of figure {numref}`fr_fig4` is that despite having a population less than half of France's, Britain was able to finance military expenses of about the same amounts as France's. + +This testifies to Britain's having created state institutions that could sustain high tax collections, government spending , and government borrowing. See {cite}`north1989`. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Government Expenditures and Tax Revenues in Britain" + name: fr_fig2 +--- + +# Read the data from Excel file +data2 = pd.read_excel(dette_url, sheet_name='Militspe', usecols='M:X', + skiprows=7, nrows=102, header=None) + +# Plot the data +plt.figure() +plt.plot(range(1689, 1791), data2.iloc[:, 5], linewidth=0.8) +plt.plot(range(1689, 1791), data2.iloc[:, 11], linewidth=0.8, color='red') +plt.plot(range(1689, 1791), data2.iloc[:, 9], linewidth=0.8, color='orange') +plt.plot(range(1689, 1791), data2.iloc[:, 8], 'o-', + markerfacecolor='none', linewidth=0.8, color='purple') + +# Customize the plot +plt.gca().spines['top'].set_visible(False) +plt.gca().spines['right'].set_visible(False) +plt.gca().tick_params(labelsize=12) +plt.xlim([1689, 1790]) +plt.ylabel('millions of pounds', fontsize=12) + +# Add text annotations +plt.text(1765, 1.5, 'civil', fontsize=10) +plt.text(1760, 4.2, 'civil plus debt service', fontsize=10) +plt.text(1708, 15.5, 'total govt spending', fontsize=10) +plt.text(1759, 7.3, 'revenues', fontsize=10) + +plt.tight_layout() +plt.show() +``` + + +Figures {numref}`fr_fig2` and {numref}`fr_fig3` summarize British and French government fiscal policies during the century before the start of the French Revolution in 1789. + + +Before 1789, progressive forces in France admired how Britain had financed its government expenditures and wanted to redesign French fiscal arrangements to make them more like Britain's. + +Figure {numref}`fr_fig2` shows government expenditures and how it was distributed among expenditures for + + * civil (non-military) activities + * debt service, i.e., interest payments + * military expenditures (the yellow line minus the red line) + +Figure {numref}`fr_fig2` also plots total government revenues from tax collections (the purple circled line) + +Notice the surges in total government expenditures associated with surges in military expenditures +in these four wars + + * Wars against France's King Louis XIV early in the 18th century + * The War of the Austrian Succession in the 1740s + * The French and Indian War in the 1750's and 1760s + * The American War for Independence from 1775 to 1783 + +Figure {numref}`fr_fig2` indicates that + + * during times of peace, government expenditures approximately equal taxes and debt service payments neither grow nor decline over time + * during times of wars, government expenditures exceed tax revenues + * the government finances the deficit of revenues relative to expenditures by issuing debt + * after a war is over, the government's tax revenues exceed its non-interest expenditures by just enough to service the debt that the government issued to finance earlier deficits + * thus, after a war, the government does *not* raise taxes by enough to pay off its debt + * instead, it just rolls over whatever debt it inherits, raising taxes by just enough to service the interest payments on that debt + +Eighteenth-century British fiscal policy portrayed Figure {numref}`fr_fig2` thus looks very much like a text-book example of a *tax-smoothing* model like Robert Barro's {cite}`Barro1979`. + +A striking feature of the graph is what we'll label a *law of gravity* between tax collections and government expenditures. + + * levels of government expenditures at taxes attract each other + * while they can temporarily differ -- as they do during wars -- they come back together when peace returns + + + +Next we'll plot data on debt service costs as fractions of government revenues in Great Britain and France during the 18th century. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Ratio of debt service to taxes, Britain and France" + name: fr_fig1 +--- + +# Read the data from the Excel file +data1 = pd.read_excel(dette_url, sheet_name='Debt', + usecols='R:S', skiprows=5, nrows=99, header=None) +data1a = pd.read_excel(dette_url, sheet_name='Debt', + usecols='P', skiprows=89, nrows=15, header=None) + +# Plot the data +plt.figure() +plt.plot(range(1690, 1789), 100 * data1.iloc[:, 1], linewidth=0.8) + +date = np.arange(1690, 1789) +index = (date < 1774) & (data1.iloc[:, 0] > 0) +plt.plot(date[index], 100 * data1[index].iloc[:, 0], + '*:', color='r', linewidth=0.8) + +# Plot the additional data +plt.plot(range(1774, 1789), 100 * data1a, '*:', color='orange') + +# Note about the data +# The French data before 1720 don't match up with the published version +# Set the plot properties +plt.gca().spines['top'].set_visible(False) +plt.gca().spines['right'].set_visible(False) +plt.gca().set_facecolor('white') +plt.gca().set_xlim([1688, 1788]) +plt.ylabel('% of Taxes') + +plt.tight_layout() +plt.show() +``` + +Figure {numref}`fr_fig1` shows that interest payments on government debt (i.e., so-called ''debt service'') were high fractions of government tax revenues in both Great Britain and France. + +{numref}`fr_fig2` showed us that in peace times Britain managed to balance its budget despite those large interest costs. + +But as we'll see in our next graph, on the eve of the French Revolution in 1788, the fiscal *law of gravity* that worked so well in Britain did not working very well in France. + + +```{code-cell} ipython3 +# Read the data from the Excel file +data1 = pd.read_excel(fig_3_url, sheet_name='Sheet1', + usecols='C:F', skiprows=5, nrows=30, header=None) + +data1.replace(0, np.nan, inplace=True) +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Government Spending and Tax Revenues in France" + name: fr_fig3 +--- +# Plot the data +plt.figure() + +plt.plot(range(1759, 1789, 1), data1.iloc[:, 0], '-x', linewidth=0.8) +plt.plot(range(1759, 1789, 1), data1.iloc[:, 1], '--*', linewidth=0.8) +plt.plot(range(1759, 1789, 1), data1.iloc[:, 2], + '-o', linewidth=0.8, markerfacecolor='none') +plt.plot(range(1759, 1789, 1), data1.iloc[:, 3], '-*', linewidth=0.8) + +plt.text(1775, 610, 'total spending', fontsize=10) +plt.text(1773, 325, 'military', fontsize=10) +plt.text(1773, 220, 'civil plus debt service', fontsize=10) +plt.text(1773, 80, 'debt service', fontsize=10) +plt.text(1785, 500, 'revenues', fontsize=10) + +plt.gca().spines['top'].set_visible(False) +plt.gca().spines['right'].set_visible(False) +plt.ylim([0, 700]) +plt.ylabel('millions of livres') + +plt.tight_layout() +plt.show() +``` + +{numref}`fr_fig3` shows that on the eve of the French Revolution in 1788, government expenditures exceeded tax revenues. + + +Especially during and after France's expenditures to help the Americans in their War of Independence from Great Britain, growing government debt service (i.e., interest payments) +contributed to this situation. + +This was partly a consequence of the unfolding of the debt dynamics that underlies the Unpleasant Arithmetic discussed in this quantecon lecture {doc}`unpleasant`. + + +{cite}`sargent_velde1995` describe how the Ancient Regime that until 1788 had governed France had stable institutional features that made it difficult for the government to balance its budget. + +Powerful contending interests had prevented from the government from closing the gap between its +total expenditures and its tax revenues by either + + * raising taxes, or + * lowering government's non-debt service (i.e., non-interest) expenditures, or + * lowering debt service (i.e., interest) costs by rescheduling, i.e., defaulting on some debts + +Precedents and prevailing French arrangements had empowered three constituencies to block adjustments to components of the government budget constraint that they cared especially about + +* tax payers +* beneficiaries of government expenditures +* government creditors (i.e., owners of government bonds) + +When the French government had confronted a similar situation around 1720 after King Louis XIV's +Wars had left it with a debt crisis, it had sacrificed the interests of +government creditors, i.e., by defaulting enough of its debt to bring reduce interest payments down enough to balance the budget. + +Somehow, in 1789, creditors of the French government were more powerful than they had been in 1720. + +Therefore, King Louis XVI convened the Estates General together to ask them to redesign the French constitution in a way that would lower government expenditures or increase taxes, thereby +allowing him to balance the budget while also honoring his promises to creditors of the French government. + +The King called the Estates General together in an effort to promote the reforms that would +would bring sustained budget balance. + +{cite}`sargent_velde1995` describe how the French Revolutionaries set out to accomplish that. + +## Nationalization, Privatization, Debt Reduction + +In 1789, the Revolutionaries quickly reorganized the Estates General into a National Assembly. + +A first piece of business was to address the fiscal crisis, the situation that had motivated the King to convene the Estates General. + +The Revolutionaries were not socialists or communists. + +To the contrary, they respected private property and knew state-of-the-art economics. + +They knew that to honor government debts, they would have to raise new revenues or reduce expenditures. + +A coincidence was that the Catholic Church owned vast income-producing properties. + +Indeed, the capitalized value of those income streams put estimates of the value of church lands at +about the same amount as the entire French government debt. + +This coincidence fostered a three step plan for servicing the French government debt + + * nationalize the church lands -- i.e., sequester or confiscate it without paying for it + * sell the church lands + * use the proceeds from those sales to service or even retire French government debt + +The monetary theory underlying this plan had been set out by Adam Smith in his analysis of what he called *real bills* in his 1776 book +**The Wealth of Nations** {cite}`smith2010wealth`, which many of the revolutionaries had read. + +Adam Smith defined a *real bill* as a paper money note that is backed by a claims on a real asset like productive capital or inventories. + +The National Assembly put together an ingenious institutional arrangement to implement this plan. + +In response to a motion by Catholic Bishop Talleyrand (an atheist), +the National Assembly confiscated and nationalized Church lands. + +The National Assembly intended to use earnings from Church lands to service its national debt. + +To do this, it began to implement a ''privatization plan'' that would let it service its debt while +not raising taxes. + +Their plan involved issuing paper notes called ''assignats'' that entitled bearers to use them to purchase state lands. + +These paper notes would be ''as good as silver coins'' in the sense that both were acceptable means of payment in exchange for those (formerly) church lands. + +Finance Minister Necker and the Constituents of the National Assembly thus planned +to solve the privatization problem *and* the debt problem simultaneously +by creating a new currency. + +They devised a scheme to raise revenues by auctioning +the confiscated lands, thereby withdrawing paper notes issued on the security of +the lands sold by the government. + + This ''tax-backed money'' scheme propelled the National Assembly into the domains of then modern monetary theories. + +Records of debates show +how members of the Assembly marshaled theory and evidence to assess the likely +effects of their innovation. + + * Members of the National Assembly quoted David Hume and Adam Smith + * They cited John Law's System of 1720 and the American experiences with paper money fifteen years +earlier as examples of how paper money schemes can go awry + * Knowing pitfalls, they set out to avoid them + +They succeeded for two or three years. + +But after that, France entered a big War that disrupted the plan in ways that completely altered the character of France's paper money. {cite}`sargent_velde1995` describe what happened. + +## Remaking the tax code and tax administration + +In 1789 the French Revolutionaries formed a National Assembly and set out to remake French +fiscal policy. + +They wanted to honor government debts -- interests of French government creditors were well represented in the National Assembly. + +But they set out to remake the French tax code and the administrative machinery for collecting taxes. + + * they abolished many taxes + * they abolished the Ancient Regimes scheme for *tax farming* + * tax farming meant that the government had privatized tax collection by hiring private citizens -- so-called tax farmers to collect taxes, while retaining a fraction of them as payment for their services + * the great chemist Lavoisier was also a tax farmer, one of the reasons that the Committee for Public Safety sent him to the guillotine in 1794 + +As a consequence of these tax reforms, government tax revenues declined + +The next figure shows this + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Index of real per capital revenues, France" + name: fr_fig5 +--- +# Read data from Excel file +data5 = pd.read_excel(dette_url, sheet_name='Debt', usecols='K', + skiprows=41, nrows=120, header=None) + +# Plot the data +plt.figure() +plt.plot(range(1726, 1846), data5.iloc[:, 0], linewidth=0.8) + +plt.gca().spines['top'].set_visible(False) +plt.gca().spines['right'].set_visible(False) +plt.gca().set_facecolor('white') +plt.gca().tick_params(labelsize=12) +plt.xlim([1726, 1845]) +plt.ylabel('1726 = 1', fontsize=12) + +plt.tight_layout() +plt.show() +``` + +According to {numref}`fr_fig5`, tax revenues per capita did not rise to their pre 1789 levels +until after 1815, when Napoleon Bonaparte was exiled to St Helena and King Louis XVIII was restored to the French Crown. + + * from 1799 to 1814, Napoleon Bonaparte had other sources of revenues -- booty and reparations from provinces and nations that he defeated in war + + * from 1789 to 1799, the French Revolutionaries turned to another source to raise resources to pay for government purchases of goods and services and to service French government debt. + +And as the next figure shows, government expenditures exceeded tax revenues by substantial +amounts during the period form 1789 to 1799. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Spending (blue) and Revenues (orange), (real values)" + name: fr_fig11 +--- +# Read data from Excel file +data11 = pd.read_excel(assignat_url, sheet_name='Budgets', + usecols='J:K', skiprows=22, nrows=52, header=None) + +# Prepare the x-axis data +x_data = np.concatenate([ + np.arange(1791, 1794 + 8/12, 1/12), + np.arange(1794 + 9/12, 1795 + 3/12, 1/12) +]) + +# Remove NaN values from the data +data11_clean = data11.dropna() + +# Plot the data +plt.figure() +h = plt.plot(x_data, data11_clean.values[:, 0], linewidth=0.8) +h = plt.plot(x_data, data11_clean.values[:, 1], '--', linewidth=0.8) + +# Set plot properties +plt.gca().spines['top'].set_visible(False) +plt.gca().spines['right'].set_visible(False) +plt.gca().set_facecolor('white') +plt.gca().tick_params(axis='both', which='major', labelsize=12) +plt.xlim([1791, 1795 + 3/12]) +plt.xticks(np.arange(1791, 1796)) +plt.yticks(np.arange(0, 201, 20)) + +# Set the y-axis label +plt.ylabel('millions of livres', fontsize=12) + +plt.tight_layout() +plt.show() +``` + +To cover the discrepancies between government expenditures and tax revenues revealed in {numref}`fr_fig11`, the French revolutionaries printed paper money and spent it. + +The next figure shows that by printing money, they were able to finance substantial purchases +of goods and services, including military goods and soldiers' pay. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Revenues raised by printing paper money notes" + name: fr_fig24 +--- +# Read data from Excel file +data12 = pd.read_excel(assignat_url, sheet_name='seignor', + usecols='F', skiprows=6, nrows=75, header=None).squeeze() + +# Create a figure and plot the data +plt.figure() +plt.plot(pd.date_range(start='1790', periods=len(data12), freq='M'), + data12, linewidth=0.8) + +plt.gca().spines['top'].set_visible(False) +plt.gca().spines['right'].set_visible(False) + +plt.axhline(y=472.42/12, color='r', linestyle=':') +plt.xticks(ticks=pd.date_range(start='1790', + end='1796', freq='AS'), labels=range(1790, 1797)) +plt.xlim(pd.Timestamp('1791'), + pd.Timestamp('1796-02') + pd.DateOffset(months=2)) +plt.ylabel('millions of livres', fontsize=12) +plt.text(pd.Timestamp('1793-11'), 39.5, 'revenues in 1788', + verticalalignment='top', fontsize=12) + +plt.tight_layout() +plt.show() +``` + +{numref}`fr_fig24` compares the revenues raised by printing money from 1789 to 1796 with tax revenues that the Ancient Regime had raised in 1788. + +Measured in goods, revenues raised at time $t$ by printing new money equal + +$$ +\frac{M_{t+1} - M_t}{p_t} +$$ + +where + +* $M_t$ is the stock of paper money at time $t$ measured in livres +* $p_t$ is the price level at time $t$ measured in units of goods per livre at time $t$ +* $M_{t+1} - M_t$ is the amount of new money printed at time $t$ + +Notice the 1793-1794 surge in revenues raised by printing money. + +* This reflects extraordinary measures that the Committee for Public Safety adopted to force citizens to accept paper money, or else. + +Also note the abrupt fall off in revenues raised by 1797 and the absence of further observations after 1797. + +* This reflects the end of using the printing press to raise revenues. + +What French paper money entitled its holders to changed over time in interesting ways. + +These led to outcomes that vary over time and that illustrate the playing out in practice of theories that guided the Revolutionaries' monetary policy decisions. + + +The next figure shows the price level in France during the time that the Revolutionaries used paper money to finance parts of their expenditures. + +Note that we use a log scale because the price level rose so much. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Price Level and Price of Gold (log scale)" + name: fr_fig9 +--- +# Read the data from Excel file +data7 = pd.read_excel(assignat_url, sheet_name='Data', + usecols='P:Q', skiprows=4, nrows=80, header=None) +data7a = pd.read_excel(assignat_url, sheet_name='Data', + usecols='L', skiprows=4, nrows=80, header=None) +# Create the figure and plot +plt.figure() +x = np.arange(1789 + 10/12, 1796 + 5/12, 1/12) +h, = plt.plot(x, 1. / data7.iloc[:, 0], linestyle='--') +h, = plt.plot(x, 1. / data7.iloc[:, 1], color='r') + +# Set properties of the plot +plt.gca().tick_params(labelsize=12) +plt.yscale('log') +plt.xlim([1789 + 10/12, 1796 + 5/12]) +plt.gca().spines['top'].set_visible(False) +plt.gca().spines['right'].set_visible(False) + +# Add vertical lines +plt.axvline(x=1793 + 6.5/12, linestyle='-', linewidth=0.8, color='orange') +plt.axvline(x=1794 + 6.5/12, linestyle='-', linewidth=0.8, color='purple') + +# Add text +plt.text(1793.75, 120, 'Terror', fontsize=12) +plt.text(1795, 2.8, 'price level', fontsize=12) +plt.text(1794.9, 40, 'gold', fontsize=12) + + +plt.tight_layout() +plt.show() +``` + +We have partioned {numref}`fr_fig9` that shows the log of the price level and {numref}`fr_fig8` +below that plots real balances $\frac{M_t}{p_t}$ into three periods that correspond to different monetary experiments or *regimes*. + +The first period ends in the late summer of 1793, and is characterized +by growing real balances and moderate inflation. + +The second period begins and ends +with the Terror. It is marked by high real balances, around 2,500 million, and +roughly stable prices. The fall of Robespierre in late July 1794 begins the third +of our episodes, in which real balances decline and prices rise rapidly. + +We interpret +these three episodes in terms of distinct theories + +* a *backing* or *real bills* theory (the classic text for this theory is Adam Smith {cite}`smith2010wealth`) +* a legal restrictions theory ( {cite}`keynes1940pay`, {cite}`bryant1984price` ) +* a classical hyperinflation theory ({cite}`Cagan`) +* +```{note} +According to the empirical definition of hyperinflation adopted by {cite}`Cagan`, +beginning in the month that inflation exceeds 50 percent +per month and ending in the month before inflation drops below 50 percent per month +for at least a year, the *assignat* experienced a hyperinflation from May to December +1795. +``` +We view these +theories not as competitors but as alternative collections of ''if-then'' +statements about government note issues, each of which finds its conditions more +nearly met in one of these episodes than in the other two. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Real balances of assignats (in gold and goods)" + name: fr_fig8 +--- +# Read the data from Excel file +data7 = pd.read_excel(assignat_url, sheet_name='Data', + usecols='P:Q', skiprows=4, nrows=80, header=None) +data7a = pd.read_excel(assignat_url, sheet_name='Data', + usecols='L', skiprows=4, nrows=80, header=None) + +# Create the figure and plot +plt.figure() +h = plt.plot(pd.date_range(start='1789-11-01', periods=len(data7), freq='M'), + (data7a.values * [1, 1]) * data7.values, linewidth=1.) +plt.setp(h[1], linestyle='--', color='red') + +plt.vlines([pd.Timestamp('1793-07-15'), pd.Timestamp('1793-07-15')], + 0, 3000, linewidth=0.8, color='orange') +plt.vlines([pd.Timestamp('1794-07-15'), pd.Timestamp('1794-07-15')], + 0, 3000, linewidth=0.8, color='purple') + +plt.ylim([0, 3000]) + +# Set properties of the plot +plt.gca().spines['top'].set_visible(False) +plt.gca().spines['right'].set_visible(False) +plt.gca().set_facecolor('white') +plt.gca().tick_params(labelsize=12) +plt.xlim(pd.Timestamp('1789-11-01'), pd.Timestamp('1796-06-01')) +plt.ylabel('millions of livres', fontsize=12) + +# Add text annotations +plt.text(pd.Timestamp('1793-09-01'), 200, 'Terror', fontsize=12) +plt.text(pd.Timestamp('1791-05-01'), 750, 'gold value', fontsize=12) +plt.text(pd.Timestamp('1794-10-01'), 2500, 'real value', fontsize=12) + + +plt.tight_layout() +plt.show() +``` + +The three clouds of points in Figure +{numref}`fr_fig104` + depict different real balance-inflation relationships. + +Only the cloud for the +third period has the inverse relationship familiar to us now from twentieth-century +hyperinflations. + + + + +* subperiod 1: ("*real bills* period): January 1791 to July 1793 + +* subperiod 2: ("terror"): August 1793 - July 1794 + +* subperiod 3: ("classic Cagan hyperinflation"): August 1794 - March 1796 + +```{code-cell} ipython3 +def fit(x, y): + + b = np.cov(x, y)[0, 1] / np.var(x) + a = y.mean() - b * x.mean() + + return a, b +``` + +```{code-cell} ipython3 +# Load data +caron = np.load('datasets/caron.npy') +nom_balances = np.load('datasets/nom_balances.npy') + +infl = np.concatenate(([np.nan], + -np.log(caron[1:63, 1] / caron[0:62, 1]))) +bal = nom_balances[14:77, 1] * caron[:, 1] / 1000 +``` + +```{code-cell} ipython3 +# Regress y on x for three periods +a1, b1 = fit(bal[1:31], infl[1:31]) +a2, b2 = fit(bal[31:44], infl[31:44]) +a3, b3 = fit(bal[44:63], infl[44:63]) + +# Regress x on y for three periods +a1_rev, b1_rev = fit(infl[1:31], bal[1:31]) +a2_rev, b2_rev = fit(infl[31:44], bal[31:44]) +a3_rev, b3_rev = fit(infl[44:63], bal[44:63]) +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Inflation and Real Balances" + name: fr_fig104 +--- +plt.figure() +plt.gca().spines['top'].set_visible(False) +plt.gca().spines['right'].set_visible(False) + +# First subsample +plt.plot(bal[1:31], infl[1:31], 'o', markerfacecolor='none', + color='blue', label='real bills period') + +# Second subsample +plt.plot(bal[31:44], infl[31:44], '+', color='red', label='terror') + +# Third subsample +plt.plot(bal[44:63], infl[44:63], '*', + color='orange', label='classic Cagan hyperinflation') + +plt.xlabel('real balances') +plt.ylabel('inflation') +plt.legend() + +plt.tight_layout() +plt.show() +``` + +The three clouds of points in {numref}`fr_fig104` evidently + depict different real balance-inflation relationships. + +Only the cloud for the +third period has the inverse relationship familiar to us now from twentieth-century +hyperinflations. + + To bring this out, we'll use linear regressions to draw straight lines that compress the + inflation-real balance relationship for our three sub-periods. + + Before we do that, we'll drop some of the early observations during the terror period + to obtain the following graph. + +```{code-cell} ipython3 +# Regress y on x for three periods +a1, b1 = fit(bal[1:31], infl[1:31]) +a2, b2 = fit(bal[31:44], infl[31:44]) +a3, b3 = fit(bal[44:63], infl[44:63]) + +# Regress x on y for three periods +a1_rev, b1_rev = fit(infl[1:31], bal[1:31]) +a2_rev, b2_rev = fit(infl[31:44], bal[31:44]) +a3_rev, b3_rev = fit(infl[44:63], bal[44:63]) +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Inflation and Real Balances" + name: fr_fig104b +--- +plt.figure() +plt.gca().spines['top'].set_visible(False) +plt.gca().spines['right'].set_visible(False) + +# First subsample +plt.plot(bal[1:31], infl[1:31], 'o', markerfacecolor='none', color='blue', label='real bills period') + +# Second subsample +plt.plot(bal[34:44], infl[34:44], '+', color='red', label='terror') + +# Third subsample +plt.plot(bal[44:63], infl[44:63], '*', color='orange', label='classic Cagan hyperinflation') + +plt.xlabel('real balances') +plt.ylabel('inflation') +plt.legend() + +plt.tight_layout() +plt.show() +``` + +Now let's regress inflation on real balances during the *real bills* period and plot the regression +line. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Inflation and Real Balances" + name: fr_fig104c +--- +plt.figure() +plt.gca().spines['top'].set_visible(False) +plt.gca().spines['right'].set_visible(False) + +# First subsample +plt.plot(bal[1:31], infl[1:31], 'o', markerfacecolor='none', + color='blue', label='real bills period') +plt.plot(bal[1:31], a1 + bal[1:31] * b1, color='blue') + +# Second subsample +plt.plot(bal[31:44], infl[31:44], '+', color='red', label='terror') + +# Third subsample +plt.plot(bal[44:63], infl[44:63], '*', + color='orange', label='classic Cagan hyperinflation') + +plt.xlabel('real balances') +plt.ylabel('inflation') +plt.legend() + +plt.tight_layout() +plt.show() +``` + +The regression line in {numref}`fr_fig104c` shows that large increases in real balances of +assignats (paper money) were accompanied by only modest rises in the price level, an outcome in line +with the *real bills* theory. + +During this period, assignats were claims on church lands. + +But towards the end of this period, the price level started to rise and real balances to fall +as the government continued to print money but stopped selling church land. + +To get people to hold that paper money, the government forced people to hold it by using legal restrictions. + +Now let's regress real balances on inflation during the terror and plot the regression +line. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Inflation and Real Balances" + name: fr_fig104d +--- +plt.figure() +plt.gca().spines['top'].set_visible(False) +plt.gca().spines['right'].set_visible(False) + +# First subsample +plt.plot(bal[1:31], infl[1:31], 'o', markerfacecolor='none', + color='blue', label='real bills period') + +# Second subsample +plt.plot(bal[31:44], infl[31:44], '+', color='red', label='terror') +plt.plot(a2_rev + b2_rev * infl[31:44], infl[31:44], color='red') + +# Third subsample +plt.plot(bal[44:63], infl[44:63], '*', + color='orange', label='classic Cagan hyperinflation') + +plt.xlabel('real balances') +plt.ylabel('inflation') +plt.legend() + +plt.tight_layout() +plt.show() +``` + +The regression line in {numref}`fr_fig104d` shows that large increases in real balances of +assignats (paper money) were accompanied by little upward price level pressure, even some declines in prices. + +This reflects how well legal restrictions -- financial repression -- was working during the period of the Terror. + +But the Terror ended in July 1794. That unleashed a big inflation as people tried to find other ways to transact and store values. + +The following two graphs are for the classical hyperinflation period. + +One regresses inflation on real balances, the other regresses real balances on inflation. + +Both show a prounced inverse relationship that is the hallmark of the hyperinflations studied by +Cagan {cite}`Cagan`. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Inflation and Real Balances" + name: fr_fig104e +--- +plt.figure() +plt.gca().spines['top'].set_visible(False) +plt.gca().spines['right'].set_visible(False) + +# First subsample +plt.plot(bal[1:31], infl[1:31], 'o', markerfacecolor='none', + color='blue', label='real bills period') + +# Second subsample +plt.plot(bal[31:44], infl[31:44], '+', color='red', label='terror') + +# Third subsample +plt.plot(bal[44:63], infl[44:63], '*', + color='orange', label='classic Cagan hyperinflation') +plt.plot(bal[44:63], a3 + bal[44:63] * b3, color='orange') + +plt.xlabel('real balances') +plt.ylabel('inflation') +plt.legend() + +plt.tight_layout() +plt.show() +``` + +{numref}`fr_fig104e` shows the results of regressing inflation on real balances during the +period of the hyperinflation. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Inflation and Real Balances" + name: fr_fig104f +--- +plt.figure() +plt.gca().spines['top'].set_visible(False) +plt.gca().spines['right'].set_visible(False) + +# First subsample +plt.plot(bal[1:31], infl[1:31], 'o', + markerfacecolor='none', color='blue', label='real bills period') + +# Second subsample +plt.plot(bal[31:44], infl[31:44], '+', color='red', label='terror') + +# Third subsample +plt.plot(bal[44:63], infl[44:63], '*', + color='orange', label='classic Cagan hyperinflation') +plt.plot(a3_rev + b3_rev * infl[44:63], infl[44:63], color='orange') + +plt.xlabel('real balances') +plt.ylabel('inflation') +plt.legend() + +plt.tight_layout() +plt.show() +``` + +{numref}`fr_fig104e` shows the results of regressing real money balances on inflation during the +period of the hyperinflation. + +## Hyperinflation Ends + +{cite}`sargent_velde1995` tell how in 1797 the Revolutionary government abruptly ended the inflation by + + * repudiating 2/3 of the national debt, and thereby + * eliminating the net-of-interest government defict + * no longer printing money, but instead + * using gold and silver coins as money + +In 1799, Napoleon Bonaparte became first consul and for the next 15 years used resources confiscated from conquered territories to help pay for French government expenditures. + +## Underlying Theories + +This lecture sets the stage for studying theories of inflation and the government monetary and fiscal policies that bring it about. + +A *monetarist theory of the price level* is described in this quantecon lecture {doc}`cagan_ree`. + +That lecture sets the stage for these quantecon lectures {doc}`money_inflation` and {doc}`unpleasant`. diff --git a/content/lectures/geom_series.ipynb b/book/_build/html/_sources/geom_series.ipynb similarity index 94% rename from content/lectures/geom_series.ipynb rename to book/_build/html/_sources/geom_series.ipynb index c03a75c..ee279f3 100644 --- a/content/lectures/geom_series.ipynb +++ b/book/_build/html/_sources/geom_series.ipynb @@ -2,11 +2,11 @@ "cells": [ { "cell_type": "markdown", - "id": "226cf3d1", + "id": "dad4c518", "metadata": {}, "source": [ "(geom_series)=\n", - "```{raw} html\n", + "```{raw} jupyter\n", "
\n", " \n", " \"QuantEcon\"\n", @@ -19,10 +19,6 @@ "\n", "# Geometric Series for Elementary Economics\n", "\n", - "```{contents} Contents\n", - ":depth: 2\n", - "```\n", - "\n", "## Overview\n", "\n", "The lecture describes important ideas in economics that use the mathematics of geometric series.\n", @@ -39,7 +35,7 @@ "These and other applications prove the truth of the wise crack that\n", "\n", "```{epigraph}\n", - "\"in economics, a little knowledge of geometric series goes a long way \"\n", + "\"In economics, a little knowledge of geometric series goes a long way.\"\n", "```\n", "\n", "Below we'll use the following imports:" @@ -48,26 +44,24 @@ { "cell_type": "code", "execution_count": null, - "id": "094cd466", + "id": "978932ba", "metadata": {}, "outputs": [], "source": [ - "%matplotlib inline\n", "import matplotlib.pyplot as plt\n", "plt.rcParams[\"figure.figsize\"] = (11, 5) #set default figure size\n", "import numpy as np\n", "import sympy as sym\n", - "from sympy import init_printing, latex\n", - "from matplotlib import cm\n", - "from mpl_toolkits.mplot3d import Axes3D" + "from sympy import init_printing\n", + "from matplotlib import cm" ] }, { "cell_type": "markdown", - "id": "8975f692", + "id": "94b12a31", "metadata": {}, "source": [ - "## Key Formulas\n", + "## Key formulas\n", "\n", "To start, let $c$ be a real number that lies strictly between\n", "$-1$ and $1$.\n", @@ -79,7 +73,7 @@ "\n", "We want to evaluate geometric series of two types -- infinite and finite.\n", "\n", - "### Infinite Geometric Series\n", + "### Infinite geometric series\n", "\n", "The first type of geometric that interests us is the infinite series\n", "\n", @@ -101,7 +95,7 @@ "that if $c \\in (-1,1)$, then the outcome is the\n", "equation $1 = 1$.\n", "\n", - "### Finite Geometric Series\n", + "### Finite geometric series\n", "\n", "The second series that interests us is the finite geometric series\n", "\n", @@ -117,9 +111,12 @@ "1 + c + c^2 + c^3 + \\cdots + c^T = \\frac{1 - c^{T+1}}{1-c}\n", "$$\n", "\n", - "**Remark:** The above formula works for any value of the scalar\n", + "```{prf:remark}\n", + ":label: geom_formula\n", + "The above formula works for any value of the scalar\n", "$c$. We don't have to restrict $c$ to be in the\n", "set $(-1,1)$.\n", + "```\n", "\n", "We now move on to describe some famous economic applications of\n", "geometric series.\n", @@ -154,7 +151,7 @@ "The geometric series formula {eq}`infinite` is at the heart of the classic model of the money creation process -- one that leads us to the celebrated\n", "**money multiplier**.\n", "\n", - "### A Simple Model\n", + "### A simple model\n", "\n", "There is a set of banks named $i = 0, 1, 2, \\ldots$.\n", "\n", @@ -176,7 +173,7 @@ "namely, the deposits $D_i$ held by its depositors; these are\n", "IOU's from the bank to its depositors in the form of either checking\n", "accounts or savings accounts (or before 1914, bank notes issued by a\n", - "bank stating promises to redeem note for gold or silver on demand).\n", + "bank stating promises to redeem notes for gold or silver on demand).\n", "\n", "Each bank $i$ sets its reserves to satisfy the equation\n", "\n", @@ -260,7 +257,7 @@ "\\sum_{i=0}^\\infty (1-r)^i D_0 = \\frac{D_0}{1 - (1-r)} = \\frac{D_0}{r}\n", "```\n", "\n", - "### Money Multiplier\n", + "### Money multiplier\n", "\n", "The **money multiplier** is a number that tells the multiplicative\n", "factor by which an exogenous injection of cash into bank $0$ leads\n", @@ -286,7 +283,7 @@ " equal demand** (e.g., prices and interest rates are frozen)\n", "- national income is entirely determined by aggregate demand\n", "\n", - "### Static Version\n", + "### Static version\n", "\n", "An elementary Keynesian model of national income determination consists\n", "of three equations that describe aggregate demand for $y$ and its\n", @@ -348,7 +345,7 @@ "of the multiplier as the outcome of a dynamic process that we describe\n", "next.\n", "\n", - "### Dynamic Version\n", + "### Dynamic version\n", "\n", "We arrive at a dynamic version by interpreting the nonnegative integer\n", "$t$ as indexing time and changing our specification of the\n", @@ -549,7 +546,7 @@ "So if someone has a claim on $x$ dollars at time $t+j$, it\n", "is worth $x R^{-j}$ dollars at time $t$ (e.g., today).\n", "\n", - "### Application to Asset Pricing\n", + "### Application to asset pricing\n", "\n", "A **lease** requires a payments stream of $x_t$ dollars at\n", "times $t = 0, 1, 2, \\ldots$ where\n", @@ -567,7 +564,7 @@ "The **present value** of the lease is\n", "\n", "$$\n", - "\\begin{aligned} p_0 & = x_0 + x_1/R + x_2/(R^2) + \\ddots \\\\\n", + "\\begin{aligned} p_0 & = x_0 + x_1/R + x_2/(R^2) + \\cdots \\\\\n", " & = x_0 (1 + G R^{-1} + G^2 R^{-2} + \\cdots ) \\\\\n", " & = x_0 \\frac{1}{1 - G R^{-1}} \\end{aligned}\n", "$$\n", @@ -578,7 +575,7 @@ "and $r > g$ and that $r$ and $g$ are typically small\n", "numbers, e.g., .05 or .03.\n", "\n", - "Use the Taylor series of $\\frac{1}{1+r}$ about $r=0$,\n", + "Use the [Taylor series](https://en.wikipedia.org/wiki/Taylor_series) of $\\frac{1}{1+r}$ about $r=0$,\n", "namely,\n", "\n", "$$\n", @@ -646,7 +643,7 @@ "Expanding:\n", "\n", "$$\n", - "\\begin{aligned} p_0 &=\\frac{x_0(1-1+(T+1)^2 rg -r(T+1)+g(T+1))}{1-1+r-g+rg} \\\\&=\\frac{x_0(T+1)((T+1)rg+r-g)}{r-g+rg} \\\\ &\\approx \\frac{x_0(T+1)(r-g)}{r-g}+\\frac{x_0rg(T+1)}{r-g}\\\\ &= x_0(T+1) + \\frac{x_0rg(T+1)}{r-g} \\end{aligned}\n", + "\\begin{aligned} p_0 &=\\frac{x_0(1-1+(T+1)^2 rg +r(T+1)-g(T+1))}{1-1+r-g+rg} \\\\&=\\frac{x_0(T+1)((T+1)rg+r-g)}{r-g+rg} \\\\ &= \\frac{x_0(T+1)(r-g)}{r-g + rg}+\\frac{x_0rg(T+1)^2}{r-g+rg}\\\\ &\\approx \\frac{x_0(T+1)(r-g)}{r-g}+\\frac{x_0rg(T+1)}{r-g}\\\\ &= x_0(T+1) + \\frac{x_0rg(T+1)}{r-g} \\end{aligned}\n", "$$\n", "\n", "We could have also approximated by removing the second term\n", @@ -664,7 +661,7 @@ { "cell_type": "code", "execution_count": null, - "id": "31b118f8", + "id": "bdf48e0e", "metadata": {}, "outputs": [], "source": [ @@ -692,7 +689,7 @@ }, { "cell_type": "markdown", - "id": "b60302a8", + "id": "051d82c4", "metadata": {}, "source": [ "Now that we have defined our functions, we can plot some outcomes.\n", @@ -703,7 +700,7 @@ { "cell_type": "code", "execution_count": null, - "id": "068dc539", + "id": "78eea995", "metadata": { "mystnb": { "figure": { @@ -741,7 +738,7 @@ }, { "cell_type": "markdown", - "id": "8980b721", + "id": "314d9cda", "metadata": {}, "source": [ "Evidently our approximations perform well for small values of $T$.\n", @@ -755,7 +752,7 @@ { "cell_type": "code", "execution_count": null, - "id": "2b4f88ef", + "id": "9ebc6180", "metadata": { "mystnb": { "figure": { @@ -782,7 +779,7 @@ }, { "cell_type": "markdown", - "id": "fac082e3", + "id": "1e21ae05", "metadata": {}, "source": [ "The graph above shows how as duration $T \\rightarrow +\\infty$,\n", @@ -796,7 +793,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6619023b", + "id": "b0ec1aba", "metadata": { "mystnb": { "figure": { @@ -826,7 +823,7 @@ }, { "cell_type": "markdown", - "id": "ae3d992d", + "id": "1b8ef7ae", "metadata": {}, "source": [ "This graph gives a big hint for why the condition $r > g$ is\n", @@ -843,7 +840,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1b5d88cd", + "id": "d6fe35d5", "metadata": { "mystnb": { "figure": { @@ -879,7 +876,7 @@ }, { "cell_type": "markdown", - "id": "be722528", + "id": "474bd8d9", "metadata": {}, "source": [ "We can use a little calculus to study how the present value $p_0$\n", @@ -899,7 +896,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4d5229b0", + "id": "3138d456", "metadata": {}, "outputs": [], "source": [ @@ -916,7 +913,7 @@ { "cell_type": "code", "execution_count": null, - "id": "aa08e463", + "id": "6ea57fd6", "metadata": {}, "outputs": [], "source": [ @@ -928,7 +925,7 @@ { "cell_type": "code", "execution_count": null, - "id": "d4d62cc6", + "id": "306c8e06", "metadata": {}, "outputs": [], "source": [ @@ -939,7 +936,7 @@ }, { "cell_type": "markdown", - "id": "2ea7388f", + "id": "5aae5ee7", "metadata": {}, "source": [ "We can see that for $\\frac{\\partial p_0}{\\partial r}<0$ as long as\n", @@ -949,7 +946,7 @@ "Similarly, $\\frac{\\partial p_0}{\\partial g}>0$ as long as $r>g$, $r>0$ and $g>0$ and $x_0$ is positive, so $\\frac{\\partial p_0}{\\partial g}$\n", "will always be positive.\n", "\n", - "## Back to the Keynesian Multiplier\n", + "## Back to the Keynesian multiplier\n", "\n", "We will now go back to the case of the Keynesian multiplier and plot the\n", "time path of $y_t$, given that consumption is a constant fraction\n", @@ -959,7 +956,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f26736cc", + "id": "aafad7c9", "metadata": { "mystnb": { "figure": { @@ -997,7 +994,7 @@ }, { "cell_type": "markdown", - "id": "5799b7b0", + "id": "8c9e73bd", "metadata": {}, "source": [ "In this model, income grows over time, until it gradually converges to\n", @@ -1011,7 +1008,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e2ff233b", + "id": "2d6ef7a4", "metadata": { "mystnb": { "figure": { @@ -1037,7 +1034,7 @@ }, { "cell_type": "markdown", - "id": "d754b9a1", + "id": "2737c171", "metadata": {}, "source": [ "Increasing the marginal propensity to consume $b$ increases the\n", @@ -1049,7 +1046,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b7c517db", + "id": "94acefe5", "metadata": { "mystnb": { "figure": { @@ -1085,7 +1082,7 @@ }, { "cell_type": "markdown", - "id": "27f9d268", + "id": "246763b2", "metadata": {}, "source": [ "Notice here, whether government spending increases from 0.3 to 0.4 or\n", @@ -1095,12 +1092,45 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.5" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 12, + 49, + 56, + 654, + 675, + 681, + 711, + 720, + 739, + 748, + 770, + 782, + 810, + 825, + 836, + 842, + 846, + 861, + 891, + 900, + 918, + 925, + 953 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/geom_series.md b/book/_build/html/_sources/geom_series.md new file mode 100644 index 0000000..0ea9727 --- /dev/null +++ b/book/_build/html/_sources/geom_series.md @@ -0,0 +1,957 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.5 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +(geom_series)= +```{raw} jupyter + +``` + +```{index} single: python +``` + +# Geometric Series for Elementary Economics + +## Overview + +The lecture describes important ideas in economics that use the mathematics of geometric series. + +Among these are + +- the Keynesian **multiplier** +- the money **multiplier** that prevails in fractional reserve banking + systems +- interest rates and present values of streams of payouts from assets + +(As we shall see below, the term **multiplier** comes down to meaning **sum of a convergent geometric series**) + +These and other applications prove the truth of the wise crack that + +```{epigraph} +"In economics, a little knowledge of geometric series goes a long way." +``` + +Below we'll use the following imports: + +```{code-cell} ipython +import matplotlib.pyplot as plt +plt.rcParams["figure.figsize"] = (11, 5) #set default figure size +import numpy as np +import sympy as sym +from sympy import init_printing +from matplotlib import cm +``` + +## Key formulas + +To start, let $c$ be a real number that lies strictly between +$-1$ and $1$. + +- We often write this as $c \in (-1,1)$. +- Here $(-1,1)$ denotes the collection of all real numbers that + are strictly less than $1$ and strictly greater than $-1$. +- The symbol $\in$ means *in* or *belongs to the set after the symbol*. + +We want to evaluate geometric series of two types -- infinite and finite. + +### Infinite geometric series + +The first type of geometric that interests us is the infinite series + +$$ +1 + c + c^2 + c^3 + \cdots +$$ + +Where $\cdots$ means that the series continues without end. + +The key formula is + +```{math} +:label: infinite + +1 + c + c^2 + c^3 + \cdots = \frac{1}{1 -c } +``` + +To prove key formula {eq}`infinite`, multiply both sides by $(1-c)$ and verify +that if $c \in (-1,1)$, then the outcome is the +equation $1 = 1$. + +### Finite geometric series + +The second series that interests us is the finite geometric series + +$$ +1 + c + c^2 + c^3 + \cdots + c^T +$$ + +where $T$ is a positive integer. + +The key formula here is + +$$ +1 + c + c^2 + c^3 + \cdots + c^T = \frac{1 - c^{T+1}}{1-c} +$$ + +```{prf:remark} +:label: geom_formula +The above formula works for any value of the scalar +$c$. We don't have to restrict $c$ to be in the +set $(-1,1)$. +``` + +We now move on to describe some famous economic applications of +geometric series. + +## Example: The Money Multiplier in Fractional Reserve Banking + +In a fractional reserve banking system, banks hold only a fraction +$r \in (0,1)$ of cash behind each **deposit receipt** that they +issue + +* In recent times + - cash consists of pieces of paper issued by the government and + called dollars or pounds or $\ldots$ + - a *deposit* is a balance in a checking or savings account that + entitles the owner to ask the bank for immediate payment in cash +* When the UK and France and the US were on either a gold or silver + standard (before 1914, for example) + - cash was a gold or silver coin + - a *deposit receipt* was a *bank note* that the bank promised to + convert into gold or silver on demand; (sometimes it was also a + checking or savings account balance) + +Economists and financiers often define the **supply of money** as an +economy-wide sum of **cash** plus **deposits**. + +In a **fractional reserve banking system** (one in which the reserve +ratio $r$ satisfies $0 < r < 1$), **banks create money** by issuing deposits *backed* by fractional reserves plus loans that they make to their customers. + +A geometric series is a key tool for understanding how banks create +money (i.e., deposits) in a fractional reserve system. + +The geometric series formula {eq}`infinite` is at the heart of the classic model of the money creation process -- one that leads us to the celebrated +**money multiplier**. + +### A simple model + +There is a set of banks named $i = 0, 1, 2, \ldots$. + +Bank $i$'s loans $L_i$, deposits $D_i$, and +reserves $R_i$ must satisfy the balance sheet equation (because +**balance sheets balance**): + +```{math} +:label: balance + +L_i + R_i = D_i +``` + +The left side of the above equation is the sum of the bank's **assets**, +namely, the loans $L_i$ it has outstanding plus its reserves of +cash $R_i$. + +The right side records bank $i$'s liabilities, +namely, the deposits $D_i$ held by its depositors; these are +IOU's from the bank to its depositors in the form of either checking +accounts or savings accounts (or before 1914, bank notes issued by a +bank stating promises to redeem notes for gold or silver on demand). + +Each bank $i$ sets its reserves to satisfy the equation + +```{math} +:label: reserves + +R_i = r D_i +``` + +where $r \in (0,1)$ is its **reserve-deposit ratio** or **reserve +ratio** for short + +- the reserve ratio is either set by a government or chosen by banks + for precautionary reasons + +Next we add a theory stating that bank $i+1$'s deposits depend +entirely on loans made by bank $i$, namely + +```{math} +:label: deposits + +D_{i+1} = L_i +``` + +Thus, we can think of the banks as being arranged along a line with +loans from bank $i$ being immediately deposited in $i+1$ + +- in this way, the debtors to bank $i$ become creditors of + bank $i+1$ + +Finally, we add an *initial condition* about an exogenous level of bank +$0$'s deposits + +$$ +D_0 \ \text{ is given exogenously} +$$ + +We can think of $D_0$ as being the amount of cash that a first +depositor put into the first bank in the system, bank number $i=0$. + +Now we do a little algebra. + +Combining equations {eq}`balance` and {eq}`reserves` tells us that + +```{math} +:label: fraction + +L_i = (1-r) D_i +``` + +This states that bank $i$ loans a fraction $(1-r)$ of its +deposits and keeps a fraction $r$ as cash reserves. + +Combining equation {eq}`fraction` with equation {eq}`deposits` tells us that + +$$ +D_{i+1} = (1-r) D_i \ \text{ for } i \geq 0 +$$ + +which implies that + +```{math} +:label: geomseries + +D_i = (1 - r)^i D_0 \ \text{ for } i \geq 0 +``` + +Equation {eq}`geomseries` expresses $D_i$ as the $i$ th term in the +product of $D_0$ and the geometric series + +$$ +1, (1-r), (1-r)^2, \cdots +$$ + +Therefore, the sum of all deposits in our banking system +$i=0, 1, 2, \ldots$ is + +```{math} +:label: sumdeposits + +\sum_{i=0}^\infty (1-r)^i D_0 = \frac{D_0}{1 - (1-r)} = \frac{D_0}{r} +``` + +### Money multiplier + +The **money multiplier** is a number that tells the multiplicative +factor by which an exogenous injection of cash into bank $0$ leads +to an increase in the total deposits in the banking system. + +Equation {eq}`sumdeposits` asserts that the **money multiplier** is +$\frac{1}{r}$ + +- An initial deposit of cash of $D_0$ in bank $0$ leads + the banking system to create total deposits of $\frac{D_0}{r}$. +- The initial deposit $D_0$ is held as reserves, distributed + throughout the banking system according to $D_0 = \sum_{i=0}^\infty R_i$. + +## Example: The Keynesian Multiplier + +The famous economist John Maynard Keynes and his followers created a +simple model intended to determine national income $y$ in +circumstances in which + +- there are substantial unemployed resources, in particular **excess + supply** of labor and capital +- prices and interest rates fail to adjust to make aggregate **supply + equal demand** (e.g., prices and interest rates are frozen) +- national income is entirely determined by aggregate demand + +### Static version + +An elementary Keynesian model of national income determination consists +of three equations that describe aggregate demand for $y$ and its +components. + +The first equation is a national income identity asserting that +consumption $c$ plus investment $i$ equals national income +$y$: + +$$ +c+ i = y +$$ + +The second equation is a Keynesian consumption function asserting that +people consume a fraction $b \in (0,1)$ of their income: + +$$ +c = b y +$$ + +The fraction $b \in (0,1)$ is called the **marginal propensity to +consume**. + +The fraction $1-b \in (0,1)$ is called the **marginal propensity +to save**. + +The third equation simply states that investment is exogenous at level +$i$. + +- *exogenous* means *determined outside this model*. + +Substituting the second equation into the first gives $(1-b) y = i$. + +Solving this equation for $y$ gives + +$$ +y = \frac{1}{1-b} i +$$ + +The quantity $\frac{1}{1-b}$ is called the **investment +multiplier** or simply the **multiplier**. + +Applying the formula for the sum of an infinite geometric series, we can +write the above equation as + +$$ +y = i \sum_{t=0}^\infty b^t +$$ + +where $t$ is a nonnegative integer. + +So we arrive at the following equivalent expressions for the multiplier: + +$$ +\frac{1}{1-b} = \sum_{t=0}^\infty b^t +$$ + +The expression $\sum_{t=0}^\infty b^t$ motivates an interpretation +of the multiplier as the outcome of a dynamic process that we describe +next. + +### Dynamic version + +We arrive at a dynamic version by interpreting the nonnegative integer +$t$ as indexing time and changing our specification of the +consumption function to take time into account + +- we add a one-period lag in how income affects consumption + +We let $c_t$ be consumption at time $t$ and $i_t$ be +investment at time $t$. + +We modify our consumption function to assume the form + +$$ +c_t = b y_{t-1} +$$ + +so that $b$ is the marginal propensity to consume (now) out of +last period's income. + +We begin with an initial condition stating that + +$$ +y_{-1} = 0 +$$ + +We also assume that + +$$ +i_t = i \ \ \textrm {for all } t \geq 0 +$$ + +so that investment is constant over time. + +It follows that + +$$ +y_0 = i + c_0 = i + b y_{-1} = i +$$ + +and + +$$ +y_1 = c_1 + i = b y_0 + i = (1 + b) i +$$ + +and + +$$ +y_2 = c_2 + i = b y_1 + i = (1 + b + b^2) i +$$ + +and more generally + +$$ +y_t = b y_{t-1} + i = (1+ b + b^2 + \cdots + b^t) i +$$ + +or + +$$ +y_t = \frac{1-b^{t+1}}{1 -b } i +$$ + +Evidently, as $t \rightarrow + \infty$, + +$$ +y_t \rightarrow \frac{1}{1-b} i +$$ + +**Remark 1:** The above formula is often applied to assert that an +exogenous increase in investment of $\Delta i$ at time $0$ +ignites a dynamic process of increases in national income by successive amounts + +$$ +\Delta i, (1 + b )\Delta i, (1+b + b^2) \Delta i , \cdots +$$ + +at times $0, 1, 2, \ldots$. + +**Remark 2** Let $g_t$ be an exogenous sequence of government +expenditures. + +If we generalize the model so that the national income identity +becomes + +$$ +c_t + i_t + g_t = y_t +$$ + +then a version of the preceding argument shows that the **government +expenditures multiplier** is also $\frac{1}{1-b}$, so that a +permanent increase in government expenditures ultimately leads to an +increase in national income equal to the multiplier times the increase +in government expenditures. + +## Example: Interest Rates and Present Values + +We can apply our formula for geometric series to study how interest +rates affect values of streams of dollar payments that extend over time. + +We work in discrete time and assume that $t = 0, 1, 2, \ldots$ +indexes time. + +We let $r \in (0,1)$ be a one-period **net nominal interest rate** + +- if the nominal interest rate is $5$ percent, + then $r= .05$ + +A one-period **gross nominal interest rate** $R$ is defined as + +$$ +R = 1 + r \in (1, 2) +$$ + +- if $r=.05$, then $R = 1.05$ + +**Remark:** The gross nominal interest rate $R$ is an **exchange +rate** or **relative price** of dollars at between times $t$ and +$t+1$. The units of $R$ are dollars at time $t+1$ per +dollar at time $t$. + +When people borrow and lend, they trade dollars now for dollars later or +dollars later for dollars now. + +The price at which these exchanges occur is the gross nominal interest +rate. + +- If I sell $x$ dollars to you today, you pay me $R x$ + dollars tomorrow. +- This means that you borrowed $x$ dollars for me at a gross + interest rate $R$ and a net interest rate $r$. + +We assume that the net nominal interest rate $r$ is fixed over +time, so that $R$ is the gross nominal interest rate at times +$t=0, 1, 2, \ldots$. + +Two important geometric sequences are + +```{math} +:label: geom1 + +1, R, R^2, \cdots +``` + +and + +```{math} +:label: geom2 + +1, R^{-1}, R^{-2}, \cdots +``` + +Sequence {eq}`geom1` tells us how dollar values of an investment **accumulate** +through time. + +Sequence {eq}`geom2` tells us how to **discount** future dollars to get their +values in terms of today's dollars. + +### Accumulation + +Geometric sequence {eq}`geom1` tells us how one dollar invested and re-invested +in a project with gross one period nominal rate of return accumulates + +- here we assume that net interest payments are reinvested in the + project +- thus, $1$ dollar invested at time $0$ pays interest + $r$ dollars after one period, so we have $r+1 = R$ + dollars at time$1$ +- at time $1$ we reinvest $1+r =R$ dollars and receive interest + of $r R$ dollars at time $2$ plus the *principal* + $R$ dollars, so we receive $r R + R = (1+r)R = R^2$ + dollars at the end of period $2$ +- and so on + +Evidently, if we invest $x$ dollars at time $0$ and +reinvest the proceeds, then the sequence + +$$ +x , xR , x R^2, \cdots +$$ + +tells how our account accumulates at dates $t=0, 1, 2, \ldots$. + +### Discounting + +Geometric sequence {eq}`geom2` tells us how much future dollars are worth in terms of today's dollars. + +Remember that the units of $R$ are dollars at $t+1$ per +dollar at $t$. + +It follows that + +- the units of $R^{-1}$ are dollars at $t$ per dollar at $t+1$ +- the units of $R^{-2}$ are dollars at $t$ per dollar at $t+2$ +- and so on; the units of $R^{-j}$ are dollars at $t$ per + dollar at $t+j$ + +So if someone has a claim on $x$ dollars at time $t+j$, it +is worth $x R^{-j}$ dollars at time $t$ (e.g., today). + +### Application to asset pricing + +A **lease** requires a payments stream of $x_t$ dollars at +times $t = 0, 1, 2, \ldots$ where + +$$ +x_t = G^t x_0 +$$ + +where $G = (1+g)$ and $g \in (0,1)$. + +Thus, lease payments increase at $g$ percent per period. + +For a reason soon to be revealed, we assume that $G < R$. + +The **present value** of the lease is + +$$ +\begin{aligned} p_0 & = x_0 + x_1/R + x_2/(R^2) + \cdots \\ + & = x_0 (1 + G R^{-1} + G^2 R^{-2} + \cdots ) \\ + & = x_0 \frac{1}{1 - G R^{-1}} \end{aligned} +$$ + +where the last line uses the formula for an infinite geometric series. + +Recall that $R = 1+r$ and $G = 1+g$ and that $R > G$ +and $r > g$ and that $r$ and $g$ are typically small +numbers, e.g., .05 or .03. + +Use the [Taylor series](https://en.wikipedia.org/wiki/Taylor_series) of $\frac{1}{1+r}$ about $r=0$, +namely, + +$$ +\frac{1}{1+r} = 1 - r + r^2 - r^3 + \cdots +$$ + +and the fact that $r$ is small to approximate +$\frac{1}{1+r} \approx 1 - r$. + +Use this approximation to write $p_0$ as + +$$ +\begin{aligned} + p_0 &= x_0 \frac{1}{1 - G R^{-1}} \\ + &= x_0 \frac{1}{1 - (1+g) (1-r) } \\ + &= x_0 \frac{1}{1 - (1+g - r - rg)} \\ + & \approx x_0 \frac{1}{r -g } +\end{aligned} +$$ + +where the last step uses the approximation $r g \approx 0$. + +The approximation + +$$ +p_0 = \frac{x_0 }{r -g } +$$ + +is known as the **Gordon formula** for the present value or current +price of an infinite payment stream $x_0 G^t$ when the nominal +one-period interest rate is $r$ and when $r > g$. + +We can also extend the asset pricing formula so that it applies to finite leases. + +Let the payment stream on the lease now be $x_t$ for $t= 1,2, \dots,T$, where again + +$$ +x_t = G^t x_0 +$$ + +The present value of this lease is: + +$$ +\begin{aligned} \begin{split}p_0&=x_0 + x_1/R + \dots +x_T/R^T \\ &= x_0(1+GR^{-1}+\dots +G^{T}R^{-T}) \\ &= \frac{x_0(1-G^{T+1}R^{-(T+1)})}{1-GR^{-1}} \end{split}\end{aligned} +$$ + +Applying the Taylor series to $R^{-(T+1)}$ about $r=0$ we get: + +$$ +\frac{1}{(1+r)^{T+1}}= 1-r(T+1)+\frac{1}{2}r^2(T+1)(T+2)+\dots \approx 1-r(T+1) +$$ + +Similarly, applying the Taylor series to $G^{T+1}$ about $g=0$: + +$$ +(1+g)^{T+1} = 1+(T+1)g+\frac{T(T+1)}{2!}g^2+\frac{(T-1)T(T+1)}{3!}g^3+\dots \approx 1+ (T+1)g +$$ + +Thus, we get the following approximation: + +$$ +p_0 =\frac{x_0(1-(1+(T+1)g)(1-r(T+1)))}{1-(1-r)(1+g) } +$$ + +Expanding: + +$$ +\begin{aligned} p_0 &=\frac{x_0(1-1+(T+1)^2 rg +r(T+1)-g(T+1))}{1-1+r-g+rg} \\&=\frac{x_0(T+1)((T+1)rg+r-g)}{r-g+rg} \\ &= \frac{x_0(T+1)(r-g)}{r-g + rg}+\frac{x_0rg(T+1)^2}{r-g+rg}\\ &\approx \frac{x_0(T+1)(r-g)}{r-g}+\frac{x_0rg(T+1)}{r-g}\\ &= x_0(T+1) + \frac{x_0rg(T+1)}{r-g} \end{aligned} +$$ + +We could have also approximated by removing the second term +$rgx_0(T+1)$ when $T$ is relatively small compared to +$1/(rg)$ to get $x_0(T+1)$ as in the finite stream +approximation. + +We will plot the true finite stream present-value and the two +approximations, under different values of $T$, and $g$ and $r$ in Python. + +First we plot the true finite stream present-value after computing it +below + +```{code-cell} ipython3 +# True present value of a finite lease +def finite_lease_pv_true(T, g, r, x_0): + G = (1 + g) + R = (1 + r) + return (x_0 * (1 - G**(T + 1) * R**(-T - 1))) / (1 - G * R**(-1)) +# First approximation for our finite lease + +def finite_lease_pv_approx_1(T, g, r, x_0): + p = x_0 * (T + 1) + x_0 * r * g * (T + 1) / (r - g) + return p + +# Second approximation for our finite lease +def finite_lease_pv_approx_2(T, g, r, x_0): + return (x_0 * (T + 1)) + +# Infinite lease +def infinite_lease(g, r, x_0): + G = (1 + g) + R = (1 + r) + return x_0 / (1 - G * R**(-1)) +``` + +Now that we have defined our functions, we can plot some outcomes. + +First we study the quality of our approximations + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Finite lease present value $T$ periods ahead" + name: finite_lease_present_value +--- +def plot_function(axes, x_vals, func, args): + axes.plot(x_vals, func(*args), label=func.__name__) + +T_max = 50 + +T = np.arange(0, T_max+1) +g = 0.02 +r = 0.03 +x_0 = 1 + +our_args = (T, g, r, x_0) +funcs = [finite_lease_pv_true, + finite_lease_pv_approx_1, + finite_lease_pv_approx_2] + # the three functions we want to compare + +fig, ax = plt.subplots() +for f in funcs: + plot_function(ax, T, f, our_args) +ax.legend() +ax.set_xlabel('$T$ Periods Ahead') +ax.set_ylabel('Present Value, $p_0$') +plt.show() +``` + +Evidently our approximations perform well for small values of $T$. + +However, holding $g$ and r fixed, our approximations deteriorate as $T$ increases. + +Next we compare the infinite and finite duration lease present values +over different lease lengths $T$. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Infinite and finite lease present value $T$ periods ahead" + name: infinite_and_finite_lease_present_value +--- +# Convergence of infinite and finite +T_max = 1000 +T = np.arange(0, T_max+1) +fig, ax = plt.subplots() +f_1 = finite_lease_pv_true(T, g, r, x_0) +f_2 = np.full(T_max+1, infinite_lease(g, r, x_0)) +ax.plot(T, f_1, label='T-period lease PV') +ax.plot(T, f_2, '--', label='Infinite lease PV') +ax.set_xlabel('$T$ Periods Ahead') +ax.set_ylabel('Present Value, $p_0$') +ax.legend() +plt.show() +``` + +The graph above shows how as duration $T \rightarrow +\infty$, +the value of a lease of duration $T$ approaches the value of a +perpetual lease. + +Now we consider two different views of what happens as $r$ and +$g$ covary + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Value of lease of length $T$" + name: value_of_lease +--- +# First view +# Changing r and g +fig, ax = plt.subplots() +ax.set_ylabel('Present Value, $p_0$') +ax.set_xlabel('$T$ periods ahead') +T_max = 10 +T=np.arange(0, T_max+1) + +rs, gs = (0.9, 0.5, 0.4001, 0.4), (0.4, 0.4, 0.4, 0.5), +comparisons = ('$\gg$', '$>$', r'$\approx$', '$<$') +for r, g, comp in zip(rs, gs, comparisons): + ax.plot(finite_lease_pv_true(T, g, r, x_0), label=f'r(={r}) {comp} g(={g})') + +ax.legend() +plt.show() +``` + +This graph gives a big hint for why the condition $r > g$ is +necessary if a lease of length $T = +\infty$ is to have finite +value. + +For fans of 3-d graphs the same point comes through in the following +graph. + +If you aren't enamored of 3-d graphs, feel free to skip the next +visualization! + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Three period lease PV with varying $g$ and $r$" + name: three_period_lease_PV +--- +# Second view +fig = plt.figure(figsize = [16, 5]) +T = 3 +ax = plt.subplot(projection='3d') +r = np.arange(0.01, 0.99, 0.005) +g = np.arange(0.011, 0.991, 0.005) + +rr, gg = np.meshgrid(r, g) +z = finite_lease_pv_true(T, gg, rr, x_0) + +# Removes points where undefined +same = (rr == gg) +z[same] = np.nan +surf = ax.plot_surface(rr, gg, z, cmap=cm.coolwarm, + antialiased=True, clim=(0, 15)) +fig.colorbar(surf, shrink=0.5, aspect=5) +ax.set_xlabel('$r$') +ax.set_ylabel('$g$') +ax.set_zlabel('Present Value, $p_0$') +ax.view_init(20, 8) +plt.show() +``` + +We can use a little calculus to study how the present value $p_0$ +of a lease varies with $r$ and $g$. + +We will use a library called [SymPy](https://www.sympy.org/). + +SymPy enables us to do symbolic math calculations including +computing derivatives of algebraic equations. + +We will illustrate how it works by creating a symbolic expression that +represents our present value formula for an infinite lease. + +After that, we'll use SymPy to compute derivatives + +```{code-cell} ipython3 +# Creates algebraic symbols that can be used in an algebraic expression +g, r, x0 = sym.symbols('g, r, x0') +G = (1 + g) +R = (1 + r) +p0 = x0 / (1 - G * R**(-1)) +init_printing(use_latex='mathjax') +print('Our formula is:') +p0 +``` + +```{code-cell} ipython3 +print('dp0 / dg is:') +dp_dg = sym.diff(p0, g) +dp_dg +``` + +```{code-cell} ipython3 +print('dp0 / dr is:') +dp_dr = sym.diff(p0, r) +dp_dr +``` + +We can see that for $\frac{\partial p_0}{\partial r}<0$ as long as +$r>g$, $r>0$ and $g>0$ and $x_0$ is positive, +so $\frac{\partial p_0}{\partial r}$ will always be negative. + +Similarly, $\frac{\partial p_0}{\partial g}>0$ as long as $r>g$, $r>0$ and $g>0$ and $x_0$ is positive, so $\frac{\partial p_0}{\partial g}$ +will always be positive. + +## Back to the Keynesian multiplier + +We will now go back to the case of the Keynesian multiplier and plot the +time path of $y_t$, given that consumption is a constant fraction +of national income, and investment is fixed. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Path of aggregate output tver time" + name: path_of_aggregate_output_over_time +--- +# Function that calculates a path of y +def calculate_y(i, b, g, T, y_init): + y = np.zeros(T+1) + y[0] = i + b * y_init + g + for t in range(1, T+1): + y[t] = b * y[t-1] + i + g + return y + +# Initial values +i_0 = 0.3 +g_0 = 0.3 +# 2/3 of income goes towards consumption +b = 2/3 +y_init = 0 +T = 100 + +fig, ax = plt.subplots() +ax.set_xlabel('$t$') +ax.set_ylabel('$y_t$') +ax.plot(np.arange(0, T+1), calculate_y(i_0, b, g_0, T, y_init)) +# Output predicted by geometric series +ax.hlines(i_0 / (1 - b) + g_0 / (1 - b), xmin=-1, xmax=101, linestyles='--') +plt.show() +``` + +In this model, income grows over time, until it gradually converges to +the infinite geometric series sum of income. + +We now examine what will +happen if we vary the so-called **marginal propensity to consume**, +i.e., the fraction of income that is consumed + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Changing consumption as a fraction of income" + name: changing_consumption_as_fraction_of_income +--- +bs = (1/3, 2/3, 5/6, 0.9) + +fig,ax = plt.subplots() +ax.set_ylabel('$y_t$') +ax.set_xlabel('$t$') +x = np.arange(0, T+1) +for b in bs: + y = calculate_y(i_0, b, g_0, T, y_init) + ax.plot(x, y, label=r'$b=$'+f"{b:.2f}") +ax.legend() +plt.show() +``` + +Increasing the marginal propensity to consume $b$ increases the +path of output over time. + +Now we will compare the effects on output of increases in investment and government spending. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Different increase on output" + name: different_increase_on_output +--- +fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 10)) +fig.subplots_adjust(hspace=0.3) + +x = np.arange(0, T+1) +values = [0.3, 0.4] + +for i in values: + y = calculate_y(i, b, g_0, T, y_init) + ax1.plot(x, y, label=f"i={i}") +for g in values: + y = calculate_y(i_0, b, g, T, y_init) + ax2.plot(x, y, label=f"g={g}") + +axes = ax1, ax2 +param_labels = "Investment", "Government Spending" +for ax, param in zip(axes, param_labels): + ax.set_title(f'An Increase in {param} on Output') + ax.legend(loc ="lower right") + ax.set_ylabel('$y_t$') + ax.set_xlabel('$t$') +plt.show() +``` + +Notice here, whether government spending increases from 0.3 to 0.4 or +investment increases from 0.3 to 0.4, the shifts in the graphs are +identical. diff --git a/book/_build/html/_sources/greek_square.ipynb b/book/_build/html/_sources/greek_square.ipynb new file mode 100644 index 0000000..baec005 --- /dev/null +++ b/book/_build/html/_sources/greek_square.ipynb @@ -0,0 +1,983 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "d2083501", + "metadata": {}, + "source": [ + "# Computing Square Roots\n", + "\n", + "\n", + "## Introduction\n", + "\n", + "Chapter 24 of {cite}`russell2004history` about early Greek mathematics and astronomy contains this\n", + "fascinating passage:\n", + "\n", + " ```{epigraph} \n", + " The square root of 2, which was the first irrational to be discovered, was known to the early Pythagoreans, and ingenious methods of approximating to its value were discovered. The best was as follows: Form two columns of numbers, which we will call the $a$'s and the $b$'s; each starts with a $1$. The next $a$, at each stage, is formed by adding the last $a$ and the $b$ already obtained; the next $b$ is formed by adding twice the previous $a$ to the previous $b$. The first 6 pairs so obtained are $(1,1), (2,3), (5,7), (12,17), (29,41), (70,99)$. In each pair, $2 a - b$ is $1$ or $-1$. Thus $b/a$ is nearly the square root of two, and at each fresh step it gets nearer. For instance, the reader may satisy himself that the square of $99/70$ is very nearly equal to $2$.\n", + " ```\n", + "\n", + "This lecture drills down and studies this ancient method for computing square roots by using some of the matrix algebra that we've learned in earlier quantecon lectures. \n", + "\n", + "In particular, this lecture can be viewed as a sequel to {doc}`eigen_I`.\n", + "\n", + "It provides an example of how eigenvectors isolate *invariant subspaces* that help construct and analyze solutions of linear difference equations. \n", + "\n", + "When vector $x_t$ starts in an invariant subspace, iterating the different equation keeps $x_{t+j}$\n", + "in that subspace for all $j \\geq 1$. \n", + "\n", + "Invariant subspace methods are used throughout applied economic dynamics, for example, in the lecture {doc}`money_inflation`.\n", + "\n", + "Our approach here is to illustrate the method with an ancient example, one that ancient Greek mathematicians used to compute square roots of positive integers.\n", + "\n", + "## Perfect squares and irrational numbers\n", + "\n", + "An integer is called a **perfect square** if its square root is also an integer.\n", + "\n", + "An ordered sequence of perfect squares starts with \n", + "\n", + "$$\n", + "4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, \\ldots \n", + "$$\n", + "\n", + "If an integer is not a perfect square, then its square root is an irrational number -- i.e., it cannot be expressed as a ratio of two integers, and its decimal expansion is indefinite.\n", + "\n", + "The ancient Greeks invented an algorithm to compute square roots of integers, including integers that are not perfect squares.\n", + "\n", + "Their method involved\n", + "\n", + " * computing a particular sequence of integers $\\{y_t\\}_{t=0}^\\infty$;\n", + " \n", + " * computing $\\lim_{t \\rightarrow \\infty} \\left(\\frac{y_{t+1}}{y_t}\\right) = \\bar r$;\n", + " \n", + " * deducing the desired square root from $\\bar r$.\n", + " \n", + "In this lecture, we'll describe this method.\n", + "\n", + "We'll also use invariant subspaces to describe variations on this method that are faster.\n", + "\n", + "## Second-order linear difference equations\n", + "\n", + "Before telling how the ancient Greeks computed square roots, we'll provide a quick introduction\n", + "to second-order linear difference equations.\n", + "\n", + "We'll study the following second-order linear difference equation\n", + "\n", + "$$\n", + "y_t = a_1 y_{t-1} + a_2 y_{t-2}, \\quad t \\geq 0\n", + "$$ (eq:2diff1)\n", + "\n", + "where $(y_{-1}, y_{-2})$ is a pair of given initial conditions. \n", + "\n", + "Equation {eq}`eq:2diff1` is actually an infinite number of linear equations in the sequence\n", + "$\\{y_t\\}_{t=0}^\\infty$.\n", + "\n", + "There is one equation each for $t = 0, 1, 2, \\ldots$. \n", + "\n", + "We could follow an approach taken in the lecture on {doc}`present values` and stack all of these equations into a single matrix equation that we would then solve by using matrix inversion.\n", + "\n", + "```{note} \n", + "In the present instance, the matrix equation would multiply a countably infinite dimensional square matrix by a countably infinite dimensional vector. With some qualifications, matrix multiplication and inversion tools apply to such an equation.\n", + "```\n", + "\n", + "But we won't pursue that approach here. \n", + "\n", + "\n", + "Instead, we'll seek to find a time-invariant function that *solves* our difference equation, meaning\n", + "that it provides a formula for a $\\{y_t\\}_{t=0}^\\infty$ sequence that satisfies \n", + "equation {eq}`eq:2diff1` for each $t \\geq 0$.\n", + "\n", + "We seek an expression for $y_t, t \\geq 0$ as functions of the initial conditions $(y_{-1}, y_{-2})$:\n", + "\n", + "$$ \n", + "y_t = g((y_{-1}, y_{-2});t), \\quad t \\geq 0.\n", + "$$ (eq:2diff2)\n", + "\n", + "We call such a function $g$ a *solution* of the difference equation {eq}`eq:2diff1`.\n", + "\n", + "One way to discover a solution is to use a guess and verify method.\n", + "\n", + "We shall begin by considering a special initial pair of initial conditions\n", + "that satisfy\n", + "\n", + "$$\n", + "y_{-1} = \\delta y_{-2}\n", + "$$ (eq:2diff3)\n", + "\n", + "where $\\delta$ is a scalar to be determined.\n", + "\n", + "For initial condition that satisfy {eq}`eq:2diff3`\n", + "equation {eq}`eq:2diff1` impllies that\n", + "\n", + "$$\n", + "y_0 = \\left(a_1 + \\frac{a_2}{\\delta}\\right) y_{-1}.\n", + "$$ (eq:2diff4)\n", + "\n", + "We want \n", + "\n", + "$$\n", + "\\left(a_1 + \\frac{a_2}{\\delta}\\right) = \\delta\n", + "$$ (eq:2diff5)\n", + "\n", + "which we can rewrite as the *characteristic equation* \n", + "\n", + "$$\n", + "\\delta^2 - a_1 \\delta - a_2 = 0.\n", + "$$ (eq:2diff6)\n", + "\n", + "Applying the quadratic formula to solve for the roots of {eq}`eq:2diff6` we find that\n", + "\n", + "$$\n", + "\\delta = \\frac{ a_1 \\pm \\sqrt{a_1^2 + 4 a_2}}{2}.\n", + "$$ (eq:2diff7)\n", + "\n", + "For either of the two $\\delta$'s that satisfy equation {eq}`eq:2diff7`, \n", + "a solution of difference equation {eq}`eq:2diff1` is \n", + "\n", + "$$\n", + "y_t = \\delta^t y_0 , \\forall t \\geq 0\n", + "$$ (eq:2diff8)\n", + "\n", + "provided that we set \n", + "\n", + "$$\n", + "y_0 = \\delta y_{-1} . \n", + "$$ \n", + "\n", + "The *general* solution of difference equation {eq}`eq:2diff1` takes the form\n", + "\n", + "$$\n", + "y_t = \\eta_1 \\delta_1^t + \\eta_2 \\delta_2^t\n", + "$$ (eq:2diff9)\n", + "\n", + "where $\\delta_1, \\delta_2$ are the two solutions {eq}`eq:2diff7` of the characteristic equation {eq}`eq:2diff6`, and $\\eta_1, \\eta_2$ are two constants chosen to satisfy\n", + " \n", + "$$ \n", + " \\begin{bmatrix} y_{-1} \\cr y_{-2} \\end{bmatrix} = \\begin{bmatrix} \\delta_1^{-1} & \\delta_2^{-1} \\cr \\delta_1^{-2} & \\delta_2^{-2} \\end{bmatrix} \\begin{bmatrix} \\eta_1 \\cr \\eta_2 \\end{bmatrix} \n", + "$$ (eq:2diff10)\n", + "\n", + "or\n", + "\n", + "$$\n", + "\\begin{bmatrix} \\eta_1 \\cr \\eta_2 \\end{bmatrix} = \\begin{bmatrix} \\delta_1^{-1} & \\delta_2^{-1} \\cr \\delta_1^{-2} & \\delta_2^{-2} \\end{bmatrix}^{-1} \\begin{bmatrix} y_{-1} \\cr y_{-2} \\end{bmatrix}\n", + "$$ (eq:2diff11)\n", + "\n", + "Sometimes we are free to choose the initial conditions $(y_{-1}, y_{-2})$, in which case we \n", + "use system {eq}`eq:2diff10` to find the associated $(\\eta_1, \\eta_2)$.\n", + "\n", + "If we choose $(y_{-1}, y_{-2})$ to set $(\\eta_1, \\eta_2) = (1, 0)$, then $y_t = \\delta_1^t$ for all $t \\geq 0$.\n", + "\n", + "\n", + "If we choose $(y_{-1}, y_{-2})$ to set $(\\eta_1, \\eta_2) = (0, 1)$, then $y_t = \\delta_2^t$ for all $t \\geq 0$.\n", + "\n", + "Soon we'll relate the preceding calculations to components an eigen decomposition of a transition matrix that represents difference equation {eq}`eq:2diff1` in a very convenient way.\n", + "\n", + "We'll turn to that after we describe how Ancient Greeks figured out how to compute square roots of positive integers that are not perfect squares.\n", + "\n", + "\n", + "## Algorithm of the Ancient Greeks\n", + "\n", + "Let $\\sigma$ be a positive integer greater than $1$.\n", + "\n", + "So $\\sigma \\in {\\mathcal I} \\equiv \\{2, 3, \\ldots \\}$.\n", + "\n", + "We want an algorithm to compute the square root of $\\sigma \\in {\\mathcal I}$.\n", + "\n", + "If $\\sqrt{\\sigma} \\in {\\mathcal I}$, $\\sigma $ is said to be a *perfect square*.\n", + "\n", + "If $\\sqrt{\\sigma} \\not\\in {\\mathcal I}$, it turns out that it is irrational.\n", + "\n", + "Ancient Greeks used a recursive algorithm to compute square roots of integers that are not perfect squares. \n", + "\n", + "The algorithm iterates on a second-order linear difference equation in the sequence $\\{y_t\\}_{t=0}^\\infty$:\n", + "\n", + "$$\n", + "y_{t} = 2 y_{t-1} - (1 - \\sigma) y_{t-2}, \\quad t \\geq 0\n", + "$$ (eq:second_order)\n", + "\n", + "together with a pair of integers that are initial conditions for $y_{-1}, y_{-2}$.\n", + "\n", + "First, we'll deploy some techniques for solving the difference equations that are also deployed in {doc}`dynam:samuelson`.\n", + "\n", + "The characteristic equation associated with difference equation {eq}`eq:second_order` is\n", + "\n", + "$$\n", + "c(x) \\equiv x^2 - 2 x + (1 - \\sigma) = 0\n", + "$$ (eq:cha_eq0)\n", + "\n", + "(Notice how this is an instance of equation {eq}`eq:2diff6` above.)\n", + "\n", + "Factoring the right side of equation {eq}`eq:cha_eq0`, we obtain \n", + "\n", + "$$\n", + "c(x)= (x - \\lambda_1) (x-\\lambda_2) = 0\n", + "$$(eq:cha_eq)\n", + "\n", + "\n", + "where \n", + "\n", + "$$ \n", + "c(x) = 0 \n", + "$$\n", + "\n", + "for $x = \\lambda_1$ or $x = \\lambda_2$.\n", + "\n", + "These two special values of $x$ are sometimes called zeros or roots of $c(x)$.\n", + "\n", + "\n", + "By applying the quadratic formula to solve for the roots the characteristic equation \n", + "{eq}`eq:cha_eq0`, we find that\n", + "\n", + "$$\n", + "\\lambda_1 = 1 + \\sqrt{\\sigma}, \\quad \\lambda_2 = 1 - \\sqrt{\\sigma}.\n", + "$$ (eq:secretweapon)\n", + "\n", + "Formulas {eq}`eq:secretweapon` indicate that $\\lambda_1$ and $\\lambda_2$ are each functions\n", + "of a single variable, namely, $\\sqrt{\\sigma}$, the object that we along with some Ancient Greeks want to compute.\n", + "\n", + "Ancient Greeks had an indirect way of exploiting this fact to compute square roots of a positive integer.\n", + "\n", + "They did this by starting from particular initial conditions $y_{-1}, y_{-2}$ and iterating on the difference equation {eq}`eq:second_order`.\n", + "\n", + "\n", + "Solutions of difference equation {eq}`eq:second_order` take the form\n", + "\n", + "$$\n", + "y_t = \\lambda_1^t \\eta_1 + \\lambda_2^t \\eta_2\n", + "$$\n", + "\n", + "where $\\eta_1$ and $\\eta_2$ are chosen to satisfy prescribed initial conditions $y_{-1}, y_{-2}$:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "\\lambda_1^{-1} \\eta_1 + \\lambda_2^{-1} \\eta_2 & = y_{-1} \\cr\n", + "\\lambda_1^{-2} \\eta_1 + \\lambda_2^{-2} \\eta_2 & = y_{-2}\n", + "\\end{aligned}\n", + "$$(eq:leq_sq)\n", + "\n", + "System {eq}`eq:leq_sq` of simultaneous linear equations will play a big role in the remainder of this lecture. \n", + "\n", + "Since $\\lambda_1 = 1 + \\sqrt{\\sigma} > 1 > \\lambda_2 = 1 - \\sqrt{\\sigma} $,\n", + "it follows that for *almost all* (but not all) initial conditions\n", + "\n", + "$$\n", + "\\lim_{t \\rightarrow \\infty} \\left(\\frac{y_{t+1}}{y_t}\\right) = 1 + \\sqrt{\\sigma}.\n", + "$$\n", + "\n", + "Thus,\n", + "\n", + "$$\n", + "\\sqrt{\\sigma} = \\lim_{t \\rightarrow \\infty} \\left(\\frac{y_{t+1}}{y_t}\\right) - 1.\n", + "$$\n", + "\n", + "However, notice that if $\\eta_1 = 0$, then\n", + "\n", + "$$\n", + "\\lim_{t \\rightarrow \\infty} \\left(\\frac{y_{t+1}}{y_t}\\right) = 1 - \\sqrt{\\sigma}\n", + "$$\n", + "\n", + "so that \n", + "\n", + "$$\n", + "\\sqrt{\\sigma} = 1 - \\lim_{t \\rightarrow \\infty} \\left(\\frac{y_{t+1}}{y_t}\\right).\n", + "$$\n", + "\n", + "Actually, if $\\eta_1 =0$, it follows that\n", + "\n", + "$$\n", + "\\sqrt{\\sigma} = 1 - \\left(\\frac{y_{t+1}}{y_t}\\right) \\quad \\forall t \\geq 0,\n", + "$$\n", + "\n", + "so that convergence is immediate and there is no need to take limits.\n", + "\n", + "Symmetrically, if $\\eta_2 =0$, it follows that \n", + "\n", + "\n", + "$$\n", + "\\sqrt{\\sigma} = \\left(\\frac{y_{t+1}}{y_t}\\right) - 1 \\quad \\forall t \\geq 0\n", + "$$\n", + "\n", + "so again, convergence is immediate, and we have no need to compute a limit.\n", + "\n", + "\n", + "System {eq}`eq:leq_sq` of simultaneous linear equations can be used in various ways.\n", + "\n", + " * we can take $y_{-1}, y_{-2}$ as given initial conditions and solve for $\\eta_1, \\eta_2$;\n", + " \n", + " * we can instead take $\\eta_1, \\eta_2$ as given and solve for initial conditions $y_{-1}, y_{-2}$.\n", + " \n", + "Notice how we used the second approach above when we set $\\eta_1, \\eta_2$ either to $(0, 1)$, for example, or $(1, 0)$, for example.\n", + "\n", + "In taking this second approach, we constructed an *invariant subspace* of ${\\bf R}^2$. \n", + "\n", + "Here is what is going on. \n", + "\n", + "For $ t \\geq 0$ and for most pairs of initial conditions $(y_{-1}, y_{-2}) \\in {\\bf R}^2$ for equation {eq}`eq:second_order`, $y_t$ can be expressed as a linear combination of $y_{t-1}$ and $y_{t-2}$.\n", + "\n", + "But for some special initial conditions $(y_{-1}, y_{-2}) \\in {\\bf R}^2$, $y_t$ can be expressed as a linear function of $y_{t-1}$ only. \n", + "\n", + "These special initial conditions require that $y_{-1}$ be a linear function of $y_{-2}$.\n", + "\n", + "We'll study these special initial conditions soon. \n", + "\n", + "But first let's write some Python code to iterate on equation {eq}`eq:second_order` starting from an arbitrary $(y_{-1}, y_{-2}) \\in {\\bf R}^2$.\n", + "\n", + "## Implementation\n", + "\n", + "We now implement the above algorithm to compute the square root of $\\sigma$.\n", + "\n", + "In this lecture, we use the following import:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "84a8cc44", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "45ab0680", + "metadata": {}, + "outputs": [], + "source": [ + "def solve_λs(coefs): \n", + " # Calculate the roots using numpy.roots\n", + " λs = np.roots(coefs)\n", + " \n", + " # Sort the roots for consistency\n", + " return sorted(λs, reverse=True)\n", + "\n", + "def solve_η(λ_1, λ_2, y_neg1, y_neg2):\n", + " # Solve the system of linear equation\n", + " A = np.array([\n", + " [1/λ_1, 1/λ_2],\n", + " [1/(λ_1**2), 1/(λ_2**2)]\n", + " ])\n", + " b = np.array((y_neg1, y_neg2))\n", + " ηs = np.linalg.solve(A, b)\n", + " \n", + " return ηs\n", + "\n", + "def solve_sqrt(σ, coefs, y_neg1, y_neg2, t_max=100):\n", + " # Ensure σ is greater than 1\n", + " if σ <= 1:\n", + " raise ValueError(\"σ must be greater than 1\")\n", + " \n", + " # Characteristic roots\n", + " λ_1, λ_2 = solve_λs(coefs)\n", + " \n", + " # Solve for η_1 and η_2\n", + " η_1, η_2 = solve_η(λ_1, λ_2, y_neg1, y_neg2)\n", + "\n", + " # Compute the sequence up to t_max\n", + " t = np.arange(t_max + 1)\n", + " y = (λ_1 ** t) * η_1 + (λ_2 ** t) * η_2\n", + " \n", + " # Compute the ratio y_{t+1} / y_t for large t\n", + " sqrt_σ_estimate = (y[-1] / y[-2]) - 1\n", + " \n", + " return sqrt_σ_estimate\n", + "\n", + "# Use σ = 2 as an example\n", + "σ = 2\n", + "\n", + "# Encode characteristic equation\n", + "coefs = (1, -2, (1 - σ))\n", + "\n", + "# Solve for the square root of σ\n", + "sqrt_σ = solve_sqrt(σ, coefs, y_neg1=2, y_neg2=1)\n", + "\n", + "# Calculate the deviation\n", + "dev = abs(sqrt_σ-np.sqrt(σ))\n", + "print(f\"sqrt({σ}) is approximately {sqrt_σ:.5f} (error: {dev:.5f})\")" + ] + }, + { + "cell_type": "markdown", + "id": "14059b39", + "metadata": {}, + "source": [ + "Now we consider cases where $(\\eta_1, \\eta_2) = (0, 1)$ and $(\\eta_1, \\eta_2) = (1, 0)$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8c672469", + "metadata": {}, + "outputs": [], + "source": [ + "# Compute λ_1, λ_2\n", + "λ_1, λ_2 = solve_λs(coefs)\n", + "print(f'Roots for the characteristic equation are ({λ_1:.5f}, {λ_2:.5f}))')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5577af2f", + "metadata": {}, + "outputs": [], + "source": [ + "# Case 1: η_1, η_2 = (0, 1)\n", + "ηs = (0, 1)\n", + "\n", + "# Compute y_{t} and y_{t-1} with t >= 0\n", + "y = lambda t, ηs: (λ_1 ** t) * ηs[0] + (λ_2 ** t) * ηs[1]\n", + "sqrt_σ = 1 - y(1, ηs) / y(0, ηs)\n", + "\n", + "print(f\"For η_1, η_2 = (0, 1), sqrt_σ = {sqrt_σ:.5f}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c56e433b", + "metadata": {}, + "outputs": [], + "source": [ + "# Case 2: η_1, η_2 = (1, 0)\n", + "ηs = (1, 0)\n", + "sqrt_σ = y(1, ηs) / y(0, ηs) - 1\n", + "\n", + "print(f\"For η_1, η_2 = (1, 0), sqrt_σ = {sqrt_σ:.5f}\")" + ] + }, + { + "cell_type": "markdown", + "id": "b49a6365", + "metadata": {}, + "source": [ + "We find that convergence is immediate.\n", + "\n", + "Next, we'll represent the preceding analysis by first vectorizing our second-order difference equation {eq}`eq:second_order` and then using eigendecompositions of an associated state transition matrix.\n", + "\n", + "## Vectorizing the difference equation\n", + "\n", + "\n", + "Represent {eq}`eq:second_order` with the first-order matrix difference equation\n", + "\n", + "$$\n", + "\\begin{bmatrix} y_{t+1} \\cr y_{t} \\end{bmatrix}\n", + "= \\begin{bmatrix} 2 & - ( 1 - \\sigma) \\cr 1 & 0 \\end{bmatrix} \\begin{bmatrix} y_{t} \\cr y_{t-1} \\end{bmatrix}\n", + "$$\n", + "\n", + "or\n", + "\n", + "$$\n", + "x_{t+1} = M x_t \n", + "$$\n", + "\n", + "where \n", + "\n", + "$$\n", + "M = \\begin{bmatrix} 2 & - (1 - \\sigma ) \\cr 1 & 0 \\end{bmatrix}, \\quad x_t= \\begin{bmatrix} y_{t} \\cr y_{t-1} \\end{bmatrix}\n", + "$$\n", + "\n", + "Construct an eigendecomposition of $M$:\n", + "\n", + "$$\n", + "M = V \\begin{bmatrix} \\lambda_1 & 0 \\cr 0 & \\lambda_2 \\end{bmatrix} V^{-1} \n", + "$$ (eq:eigen_sqrt)\n", + "\n", + "where columns of $V$ are eigenvectors corresponding to eigenvalues $\\lambda_1$ and $\\lambda_2$.\n", + "\n", + "The eigenvalues can be ordered so that $\\lambda_1 > 1 > \\lambda_2$.\n", + "\n", + "Write equation {eq}`eq:second_order` as\n", + "\n", + "$$\n", + "x_{t+1} = V \\Lambda V^{-1} x_t\n", + "$$\n", + "\n", + "Now we implement the algorithm above.\n", + "\n", + "First we write a function that iterates $M$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dfcaae03", + "metadata": {}, + "outputs": [], + "source": [ + "def iterate_M(x_0, M, num_steps, dtype=np.float64):\n", + " \n", + " # Eigendecomposition of M\n", + " Λ, V = np.linalg.eig(M)\n", + " V_inv = np.linalg.inv(V)\n", + " \n", + " # Initialize the array to store results\n", + " xs = np.zeros((x_0.shape[0], \n", + " num_steps + 1))\n", + " \n", + " # Perform the iterations\n", + " xs[:, 0] = x_0\n", + " for t in range(num_steps):\n", + " xs[:, t + 1] = M @ xs[:, t]\n", + " \n", + " return xs, Λ, V, V_inv\n", + "\n", + "# Define the state transition matrix M\n", + "M = np.array([\n", + " [2, -(1 - σ)],\n", + " [1, 0]])\n", + "\n", + "# Initial condition vector x_0\n", + "x_0 = np.array([2, 2])\n", + "\n", + "# Perform the iteration\n", + "xs, Λ, V, V_inv = iterate_M(x_0, M, num_steps=100)\n", + "\n", + "print(f\"eigenvalues:\\n{Λ}\")\n", + "print(f\"eigenvectors:\\n{V}\")\n", + "print(f\"inverse eigenvectors:\\n{V_inv}\")" + ] + }, + { + "cell_type": "markdown", + "id": "30b8501f", + "metadata": {}, + "source": [ + "Let's compare the eigenvalues to the roots {eq}`eq:secretweapon` of equation \n", + "{eq}`eq:cha_eq0` that we computed above." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f517a4e0", + "metadata": {}, + "outputs": [], + "source": [ + "roots = solve_λs((1, -2, (1 - σ)))\n", + "print(f\"roots: {np.round(roots, 8)}\")" + ] + }, + { + "cell_type": "markdown", + "id": "17f9d0f6", + "metadata": {}, + "source": [ + "Hence we confirmed {eq}`eq:eigen_sqrt`.\n", + "\n", + "Information about the square root we are after is also contained\n", + "in the two eigenvectors.\n", + "\n", + "Indeed, each eigenvector is just a two-dimensional subspace of ${\\mathbb R}^3$ pinned down by dynamics of the form \n", + "\n", + "$$\n", + "y_{t} = \\lambda_i y_{t-1}, \\quad i = 1, 2 \n", + "$$ (eq:invariantsub101)\n", + "\n", + "that we encountered above in equation {eq}`eq:2diff8` above.\n", + "\n", + "In equation {eq}`eq:invariantsub101`, the $i$th $\\lambda_i$ equals the $V_{i, 1}/V_{i,2}$.\n", + "\n", + "The following graph verifies this for our example." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4c024749", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "# Plotting the eigenvectors\n", + "plt.figure(figsize=(8, 8))\n", + "\n", + "plt.quiver(0, 0, V[0, 0], V[1, 0], angles='xy', scale_units='xy', \n", + " scale=1, color='C0', label=fr'$\\lambda_1={np.round(Λ[0], 4)}$')\n", + "plt.quiver(0, 0, V[0, 1], V[1, 1], angles='xy', scale_units='xy', \n", + " scale=1, color='C1', label=fr'$\\lambda_2={np.round(Λ[1], 4)}$')\n", + "\n", + "# Annotating the slopes\n", + "plt.text(V[0, 0]-0.5, V[1, 0]*1.2, \n", + " r'slope=$\\frac{V_{1,1}}{V_{1,2}}=$'+f'{np.round(V[0, 0] / V[1, 0], 4)}', \n", + " fontsize=12, color='C0')\n", + "plt.text(V[0, 1]-0.5, V[1, 1]*1.2, \n", + " r'slope=$\\frac{V_{2,1}}{V_{2,2}}=$'+f'{np.round(V[0, 1] / V[1, 1], 4)}', \n", + " fontsize=12, color='C1')\n", + "\n", + "# Adding labels\n", + "plt.axhline(0, color='grey', linewidth=0.5, alpha=0.4)\n", + "plt.axvline(0, color='grey', linewidth=0.5, alpha=0.4)\n", + "plt.legend()\n", + "\n", + "plt.xlim(-1.5, 1.5)\n", + "plt.ylim(-1.5, 1.5)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "1c45f08c", + "metadata": {}, + "source": [ + "## Invariant subspace approach \n", + "\n", + "The preceding calculation indicates that we can use the eigenvectors $V$ to construct 2-dimensional *invariant subspaces*.\n", + "\n", + "We'll pursue that possibility now.\n", + "\n", + "Define the transformed variables\n", + "\n", + "\n", + "$$\n", + "x_t^* = V^{-1} x_t\n", + "$$\n", + "\n", + "Evidently, we can recover $x_t$ from $x_t^*$:\n", + "\n", + "$$\n", + "x_t = V x_t^*\n", + "$$\n", + "\n", + "\n", + "The following notations and equations will help us.\n", + "\n", + "Let \n", + "\n", + "$$\n", + "\n", + "V = \\begin{bmatrix} V_{1,1} & V_{1,2} \\cr \n", + " V_{2,1} & V_{2,2} \\end{bmatrix}, \\quad\n", + "V^{-1} = \\begin{bmatrix} V^{1,1} & V^{1,2} \\cr \n", + " V^{2,1} & V^{2,2} \\end{bmatrix}\n", + "$$\n", + "\n", + "Notice that it follows from\n", + "\n", + "$$\n", + " \\begin{bmatrix} V^{1,1} & V^{1,2} \\cr \n", + " V^{2,1} & V^{2,2} \\end{bmatrix} \\begin{bmatrix} V_{1,1} & V_{1,2} \\cr \n", + " V_{2,1} & V_{2,2} \\end{bmatrix} = \\begin{bmatrix} 1 & 0 \\cr 0 & 1 \\end{bmatrix}\n", + "$$\n", + "\n", + "that\n", + "\n", + "$$\n", + "V^{2,1} V_{1,1} + V^{2,2} V_{2,1} = 0\n", + "$$\n", + "\n", + "and\n", + "\n", + "$$\n", + "V^{1,1}V_{1,2} + V^{1,2} V_{2,2} = 0.\n", + "$$\n", + "\n", + "These equations will be very useful soon.\n", + "\n", + "\n", + "Notice that\n", + "\n", + "$$\n", + "\\begin{bmatrix} x_{1,t+1}^* \\cr x_{2,t+1}^* \\end{bmatrix} = \\begin{bmatrix} \\lambda_1 & 0 \\cr 0 & \\lambda_2 \\end{bmatrix}\n", + "\\begin{bmatrix} x_{1,t}^* \\cr x_{2,t}^* \\end{bmatrix}\n", + "$$\n", + "\n", + "To deactivate $\\lambda_1$ we want to set\n", + "\n", + "$$\n", + "x_{1,0}^* = 0.\n", + "$$\n", + "\n", + "\n", + "This can be achieved by setting \n", + "\n", + "$$\n", + "x_{2,0} = -( V^{1,2})^{-1} V^{1,1} x_{1,0} = V_{2,2} V_{1,2}^{-1} x_{1,0}.\n", + "$$ (eq:deactivate1)\n", + "\n", + "To deactivate $\\lambda_2$, we want to set\n", + "\n", + "$$\n", + "x_{2,0}^* = 0\n", + "$$\n", + "\n", + "This can be achieved by setting \n", + "\n", + "$$\n", + "x_{2,0} = -(V^{2,2})^{-1} V^{2,1} x_{1,0} = V_{2,1} V_{1,1}^{-1} x_{1,0}.\n", + "$$ (eq:deactivate2)\n", + "\n", + "Let's verify {eq}`eq:deactivate1` and {eq}`eq:deactivate2` below\n", + "\n", + "To deactivate $\\lambda_1$ we use {eq}`eq:deactivate1`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8a1da3d3", + "metadata": {}, + "outputs": [], + "source": [ + "xd_1 = np.array((x_0[0], \n", + " V[1,1]/V[0,1] * x_0[0]),\n", + " dtype=np.float64)\n", + "\n", + "# Compute x_{1,0}^*\n", + "np.round(V_inv @ xd_1, 8)" + ] + }, + { + "cell_type": "markdown", + "id": "9856457e", + "metadata": {}, + "source": [ + "We find $x_{1,0}^* = 0$.\n", + "\n", + "Now we deactivate $\\lambda_2$ using {eq}`eq:deactivate2`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "90538d86", + "metadata": {}, + "outputs": [], + "source": [ + "xd_2 = np.array((x_0[0], \n", + " V[1,0]/V[0,0] * x_0[0]), \n", + " dtype=np.float64)\n", + "\n", + "# Compute x_{2,0}^*\n", + "np.round(V_inv @ xd_2, 8)" + ] + }, + { + "cell_type": "markdown", + "id": "9f5c47a9", + "metadata": {}, + "source": [ + "We find $x_{2,0}^* = 0$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "63cc75fe", + "metadata": {}, + "outputs": [], + "source": [ + "# Simulate with muted λ1 λ2.\n", + "num_steps = 10\n", + "xs_λ1 = iterate_M(xd_1, M, num_steps)[0]\n", + "xs_λ2 = iterate_M(xd_2, M, num_steps)[0]\n", + "\n", + "# Compute ratios y_t / y_{t-1}\n", + "ratios_λ1 = xs_λ1[1, 1:] / xs_λ1[1, :-1]\n", + "ratios_λ2 = xs_λ2[1, 1:] / xs_λ2[1, :-1] " + ] + }, + { + "cell_type": "markdown", + "id": "36c156aa", + "metadata": {}, + "source": [ + "The following graph shows the ratios $y_t / y_{t-1}$ for the two cases.\n", + "\n", + "We find that the ratios converge to $\\lambda_2$ in the first case and $\\lambda_1$ in the second case." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "60c6d0da", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "# Plot the ratios for y_t / y_{t-1}\n", + "fig, axs = plt.subplots(1, 2, figsize=(12, 6), dpi=500)\n", + "\n", + "# First subplot\n", + "axs[0].plot(np.round(ratios_λ1, 6), \n", + " label=r'$\\frac{y_t}{y_{t-1}}$', linewidth=3)\n", + "axs[0].axhline(y=Λ[1], color='red', linestyle='--', \n", + " label='$\\lambda_2$', alpha=0.5)\n", + "axs[0].set_xlabel('t', size=18)\n", + "axs[0].set_ylabel(r'$\\frac{y_t}{y_{t-1}}$', size=18)\n", + "axs[0].set_title(r'$\\frac{y_t}{y_{t-1}}$ after Muting $\\lambda_1$', \n", + " size=13)\n", + "axs[0].legend()\n", + "\n", + "# Second subplot\n", + "axs[1].plot(ratios_λ2, label=r'$\\frac{y_t}{y_{t-1}}$', \n", + " linewidth=3)\n", + "axs[1].axhline(y=Λ[0], color='green', linestyle='--', \n", + " label='$\\lambda_1$', alpha=0.5)\n", + "axs[1].set_xlabel('t', size=18)\n", + "axs[1].set_ylabel(r'$\\frac{y_t}{y_{t-1}}$', size=18)\n", + "axs[1].set_title(r'$\\frac{y_t}{y_{t-1}}$ after Muting $\\lambda_2$', \n", + " size=13)\n", + "axs[1].legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "a507d198", + "metadata": {}, + "source": [ + "## Concluding remarks\n", + "\n", + "This lecture sets the stage for many other applications of the *invariant subspace* methods.\n", + "\n", + "All of these exploit very similar equations based on eigen decompositions. \n", + "\n", + "We shall encounter equations very similar to {eq}`eq:deactivate1` and {eq}`eq:deactivate2`\n", + "in {doc}`money_inflation` and in many other places in dynamic economic theory.\n", + "\n", + "\n", + "## Exercise\n", + "\n", + "```{exercise-start} \n", + ":label: greek_square_ex_a\n", + "```\n", + "Please use matrix algebra to formulate the method described by Bertrand Russell at the beginning of this lecture. \n", + "\n", + "1. Define a state vector $x_t = \\begin{bmatrix} a_t \\cr b_t \\end{bmatrix}$.\n", + "2. Formulate a first-order vector difference equation for $x_t$ of the form $x_{t+1} = A x_t$ and\n", + "compute the matrix $A$.\n", + "3. Use the system $x_{t+1} = A x_t$ to replicate the sequence of $a_t$'s and $b_t$'s described by Bertrand Russell.\n", + "4. Compute the eigenvectors and eigenvalues of $A$ and compare them to corresponding objects computed in the text of this lecture. \n", + "\n", + "```{exercise-end} \n", + "```\n", + "\n", + "```{solution-start} greek_square_ex_a\n", + ":class: dropdown\n", + "```\n", + "\n", + "Here is one soluition.\n", + "\n", + "According to the quote, we can formulate \n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "a_{t+1} &= a_t + b_t \\\\\n", + "b_{t+1} &= 2a_t + b_t\n", + "\\end{aligned}\n", + "$$ (eq:gs_ex1system)\n", + "\n", + "with $x_0 = \\begin{bmatrix} a_0 \\cr b_0 \\end{bmatrix} = \\begin{bmatrix} 1 \\cr 1 \\end{bmatrix}$\n", + "\n", + "By {eq}`eq:gs_ex1system`, we can write matrix $A$ as \n", + "\n", + "$$\n", + "A = \\begin{bmatrix} 1 & 1 \\cr \n", + " 2 & 1 \\end{bmatrix}\n", + "$$\n", + "\n", + "Then $x_{t+1} = A x_t$ for $t \\in \\{0, \\dots, 5\\}$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "32b267b1", + "metadata": {}, + "outputs": [], + "source": [ + "# Define the matrix A\n", + "A = np.array([[1, 1],\n", + " [2, 1]])\n", + "\n", + "# Initial vector x_0\n", + "x_0 = np.array([1, 1])\n", + "\n", + "# Number of iterations\n", + "n = 6\n", + "\n", + "# Generate the sequence\n", + "xs = np.array([x_0])\n", + "x_t = x_0\n", + "for _ in range(1, n):\n", + " x_t = A @ x_t\n", + " xs = np.vstack([xs, x_t])\n", + "\n", + "# Print the sequence\n", + "for i, (a_t, b_t) in enumerate(xs):\n", + " print(f\"Iter {i}: a_t = {a_t}, b_t = {b_t}\")\n", + "\n", + "# Compute eigenvalues and eigenvectors of A\n", + "eigenvalues, eigenvectors = np.linalg.eig(A)\n", + "\n", + "print(f'\\nEigenvalues:\\n{eigenvalues}')\n", + "print(f'\\nEigenvectors:\\n{eigenvectors}')" + ] + }, + { + "cell_type": "markdown", + "id": "8b9ed752", + "metadata": {}, + "source": [ + "```{solution-end}\n", + "```" + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.16.1" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 337, + 342, + 393, + 397, + 403, + 414, + 420, + 468, + 500, + 505, + 508, + 527, + 554, + 647, + 654, + 660, + 667, + 671, + 680, + 686, + 716, + 770, + 797 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/greek_square.md b/book/_build/html/_sources/greek_square.md new file mode 100644 index 0000000..8bf4a98 --- /dev/null +++ b/book/_build/html/_sources/greek_square.md @@ -0,0 +1,800 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.16.1 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Computing Square Roots + + +## Introduction + +Chapter 24 of {cite}`russell2004history` about early Greek mathematics and astronomy contains this +fascinating passage: + + ```{epigraph} + The square root of 2, which was the first irrational to be discovered, was known to the early Pythagoreans, and ingenious methods of approximating to its value were discovered. The best was as follows: Form two columns of numbers, which we will call the $a$'s and the $b$'s; each starts with a $1$. The next $a$, at each stage, is formed by adding the last $a$ and the $b$ already obtained; the next $b$ is formed by adding twice the previous $a$ to the previous $b$. The first 6 pairs so obtained are $(1,1), (2,3), (5,7), (12,17), (29,41), (70,99)$. In each pair, $2 a - b$ is $1$ or $-1$. Thus $b/a$ is nearly the square root of two, and at each fresh step it gets nearer. For instance, the reader may satisy himself that the square of $99/70$ is very nearly equal to $2$. + ``` + +This lecture drills down and studies this ancient method for computing square roots by using some of the matrix algebra that we've learned in earlier quantecon lectures. + +In particular, this lecture can be viewed as a sequel to {doc}`eigen_I`. + +It provides an example of how eigenvectors isolate *invariant subspaces* that help construct and analyze solutions of linear difference equations. + +When vector $x_t$ starts in an invariant subspace, iterating the different equation keeps $x_{t+j}$ +in that subspace for all $j \geq 1$. + +Invariant subspace methods are used throughout applied economic dynamics, for example, in the lecture {doc}`money_inflation`. + +Our approach here is to illustrate the method with an ancient example, one that ancient Greek mathematicians used to compute square roots of positive integers. + +## Perfect squares and irrational numbers + +An integer is called a **perfect square** if its square root is also an integer. + +An ordered sequence of perfect squares starts with + +$$ +4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, \ldots +$$ + +If an integer is not a perfect square, then its square root is an irrational number -- i.e., it cannot be expressed as a ratio of two integers, and its decimal expansion is indefinite. + +The ancient Greeks invented an algorithm to compute square roots of integers, including integers that are not perfect squares. + +Their method involved + + * computing a particular sequence of integers $\{y_t\}_{t=0}^\infty$; + + * computing $\lim_{t \rightarrow \infty} \left(\frac{y_{t+1}}{y_t}\right) = \bar r$; + + * deducing the desired square root from $\bar r$. + +In this lecture, we'll describe this method. + +We'll also use invariant subspaces to describe variations on this method that are faster. + +## Second-order linear difference equations + +Before telling how the ancient Greeks computed square roots, we'll provide a quick introduction +to second-order linear difference equations. + +We'll study the following second-order linear difference equation + +$$ +y_t = a_1 y_{t-1} + a_2 y_{t-2}, \quad t \geq 0 +$$ (eq:2diff1) + +where $(y_{-1}, y_{-2})$ is a pair of given initial conditions. + +Equation {eq}`eq:2diff1` is actually an infinite number of linear equations in the sequence +$\{y_t\}_{t=0}^\infty$. + +There is one equation each for $t = 0, 1, 2, \ldots$. + +We could follow an approach taken in the lecture on {doc}`present values` and stack all of these equations into a single matrix equation that we would then solve by using matrix inversion. + +```{note} +In the present instance, the matrix equation would multiply a countably infinite dimensional square matrix by a countably infinite dimensional vector. With some qualifications, matrix multiplication and inversion tools apply to such an equation. +``` + +But we won't pursue that approach here. + + +Instead, we'll seek to find a time-invariant function that *solves* our difference equation, meaning +that it provides a formula for a $\{y_t\}_{t=0}^\infty$ sequence that satisfies +equation {eq}`eq:2diff1` for each $t \geq 0$. + +We seek an expression for $y_t, t \geq 0$ as functions of the initial conditions $(y_{-1}, y_{-2})$: + +$$ +y_t = g((y_{-1}, y_{-2});t), \quad t \geq 0. +$$ (eq:2diff2) + +We call such a function $g$ a *solution* of the difference equation {eq}`eq:2diff1`. + +One way to discover a solution is to use a guess and verify method. + +We shall begin by considering a special initial pair of initial conditions +that satisfy + +$$ +y_{-1} = \delta y_{-2} +$$ (eq:2diff3) + +where $\delta$ is a scalar to be determined. + +For initial condition that satisfy {eq}`eq:2diff3` +equation {eq}`eq:2diff1` impllies that + +$$ +y_0 = \left(a_1 + \frac{a_2}{\delta}\right) y_{-1}. +$$ (eq:2diff4) + +We want + +$$ +\left(a_1 + \frac{a_2}{\delta}\right) = \delta +$$ (eq:2diff5) + +which we can rewrite as the *characteristic equation* + +$$ +\delta^2 - a_1 \delta - a_2 = 0. +$$ (eq:2diff6) + +Applying the quadratic formula to solve for the roots of {eq}`eq:2diff6` we find that + +$$ +\delta = \frac{ a_1 \pm \sqrt{a_1^2 + 4 a_2}}{2}. +$$ (eq:2diff7) + +For either of the two $\delta$'s that satisfy equation {eq}`eq:2diff7`, +a solution of difference equation {eq}`eq:2diff1` is + +$$ +y_t = \delta^t y_0 , \forall t \geq 0 +$$ (eq:2diff8) + +provided that we set + +$$ +y_0 = \delta y_{-1} . +$$ + +The *general* solution of difference equation {eq}`eq:2diff1` takes the form + +$$ +y_t = \eta_1 \delta_1^t + \eta_2 \delta_2^t +$$ (eq:2diff9) + +where $\delta_1, \delta_2$ are the two solutions {eq}`eq:2diff7` of the characteristic equation {eq}`eq:2diff6`, and $\eta_1, \eta_2$ are two constants chosen to satisfy + +$$ + \begin{bmatrix} y_{-1} \cr y_{-2} \end{bmatrix} = \begin{bmatrix} \delta_1^{-1} & \delta_2^{-1} \cr \delta_1^{-2} & \delta_2^{-2} \end{bmatrix} \begin{bmatrix} \eta_1 \cr \eta_2 \end{bmatrix} +$$ (eq:2diff10) + +or + +$$ +\begin{bmatrix} \eta_1 \cr \eta_2 \end{bmatrix} = \begin{bmatrix} \delta_1^{-1} & \delta_2^{-1} \cr \delta_1^{-2} & \delta_2^{-2} \end{bmatrix}^{-1} \begin{bmatrix} y_{-1} \cr y_{-2} \end{bmatrix} +$$ (eq:2diff11) + +Sometimes we are free to choose the initial conditions $(y_{-1}, y_{-2})$, in which case we +use system {eq}`eq:2diff10` to find the associated $(\eta_1, \eta_2)$. + +If we choose $(y_{-1}, y_{-2})$ to set $(\eta_1, \eta_2) = (1, 0)$, then $y_t = \delta_1^t$ for all $t \geq 0$. + + +If we choose $(y_{-1}, y_{-2})$ to set $(\eta_1, \eta_2) = (0, 1)$, then $y_t = \delta_2^t$ for all $t \geq 0$. + +Soon we'll relate the preceding calculations to components an eigen decomposition of a transition matrix that represents difference equation {eq}`eq:2diff1` in a very convenient way. + +We'll turn to that after we describe how Ancient Greeks figured out how to compute square roots of positive integers that are not perfect squares. + + +## Algorithm of the Ancient Greeks + +Let $\sigma$ be a positive integer greater than $1$. + +So $\sigma \in {\mathcal I} \equiv \{2, 3, \ldots \}$. + +We want an algorithm to compute the square root of $\sigma \in {\mathcal I}$. + +If $\sqrt{\sigma} \in {\mathcal I}$, $\sigma $ is said to be a *perfect square*. + +If $\sqrt{\sigma} \not\in {\mathcal I}$, it turns out that it is irrational. + +Ancient Greeks used a recursive algorithm to compute square roots of integers that are not perfect squares. + +The algorithm iterates on a second-order linear difference equation in the sequence $\{y_t\}_{t=0}^\infty$: + +$$ +y_{t} = 2 y_{t-1} - (1 - \sigma) y_{t-2}, \quad t \geq 0 +$$ (eq:second_order) + +together with a pair of integers that are initial conditions for $y_{-1}, y_{-2}$. + +First, we'll deploy some techniques for solving the difference equations that are also deployed in {doc}`dynam:samuelson`. + +The characteristic equation associated with difference equation {eq}`eq:second_order` is + +$$ +c(x) \equiv x^2 - 2 x + (1 - \sigma) = 0 +$$ (eq:cha_eq0) + +(Notice how this is an instance of equation {eq}`eq:2diff6` above.) + +Factoring the right side of equation {eq}`eq:cha_eq0`, we obtain + +$$ +c(x)= (x - \lambda_1) (x-\lambda_2) = 0 +$$(eq:cha_eq) + + +where + +$$ +c(x) = 0 +$$ + +for $x = \lambda_1$ or $x = \lambda_2$. + +These two special values of $x$ are sometimes called zeros or roots of $c(x)$. + + +By applying the quadratic formula to solve for the roots the characteristic equation +{eq}`eq:cha_eq0`, we find that + +$$ +\lambda_1 = 1 + \sqrt{\sigma}, \quad \lambda_2 = 1 - \sqrt{\sigma}. +$$ (eq:secretweapon) + +Formulas {eq}`eq:secretweapon` indicate that $\lambda_1$ and $\lambda_2$ are each functions +of a single variable, namely, $\sqrt{\sigma}$, the object that we along with some Ancient Greeks want to compute. + +Ancient Greeks had an indirect way of exploiting this fact to compute square roots of a positive integer. + +They did this by starting from particular initial conditions $y_{-1}, y_{-2}$ and iterating on the difference equation {eq}`eq:second_order`. + + +Solutions of difference equation {eq}`eq:second_order` take the form + +$$ +y_t = \lambda_1^t \eta_1 + \lambda_2^t \eta_2 +$$ + +where $\eta_1$ and $\eta_2$ are chosen to satisfy prescribed initial conditions $y_{-1}, y_{-2}$: + +$$ +\begin{aligned} +\lambda_1^{-1} \eta_1 + \lambda_2^{-1} \eta_2 & = y_{-1} \cr +\lambda_1^{-2} \eta_1 + \lambda_2^{-2} \eta_2 & = y_{-2} +\end{aligned} +$$(eq:leq_sq) + +System {eq}`eq:leq_sq` of simultaneous linear equations will play a big role in the remainder of this lecture. + +Since $\lambda_1 = 1 + \sqrt{\sigma} > 1 > \lambda_2 = 1 - \sqrt{\sigma} $, +it follows that for *almost all* (but not all) initial conditions + +$$ +\lim_{t \rightarrow \infty} \left(\frac{y_{t+1}}{y_t}\right) = 1 + \sqrt{\sigma}. +$$ + +Thus, + +$$ +\sqrt{\sigma} = \lim_{t \rightarrow \infty} \left(\frac{y_{t+1}}{y_t}\right) - 1. +$$ + +However, notice that if $\eta_1 = 0$, then + +$$ +\lim_{t \rightarrow \infty} \left(\frac{y_{t+1}}{y_t}\right) = 1 - \sqrt{\sigma} +$$ + +so that + +$$ +\sqrt{\sigma} = 1 - \lim_{t \rightarrow \infty} \left(\frac{y_{t+1}}{y_t}\right). +$$ + +Actually, if $\eta_1 =0$, it follows that + +$$ +\sqrt{\sigma} = 1 - \left(\frac{y_{t+1}}{y_t}\right) \quad \forall t \geq 0, +$$ + +so that convergence is immediate and there is no need to take limits. + +Symmetrically, if $\eta_2 =0$, it follows that + + +$$ +\sqrt{\sigma} = \left(\frac{y_{t+1}}{y_t}\right) - 1 \quad \forall t \geq 0 +$$ + +so again, convergence is immediate, and we have no need to compute a limit. + + +System {eq}`eq:leq_sq` of simultaneous linear equations can be used in various ways. + + * we can take $y_{-1}, y_{-2}$ as given initial conditions and solve for $\eta_1, \eta_2$; + + * we can instead take $\eta_1, \eta_2$ as given and solve for initial conditions $y_{-1}, y_{-2}$. + +Notice how we used the second approach above when we set $\eta_1, \eta_2$ either to $(0, 1)$, for example, or $(1, 0)$, for example. + +In taking this second approach, we constructed an *invariant subspace* of ${\bf R}^2$. + +Here is what is going on. + +For $ t \geq 0$ and for most pairs of initial conditions $(y_{-1}, y_{-2}) \in {\bf R}^2$ for equation {eq}`eq:second_order`, $y_t$ can be expressed as a linear combination of $y_{t-1}$ and $y_{t-2}$. + +But for some special initial conditions $(y_{-1}, y_{-2}) \in {\bf R}^2$, $y_t$ can be expressed as a linear function of $y_{t-1}$ only. + +These special initial conditions require that $y_{-1}$ be a linear function of $y_{-2}$. + +We'll study these special initial conditions soon. + +But first let's write some Python code to iterate on equation {eq}`eq:second_order` starting from an arbitrary $(y_{-1}, y_{-2}) \in {\bf R}^2$. + +## Implementation + +We now implement the above algorithm to compute the square root of $\sigma$. + +In this lecture, we use the following import: + +```{code-cell} ipython3 +import numpy as np +import matplotlib.pyplot as plt +``` + +```{code-cell} ipython3 +def solve_λs(coefs): + # Calculate the roots using numpy.roots + λs = np.roots(coefs) + + # Sort the roots for consistency + return sorted(λs, reverse=True) + +def solve_η(λ_1, λ_2, y_neg1, y_neg2): + # Solve the system of linear equation + A = np.array([ + [1/λ_1, 1/λ_2], + [1/(λ_1**2), 1/(λ_2**2)] + ]) + b = np.array((y_neg1, y_neg2)) + ηs = np.linalg.solve(A, b) + + return ηs + +def solve_sqrt(σ, coefs, y_neg1, y_neg2, t_max=100): + # Ensure σ is greater than 1 + if σ <= 1: + raise ValueError("σ must be greater than 1") + + # Characteristic roots + λ_1, λ_2 = solve_λs(coefs) + + # Solve for η_1 and η_2 + η_1, η_2 = solve_η(λ_1, λ_2, y_neg1, y_neg2) + + # Compute the sequence up to t_max + t = np.arange(t_max + 1) + y = (λ_1 ** t) * η_1 + (λ_2 ** t) * η_2 + + # Compute the ratio y_{t+1} / y_t for large t + sqrt_σ_estimate = (y[-1] / y[-2]) - 1 + + return sqrt_σ_estimate + +# Use σ = 2 as an example +σ = 2 + +# Encode characteristic equation +coefs = (1, -2, (1 - σ)) + +# Solve for the square root of σ +sqrt_σ = solve_sqrt(σ, coefs, y_neg1=2, y_neg2=1) + +# Calculate the deviation +dev = abs(sqrt_σ-np.sqrt(σ)) +print(f"sqrt({σ}) is approximately {sqrt_σ:.5f} (error: {dev:.5f})") +``` + +Now we consider cases where $(\eta_1, \eta_2) = (0, 1)$ and $(\eta_1, \eta_2) = (1, 0)$ + +```{code-cell} ipython3 +# Compute λ_1, λ_2 +λ_1, λ_2 = solve_λs(coefs) +print(f'Roots for the characteristic equation are ({λ_1:.5f}, {λ_2:.5f}))') +``` + +```{code-cell} ipython3 +# Case 1: η_1, η_2 = (0, 1) +ηs = (0, 1) + +# Compute y_{t} and y_{t-1} with t >= 0 +y = lambda t, ηs: (λ_1 ** t) * ηs[0] + (λ_2 ** t) * ηs[1] +sqrt_σ = 1 - y(1, ηs) / y(0, ηs) + +print(f"For η_1, η_2 = (0, 1), sqrt_σ = {sqrt_σ:.5f}") +``` + +```{code-cell} ipython3 +# Case 2: η_1, η_2 = (1, 0) +ηs = (1, 0) +sqrt_σ = y(1, ηs) / y(0, ηs) - 1 + +print(f"For η_1, η_2 = (1, 0), sqrt_σ = {sqrt_σ:.5f}") +``` + +We find that convergence is immediate. + +Next, we'll represent the preceding analysis by first vectorizing our second-order difference equation {eq}`eq:second_order` and then using eigendecompositions of an associated state transition matrix. + +## Vectorizing the difference equation + + +Represent {eq}`eq:second_order` with the first-order matrix difference equation + +$$ +\begin{bmatrix} y_{t+1} \cr y_{t} \end{bmatrix} += \begin{bmatrix} 2 & - ( 1 - \sigma) \cr 1 & 0 \end{bmatrix} \begin{bmatrix} y_{t} \cr y_{t-1} \end{bmatrix} +$$ + +or + +$$ +x_{t+1} = M x_t +$$ + +where + +$$ +M = \begin{bmatrix} 2 & - (1 - \sigma ) \cr 1 & 0 \end{bmatrix}, \quad x_t= \begin{bmatrix} y_{t} \cr y_{t-1} \end{bmatrix} +$$ + +Construct an eigendecomposition of $M$: + +$$ +M = V \begin{bmatrix} \lambda_1 & 0 \cr 0 & \lambda_2 \end{bmatrix} V^{-1} +$$ (eq:eigen_sqrt) + +where columns of $V$ are eigenvectors corresponding to eigenvalues $\lambda_1$ and $\lambda_2$. + +The eigenvalues can be ordered so that $\lambda_1 > 1 > \lambda_2$. + +Write equation {eq}`eq:second_order` as + +$$ +x_{t+1} = V \Lambda V^{-1} x_t +$$ + +Now we implement the algorithm above. + +First we write a function that iterates $M$ + +```{code-cell} ipython3 +def iterate_M(x_0, M, num_steps, dtype=np.float64): + + # Eigendecomposition of M + Λ, V = np.linalg.eig(M) + V_inv = np.linalg.inv(V) + + # Initialize the array to store results + xs = np.zeros((x_0.shape[0], + num_steps + 1)) + + # Perform the iterations + xs[:, 0] = x_0 + for t in range(num_steps): + xs[:, t + 1] = M @ xs[:, t] + + return xs, Λ, V, V_inv + +# Define the state transition matrix M +M = np.array([ + [2, -(1 - σ)], + [1, 0]]) + +# Initial condition vector x_0 +x_0 = np.array([2, 2]) + +# Perform the iteration +xs, Λ, V, V_inv = iterate_M(x_0, M, num_steps=100) + +print(f"eigenvalues:\n{Λ}") +print(f"eigenvectors:\n{V}") +print(f"inverse eigenvectors:\n{V_inv}") +``` + +Let's compare the eigenvalues to the roots {eq}`eq:secretweapon` of equation +{eq}`eq:cha_eq0` that we computed above. + +```{code-cell} ipython3 +roots = solve_λs((1, -2, (1 - σ))) +print(f"roots: {np.round(roots, 8)}") +``` + +Hence we confirmed {eq}`eq:eigen_sqrt`. + +Information about the square root we are after is also contained +in the two eigenvectors. + +Indeed, each eigenvector is just a two-dimensional subspace of ${\mathbb R}^3$ pinned down by dynamics of the form + +$$ +y_{t} = \lambda_i y_{t-1}, \quad i = 1, 2 +$$ (eq:invariantsub101) + +that we encountered above in equation {eq}`eq:2diff8` above. + +In equation {eq}`eq:invariantsub101`, the $i$th $\lambda_i$ equals the $V_{i, 1}/V_{i,2}$. + +The following graph verifies this for our example. + +```{code-cell} ipython3 +:tags: [hide-input] + +# Plotting the eigenvectors +plt.figure(figsize=(8, 8)) + +plt.quiver(0, 0, V[0, 0], V[1, 0], angles='xy', scale_units='xy', + scale=1, color='C0', label=fr'$\lambda_1={np.round(Λ[0], 4)}$') +plt.quiver(0, 0, V[0, 1], V[1, 1], angles='xy', scale_units='xy', + scale=1, color='C1', label=fr'$\lambda_2={np.round(Λ[1], 4)}$') + +# Annotating the slopes +plt.text(V[0, 0]-0.5, V[1, 0]*1.2, + r'slope=$\frac{V_{1,1}}{V_{1,2}}=$'+f'{np.round(V[0, 0] / V[1, 0], 4)}', + fontsize=12, color='C0') +plt.text(V[0, 1]-0.5, V[1, 1]*1.2, + r'slope=$\frac{V_{2,1}}{V_{2,2}}=$'+f'{np.round(V[0, 1] / V[1, 1], 4)}', + fontsize=12, color='C1') + +# Adding labels +plt.axhline(0, color='grey', linewidth=0.5, alpha=0.4) +plt.axvline(0, color='grey', linewidth=0.5, alpha=0.4) +plt.legend() + +plt.xlim(-1.5, 1.5) +plt.ylim(-1.5, 1.5) +plt.show() +``` + +## Invariant subspace approach + +The preceding calculation indicates that we can use the eigenvectors $V$ to construct 2-dimensional *invariant subspaces*. + +We'll pursue that possibility now. + +Define the transformed variables + + +$$ +x_t^* = V^{-1} x_t +$$ + +Evidently, we can recover $x_t$ from $x_t^*$: + +$$ +x_t = V x_t^* +$$ + + +The following notations and equations will help us. + +Let + +$$ + +V = \begin{bmatrix} V_{1,1} & V_{1,2} \cr + V_{2,1} & V_{2,2} \end{bmatrix}, \quad +V^{-1} = \begin{bmatrix} V^{1,1} & V^{1,2} \cr + V^{2,1} & V^{2,2} \end{bmatrix} +$$ + +Notice that it follows from + +$$ + \begin{bmatrix} V^{1,1} & V^{1,2} \cr + V^{2,1} & V^{2,2} \end{bmatrix} \begin{bmatrix} V_{1,1} & V_{1,2} \cr + V_{2,1} & V_{2,2} \end{bmatrix} = \begin{bmatrix} 1 & 0 \cr 0 & 1 \end{bmatrix} +$$ + +that + +$$ +V^{2,1} V_{1,1} + V^{2,2} V_{2,1} = 0 +$$ + +and + +$$ +V^{1,1}V_{1,2} + V^{1,2} V_{2,2} = 0. +$$ + +These equations will be very useful soon. + + +Notice that + +$$ +\begin{bmatrix} x_{1,t+1}^* \cr x_{2,t+1}^* \end{bmatrix} = \begin{bmatrix} \lambda_1 & 0 \cr 0 & \lambda_2 \end{bmatrix} +\begin{bmatrix} x_{1,t}^* \cr x_{2,t}^* \end{bmatrix} +$$ + +To deactivate $\lambda_1$ we want to set + +$$ +x_{1,0}^* = 0. +$$ + + +This can be achieved by setting + +$$ +x_{2,0} = -( V^{1,2})^{-1} V^{1,1} x_{1,0} = V_{2,2} V_{1,2}^{-1} x_{1,0}. +$$ (eq:deactivate1) + +To deactivate $\lambda_2$, we want to set + +$$ +x_{2,0}^* = 0 +$$ + +This can be achieved by setting + +$$ +x_{2,0} = -(V^{2,2})^{-1} V^{2,1} x_{1,0} = V_{2,1} V_{1,1}^{-1} x_{1,0}. +$$ (eq:deactivate2) + +Let's verify {eq}`eq:deactivate1` and {eq}`eq:deactivate2` below + +To deactivate $\lambda_1$ we use {eq}`eq:deactivate1` + +```{code-cell} ipython3 +xd_1 = np.array((x_0[0], + V[1,1]/V[0,1] * x_0[0]), + dtype=np.float64) + +# Compute x_{1,0}^* +np.round(V_inv @ xd_1, 8) +``` + +We find $x_{1,0}^* = 0$. + +Now we deactivate $\lambda_2$ using {eq}`eq:deactivate2` + +```{code-cell} ipython3 +xd_2 = np.array((x_0[0], + V[1,0]/V[0,0] * x_0[0]), + dtype=np.float64) + +# Compute x_{2,0}^* +np.round(V_inv @ xd_2, 8) +``` + +We find $x_{2,0}^* = 0$. + +```{code-cell} ipython3 +# Simulate with muted λ1 λ2. +num_steps = 10 +xs_λ1 = iterate_M(xd_1, M, num_steps)[0] +xs_λ2 = iterate_M(xd_2, M, num_steps)[0] + +# Compute ratios y_t / y_{t-1} +ratios_λ1 = xs_λ1[1, 1:] / xs_λ1[1, :-1] +ratios_λ2 = xs_λ2[1, 1:] / xs_λ2[1, :-1] +``` + +The following graph shows the ratios $y_t / y_{t-1}$ for the two cases. + +We find that the ratios converge to $\lambda_2$ in the first case and $\lambda_1$ in the second case. + +```{code-cell} ipython3 +:tags: [hide-input] + +# Plot the ratios for y_t / y_{t-1} +fig, axs = plt.subplots(1, 2, figsize=(12, 6), dpi=500) + +# First subplot +axs[0].plot(np.round(ratios_λ1, 6), + label=r'$\frac{y_t}{y_{t-1}}$', linewidth=3) +axs[0].axhline(y=Λ[1], color='red', linestyle='--', + label='$\lambda_2$', alpha=0.5) +axs[0].set_xlabel('t', size=18) +axs[0].set_ylabel(r'$\frac{y_t}{y_{t-1}}$', size=18) +axs[0].set_title(r'$\frac{y_t}{y_{t-1}}$ after Muting $\lambda_1$', + size=13) +axs[0].legend() + +# Second subplot +axs[1].plot(ratios_λ2, label=r'$\frac{y_t}{y_{t-1}}$', + linewidth=3) +axs[1].axhline(y=Λ[0], color='green', linestyle='--', + label='$\lambda_1$', alpha=0.5) +axs[1].set_xlabel('t', size=18) +axs[1].set_ylabel(r'$\frac{y_t}{y_{t-1}}$', size=18) +axs[1].set_title(r'$\frac{y_t}{y_{t-1}}$ after Muting $\lambda_2$', + size=13) +axs[1].legend() + +plt.tight_layout() +plt.show() +``` + +## Concluding remarks + +This lecture sets the stage for many other applications of the *invariant subspace* methods. + +All of these exploit very similar equations based on eigen decompositions. + +We shall encounter equations very similar to {eq}`eq:deactivate1` and {eq}`eq:deactivate2` +in {doc}`money_inflation` and in many other places in dynamic economic theory. + + +## Exercise + +```{exercise-start} +:label: greek_square_ex_a +``` +Please use matrix algebra to formulate the method described by Bertrand Russell at the beginning of this lecture. + +1. Define a state vector $x_t = \begin{bmatrix} a_t \cr b_t \end{bmatrix}$. +2. Formulate a first-order vector difference equation for $x_t$ of the form $x_{t+1} = A x_t$ and +compute the matrix $A$. +3. Use the system $x_{t+1} = A x_t$ to replicate the sequence of $a_t$'s and $b_t$'s described by Bertrand Russell. +4. Compute the eigenvectors and eigenvalues of $A$ and compare them to corresponding objects computed in the text of this lecture. + +```{exercise-end} +``` + +```{solution-start} greek_square_ex_a +:class: dropdown +``` + +Here is one soluition. + +According to the quote, we can formulate + +$$ +\begin{aligned} +a_{t+1} &= a_t + b_t \\ +b_{t+1} &= 2a_t + b_t +\end{aligned} +$$ (eq:gs_ex1system) + +with $x_0 = \begin{bmatrix} a_0 \cr b_0 \end{bmatrix} = \begin{bmatrix} 1 \cr 1 \end{bmatrix}$ + +By {eq}`eq:gs_ex1system`, we can write matrix $A$ as + +$$ +A = \begin{bmatrix} 1 & 1 \cr + 2 & 1 \end{bmatrix} +$$ + +Then $x_{t+1} = A x_t$ for $t \in \{0, \dots, 5\}$ + +```{code-cell} ipython3 +# Define the matrix A +A = np.array([[1, 1], + [2, 1]]) + +# Initial vector x_0 +x_0 = np.array([1, 1]) + +# Number of iterations +n = 6 + +# Generate the sequence +xs = np.array([x_0]) +x_t = x_0 +for _ in range(1, n): + x_t = A @ x_t + xs = np.vstack([xs, x_t]) + +# Print the sequence +for i, (a_t, b_t) in enumerate(xs): + print(f"Iter {i}: a_t = {a_t}, b_t = {b_t}") + +# Compute eigenvalues and eigenvectors of A +eigenvalues, eigenvectors = np.linalg.eig(A) + +print(f'\nEigenvalues:\n{eigenvalues}') +print(f'\nEigenvectors:\n{eigenvectors}') +``` + +```{solution-end} +``` diff --git a/content/lectures/heavy_tails.ipynb b/book/_build/html/_sources/heavy_tails.ipynb similarity index 78% rename from content/lectures/heavy_tails.ipynb rename to book/_build/html/_sources/heavy_tails.ipynb index 6267f7e..9e4cd66 100644 --- a/content/lectures/heavy_tails.ipynb +++ b/book/_build/html/_sources/heavy_tails.ipynb @@ -2,23 +2,19 @@ "cells": [ { "cell_type": "markdown", - "id": "f608cad6", + "id": "e7eae18c", "metadata": {}, "source": [ "(heavy_tail)=\n", "# Heavy-Tailed Distributions\n", "\n", - "```{contents} Contents\n", - ":depth: 2\n", - "```\n", - "\n", "In addition to what's in Anaconda, this lecture will need the following libraries:" ] }, { "cell_type": "code", "execution_count": null, - "id": "702b4cb3", + "id": "4da79a73", "metadata": { "tags": [ "hide-output" @@ -26,12 +22,12 @@ }, "outputs": [], "source": [ - "%pip install --upgrade yfinance quantecon pandas_datareader interpolation" + "%pip install --upgrade yfinance pandas_datareader" ] }, { "cell_type": "markdown", - "id": "c4bf7f97", + "id": "3ef58bc9", "metadata": {}, "source": [ "We use the following imports." @@ -40,19 +36,16 @@ { "cell_type": "code", "execution_count": null, - "id": "3921090e", + "id": "95cb9ff9", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", - "import quantecon as qe\n", "import yfinance as yf\n", "import pandas as pd\n", - "import pandas_datareader.data as web\n", "import statsmodels.api as sm\n", "\n", - "from interpolation import interp\n", "from pandas_datareader import wb\n", "from scipy.stats import norm, cauchy\n", "from pandas.plotting import register_matplotlib_converters\n", @@ -61,27 +54,40 @@ }, { "cell_type": "markdown", - "id": "2fbf0939", + "id": "408ef2fb", "metadata": {}, "source": [ "## Overview\n", "\n", - "In this section we give some motivation for the lecture.\n", + "Heavy-tailed distributions are a class of distributions that generate \"extreme\" outcomes.\n", + "\n", + "In the natural sciences (and in more traditional economics courses), heavy-tailed distributions are seen as quite exotic and non-standard.\n", + "\n", + "However, it turns out that heavy-tailed distributions play a crucial role in economics.\n", + "\n", + "In fact many -- if not most -- of the important distributions in economics are heavy-tailed.\n", + "\n", + "In this lecture we explain what heavy tails are and why they are -- or at least\n", + "why they should be -- central to economic analysis.\n", + "\n", "\n", "### Introduction: light tails\n", "\n", - "Most commonly used probability distributions in classical statistics and\n", + "Most {doc}`commonly used probability distributions ` in classical statistics and\n", "the natural sciences have \"light tails.\"\n", "\n", "To explain this concept, let's look first at examples.\n", "\n", + "```{prf:example}\n", + ":label: ht_ex_nd\n", + "\n", "The classic example is the [normal distribution](https://en.wikipedia.org/wiki/Normal_distribution), which has density\n", "\n", "$$ \n", - " f(x) = \\frac{1}{\\sqrt{2\\pi}\\sigma} \n", - " \\exp\\left( -\\frac{(x-\\mu)^2}{2 \\sigma^2} \\right)\n", - " \\qquad\n", - " (-\\infty < x < \\infty)\n", + "f(x) = \\frac{1}{\\sqrt{2\\pi}\\sigma} \n", + "\\exp\\left( -\\frac{(x-\\mu)^2}{2 \\sigma^2} \\right)\n", + "\\qquad\n", + "(-\\infty < x < \\infty)\n", "$$\n", "\n", "\n", @@ -90,6 +96,7 @@ "\n", "As $x$ deviates from $\\mu$, the value of $f(x)$ goes to zero extremely\n", "quickly.\n", + "```\n", "\n", "We can see this when we plot the density and show a histogram of observations,\n", "as with the following code (which assumes $\\mu=0$ and $\\sigma=1$)." @@ -98,8 +105,15 @@ { "cell_type": "code", "execution_count": null, - "id": "81fc32fa", - "metadata": {}, + "id": "18728cfa", + "metadata": { + "mystnb": { + "figure": { + "caption": "Histogram of observations", + "name": "hist-obs" + } + } + }, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", @@ -113,7 +127,7 @@ }, { "cell_type": "markdown", - "id": "f67fc862", + "id": "d5fc8c36", "metadata": {}, "source": [ "Notice how \n", @@ -127,7 +141,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f3b9df73", + "id": "ca59c825", "metadata": {}, "outputs": [], "source": [ @@ -136,7 +150,7 @@ }, { "cell_type": "markdown", - "id": "b2394f3c", + "id": "4c9f9e4e", "metadata": {}, "source": [ "Here's another view of draws from the same distribution:" @@ -145,8 +159,15 @@ { "cell_type": "code", "execution_count": null, - "id": "03bf798c", - "metadata": {}, + "id": "fcd02b96", + "metadata": { + "mystnb": { + "figure": { + "caption": "Histogram of observations", + "name": "hist-obs2" + } + } + }, "outputs": [], "source": [ "n = 2000\n", @@ -162,7 +183,7 @@ }, { "cell_type": "markdown", - "id": "44f70929", + "id": "7c4cbe15", "metadata": {}, "source": [ "We have plotted each individual draw $X_i$ against $i$.\n", @@ -175,7 +196,7 @@ "Putting this another way, light-tailed distributions are those that\n", "rarely generate extreme values.\n", "\n", - "(A more formal definition is given below.)\n", + "(A more formal definition is given {ref}`below `.)\n", "\n", "Many statisticians and econometricians \n", "use rules of thumb such as \"outcomes more than four or five\n", @@ -202,15 +223,15 @@ "After all, there are 8 billion people in the world!\n", "\n", "In essence, the reason we don't see such draws is that the distribution of\n", - "human high has very light tails.\n", + "human height has very light tails.\n", "\n", - "In fact human height is approximately normally distributed.\n", + "In fact the distribution of human height obeys a bell-shaped curve similar to the normal distribution.\n", "\n", "\n", "### Returns on assets\n", "\n", "\n", - "But now we have to ask: does economic data always look like this?\n", + "But what about economic data?\n", "\n", "Let's look at some financial data first.\n", "\n", @@ -225,11 +246,32 @@ { "cell_type": "code", "execution_count": null, - "id": "7097dd48", - "metadata": {}, + "id": "208c5371", + "metadata": { + "tags": [ + "hide-output" + ] + }, + "outputs": [], + "source": [ + "data = yf.download('AMZN', '2015-1-1', '2022-7-1')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d09c51b0", + "metadata": { + "mystnb": { + "figure": { + "caption": "Daily Amazon returns", + "name": "dailyreturns-amzn" + } + } + }, "outputs": [], "source": [ - "s = yf.download('AMZN', '2015-1-1', '2022-7-1')['Adj Close']\n", + "s = data['Close']\n", "r = s.pct_change()\n", "\n", "fig, ax = plt.subplots()\n", @@ -244,10 +286,10 @@ }, { "cell_type": "markdown", - "id": "49094dca", + "id": "f56b7db8", "metadata": {}, "source": [ - "This data looks different to the draws from the normal distribution.\n", + "This data looks different to the draws from the normal distribution we saw above.\n", "\n", "Several of observations are quite extreme.\n", "\n", @@ -257,11 +299,32 @@ { "cell_type": "code", "execution_count": null, - "id": "f6405908", - "metadata": {}, + "id": "c360373e", + "metadata": { + "tags": [ + "hide-output" + ] + }, + "outputs": [], + "source": [ + "data = yf.download('BTC-USD', '2015-1-1', '2022-7-1')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "09047069", + "metadata": { + "mystnb": { + "figure": { + "caption": "Daily Bitcoin returns", + "name": "dailyreturns-btc" + } + } + }, "outputs": [], "source": [ - "s = yf.download('BTC-USD', '2015-1-1', '2022-7-1')['Adj Close']\n", + "s = data['Close']\n", "r = s.pct_change()\n", "\n", "fig, ax = plt.subplots()\n", @@ -276,7 +339,7 @@ }, { "cell_type": "markdown", - "id": "9a728009", + "id": "eadf42b3", "metadata": {}, "source": [ "The histogram also looks different to the histogram of the normal\n", @@ -286,19 +349,36 @@ { "cell_type": "code", "execution_count": null, - "id": "184347b3", - "metadata": {}, + "id": "cc86a066", + "metadata": { + "mystnb": { + "figure": { + "caption": "Histogram (normal vs bitcoin returns)", + "name": "hist-normal-btc" + } + } + }, "outputs": [], "source": [ + "r = np.random.standard_t(df=5, size=1000)\n", + "\n", "fig, ax = plt.subplots()\n", "ax.hist(r, bins=60, alpha=0.4, label='bitcoin returns', density=True)\n", + "\n", + "xmin, xmax = plt.xlim()\n", + "x = np.linspace(xmin, xmax, 100)\n", + "p = norm.pdf(x, np.mean(r), np.std(r))\n", + "ax.plot(x, p, linewidth=2, label='normal distribution')\n", + "\n", "ax.set_xlabel('returns', fontsize=12)\n", + "ax.legend()\n", + "\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "fda2bb8c", + "id": "1b2cab81", "metadata": {}, "source": [ "If we look at higher frequency returns data (e.g., tick-by-tick), we often see \n", @@ -314,6 +394,9 @@ "With heavy-tailed distributions, extreme outcomes occur relatively\n", "frequently.\n", "\n", + "```{prf:example}\n", + ":label: ht_ex_od\n", + "\n", "Importantly, there are many examples of heavy-tailed distributions\n", "observed in economic and financial settings!\n", "\n", @@ -329,6 +412,7 @@ "The distribution of town and city sizes is heavy-tailed \n", "\n", "* Most towns and cities are small but some are very large.\n", + "```\n", "\n", "Later in this lecture, we examine heavy tails in these distributions.\n", "\n", @@ -345,14 +429,11 @@ "* forecasting\n", "* taxation (across a heavy-tailed income distribution), etc.\n", "\n", - "We return to these points below.\n", - "\n", - "\n", - "\n", - "\n", + "We return to these points {ref}`below `.\n", "\n", "\n", "## Visual comparisons\n", + "In this section, we will introduce important concepts such as the Pareto distribution, Counter CDFs, and Power laws, which aid in recognizing heavy-tailed distributions.\n", "\n", "Later we will provide a mathematical definition of the difference between\n", "light and heavy tails.\n", @@ -376,8 +457,15 @@ { "cell_type": "code", "execution_count": null, - "id": "20ae682d", - "metadata": {}, + "id": "a50c2e7d", + "metadata": { + "mystnb": { + "figure": { + "caption": "Draws from normal and Cauchy distributions", + "name": "draws-normal-cauchy" + } + } + }, "outputs": [], "source": [ "n = 120\n", @@ -410,7 +498,7 @@ }, { "cell_type": "markdown", - "id": "ca8f1fa7", + "id": "d5080597", "metadata": {}, "source": [ "In the top subfigure, the standard deviation of the normal distribution is 2,\n", @@ -441,8 +529,15 @@ { "cell_type": "code", "execution_count": null, - "id": "4bedaaf1", - "metadata": {}, + "id": "84a8d939", + "metadata": { + "mystnb": { + "figure": { + "caption": "Draws of exponential distribution", + "name": "draws-exponential" + } + } + }, "outputs": [], "source": [ "n = 120\n", @@ -460,7 +555,7 @@ }, { "cell_type": "markdown", - "id": "a842320e", + "id": "0feb0151", "metadata": {}, "source": [ "Another nonnegative distribution is the [Pareto distribution](https://en.wikipedia.org/wiki/Pareto_distribution). \n", @@ -491,7 +586,9 @@ "\n", "In particular, if $X$ is exponentially distributed with rate parameter $\\alpha$, then\n", "\n", - "$$ Y = \\bar x \\exp(X) $$\n", + "$$\n", + "Y = \\bar x \\exp(X) \n", + "$$\n", "\n", "is Pareto-distributed with minimum $\\bar x$ and tail index $\\alpha$. \n", "\n", @@ -502,8 +599,15 @@ { "cell_type": "code", "execution_count": null, - "id": "2428434a", - "metadata": {}, + "id": "1672d297", + "metadata": { + "mystnb": { + "figure": { + "caption": "Draws from Pareto distribution", + "name": "draws-pareto" + } + } + }, "outputs": [], "source": [ "n = 120\n", @@ -521,7 +625,7 @@ }, { "cell_type": "markdown", - "id": "cf658e99", + "id": "ed43e04b", "metadata": {}, "source": [ "Notice how extreme outcomes are more common.\n", @@ -534,7 +638,9 @@ "\n", "For a random variable $X$ with CDF $F$, the CCDF is the function \n", "\n", - "$$ G(x) := 1 - F(x) = \\mathbb P\\{X > x\\} $$\n", + "$$\n", + "G(x) := 1 - F(x) = \\mathbb P\\{X > x\\} \n", + "$$\n", "\n", "(Some authors call $G$ the \"survival\" function.)\n", "\n", @@ -542,24 +648,60 @@ "\n", "If $X$ is exponentially distributed with rate parameter $\\alpha$, then the CCDF is\n", "\n", - "$$ G_E(x) = \\exp(- \\alpha x) $$\n", + "$$\n", + "G_E(x) = \\exp(- \\alpha x)\n", + "$$\n", "\n", "This function goes to zero relatively quickly as $x$ gets large.\n", "\n", - "The Pareto distribution has CCDF\n", + "The standard Pareto distribution, where $\\bar x = 1$, has CCDF\n", "\n", - "$$ G_P(x) = x^{- \\alpha} $$\n", + "$$\n", + "G_P(x) = x^{- \\alpha}\n", + "$$\n", "\n", "This function goes to zero as $x \\to \\infty$, but much slower than $G_E$.\n", "\n", + "```{exercise}\n", + ":label: ht_ex_x1\n", + "\n", + "Show how the CCDF of the standard Pareto distribution can be derived from the CCDF of the exponential distribution.\n", + "```\n", + "\n", + "```{solution-start} ht_ex_x1\n", + ":class: dropdown\n", + "```\n", + "Letting $G_E$ and $G_P$ be defined as above, letting $X$ be exponentially\n", + "distributed with rate parameter $\\alpha$, and letting $Y = \\exp(X)$, we have\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + " G_P(y) & = \\mathbb P\\{Y > y\\} \\\\\n", + " & = \\mathbb P\\{\\exp(X) > y\\} \\\\\n", + " & = \\mathbb P\\{X > \\ln y\\} \\\\\n", + " & = G_E(\\ln y) \\\\\n", + " & = \\exp( - \\alpha \\ln y) \\\\\n", + " & = y^{-\\alpha}\n", + "\\end{aligned}\n", + "$$\n", + "```{solution-end}\n", + "```\n", + "\n", "Here's a plot that illustrates how $G_E$ goes to zero faster than $G_P$." ] }, { "cell_type": "code", "execution_count": null, - "id": "a59f563c", - "metadata": {}, + "id": "f157fe52", + "metadata": { + "mystnb": { + "figure": { + "caption": "Pareto and exponential distribution comparison", + "name": "compare-pareto-exponential" + } + } + }, "outputs": [], "source": [ "x = np.linspace(1.5, 100, 1000)\n", @@ -567,37 +709,48 @@ "alpha = 1.0\n", "ax.plot(x, np.exp(- alpha * x), label='exponential', alpha=0.8)\n", "ax.plot(x, x**(- alpha), label='Pareto', alpha=0.8)\n", + "ax.set_xlabel('X value')\n", + "ax.set_ylabel('CCDF')\n", "ax.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "88fc4243", + "id": "5e215a50", "metadata": {}, "source": [ - "Here's a log-log plot of the same functions, which makes visual comparison a\n", - "bit easier." + "Here's a log-log plot of the same functions, which makes visual comparison\n", + "easier." ] }, { "cell_type": "code", "execution_count": null, - "id": "999f68be", - "metadata": {}, + "id": "882627a5", + "metadata": { + "mystnb": { + "figure": { + "caption": "Pareto and exponential distribution comparison (log-log)", + "name": "compare-pareto-exponential-log-log" + } + } + }, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", "alpha = 1.0\n", "ax.loglog(x, np.exp(- alpha * x), label='exponential', alpha=0.8)\n", "ax.loglog(x, x**(- alpha), label='Pareto', alpha=0.8)\n", + "ax.set_xlabel('log value')\n", + "ax.set_ylabel('log prob')\n", "ax.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "d208ae12", + "id": "9297549a", "metadata": {}, "source": [ "In the log-log plot, the Pareto CCDF is linear, while the exponential one is\n", @@ -613,35 +766,61 @@ "\n", "Given a sample $x_1, \\ldots, x_n$, the empirical CCDF is given by\n", "\n", - "$$ \\hat G(x) = \\frac{1}{n} \\sum_{i=1}^n \\mathbb 1\\{x_i > x\\} $$\n", - "\n", - "Thus, $\\hat G(x)$ shows the fraction of the sample that exceeds $x$.\n", + "$$\n", + "\\hat G(x) = \\frac{1}{n} \\sum_{i=1}^n \\mathbb 1\\{x_i > x\\}\n", + "$$\n", "\n", - "Here's a figure containing some empirical CCDFs from simulated data." + "Thus, $\\hat G(x)$ shows the fraction of the sample that exceeds $x$." ] }, { "cell_type": "code", "execution_count": null, - "id": "cb0e71e6", + "id": "b461de38", "metadata": {}, "outputs": [], "source": [ "def eccdf(x, data):\n", " \"Simple empirical CCDF function.\"\n", - " return np.mean(data > x)\n", - "\n", + " return np.mean(data > x)" + ] + }, + { + "cell_type": "markdown", + "id": "f33ff202", + "metadata": {}, + "source": [ + "Here's a figure containing some empirical CCDFs from simulated data." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0581ba44", + "metadata": { + "mystnb": { + "figure": { + "caption": "Empirical CCDFs", + "name": "ccdf-empirics" + } + } + }, + "outputs": [], + "source": [ + "# Parameters and grid\n", "x_grid = np.linspace(1, 1000, 1000)\n", "sample_size = 1000\n", "np.random.seed(13)\n", "z = np.random.randn(sample_size)\n", "\n", - "data_1 = np.random.exponential(size=sample_size)\n", - "data_2 = np.exp(z)\n", - "data_3 = np.exp(np.random.exponential(size=sample_size))\n", + "# Draws\n", + "data_exp = np.random.exponential(size=sample_size)\n", + "data_logn = np.exp(z)\n", + "data_pareto = np.exp(np.random.exponential(size=sample_size))\n", "\n", - "data_list = [data_1, data_2, data_3]\n", + "data_list = [data_exp, data_logn, data_pareto]\n", "\n", + "# Build figure\n", "fig, axes = plt.subplots(3, 1, figsize=(6, 8))\n", "axes = axes.flatten()\n", "labels = ['exponential', 'lognormal', 'Pareto']\n", @@ -650,11 +829,12 @@ "\n", " ax.loglog(x_grid, [eccdf(x, data) for x in x_grid], \n", " 'o', markersize=3.0, alpha=0.5, label=label)\n", - " ax.set_xlabel(\"log rank\")\n", - " ax.set_ylabel(\"log size\")\n", - "\n", + " ax.set_xlabel(\"log value\")\n", + " ax.set_ylabel(\"log prob\")\n", + " \n", " ax.legend()\n", - "\n", + " \n", + " \n", "fig.subplots_adjust(hspace=0.4)\n", "\n", "plt.show()" @@ -662,15 +842,72 @@ }, { "cell_type": "markdown", - "id": "38e85b68", + "id": "aac0349c", "metadata": {}, "source": [ "As with the CCDF, the empirical CCDF from the Pareto distributions is \n", "approximately linear in a log-log plot.\n", "\n", - "We will use this idea below when we look at real data.\n", + "We will use this idea [below](https://intro.quantecon.org/heavy_tails.html#heavy-tails-in-economic-cross-sections) when we look at real data." + ] + }, + { + "cell_type": "markdown", + "id": "540c2a73", + "metadata": {}, + "source": [ + "#### Q-Q Plots\n", + "\n", + "We can also use a [qq plot](https://en.wikipedia.org/wiki/Q%E2%80%93Q_plot) to do a visual comparison between two probability distributions. \n", "\n", + "The [statsmodels](https://www.statsmodels.org/stable/index.html) package provides a convenient [qqplot](https://www.statsmodels.org/stable/generated/statsmodels.graphics.gofplots.qqplot.html) function that, by default, compares sample data to the quintiles of the normal distribution.\n", "\n", + "If the data is drawn from a normal distribution, the plot would look like:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9e773026", + "metadata": {}, + "outputs": [], + "source": [ + "data_normal = np.random.normal(size=sample_size)\n", + "sm.qqplot(data_normal, line='45')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "93b38cac", + "metadata": {}, + "source": [ + "We can now compare this with the exponential, log-normal, and Pareto distributions" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a8dc373f", + "metadata": {}, + "outputs": [], + "source": [ + "# Build figure\n", + "fig, axes = plt.subplots(1, 3, figsize=(12, 4))\n", + "axes = axes.flatten()\n", + "labels = ['exponential', 'lognormal', 'Pareto']\n", + "for data, label, ax in zip(data_list, labels, axes):\n", + " sm.qqplot(data, line='45', ax=ax, )\n", + " ax.set_title(label)\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "4ce35583", + "metadata": {}, + "source": [ "### Power laws \n", "\n", "\n", @@ -724,7 +961,7 @@ { "cell_type": "code", "execution_count": null, - "id": "523a9803", + "id": "35880a3e", "metadata": { "tags": [ "hide-input" @@ -755,7 +992,7 @@ " fw = np.empty_like(aw, dtype='float64')\n", " for i, a in enumerate(aw):\n", " fw[i] = a / np.sum(aw)\n", - " pdf = lambda x: interp(data, fw, x)\n", + " pdf = lambda x: np.interp(x, data, fw)\n", " data = np.sort(data)\n", " j = 0\n", " for i, d in enumerate(data):\n", @@ -778,7 +1015,7 @@ " if not xlabel:\n", " xlabel='log value'\n", " ax.set_xlabel(xlabel, fontsize=12)\n", - " ax.set_ylabel(\"log prob.\", fontsize=12)\n", + " ax.set_ylabel(\"log prob\", fontsize=12)\n", " \n", " if label:\n", " ax.legend(loc='lower left', fontsize=12)\n", @@ -792,7 +1029,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6121716c", + "id": "41ffad1b", "metadata": { "tags": [ "hide-input" @@ -823,7 +1060,7 @@ }, { "cell_type": "markdown", - "id": "6b3e193b", + "id": "25f707de", "metadata": {}, "source": [ "### Firm size\n", @@ -834,15 +1071,21 @@ { "cell_type": "code", "execution_count": null, - "id": "ab392f4e", + "id": "1597ac4d", "metadata": { + "mystnb": { + "figure": { + "caption": "Firm size distribution", + "name": "firm-size-dist" + } + }, "tags": [ "hide-input" ] }, "outputs": [], "source": [ - "df_fs = pd.read_csv('https://media.githubusercontent.com/media/QuantEcon/high_dim_data/update_csdata/cross_section/forbes-global2000.csv')\n", + "df_fs = pd.read_csv('https://media.githubusercontent.com/media/QuantEcon/high_dim_data/main/cross_section/forbes-global2000.csv')\n", "df_fs = df_fs[['Country', 'Sales', 'Profits', 'Assets', 'Market Value']]\n", "fig, ax = plt.subplots(figsize=(6.4, 3.5))\n", "\n", @@ -856,12 +1099,12 @@ }, { "cell_type": "markdown", - "id": "7265e08b", + "id": "53118706", "metadata": {}, "source": [ "### City size\n", "\n", - "Here are plots of the city size distribution for the US and brazil in 2023 from world population review.\n", + "Here are plots of the city size distribution for the US and Brazil in 2023 from the World Population Review.\n", "\n", "The size is measured by population." ] @@ -869,8 +1112,14 @@ { "cell_type": "code", "execution_count": null, - "id": "d1bf0ae3", + "id": "2a1b7098", "metadata": { + "mystnb": { + "figure": { + "caption": "City size distribution", + "name": "city-size-dist" + } + }, "tags": [ "hide-input" ] @@ -878,8 +1127,8 @@ "outputs": [], "source": [ "# import population data of cities in 2023 United States and 2023 Brazil from world population review\n", - "df_cs_us = pd.read_csv('https://media.githubusercontent.com/media/QuantEcon/high_dim_data/update_csdata/cross_section/cities_us.csv')\n", - "df_cs_br = pd.read_csv('https://media.githubusercontent.com/media/QuantEcon/high_dim_data/update_csdata/cross_section/cities_brazil.csv')\n", + "df_cs_us = pd.read_csv('https://media.githubusercontent.com/media/QuantEcon/high_dim_data/main/cross_section/cities_us.csv')\n", + "df_cs_br = pd.read_csv('https://media.githubusercontent.com/media/QuantEcon/high_dim_data/main/cross_section/cities_brazil.csv')\n", "\n", "fig, axes = plt.subplots(1, 2, figsize=(8.8, 3.6))\n", "\n", @@ -891,7 +1140,7 @@ }, { "cell_type": "markdown", - "id": "8fe1ade3", + "id": "9700fa29", "metadata": {}, "source": [ "### Wealth\n", @@ -904,15 +1153,21 @@ { "cell_type": "code", "execution_count": null, - "id": "1acf1cdb", + "id": "07d6e437", "metadata": { + "mystnb": { + "figure": { + "caption": "Wealth distribution (Forbes billionaires in 2020)", + "name": "wealth-dist" + } + }, "tags": [ "hide-input" ] }, "outputs": [], "source": [ - "df_w = pd.read_csv('https://media.githubusercontent.com/media/QuantEcon/high_dim_data/update_csdata/cross_section/forbes-billionaires.csv')\n", + "df_w = pd.read_csv('https://media.githubusercontent.com/media/QuantEcon/high_dim_data/main/cross_section/forbes-billionaires.csv')\n", "df_w = df_w[['country', 'realTimeWorth', 'realTimeRank']].dropna()\n", "df_w = df_w.astype({'realTimeRank': int})\n", "df_w = df_w.sort_values('realTimeRank', ascending=True).copy()\n", @@ -939,7 +1194,7 @@ }, { "cell_type": "markdown", - "id": "94fcaf1b", + "id": "fa12cce4", "metadata": {}, "source": [ "### GDP\n", @@ -952,7 +1207,7 @@ { "cell_type": "code", "execution_count": null, - "id": "98db4a23", + "id": "90ca03bd", "metadata": { "tags": [ "hide-input" @@ -969,14 +1224,21 @@ " c=\"all_countries\", \n", " s=\"2021\", \n", " e=\"2021\", \n", - " varnames=variable_names)" + " varnames=variable_names)\n", + "df_gdp1.dropna(inplace=True)" ] }, { "cell_type": "code", "execution_count": null, - "id": "49ea2533", + "id": "7378b27e", "metadata": { + "mystnb": { + "figure": { + "caption": "GDP per capita distribution", + "name": "gdppc-dist" + } + }, "tags": [ "hide-input" ] @@ -993,7 +1255,7 @@ }, { "cell_type": "markdown", - "id": "053a21fb", + "id": "fe2d4ad2", "metadata": {}, "source": [ "The plot is concave rather than linear, so the distribution has light tails.\n", @@ -1010,7 +1272,7 @@ "the underlying mean of the distribution.\n", "\n", "To understand this point better, recall {doc}`our earlier discussion ` \n", - "of the Law of Large Numbers, which considered IID $X_1, \\ldots, X_n$ with common distribution $F$\n", + "of the law of large numbers, which considered IID $X_1, \\ldots, X_n$ with common distribution $F$\n", "\n", "If $\\mathbb E |X_i|$ is finite, then\n", "the sample mean $\\bar X_n := \\frac{1}{n} \\sum_{i=1}^n X_i$ satisfies\n", @@ -1024,7 +1286,7 @@ "where $\\mu := \\mathbb E X_i = \\int x F(dx)$ is the common mean of the sample.\n", "\n", "The condition $\\mathbb E | X_i | = \\int |x| F(dx) < \\infty$ holds\n", - "in most cases but can fail if the distribution $F$ is very heavy tailed.\n", + "in most cases but can fail if the distribution $F$ is very heavy-tailed.\n", "\n", "For example, it fails for the Cauchy distribution.\n", "\n", @@ -1035,8 +1297,15 @@ { "cell_type": "code", "execution_count": null, - "id": "8ad61030", - "metadata": {}, + "id": "1b9294ea", + "metadata": { + "mystnb": { + "figure": { + "caption": "LLN failure", + "name": "fail-lln" + } + } + }, "outputs": [], "source": [ "from scipy.stats import cauchy\n", @@ -1056,8 +1325,8 @@ "\n", "# Plot\n", "ax.plot(range(N), sample_mean, alpha=0.6, label='$\\\\bar{X}_n$')\n", - "\n", "ax.plot(range(N), np.zeros(N), 'k--', lw=0.5)\n", + "ax.set_xlabel(r\"$n$\")\n", "ax.legend()\n", "\n", "plt.show()" @@ -1065,7 +1334,7 @@ }, { "cell_type": "markdown", - "id": "871afdeb", + "id": "7709faaa", "metadata": {}, "source": [ "The sequence shows no sign of converging.\n", @@ -1073,12 +1342,13 @@ "We return to this point in the exercises.\n", "\n", "\n", + "(heavy-tail:application)=\n", "## Why do heavy tails matter?\n", "\n", "We have now seen that \n", "\n", "1. heavy tails are frequent in economics and\n", - "2. the Law of Large Numbers fails when tails are very heavy.\n", + "2. the law of large numbers fails when tails are very heavy.\n", "\n", "But what about in the real world? Do heavy tails matter?\n", "\n", @@ -1103,7 +1373,9 @@ "\n", "If instead the investor puts share $1/n$ of her wealth in each asset, then the portfolio payoff is\n", "\n", - "$$ Y_n = \\sum_{i=1}^n \\frac{X_i}{n} = \\frac{1}{n} \\sum_{i=1}^n X_i. $$ \n", + "$$\n", + "Y_n = \\sum_{i=1}^n \\frac{X_i}{n} = \\frac{1}{n} \\sum_{i=1}^n X_i. \n", + "$$ \n", "\n", "Try computing the mean and variance.\n", "\n", @@ -1131,9 +1403,7 @@ "The same is true for the income distribution.\n", "\n", "For example, the heaviness of the tail of the income distribution helps\n", - "determine how much revenue a given tax policy will raise.\n", - "\n", - "\n", + "determine {doc}`how much revenue a given tax policy will raise `.\n", "\n", "\n", "(cltail)=\n", @@ -1150,9 +1420,10 @@ "The definitions for\n", "left hand tails are very similar and we omit them to simplify the exposition.\n", "\n", + "(heavy-tail:formal-definition)=\n", "### Light and heavy tails\n", "\n", - "A distribution $F$ with density $f$ on $\\mathbb R_+$ is called **heavy-tailed** if\n", + "A distribution $F$ with density $f$ on $\\mathbb R_+$ is called [heavy-tailed](https://en.wikipedia.org/wiki/Heavy-tailed_distribution) if\n", "\n", "```{math}\n", ":label: defht\n", @@ -1170,10 +1441,9 @@ "heavy-tailed because its moment generating function is infinite everywhere on\n", "$(0, \\infty)$.\n", "\n", - "As claimed above, the Pareto distribution is also heavy-tailed.\n", - "\n", - "It is easy to see that, under the Pareto law, $\\mathbb P\\{X > x\\}$ satisfies {eq}`plrt`.\n", + "The Pareto distribution is also heavy-tailed.\n", "\n", + "Less formally, a heavy-tailed distribution is one that is not exponentially bounded (i.e. the tails are heavier than the exponential distribution). \n", "\n", "A distribution $F$ on $\\mathbb R_+$ is called **light-tailed** if it is not heavy-tailed.\n", "\n", @@ -1183,7 +1453,9 @@ "\n", "As another example, if $X$ has the [exponential distribution](https://en.wikipedia.org/wiki/Exponential_distribution), with cdf $F(x) = 1 - \\exp(-\\lambda x)$ for some $\\lambda > 0$, then its moment generating function is \n", "\n", - "$$ m(t) = \\frac{\\lambda}{\\lambda - t} \\quad \\text{when } t < \\lambda $$\n", + "$$\n", + "m(t) = \\frac{\\lambda}{\\lambda - t} \\quad \\text{when } t < \\lambda \n", + "$$\n", "\n", "In particular, $m(t)$ is finite whenever $t < \\lambda$, so $X$ is light-tailed.\n", "\n", @@ -1233,7 +1505,7 @@ "\n", "Fix $r \\geq \\alpha$.\n", "\n", - "As discussed after {eq}`plrt`, we can take positive constants $b$ and $\\bar x$ such that\n", + "In view of {eq}`plrt`, we can take positive constants $b$ and $\\bar x$ such that\n", "\n", "$$\n", "\\mathbb P\\{X > x\\} \\geq b x^{- \\alpha} \\text{ whenever } x \\geq \\bar x\n", @@ -1242,13 +1514,13 @@ "But then\n", "\n", "$$\n", - "\\mathbb E X^r = r \\int_0^\\infty x^{r-1} \\mathbb P\\{ X > x \\} x\n", + "\\mathbb E X^r = r \\int_0^\\infty x^{r-1} \\mathbb P\\{ X > x \\} dx\n", "\\geq\n", - "r \\int_0^{\\bar x} x^{r-1} \\mathbb P\\{ X > x \\} x\n", - "+ r \\int_{\\bar x}^\\infty x^{r-1} b x^{-\\alpha} x.\n", + "r \\int_0^{\\bar x} x^{r-1} \\mathbb P\\{ X > x \\} dx\n", + "+ r \\int_{\\bar x}^\\infty x^{r-1} b x^{-\\alpha} dx.\n", "$$\n", "\n", - "We know that $\\int_{\\bar x}^\\infty x^{r-\\alpha-1} x = \\infty$ whenever $r - \\alpha - 1 \\geq -1$.\n", + "We know that $\\int_{\\bar x}^\\infty x^{r-\\alpha-1} dx = \\infty$ whenever $r - \\alpha - 1 \\geq -1$.\n", "\n", "Since $r \\geq \\alpha$, we have $\\mathbb E X^r = \\infty$.\n", "\n", @@ -1277,7 +1549,7 @@ { "cell_type": "code", "execution_count": null, - "id": "25174f6d", + "id": "a84a06ab", "metadata": {}, "outputs": [], "source": [ @@ -1304,7 +1576,7 @@ }, { "cell_type": "markdown", - "id": "3ffa70ff", + "id": "fd5558c9", "metadata": {}, "source": [ "```{solution-end}\n", @@ -1343,7 +1615,7 @@ "\n", "The Pareto distribution is assumed to take the form {eq}`pareto` with $\\bar x = 1$ and $\\alpha = 1.05$.\n", "\n", - "(The value the tail index $\\alpha$ is plausible given the data {cite}`gabaix2016power`.)\n", + "(The value of the tail index $\\alpha$ is plausible given the data {cite}`gabaix2016power`.)\n", "\n", "To make the lognormal option as similar as possible to the Pareto option, choose \n", "its parameters such that the mean and median of both distributions are the same.\n", @@ -1397,14 +1669,14 @@ "\n", "which we solve for $\\mu$ and $\\sigma$ given $\\alpha = 1.05$.\n", "\n", - "Here is code that generates the two samples, produces the violin plot and\n", + "Here is the code that generates the two samples, produces the violin plot and\n", "prints the mean and standard deviation of the two samples." ] }, { "cell_type": "code", "execution_count": null, - "id": "020a6a84", + "id": "396ec677", "metadata": {}, "outputs": [], "source": [ @@ -1427,7 +1699,7 @@ }, { "cell_type": "markdown", - "id": "4d336ceb", + "id": "e1ff1e9b", "metadata": {}, "source": [ "Let's compute the lognormal parameters:" @@ -1436,7 +1708,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f0245d3d", + "id": "a69f96b2", "metadata": {}, "outputs": [], "source": [ @@ -1447,7 +1719,7 @@ }, { "cell_type": "markdown", - "id": "950b3969", + "id": "556852d4", "metadata": {}, "source": [ "Here's a function to compute a single estimate of tax revenue for a particular\n", @@ -1457,7 +1729,7 @@ { "cell_type": "code", "execution_count": null, - "id": "184969f4", + "id": "479cb120", "metadata": {}, "outputs": [], "source": [ @@ -1474,7 +1746,7 @@ }, { "cell_type": "markdown", - "id": "c82073a9", + "id": "33c1eade", "metadata": {}, "source": [ "Now let's generate the violin plot." @@ -1483,7 +1755,7 @@ { "cell_type": "code", "execution_count": null, - "id": "604e2ef3", + "id": "02745b46", "metadata": {}, "outputs": [], "source": [ @@ -1508,7 +1780,7 @@ }, { "cell_type": "markdown", - "id": "ec01727e", + "id": "4ed3c40b", "metadata": {}, "source": [ "Finally, let's print the means and standard deviations." @@ -1517,7 +1789,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1912ec0f", + "id": "d97578a4", "metadata": {}, "outputs": [], "source": [ @@ -1527,7 +1799,7 @@ { "cell_type": "code", "execution_count": null, - "id": "d55269f7", + "id": "d886a812", "metadata": {}, "outputs": [], "source": [ @@ -1536,7 +1808,7 @@ }, { "cell_type": "markdown", - "id": "e37a8195", + "id": "704c9601", "metadata": {}, "source": [ "Looking at the output of the code, our main conclusion is that the Pareto\n", @@ -1551,7 +1823,7 @@ "The [characteristic function](https://en.wikipedia.org/wiki/Characteristic_function_%28probability_theory%29) of the Cauchy distribution is\n", "\n", "$$\n", - " \\phi(t) = \\mathbb E e^{itX} = \\int e^{i t x} f(x) dx = e^{-|t|}\n", + "\\phi(t) = \\mathbb E e^{itX} = \\int e^{i t x} f(x) dx = e^{-|t|}\n", "$$ (lln_cch)\n", "\n", "Prove that the sample mean $\\bar X_n$ of $n$ independent draws $X_1, \\ldots,\n", @@ -1590,12 +1862,87 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.16.1" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 12, + 19, + 23, + 27, + 38, + 84, + 98, + 107, + 109, + 113, + 129, + 187, + 193, + 211, + 219, + 225, + 243, + 248, + 269, + 343, + 376, + 402, + 420, + 459, + 477, + 540, + 556, + 561, + 576, + 597, + 601, + 605, + 643, + 650, + 660, + 664, + 668, + 678, + 729, + 789, + 811, + 817, + 835, + 843, + 861, + 869, + 900, + 908, + 924, + 938, + 975, + 1004, + 1214, + 1234, + 1329, + 1345, + 1349, + 1353, + 1358, + 1368, + 1372, + 1390, + 1394, + 1398, + 1400 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/heavy_tails.md b/book/_build/html/_sources/heavy_tails.md new file mode 100644 index 0000000..ce05137 --- /dev/null +++ b/book/_build/html/_sources/heavy_tails.md @@ -0,0 +1,1448 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.16.1 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +(heavy_tail)= +# Heavy-Tailed Distributions + +In addition to what's in Anaconda, this lecture will need the following libraries: + +```{code-cell} ipython3 +:tags: [hide-output] + +%pip install --upgrade yfinance pandas_datareader +``` + +We use the following imports. + +```{code-cell} ipython3 +import matplotlib.pyplot as plt +import numpy as np +import yfinance as yf +import pandas as pd +import statsmodels.api as sm + +from pandas_datareader import wb +from scipy.stats import norm, cauchy +from pandas.plotting import register_matplotlib_converters +register_matplotlib_converters() +``` + +## Overview + +Heavy-tailed distributions are a class of distributions that generate "extreme" outcomes. + +In the natural sciences (and in more traditional economics courses), heavy-tailed distributions are seen as quite exotic and non-standard. + +However, it turns out that heavy-tailed distributions play a crucial role in economics. + +In fact many -- if not most -- of the important distributions in economics are heavy-tailed. + +In this lecture we explain what heavy tails are and why they are -- or at least +why they should be -- central to economic analysis. + + +### Introduction: light tails + +Most {doc}`commonly used probability distributions ` in classical statistics and +the natural sciences have "light tails." + +To explain this concept, let's look first at examples. + +```{prf:example} +:label: ht_ex_nd + +The classic example is the [normal distribution](https://en.wikipedia.org/wiki/Normal_distribution), which has density + +$$ +f(x) = \frac{1}{\sqrt{2\pi}\sigma} +\exp\left( -\frac{(x-\mu)^2}{2 \sigma^2} \right) +\qquad +(-\infty < x < \infty) +$$ + + +The two parameters $\mu$ and $\sigma$ are the mean and standard deviation +respectively. + +As $x$ deviates from $\mu$, the value of $f(x)$ goes to zero extremely +quickly. +``` + +We can see this when we plot the density and show a histogram of observations, +as with the following code (which assumes $\mu=0$ and $\sigma=1$). + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Histogram of observations + name: hist-obs +--- +fig, ax = plt.subplots() +X = norm.rvs(size=1_000_000) +ax.hist(X, bins=40, alpha=0.4, label='histogram', density=True) +x_grid = np.linspace(-4, 4, 400) +ax.plot(x_grid, norm.pdf(x_grid), label='density') +ax.legend() +plt.show() +``` + +Notice how + +* the density's tails converge quickly to zero in both directions and +* even with 1,000,000 draws, we get no very large or very small observations. + +We can see the last point more clearly by executing + +```{code-cell} ipython3 +X.min(), X.max() +``` + +Here's another view of draws from the same distribution: + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Histogram of observations + name: hist-obs2 +--- +n = 2000 +fig, ax = plt.subplots() +data = norm.rvs(size=n) +ax.plot(list(range(n)), data, linestyle='', marker='o', alpha=0.5, ms=4) +ax.vlines(list(range(n)), 0, data, lw=0.2) +ax.set_ylim(-15, 15) +ax.set_xlabel('$i$') +ax.set_ylabel('$X_i$', rotation=0) +plt.show() +``` + +We have plotted each individual draw $X_i$ against $i$. + +None are very large or very small. + +In other words, extreme observations are rare and draws tend not to deviate +too much from the mean. + +Putting this another way, light-tailed distributions are those that +rarely generate extreme values. + +(A more formal definition is given {ref}`below `.) + +Many statisticians and econometricians +use rules of thumb such as "outcomes more than four or five +standard deviations from the mean can safely be ignored." + +But this is only true when distributions have light tails. + + +### When are light tails valid? + +In probability theory and in the real world, many distributions are +light-tailed. + +For example, human height is light-tailed. + +Yes, it's true that we see some very tall people. + +* For example, basketballer [Sun Mingming](https://en.wikipedia.org/wiki/Sun_Mingming) is 2.32 meters tall + +But have you ever heard of someone who is 20 meters tall? Or 200? Or 2000? + +Have you ever wondered why not? + +After all, there are 8 billion people in the world! + +In essence, the reason we don't see such draws is that the distribution of +human height has very light tails. + +In fact the distribution of human height obeys a bell-shaped curve similar to the normal distribution. + + +### Returns on assets + + +But what about economic data? + +Let's look at some financial data first. + +Our aim is to plot the daily change in the price of Amazon (AMZN) stock for +the period from 1st January 2015 to 1st July 2022. + +This equates to daily returns if we set dividends aside. + +The code below produces the desired plot using Yahoo financial data via the `yfinance` library. + +```{code-cell} ipython3 +:tags: [hide-output] + +data = yf.download('AMZN', '2015-1-1', '2022-7-1') +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Daily Amazon returns + name: dailyreturns-amzn +--- +s = data['Close'] +r = s.pct_change() + +fig, ax = plt.subplots() + +ax.plot(r, linestyle='', marker='o', alpha=0.5, ms=4) +ax.vlines(r.index, 0, r.values, lw=0.2) +ax.set_ylabel('returns', fontsize=12) +ax.set_xlabel('date', fontsize=12) + +plt.show() +``` + +This data looks different to the draws from the normal distribution we saw above. + +Several of observations are quite extreme. + +We get a similar picture if we look at other assets, such as Bitcoin + +```{code-cell} ipython3 +:tags: [hide-output] + +data = yf.download('BTC-USD', '2015-1-1', '2022-7-1') +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Daily Bitcoin returns + name: dailyreturns-btc +--- +s = data['Close'] +r = s.pct_change() + +fig, ax = plt.subplots() + +ax.plot(r, linestyle='', marker='o', alpha=0.5, ms=4) +ax.vlines(r.index, 0, r.values, lw=0.2) +ax.set_ylabel('returns', fontsize=12) +ax.set_xlabel('date', fontsize=12) + +plt.show() +``` + +The histogram also looks different to the histogram of the normal +distribution: + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Histogram (normal vs bitcoin returns) + name: hist-normal-btc +--- +r = np.random.standard_t(df=5, size=1000) + +fig, ax = plt.subplots() +ax.hist(r, bins=60, alpha=0.4, label='bitcoin returns', density=True) + +xmin, xmax = plt.xlim() +x = np.linspace(xmin, xmax, 100) +p = norm.pdf(x, np.mean(r), np.std(r)) +ax.plot(x, p, linewidth=2, label='normal distribution') + +ax.set_xlabel('returns', fontsize=12) +ax.legend() + +plt.show() +``` + +If we look at higher frequency returns data (e.g., tick-by-tick), we often see +even more extreme observations. + +See, for example, {cite}`mandelbrot1963variation` or {cite}`rachev2003handbook`. + + +### Other data + +The data we have just seen is said to be "heavy-tailed". + +With heavy-tailed distributions, extreme outcomes occur relatively +frequently. + +```{prf:example} +:label: ht_ex_od + +Importantly, there are many examples of heavy-tailed distributions +observed in economic and financial settings! + +For example, the income and the wealth distributions are heavy-tailed + +* You can imagine this: most people have low or modest wealth but some people + are extremely rich. + +The firm size distribution is also heavy-tailed + +* You can imagine this too: most firms are small but some firms are enormous. + +The distribution of town and city sizes is heavy-tailed + +* Most towns and cities are small but some are very large. +``` + +Later in this lecture, we examine heavy tails in these distributions. + +### Why should we care? + +Heavy tails are common in economic data but does that mean they are important? + +The answer to this question is affirmative! + +When distributions are heavy-tailed, we need to think carefully about issues +like + +* diversification and risk +* forecasting +* taxation (across a heavy-tailed income distribution), etc. + +We return to these points {ref}`below `. + + +## Visual comparisons +In this section, we will introduce important concepts such as the Pareto distribution, Counter CDFs, and Power laws, which aid in recognizing heavy-tailed distributions. + +Later we will provide a mathematical definition of the difference between +light and heavy tails. + +But for now let's do some visual comparisons to help us build intuition on the +difference between these two types of distributions. + + +### Simulations + +The figure below shows a simulation. + +The top two subfigures each show 120 independent draws from the normal +distribution, which is light-tailed. + +The bottom subfigure shows 120 independent draws from [the Cauchy +distribution](https://en.wikipedia.org/wiki/Cauchy_distribution), which is +heavy-tailed. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Draws from normal and Cauchy distributions + name: draws-normal-cauchy +--- +n = 120 +np.random.seed(11) + +fig, axes = plt.subplots(3, 1, figsize=(6, 12)) + +for ax in axes: + ax.set_ylim((-120, 120)) + +s_vals = 2, 12 + +for ax, s in zip(axes[:2], s_vals): + data = np.random.randn(n) * s + ax.plot(list(range(n)), data, linestyle='', marker='o', alpha=0.5, ms=4) + ax.vlines(list(range(n)), 0, data, lw=0.2) + ax.set_title(f"draws from $N(0, \sigma^2)$ with $\sigma = {s}$", fontsize=11) + +ax = axes[2] +distribution = cauchy() +data = distribution.rvs(n) +ax.plot(list(range(n)), data, linestyle='', marker='o', alpha=0.5, ms=4) +ax.vlines(list(range(n)), 0, data, lw=0.2) +ax.set_title(f"draws from the Cauchy distribution", fontsize=11) + +plt.subplots_adjust(hspace=0.25) + +plt.show() +``` + +In the top subfigure, the standard deviation of the normal distribution is 2, +and the draws are clustered around the mean. + +In the middle subfigure, the standard deviation is increased to 12 and, as +expected, the amount of dispersion rises. + +The bottom subfigure, with the Cauchy draws, shows a different pattern: tight +clustering around the mean for the great majority of observations, combined +with a few sudden large deviations from the mean. + +This is typical of a heavy-tailed distribution. + + +### Nonnegative distributions + +Let's compare some distributions that only take nonnegative values. + +One is the exponential distribution, which we discussed in {doc}`our lecture +on probability and distributions `. + +The exponential distribution is a light-tailed distribution. + +Here are some draws from the exponential distribution. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Draws of exponential distribution + name: draws-exponential +--- +n = 120 +np.random.seed(11) + +fig, ax = plt.subplots() +ax.set_ylim((0, 50)) + +data = np.random.exponential(size=n) +ax.plot(list(range(n)), data, linestyle='', marker='o', alpha=0.5, ms=4) +ax.vlines(list(range(n)), 0, data, lw=0.2) + +plt.show() +``` + +Another nonnegative distribution is the [Pareto distribution](https://en.wikipedia.org/wiki/Pareto_distribution). + +If $X$ has the Pareto distribution, then there are positive constants $\bar x$ +and $\alpha$ such that + +```{math} +:label: pareto + +\mathbb P\{X > x\} = +\begin{cases} + \left( \bar x/x \right)^{\alpha} + & \text{ if } x \geq \bar x + \\ + 1 + & \text{ if } x < \bar x +\end{cases} +``` + +The parameter $\alpha$ is called the **tail index** and $\bar x$ is called the +**minimum**. + +The Pareto distribution is a heavy-tailed distribution. + +One way that the Pareto distribution arises is as the exponential of an +exponential random variable. + +In particular, if $X$ is exponentially distributed with rate parameter $\alpha$, then + +$$ +Y = \bar x \exp(X) +$$ + +is Pareto-distributed with minimum $\bar x$ and tail index $\alpha$. + +Here are some draws from the Pareto distribution with tail index $1$ and minimum +$1$. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Draws from Pareto distribution + name: draws-pareto +--- +n = 120 +np.random.seed(11) + +fig, ax = plt.subplots() +ax.set_ylim((0, 80)) +exponential_data = np.random.exponential(size=n) +pareto_data = np.exp(exponential_data) +ax.plot(list(range(n)), pareto_data, linestyle='', marker='o', alpha=0.5, ms=4) +ax.vlines(list(range(n)), 0, pareto_data, lw=0.2) + +plt.show() +``` + +Notice how extreme outcomes are more common. + +### Counter CDFs + +For nonnegative random variables, one way to visualize the difference between +light and heavy tails is to look at the +**counter CDF** (CCDF). + +For a random variable $X$ with CDF $F$, the CCDF is the function + +$$ +G(x) := 1 - F(x) = \mathbb P\{X > x\} +$$ + +(Some authors call $G$ the "survival" function.) + +The CCDF shows how fast the upper tail goes to zero as $x \to \infty$. + +If $X$ is exponentially distributed with rate parameter $\alpha$, then the CCDF is + +$$ +G_E(x) = \exp(- \alpha x) +$$ + +This function goes to zero relatively quickly as $x$ gets large. + +The standard Pareto distribution, where $\bar x = 1$, has CCDF + +$$ +G_P(x) = x^{- \alpha} +$$ + +This function goes to zero as $x \to \infty$, but much slower than $G_E$. + +```{exercise} +:label: ht_ex_x1 + +Show how the CCDF of the standard Pareto distribution can be derived from the CCDF of the exponential distribution. +``` + +```{solution-start} ht_ex_x1 +:class: dropdown +``` +Letting $G_E$ and $G_P$ be defined as above, letting $X$ be exponentially +distributed with rate parameter $\alpha$, and letting $Y = \exp(X)$, we have + +$$ +\begin{aligned} + G_P(y) & = \mathbb P\{Y > y\} \\ + & = \mathbb P\{\exp(X) > y\} \\ + & = \mathbb P\{X > \ln y\} \\ + & = G_E(\ln y) \\ + & = \exp( - \alpha \ln y) \\ + & = y^{-\alpha} +\end{aligned} +$$ +```{solution-end} +``` + +Here's a plot that illustrates how $G_E$ goes to zero faster than $G_P$. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Pareto and exponential distribution comparison + name: compare-pareto-exponential +--- +x = np.linspace(1.5, 100, 1000) +fig, ax = plt.subplots() +alpha = 1.0 +ax.plot(x, np.exp(- alpha * x), label='exponential', alpha=0.8) +ax.plot(x, x**(- alpha), label='Pareto', alpha=0.8) +ax.set_xlabel('X value') +ax.set_ylabel('CCDF') +ax.legend() +plt.show() +``` + +Here's a log-log plot of the same functions, which makes visual comparison +easier. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Pareto and exponential distribution comparison (log-log) + name: compare-pareto-exponential-log-log +--- +fig, ax = plt.subplots() +alpha = 1.0 +ax.loglog(x, np.exp(- alpha * x), label='exponential', alpha=0.8) +ax.loglog(x, x**(- alpha), label='Pareto', alpha=0.8) +ax.set_xlabel('log value') +ax.set_ylabel('log prob') +ax.legend() +plt.show() +``` + +In the log-log plot, the Pareto CCDF is linear, while the exponential one is +concave. + +This idea is often used to separate light- and heavy-tailed distributions in +visualisations --- we return to this point below. + + +### Empirical CCDFs + +The sample counterpart of the CCDF function is the **empirical CCDF**. + +Given a sample $x_1, \ldots, x_n$, the empirical CCDF is given by + +$$ +\hat G(x) = \frac{1}{n} \sum_{i=1}^n \mathbb 1\{x_i > x\} +$$ + +Thus, $\hat G(x)$ shows the fraction of the sample that exceeds $x$. + +```{code-cell} ipython3 +def eccdf(x, data): + "Simple empirical CCDF function." + return np.mean(data > x) +``` + +Here's a figure containing some empirical CCDFs from simulated data. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Empirical CCDFs + name: ccdf-empirics +--- +# Parameters and grid +x_grid = np.linspace(1, 1000, 1000) +sample_size = 1000 +np.random.seed(13) +z = np.random.randn(sample_size) + +# Draws +data_exp = np.random.exponential(size=sample_size) +data_logn = np.exp(z) +data_pareto = np.exp(np.random.exponential(size=sample_size)) + +data_list = [data_exp, data_logn, data_pareto] + +# Build figure +fig, axes = plt.subplots(3, 1, figsize=(6, 8)) +axes = axes.flatten() +labels = ['exponential', 'lognormal', 'Pareto'] + +for data, label, ax in zip(data_list, labels, axes): + + ax.loglog(x_grid, [eccdf(x, data) for x in x_grid], + 'o', markersize=3.0, alpha=0.5, label=label) + ax.set_xlabel("log value") + ax.set_ylabel("log prob") + + ax.legend() + + +fig.subplots_adjust(hspace=0.4) + +plt.show() +``` + +As with the CCDF, the empirical CCDF from the Pareto distributions is +approximately linear in a log-log plot. + +We will use this idea [below](https://intro.quantecon.org/heavy_tails.html#heavy-tails-in-economic-cross-sections) when we look at real data. + ++++ + +#### Q-Q Plots + +We can also use a [qq plot](https://en.wikipedia.org/wiki/Q%E2%80%93Q_plot) to do a visual comparison between two probability distributions. + +The [statsmodels](https://www.statsmodels.org/stable/index.html) package provides a convenient [qqplot](https://www.statsmodels.org/stable/generated/statsmodels.graphics.gofplots.qqplot.html) function that, by default, compares sample data to the quintiles of the normal distribution. + +If the data is drawn from a normal distribution, the plot would look like: + +```{code-cell} ipython3 +data_normal = np.random.normal(size=sample_size) +sm.qqplot(data_normal, line='45') +plt.show() +``` + +We can now compare this with the exponential, log-normal, and Pareto distributions + +```{code-cell} ipython3 +# Build figure +fig, axes = plt.subplots(1, 3, figsize=(12, 4)) +axes = axes.flatten() +labels = ['exponential', 'lognormal', 'Pareto'] +for data, label, ax in zip(data_list, labels, axes): + sm.qqplot(data, line='45', ax=ax, ) + ax.set_title(label) +plt.tight_layout() +plt.show() +``` + +### Power laws + + +One specific class of heavy-tailed distributions has been found repeatedly in +economic and social phenomena: the class of so-called power laws. + +A random variable $X$ is said to have a **power law** if, for some $\alpha > 0$, + +```{math} +\mathbb P\{X > x\} \approx x^{-\alpha} +\quad \text{when $x$ is large} +``` +We can write this more mathematically as + +```{math} +:label: plrt + +\lim_{x \to \infty} x^\alpha \, \mathbb P\{X > x\} = c +\quad \text{for some $c > 0$} +``` + +It is also common to say that a random variable $X$ with this property +has a **Pareto tail** with **tail index** $\alpha$. + +Notice that every Pareto distribution with tail index $\alpha$ +has a **Pareto tail** with **tail index** $\alpha$. + +We can think of power laws as a generalization of Pareto distributions. + +They are distributions that resemble Pareto distributions in their upper right +tail. + +Another way to think of power laws is a set of distributions with a specific +kind of (very) heavy tail. + +## Heavy tails in economic cross-sections + +As mentioned above, heavy tails are pervasive in economic data. + +In fact power laws seem to be very common as well. + +We now illustrate this by showing the empirical CCDF of heavy tails. + +All plots are in log-log, so that a power law shows up as a linear log-log +plot, at least in the upper tail. + +We hide the code that generates the figures, which is somewhat complex, but +readers are of course welcome to explore the code (perhaps after examining the figures). + +```{code-cell} ipython3 +:tags: [hide-input] + +def empirical_ccdf(data, + ax, + aw=None, # weights + label=None, + xlabel=None, + add_reg_line=False, + title=None): + """ + Take data vector and return prob values for plotting. + Upgraded empirical_ccdf + """ + y_vals = np.empty_like(data, dtype='float64') + p_vals = np.empty_like(data, dtype='float64') + n = len(data) + if aw is None: + for i, d in enumerate(data): + # record fraction of sample above d + y_vals[i] = np.sum(data >= d) / n + p_vals[i] = np.sum(data == d) / n + else: + fw = np.empty_like(aw, dtype='float64') + for i, a in enumerate(aw): + fw[i] = a / np.sum(aw) + pdf = lambda x: np.interp(x, data, fw) + data = np.sort(data) + j = 0 + for i, d in enumerate(data): + j += pdf(d) + y_vals[i] = 1- j + + x, y = np.log(data), np.log(y_vals) + + results = sm.OLS(y, sm.add_constant(x)).fit() + b, a = results.params + + kwargs = [('alpha', 0.3)] + if label: + kwargs.append(('label', label)) + kwargs = dict(kwargs) + + ax.scatter(x, y, **kwargs) + if add_reg_line: + ax.plot(x, x * a + b, 'k-', alpha=0.6, label=f"slope = ${a: 1.2f}$") + if not xlabel: + xlabel='log value' + ax.set_xlabel(xlabel, fontsize=12) + ax.set_ylabel("log prob", fontsize=12) + + if label: + ax.legend(loc='lower left', fontsize=12) + + if title: + ax.set_title(title) + + return np.log(data), y_vals, p_vals +``` + +```{code-cell} ipython3 +:tags: [hide-input] + +def extract_wb(varlist=['NY.GDP.MKTP.CD'], + c='all_countries', + s=1900, + e=2021, + varnames=None): + if c == "all_countries": + # Keep countries only (no aggregated regions) + countries = wb.get_countries() + countries_name = countries[countries['region'] != 'Aggregates']['name'].values + c = "all" + + df = wb.download(indicator=varlist, country=c, start=s, end=e).stack().unstack(0).reset_index() + df = df.drop(['level_1'], axis=1).transpose() + if varnames is not None: + df.columns = varnames + df = df[1:] + + df1 =df[df.index.isin(countries_name)] + return df1 +``` + +### Firm size + +Here is a plot of the firm size distribution for the largest 500 firms in 2020 taken from Forbes Global 2000. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Firm size distribution + name: firm-size-dist +tags: [hide-input] +--- +df_fs = pd.read_csv('https://media.githubusercontent.com/media/QuantEcon/high_dim_data/main/cross_section/forbes-global2000.csv') +df_fs = df_fs[['Country', 'Sales', 'Profits', 'Assets', 'Market Value']] +fig, ax = plt.subplots(figsize=(6.4, 3.5)) + +label="firm size (market value)" +top = 500 # set the cutting for top +d = df_fs.sort_values('Market Value', ascending=False) +empirical_ccdf(np.asarray(d['Market Value'])[:top], ax, label=label, add_reg_line=True) + +plt.show() +``` + +### City size + +Here are plots of the city size distribution for the US and Brazil in 2023 from the World Population Review. + +The size is measured by population. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: City size distribution + name: city-size-dist +tags: [hide-input] +--- +# import population data of cities in 2023 United States and 2023 Brazil from world population review +df_cs_us = pd.read_csv('https://media.githubusercontent.com/media/QuantEcon/high_dim_data/main/cross_section/cities_us.csv') +df_cs_br = pd.read_csv('https://media.githubusercontent.com/media/QuantEcon/high_dim_data/main/cross_section/cities_brazil.csv') + +fig, axes = plt.subplots(1, 2, figsize=(8.8, 3.6)) + +empirical_ccdf(np.asarray(df_cs_us["pop2023"]), axes[0], label="US", add_reg_line=True) +empirical_ccdf(np.asarray(df_cs_br['pop2023']), axes[1], label="Brazil", add_reg_line=True) + +plt.show() +``` + +### Wealth + +Here is a plot of the upper tail (top 500) of the wealth distribution. + +The data is from the Forbes Billionaires list in 2020. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Wealth distribution (Forbes billionaires in 2020) + name: wealth-dist +tags: [hide-input] +--- +df_w = pd.read_csv('https://media.githubusercontent.com/media/QuantEcon/high_dim_data/main/cross_section/forbes-billionaires.csv') +df_w = df_w[['country', 'realTimeWorth', 'realTimeRank']].dropna() +df_w = df_w.astype({'realTimeRank': int}) +df_w = df_w.sort_values('realTimeRank', ascending=True).copy() +countries = ['United States', 'Japan', 'India', 'Italy'] +N = len(countries) + +fig, axs = plt.subplots(2, 2, figsize=(8, 6)) +axs = axs.flatten() + +for i, c in enumerate(countries): + df_w_c = df_w[df_w['country'] == c].reset_index() + z = np.asarray(df_w_c['realTimeWorth']) + # print('number of the global richest 2000 from '+ c, len(z)) + top = 500 # cut-off number: top 500 + if len(z) <= top: + z = z[:top] + + empirical_ccdf(z[:top], axs[i], label=c, xlabel='log wealth', add_reg_line=True) + +fig.tight_layout() + +plt.show() +``` + +### GDP + +Of course, not all cross-sectional distributions are heavy-tailed. + +Here we show cross-country per capita GDP. + +```{code-cell} ipython3 +:tags: [hide-input] + +# get gdp and gdp per capita for all regions and countries in 2021 + +variable_code = ['NY.GDP.MKTP.CD', 'NY.GDP.PCAP.CD'] +variable_names = ['GDP', 'GDP per capita'] + +df_gdp1 = extract_wb(varlist=variable_code, + c="all_countries", + s="2021", + e="2021", + varnames=variable_names) +df_gdp1.dropna(inplace=True) +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: GDP per capita distribution + name: gdppc-dist +tags: [hide-input] +--- +fig, axes = plt.subplots(1, 2, figsize=(8.8, 3.6)) + +for name, ax in zip(variable_names, axes): + empirical_ccdf(np.asarray(df_gdp1[name]).astype("float64"), ax, add_reg_line=False, label=name) + +plt.show() +``` + +The plot is concave rather than linear, so the distribution has light tails. + +One reason is that this is data on an aggregate variable, which involves some +averaging in its definition. + +Averaging tends to eliminate extreme outcomes. + + +## Failure of the LLN + +One impact of heavy tails is that sample averages can be poor estimators of +the underlying mean of the distribution. + +To understand this point better, recall {doc}`our earlier discussion ` +of the law of large numbers, which considered IID $X_1, \ldots, X_n$ with common distribution $F$ + +If $\mathbb E |X_i|$ is finite, then +the sample mean $\bar X_n := \frac{1}{n} \sum_{i=1}^n X_i$ satisfies + +```{math} +:label: lln_as2 + +\mathbb P \left\{ \bar X_n \to \mu \text{ as } n \to \infty \right\} = 1 +``` + +where $\mu := \mathbb E X_i = \int x F(dx)$ is the common mean of the sample. + +The condition $\mathbb E | X_i | = \int |x| F(dx) < \infty$ holds +in most cases but can fail if the distribution $F$ is very heavy-tailed. + +For example, it fails for the Cauchy distribution. + +Let's have a look at the behavior of the sample mean in this case, and see +whether or not the LLN is still valid. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: LLN failure + name: fail-lln +--- +from scipy.stats import cauchy + +np.random.seed(1234) +N = 1_000 + +distribution = cauchy() + +fig, ax = plt.subplots() +data = distribution.rvs(N) + +# Compute sample mean at each n +sample_mean = np.empty(N) +for n in range(1, N): + sample_mean[n] = np.mean(data[:n]) + +# Plot +ax.plot(range(N), sample_mean, alpha=0.6, label='$\\bar{X}_n$') +ax.plot(range(N), np.zeros(N), 'k--', lw=0.5) +ax.set_xlabel(r"$n$") +ax.legend() + +plt.show() +``` + +The sequence shows no sign of converging. + +We return to this point in the exercises. + + +(heavy-tail:application)= +## Why do heavy tails matter? + +We have now seen that + +1. heavy tails are frequent in economics and +2. the law of large numbers fails when tails are very heavy. + +But what about in the real world? Do heavy tails matter? + +Let's briefly discuss why they do. + + +### Diversification + +One of the most important ideas in investing is using diversification to +reduce risk. + +This is a very old idea --- consider, for example, the expression "don't put all your eggs in one basket". + +To illustrate, consider an investor with one dollar of wealth and a choice over +$n$ assets with payoffs $X_1, \ldots, X_n$. + +Suppose that returns on distinct assets are +independent and each return has mean $\mu$ and variance $\sigma^2$. + +If the investor puts all wealth in one asset, say, then the expected payoff of the +portfolio is $\mu$ and the variance is $\sigma^2$. + +If instead the investor puts share $1/n$ of her wealth in each asset, then the portfolio payoff is + +$$ +Y_n = \sum_{i=1}^n \frac{X_i}{n} = \frac{1}{n} \sum_{i=1}^n X_i. +$$ + +Try computing the mean and variance. + +You will find that + +* The mean is unchanged at $\mu$, while +* the variance of the portfolio has fallen to $\sigma^2 / n$. + +Diversification reduces risk, as expected. + +But there is a hidden assumption here: the variance of returns is finite. + +If the distribution is heavy-tailed and the variance is infinite, then this +logic is incorrect. + +For example, we saw above that if every $X_i$ is Cauchy, then so is $Y_n$. + +This means that diversification doesn't help at all! + + +### Fiscal policy + +The heaviness of the tail in the wealth distribution matters for taxation and redistribution policies. + +The same is true for the income distribution. + +For example, the heaviness of the tail of the income distribution helps +determine {doc}`how much revenue a given tax policy will raise `. + + +(cltail)= +## Classifying tail properties + +Up until now we have discussed light and heavy tails without any mathematical +definitions. + +Let's now rectify this. + +We will focus our attention on the right hand tails of +nonnegative random variables and their distributions. + +The definitions for +left hand tails are very similar and we omit them to simplify the exposition. + +(heavy-tail:formal-definition)= +### Light and heavy tails + +A distribution $F$ with density $f$ on $\mathbb R_+$ is called [heavy-tailed](https://en.wikipedia.org/wiki/Heavy-tailed_distribution) if + +```{math} +:label: defht + +\int_0^\infty \exp(tx) f(x) dx = \infty \; \text{ for all } t > 0. +``` + +We say that a nonnegative random variable $X$ is **heavy-tailed** if its density is heavy-tailed. + +This is equivalent to stating that its **moment generating function** $m(t) := +\mathbb E \exp(t X)$ is infinite for all $t > 0$. + +For example, the [log-normal +distribution](https://en.wikipedia.org/wiki/Log-normal_distribution) is +heavy-tailed because its moment generating function is infinite everywhere on +$(0, \infty)$. + +The Pareto distribution is also heavy-tailed. + +Less formally, a heavy-tailed distribution is one that is not exponentially bounded (i.e. the tails are heavier than the exponential distribution). + +A distribution $F$ on $\mathbb R_+$ is called **light-tailed** if it is not heavy-tailed. + +A nonnegative random variable $X$ is **light-tailed** if its distribution $F$ is light-tailed. + +For example, every random variable with bounded support is light-tailed. (Why?) + +As another example, if $X$ has the [exponential distribution](https://en.wikipedia.org/wiki/Exponential_distribution), with cdf $F(x) = 1 - \exp(-\lambda x)$ for some $\lambda > 0$, then its moment generating function is + +$$ +m(t) = \frac{\lambda}{\lambda - t} \quad \text{when } t < \lambda +$$ + +In particular, $m(t)$ is finite whenever $t < \lambda$, so $X$ is light-tailed. + +One can show that if $X$ is light-tailed, then all of its +[moments](https://en.wikipedia.org/wiki/Moment_(mathematics)) are finite. + +Conversely, if some moment is infinite, then $X$ is heavy-tailed. + +The latter condition is not necessary, however. + +For example, the lognormal distribution is heavy-tailed but every moment is finite. + + + +## Further reading + +For more on heavy tails in the wealth distribution, see e.g., {cite}`pareto1896cours` and {cite}`benhabib2018skewed`. + +For more on heavy tails in the firm size distribution, see e.g., {cite}`axtell2001zipf`, {cite}`gabaix2016power`. + +For more on heavy tails in the city size distribution, see e.g., {cite}`rozenfeld2011area`, {cite}`gabaix2016power`. + +There are other important implications of heavy tails, aside from those +discussed above. + +For example, heavy tails in income and wealth affect productivity growth, business cycles, and political economy. + +For further reading, see, for example, {cite}`acemoglu2002political`, {cite}`glaeser2003injustice`, {cite}`bhandari2018inequality` or {cite}`ahn2018inequality`. + + + +## Exercises + + +```{exercise} +:label: ht_ex2 + +Prove: If $X$ has a Pareto tail with tail index $\alpha$, then +$\mathbb E[X^r] = \infty$ for all $r \geq \alpha$. +``` + +```{solution-start} ht_ex2 +:class: dropdown +``` + +Let $X$ have a Pareto tail with tail index $\alpha$ and let $F$ be its cdf. + +Fix $r \geq \alpha$. + +In view of {eq}`plrt`, we can take positive constants $b$ and $\bar x$ such that + +$$ +\mathbb P\{X > x\} \geq b x^{- \alpha} \text{ whenever } x \geq \bar x +$$ + +But then + +$$ +\mathbb E X^r = r \int_0^\infty x^{r-1} \mathbb P\{ X > x \} dx +\geq +r \int_0^{\bar x} x^{r-1} \mathbb P\{ X > x \} dx ++ r \int_{\bar x}^\infty x^{r-1} b x^{-\alpha} dx. +$$ + +We know that $\int_{\bar x}^\infty x^{r-\alpha-1} dx = \infty$ whenever $r - \alpha - 1 \geq -1$. + +Since $r \geq \alpha$, we have $\mathbb E X^r = \infty$. + +```{solution-end} +``` + + +```{exercise} +:label: ht_ex3 + +Repeat exercise 1, but replace the three distributions (two normal, one +Cauchy) with three Pareto distributions using different choices of +$\alpha$. + +For $\alpha$, try 1.15, 1.5 and 1.75. + +Use `np.random.seed(11)` to set the seed. +``` + + +```{solution-start} ht_ex3 +:class: dropdown +``` + +```{code-cell} ipython3 +from scipy.stats import pareto + +np.random.seed(11) + +n = 120 +alphas = [1.15, 1.50, 1.75] + +fig, axes = plt.subplots(3, 1, figsize=(6, 8)) + +for (a, ax) in zip(alphas, axes): + ax.set_ylim((-5, 50)) + data = pareto.rvs(size=n, scale=1, b=a) + ax.plot(list(range(n)), data, linestyle='', marker='o', alpha=0.5, ms=4) + ax.vlines(list(range(n)), 0, data, lw=0.2) + ax.set_title(f"Pareto draws with $\\alpha = {a}$", fontsize=11) + +plt.subplots_adjust(hspace=0.4) + +plt.show() +``` + +```{solution-end} +``` + + +```{exercise} +:label: ht_ex5 + +There is an ongoing argument about whether the firm size distribution should +be modeled as a Pareto distribution or a lognormal distribution (see, e.g., +{cite}`fujiwara2004pareto`, {cite}`kondo2018us` or {cite}`schluter2019size`). + +This sounds esoteric but has real implications for a variety of economic +phenomena. + +To illustrate this fact in a simple way, let us consider an economy with +100,000 firms, an interest rate of `r = 0.05` and a corporate tax rate of +15%. + +Your task is to estimate the present discounted value of projected corporate +tax revenue over the next 10 years. + +Because we are forecasting, we need a model. + +We will suppose that + +1. the number of firms and the firm size distribution (measured in profits) remain fixed and +1. the firm size distribution is either lognormal or Pareto. + +Present discounted value of tax revenue will be estimated by + +1. generating 100,000 draws of firm profit from the firm size distribution, +1. multiplying by the tax rate, and +1. summing the results with discounting to obtain present value. + +The Pareto distribution is assumed to take the form {eq}`pareto` with $\bar x = 1$ and $\alpha = 1.05$. + +(The value of the tail index $\alpha$ is plausible given the data {cite}`gabaix2016power`.) + +To make the lognormal option as similar as possible to the Pareto option, choose +its parameters such that the mean and median of both distributions are the same. + +Note that, for each distribution, your estimate of tax revenue will be random +because it is based on a finite number of draws. + +To take this into account, generate 100 replications (evaluations of tax revenue) +for each of the two distributions and compare the two samples by + +* producing a [violin plot](https://en.wikipedia.org/wiki/Violin_plot) visualizing the two samples side-by-side and +* printing the mean and standard deviation of both samples. + +For the seed use `np.random.seed(1234)`. + +What differences do you observe? + +(Note: a better approach to this problem would be to model firm dynamics and +try to track individual firms given the current distribution. We will discuss +firm dynamics in later lectures.) +``` + +```{solution-start} ht_ex5 +:class: dropdown +``` + +To do the exercise, we need to choose the parameters $\mu$ +and $\sigma$ of the lognormal distribution to match the mean and median +of the Pareto distribution. + +Here we understand the lognormal distribution as that of the random variable +$\exp(\mu + \sigma Z)$ when $Z$ is standard normal. + +The mean and median of the Pareto distribution {eq}`pareto` with +$\bar x = 1$ are + +$$ +\text{mean } = \frac{\alpha}{\alpha - 1} +\quad \text{and} \quad +\text{median } = 2^{1/\alpha} +$$ + +Using the corresponding expressions for the lognormal distribution leads us to +the equations + +$$ +\frac{\alpha}{\alpha - 1} = \exp(\mu + \sigma^2/2) +\quad \text{and} \quad +2^{1/\alpha} = \exp(\mu) +$$ + +which we solve for $\mu$ and $\sigma$ given $\alpha = 1.05$. + +Here is the code that generates the two samples, produces the violin plot and +prints the mean and standard deviation of the two samples. + +```{code-cell} ipython3 +num_firms = 100_000 +num_years = 10 +tax_rate = 0.15 +r = 0.05 + +β = 1 / (1 + r) # discount factor + +x_bar = 1.0 +α = 1.05 + +def pareto_rvs(n): + "Uses a standard method to generate Pareto draws." + u = np.random.uniform(size=n) + y = x_bar / (u**(1/α)) + return y +``` + +Let's compute the lognormal parameters: + +```{code-cell} ipython3 +μ = np.log(2) / α +σ_sq = 2 * (np.log(α/(α - 1)) - np.log(2)/α) +σ = np.sqrt(σ_sq) +``` + +Here's a function to compute a single estimate of tax revenue for a particular +choice of distribution `dist`. + +```{code-cell} ipython3 +def tax_rev(dist): + tax_raised = 0 + for t in range(num_years): + if dist == 'pareto': + π = pareto_rvs(num_firms) + else: + π = np.exp(μ + σ * np.random.randn(num_firms)) + tax_raised += β**t * np.sum(π * tax_rate) + return tax_raised +``` + +Now let's generate the violin plot. + +```{code-cell} ipython3 +num_reps = 100 +np.random.seed(1234) + +tax_rev_lognorm = np.empty(num_reps) +tax_rev_pareto = np.empty(num_reps) + +for i in range(num_reps): + tax_rev_pareto[i] = tax_rev('pareto') + tax_rev_lognorm[i] = tax_rev('lognorm') + +fig, ax = plt.subplots() + +data = tax_rev_pareto, tax_rev_lognorm + +ax.violinplot(data) + +plt.show() +``` + +Finally, let's print the means and standard deviations. + +```{code-cell} ipython3 +tax_rev_pareto.mean(), tax_rev_pareto.std() +``` + +```{code-cell} ipython3 +tax_rev_lognorm.mean(), tax_rev_lognorm.std() +``` + +Looking at the output of the code, our main conclusion is that the Pareto +assumption leads to a lower mean and greater dispersion. + +```{solution-end} +``` + +```{exercise} +:label: ht_ex_cauchy + +The [characteristic function](https://en.wikipedia.org/wiki/Characteristic_function_%28probability_theory%29) of the Cauchy distribution is + +$$ +\phi(t) = \mathbb E e^{itX} = \int e^{i t x} f(x) dx = e^{-|t|} +$$ (lln_cch) + +Prove that the sample mean $\bar X_n$ of $n$ independent draws $X_1, \ldots, +X_n$ from the Cauchy distribution has the same characteristic function as +$X_1$. + +(This means that the sample mean never converges.) + +``` + +```{solution-start} ht_ex_cauchy +:class: dropdown +``` + +By independence, the characteristic function of the sample mean becomes + +$$ +\begin{aligned} + \mathbb E e^{i t \bar X_n } + & = \mathbb E \exp \left\{ i \frac{t}{n} \sum_{j=1}^n X_j \right\} + \\ + & = \mathbb E \prod_{j=1}^n \exp \left\{ i \frac{t}{n} X_j \right\} + \\ + & = \prod_{j=1}^n \mathbb E \exp \left\{ i \frac{t}{n} X_j \right\} + = [\phi(t/n)]^n +\end{aligned} +$$ + +In view of {eq}`lln_cch`, this is just $e^{-|t|}$. + +Thus, in the case of the Cauchy distribution, the sample mean itself has the very same Cauchy distribution, regardless of $n$! + +```{solution-end} +``` diff --git a/book/_build/html/_sources/inequality.ipynb b/book/_build/html/_sources/inequality.ipynb new file mode 100644 index 0000000..dfd2225 --- /dev/null +++ b/book/_build/html/_sources/inequality.ipynb @@ -0,0 +1,1832 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "8ab493ba", + "metadata": {}, + "source": [ + "# Income and Wealth Inequality\n", + "\n", + "## Overview\n", + "\n", + "In the lecture {doc}`long_run_growth` we studied how GDP per capita has changed\n", + "for certain countries and regions.\n", + "\n", + "Per capita GDP is important because it gives us an idea of average income for\n", + "households in a given country.\n", + "\n", + "However, when we study income and wealth, averages are only part of the story.\n", + "\n", + "```{prf:example}\n", + ":label: ie_ex_av\n", + "\n", + "For example, imagine two societies, each with one million people, where\n", + "\n", + "* in the first society, the yearly income of one man is $100,000,000 and the income of the\n", + " others are zero\n", + "* in the second society, the yearly income of everyone is $100\n", + "\n", + "These countries have the same income per capita (average income is $100) but the lives of the people will be very different (e.g., almost everyone in the first society is\n", + "starving, even though one person is fabulously rich).\n", + "```\n", + "\n", + "The example above suggests that we should go beyond simple averages when we study income and wealth.\n", + "\n", + "This leads us to the topic of economic inequality, which examines how income and wealth (and other quantities) are distributed across a population.\n", + "\n", + "In this lecture we study inequality, beginning with measures of inequality and\n", + "then applying them to wealth and income data from the US and other countries.\n", + "\n", + "\n", + "\n", + "### Some history\n", + "\n", + "Many historians argue that inequality played a role in the fall of the Roman Republic (see, e.g., {cite}`levitt2019did`).\n", + "\n", + "Following the defeat of Carthage and the invasion of Spain, money flowed into\n", + "Rome from across the empire, greatly enriched those in power.\n", + "\n", + "Meanwhile, ordinary citizens were taken from their farms to fight for long\n", + "periods, diminishing their wealth.\n", + "\n", + "The resulting growth in inequality was a driving factor behind political turmoil that shook the foundations of the republic. \n", + "\n", + "Eventually, the Roman Republic gave way to a series of dictatorships, starting with [Octavian](https://en.wikipedia.org/wiki/Augustus) (Augustus) in 27 BCE.\n", + "\n", + "This history tells us that inequality matters, in the sense that it can drive major world events. \n", + "\n", + "There are other reasons that inequality might matter, such as how it affects\n", + "human welfare.\n", + "\n", + "With this motivation, let us start to think about what inequality is and how we\n", + "can quantify and analyze it.\n", + "\n", + "\n", + "### Measurement\n", + "\n", + "In politics and popular media, the word \"inequality\" is often used quite loosely, without any firm definition.\n", + "\n", + "To bring a scientific perspective to the topic of inequality we must start with careful definitions.\n", + "\n", + "Hence we begin by discussing ways that inequality can be measured in economic research.\n", + "\n", + "We will need to install the following packages" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a758f16f", + "metadata": { + "tags": [ + "hide-output" + ] + }, + "outputs": [], + "source": [ + "%pip install wbgapi plotly" + ] + }, + { + "cell_type": "markdown", + "id": "615fd424", + "metadata": {}, + "source": [ + "We will also use the following imports." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3f984290", + "metadata": {}, + "outputs": [], + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import random as rd\n", + "import wbgapi as wb\n", + "import plotly.express as px" + ] + }, + { + "cell_type": "markdown", + "id": "54876cc2", + "metadata": {}, + "source": [ + "## The Lorenz curve\n", + "\n", + "One popular measure of inequality is the Lorenz curve.\n", + "\n", + "In this section we define the Lorenz curve and examine its properties.\n", + "\n", + "\n", + "### Definition\n", + "\n", + "The Lorenz curve takes a sample $w_1, \\ldots, w_n$ and produces a curve $L$.\n", + "\n", + "We suppose that the sample has been sorted from smallest to largest.\n", + "\n", + "To aid our interpretation, suppose that we are measuring wealth \n", + "\n", + "* $w_1$ is the wealth of the poorest member of the population, and\n", + "* $w_n$ is the wealth of the richest member of the population.\n", + "\n", + "The curve $L$ is just a function $y = L(x)$ that we can plot and interpret.\n", + "\n", + "To create it we first generate data points $(x_i, y_i)$ according to\n", + "\n", + "```{prf:definition}\n", + ":label: define-lorenz\n", + "\n", + "$$\n", + "x_i = \\frac{i}{n},\n", + "\\qquad\n", + "y_i = \\frac{\\sum_{j \\leq i} w_j}{\\sum_{j \\leq n} w_j},\n", + "\\qquad i = 1, \\ldots, n\n", + "$$\n", + "```\n", + "\n", + "Now the Lorenz curve $L$ is formed from these data points using interpolation.\n", + "\n", + "If we use a line plot in `matplotlib`, the interpolation will be done for us.\n", + "\n", + "The meaning of the statement $y = L(x)$ is that the lowest $(100\n", + "\\times x)$\\% of people have $(100 \\times y)$\\% of all wealth.\n", + "\n", + "* if $x=0.5$ and $y=0.1$, then the bottom 50% of the population\n", + " owns 10% of the wealth.\n", + "\n", + "In the discussion above we focused on wealth but the same ideas apply to\n", + "income, consumption, etc.\n", + "\n", + "\n", + "### Lorenz curves of simulated data\n", + "\n", + "Let's look at some examples and try to build understanding.\n", + "\n", + "First let us construct a `lorenz_curve` function that we can\n", + "use in our simulations below.\n", + "\n", + "It is useful to construct a function that translates an array of\n", + "income or wealth data into the cumulative share\n", + "of individuals (or households) and the cumulative share of income (or wealth)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0bb367ec", + "metadata": {}, + "outputs": [], + "source": [ + "def lorenz_curve(y):\n", + " \"\"\"\n", + " Calculates the Lorenz Curve, a graphical representation of\n", + " the distribution of income or wealth.\n", + "\n", + " It returns the cumulative share of people (x-axis) and\n", + " the cumulative share of income earned.\n", + "\n", + " Parameters\n", + " ----------\n", + " y : array_like(float or int, ndim=1)\n", + " Array of income/wealth for each individual.\n", + " Unordered or ordered is fine.\n", + "\n", + " Returns\n", + " -------\n", + " cum_people : array_like(float, ndim=1)\n", + " Cumulative share of people for each person index (i/n)\n", + " cum_income : array_like(float, ndim=1)\n", + " Cumulative share of income for each person index\n", + "\n", + "\n", + " References\n", + " ----------\n", + " .. [1] https://en.wikipedia.org/wiki/Lorenz_curve\n", + "\n", + " Examples\n", + " --------\n", + " >>> a_val, n = 3, 10_000\n", + " >>> y = np.random.pareto(a_val, size=n)\n", + " >>> f_vals, l_vals = lorenz(y)\n", + "\n", + " \"\"\"\n", + "\n", + " n = len(y)\n", + " y = np.sort(y)\n", + " s = np.zeros(n + 1)\n", + " s[1:] = np.cumsum(y)\n", + " cum_people = np.zeros(n + 1)\n", + " cum_income = np.zeros(n + 1)\n", + " for i in range(1, n + 1):\n", + " cum_people[i] = i / n\n", + " cum_income[i] = s[i] / s[n]\n", + " return cum_people, cum_income" + ] + }, + { + "cell_type": "markdown", + "id": "c247c441", + "metadata": {}, + "source": [ + "In the next figure, we generate $n=2000$ draws from a lognormal\n", + "distribution and treat these draws as our population. \n", + "\n", + "The straight 45-degree line ($x=L(x)$ for all $x$) corresponds to perfect equality. \n", + "\n", + "The log-normal draws produce a less equal distribution. \n", + "\n", + "For example, if we imagine these draws as being observations of wealth across\n", + "a sample of households, then the dashed lines show that the bottom 80\\% of\n", + "households own just over 40\\% of total wealth." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2b1e4b28", + "metadata": { + "mystnb": { + "figure": { + "caption": "Lorenz curve of simulated wealth data", + "name": "lorenz_simulated" + } + } + }, + "outputs": [], + "source": [ + "n = 2000\n", + "sample = np.exp(np.random.randn(n))\n", + "\n", + "fig, ax = plt.subplots()\n", + "\n", + "f_vals, l_vals = lorenz_curve(sample)\n", + "ax.plot(f_vals, l_vals, label=f'lognormal sample', lw=2)\n", + "ax.plot(f_vals, f_vals, label='equality', lw=2)\n", + "\n", + "ax.vlines([0.8], [0.0], [0.43], alpha=0.5, colors='k', ls='--')\n", + "ax.hlines([0.43], [0], [0.8], alpha=0.5, colors='k', ls='--')\n", + "ax.set_xlim((0, 1))\n", + "ax.set_xlabel(\"share of households\")\n", + "ax.set_ylim((0, 1))\n", + "ax.set_ylabel(\"share of wealth\")\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "983a4195", + "metadata": {}, + "source": [ + "### Lorenz curves for US data\n", + "\n", + "Next let's look at US data for both income and wealth.\n", + "\n", + "(data:survey-consumer-finance)=\n", + "The following code block imports a subset of the dataset `SCF_plus` for 2016,\n", + "which is derived from the [Survey of Consumer Finances](https://en.wikipedia.org/wiki/Survey_of_Consumer_Finances) (SCF)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0fa93fe6", + "metadata": {}, + "outputs": [], + "source": [ + "url = 'https://github.com/QuantEcon/high_dim_data/raw/main/SCF_plus/SCF_plus_mini.csv'\n", + "df = pd.read_csv(url)\n", + "df_income_wealth = df.dropna()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1e0d3f6b", + "metadata": {}, + "outputs": [], + "source": [ + "df_income_wealth.head(n=5)" + ] + }, + { + "cell_type": "markdown", + "id": "ac61d5aa", + "metadata": {}, + "source": [ + "The next code block uses data stored in dataframe `df_income_wealth` to generate the Lorenz curves.\n", + "\n", + "(The code is somewhat complex because we need to adjust the data according to\n", + "population weights supplied by the SCF.)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "62371dc8", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "df = df_income_wealth \n", + "\n", + "varlist = ['n_wealth', # net wealth \n", + " 't_income', # total income\n", + " 'l_income'] # labor income\n", + "\n", + "years = df.year.unique()\n", + "\n", + "# Create lists to store Lorenz data\n", + "\n", + "F_vals, L_vals = [], []\n", + "\n", + "for var in varlist:\n", + " # create lists to store Lorenz curve data\n", + " f_vals = []\n", + " l_vals = []\n", + " for year in years:\n", + "\n", + " # Repeat the observations according to their weights\n", + " counts = list(round(df[df['year'] == year]['weights'] )) \n", + " y = df[df['year'] == year][var].repeat(counts)\n", + " y = np.asarray(y)\n", + " \n", + " # Shuffle the sequence to improve the plot\n", + " rd.shuffle(y) \n", + " \n", + " # calculate and store Lorenz curve data\n", + " f_val, l_val = lorenz_curve(y)\n", + " f_vals.append(f_val)\n", + " l_vals.append(l_val)\n", + " \n", + " F_vals.append(f_vals)\n", + " L_vals.append(l_vals)\n", + "\n", + "f_vals_nw, f_vals_ti, f_vals_li = F_vals\n", + "l_vals_nw, l_vals_ti, l_vals_li = L_vals" + ] + }, + { + "cell_type": "markdown", + "id": "4e74a11a", + "metadata": {}, + "source": [ + "Now we plot Lorenz curves for net wealth, total income and labor income in the\n", + "US in 2016.\n", + "\n", + "Total income is the sum of households' all income sources, including labor income but excluding capital gains.\n", + "\n", + "(All income measures are pre-tax.)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "17f8eb8d", + "metadata": { + "mystnb": { + "figure": { + "caption": "2016 US Lorenz curves", + "name": "lorenz_us" + }, + "image": { + "alt": "lorenz_us" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "ax.plot(f_vals_nw[-1], l_vals_nw[-1], label=f'net wealth')\n", + "ax.plot(f_vals_ti[-1], l_vals_ti[-1], label=f'total income')\n", + "ax.plot(f_vals_li[-1], l_vals_li[-1], label=f'labor income')\n", + "ax.plot(f_vals_nw[-1], f_vals_nw[-1], label=f'equality')\n", + "ax.set_xlabel(\"share of households\")\n", + "ax.set_ylabel(\"share of income/wealth\")\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "56fb28e7", + "metadata": {}, + "source": [ + "One key finding from this figure is that wealth inequality is more extreme than income inequality. \n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "## The Gini coefficient\n", + "\n", + "The Lorenz curve provides a visual representation of inequality in a distribution.\n", + "\n", + "Another way to study income and wealth inequality is via the Gini coefficient.\n", + "\n", + "In this section we discuss the Gini coefficient and its relationship to the Lorenz curve.\n", + "\n", + "\n", + "\n", + "### Definition\n", + "\n", + "As before, suppose that the sample $w_1, \\ldots, w_n$ has been sorted from smallest to largest.\n", + "\n", + "The Gini coefficient is defined for the sample above as \n", + "\n", + "```{prf:definition}\n", + ":label: define-gini\n", + "\n", + "$$\n", + "G :=\n", + "\\frac{\\sum_{i=1}^n \\sum_{j = 1}^n |w_j - w_i|}\n", + " {2n\\sum_{i=1}^n w_i}.\n", + "$$\n", + "```\n", + "\n", + "The Gini coefficient is closely related to the Lorenz curve.\n", + "\n", + "In fact, it can be shown that its value is twice the area between the line of\n", + "equality and the Lorenz curve (e.g., the shaded area in {numref}`lorenz_gini`).\n", + "\n", + "The idea is that $G=0$ indicates complete equality, while $G=1$ indicates complete inequality." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fe547ac4", + "metadata": { + "mystnb": { + "figure": { + "caption": "Gini coefficient (simulated wealth data)", + "name": "lorenz_gini" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "f_vals, l_vals = lorenz_curve(sample)\n", + "ax.plot(f_vals, l_vals, label=f'lognormal sample', lw=2)\n", + "ax.plot(f_vals, f_vals, label='equality', lw=2)\n", + "ax.fill_between(f_vals, l_vals, f_vals, alpha=0.06)\n", + "ax.set_ylim((0, 1))\n", + "ax.set_xlim((0, 1))\n", + "ax.text(0.04, 0.5, r'$G = 2 \\times$ shaded area')\n", + "ax.set_xlabel(\"share of households (%)\")\n", + "ax.set_ylabel(\"share of wealth (%)\")\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "8a01b2d9", + "metadata": {}, + "source": [ + "In fact the Gini coefficient can also be expressed as\n", + "\n", + "$$\n", + "G = \\frac{A}{A+B}\n", + "$$\n", + "\n", + "where $A$ is the area between the 45-degree line of \n", + "perfect equality and the Lorenz curve, while $B$ is the area below the Lorenze curve -- see {numref}`lorenz_gini2`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "61e2c156", + "metadata": { + "mystnb": { + "figure": { + "caption": "Lorenz curve and Gini coefficient", + "name": "lorenz_gini2" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "f_vals, l_vals = lorenz_curve(sample)\n", + "ax.plot(f_vals, l_vals, label='lognormal sample', lw=2)\n", + "ax.plot(f_vals, f_vals, label='equality', lw=2)\n", + "ax.fill_between(f_vals, l_vals, f_vals, alpha=0.06)\n", + "ax.fill_between(f_vals, l_vals, np.zeros_like(f_vals), alpha=0.06)\n", + "ax.set_ylim((0, 1))\n", + "ax.set_xlim((0, 1))\n", + "ax.text(0.55, 0.4, 'A')\n", + "ax.text(0.75, 0.15, 'B')\n", + "ax.set_xlabel(\"share of households\")\n", + "ax.set_ylabel(\"share of wealth\")\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "cc385f21", + "metadata": {}, + "source": [ + "```{seealso}\n", + "The World in Data project has a [graphical exploration of the Lorenz curve and the Gini coefficient](https://ourworldindata.org/what-is-the-gini-coefficient)\n", + "```\n", + "\n", + "### Gini coefficient of simulated data\n", + "\n", + "Let's examine the Gini coefficient in some simulations.\n", + "\n", + "The code below computes the Gini coefficient from a sample.\n", + "\n", + "(code:gini-coefficient)=" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cf1f8311", + "metadata": {}, + "outputs": [], + "source": [ + "def gini_coefficient(y):\n", + " r\"\"\"\n", + " Implements the Gini inequality index\n", + "\n", + " Parameters\n", + " ----------\n", + " y : array_like(float)\n", + " Array of income/wealth for each individual.\n", + " Ordered or unordered is fine\n", + "\n", + " Returns\n", + " -------\n", + " Gini index: float\n", + " The gini index describing the inequality of the array of income/wealth\n", + "\n", + " References\n", + " ----------\n", + "\n", + " https://en.wikipedia.org/wiki/Gini_coefficient\n", + " \"\"\"\n", + " n = len(y)\n", + " i_sum = np.zeros(n)\n", + " for i in range(n):\n", + " for j in range(n):\n", + " i_sum[i] += abs(y[i] - y[j])\n", + " return np.sum(i_sum) / (2 * n * np.sum(y))" + ] + }, + { + "cell_type": "markdown", + "id": "5eb5e378", + "metadata": {}, + "source": [ + "Now we can compute the Gini coefficients for five different populations.\n", + "\n", + "Each of these populations is generated by drawing from a \n", + "lognormal distribution with parameters $\\mu$ (mean) and $\\sigma$ (standard deviation).\n", + "\n", + "To create the five populations, we vary $\\sigma$ over a grid of length $5$\n", + "between $0.2$ and $4$.\n", + "\n", + "In each case we set $\\mu = - \\sigma^2 / 2$.\n", + "\n", + "This implies that the mean of the distribution does not change with $\\sigma$. \n", + "\n", + "You can check this by looking up the expression for the mean of a lognormal\n", + "distribution." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d5465504", + "metadata": {}, + "outputs": [], + "source": [ + "%%time\n", + "k = 5\n", + "σ_vals = np.linspace(0.2, 4, k)\n", + "n = 2_000\n", + "\n", + "ginis = []\n", + "\n", + "for σ in σ_vals:\n", + " μ = -σ**2 / 2\n", + " y = np.exp(μ + σ * np.random.randn(n))\n", + " ginis.append(gini_coefficient(y))" + ] + }, + { + "cell_type": "markdown", + "id": "8f7e1c60", + "metadata": {}, + "source": [ + "Let's build a function that returns a figure (so that we can use it later in the lecture)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "845d4be7", + "metadata": {}, + "outputs": [], + "source": [ + "def plot_inequality_measures(x, y, legend, xlabel, ylabel):\n", + " fig, ax = plt.subplots()\n", + " ax.plot(x, y, marker='o', label=legend)\n", + " ax.set_xlabel(xlabel)\n", + " ax.set_ylabel(ylabel)\n", + " ax.legend()\n", + " return fig, ax" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2b68f098", + "metadata": { + "mystnb": { + "figure": { + "caption": "Gini coefficients of simulated data", + "name": "gini_simulated" + } + } + }, + "outputs": [], + "source": [ + "fix, ax = plot_inequality_measures(σ_vals, \n", + " ginis, \n", + " 'simulated', \n", + " '$\\sigma$', \n", + " 'Gini coefficients')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "91336a05", + "metadata": {}, + "source": [ + "The plots show that inequality rises with $\\sigma$, according to the Gini\n", + "coefficient.\n", + "\n", + "### Gini coefficient for income (US data)\n", + "\n", + "Let's look at the Gini coefficient for the distribution of income in the US.\n", + "\n", + "We will get pre-computed Gini coefficients (based on income) from the World Bank using the [wbgapi](https://blogs.worldbank.org/opendata/introducing-wbgapi-new-python-package-accessing-world-bank-data).\n", + "\n", + "Let's use the `wbgapi` package we imported earlier to search the World Bank data for Gini to find the Series ID." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "83d1070f", + "metadata": {}, + "outputs": [], + "source": [ + "wb.search(\"gini\")" + ] + }, + { + "cell_type": "markdown", + "id": "cf43a173", + "metadata": {}, + "source": [ + "We now know the series ID is `SI.POV.GINI`.\n", + "\n", + "(Another way to find the series ID is to use the [World Bank data portal](https://data.worldbank.org) and then use `wbgapi` to fetch the data.)\n", + "\n", + "To get a quick overview, let's histogram Gini coefficients across all countries and all years in the World Bank dataset." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c878efac", + "metadata": { + "mystnb": { + "figure": { + "caption": "Histogram of Gini coefficients across countries", + "name": "gini_histogram" + } + } + }, + "outputs": [], + "source": [ + "# Fetch gini data for all countries\n", + "gini_all = wb.data.DataFrame(\"SI.POV.GINI\")\n", + "# remove 'YR' in index and convert to integer\n", + "gini_all.columns = gini_all.columns.map(lambda x: int(x.replace('YR',''))) \n", + "\n", + "# Create a long series with a multi-index of the data to get global min and max values\n", + "gini_all = gini_all.unstack(level='economy').dropna()\n", + "\n", + "# Build a histogram\n", + "ax = gini_all.plot(kind=\"hist\", bins=20)\n", + "ax.set_xlabel(\"Gini coefficient\")\n", + "ax.set_ylabel(\"frequency\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "c1437d56", + "metadata": {}, + "source": [ + "We can see in {numref}`gini_histogram` that across 50 years of data and all countries the measure varies between 20 and 65.\n", + "\n", + "Let us fetch the data `DataFrame` for the USA." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9ea72c6a", + "metadata": {}, + "outputs": [], + "source": [ + "data = wb.data.DataFrame(\"SI.POV.GINI\", \"USA\")\n", + "data.head(n=5)\n", + "# remove 'YR' in index and convert to integer\n", + "data.columns = data.columns.map(lambda x: int(x.replace('YR','')))" + ] + }, + { + "cell_type": "markdown", + "id": "d9008cc8", + "metadata": {}, + "source": [ + "(This package often returns data with year information contained in the columns. This is not always convenient for simple plotting with pandas so it can be useful to transpose the results before plotting.)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5ee1e6e2", + "metadata": {}, + "outputs": [], + "source": [ + "data = data.T # Obtain years as rows\n", + "data_usa = data['USA'] # pd.Series of US data" + ] + }, + { + "cell_type": "markdown", + "id": "4946de0c", + "metadata": {}, + "source": [ + "Let us take a look at the data for the US." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5d3255f3", + "metadata": { + "mystnb": { + "figure": { + "caption": "Gini coefficients for income distribution (USA)", + "name": "gini_usa1" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "ax = data_usa.plot(ax=ax)\n", + "ax.set_ylim(data_usa.min()-1, data_usa.max()+1)\n", + "ax.set_ylabel(\"Gini coefficient (income)\")\n", + "ax.set_xlabel(\"year\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "0f6c5877", + "metadata": {}, + "source": [ + "As can be seen in {numref}`gini_usa1`, the income Gini\n", + "trended upward from 1980 to 2020 and then dropped following at the start of the COVID pandemic.\n", + "\n", + "(compare-income-wealth-usa-over-time)=\n", + "### Gini coefficient for wealth\n", + "\n", + "In the previous section we looked at the Gini coefficient for income, focusing on using US data.\n", + "\n", + "Now let's look at the Gini coefficient for the distribution of wealth.\n", + "\n", + "We will use US data from the {ref}`Survey of Consumer Finances`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "87f8e2cb", + "metadata": {}, + "outputs": [], + "source": [ + "df_income_wealth.year.describe()" + ] + }, + { + "cell_type": "markdown", + "id": "e09a5cd8", + "metadata": {}, + "source": [ + "[This notebook](https://github.com/QuantEcon/lecture-python-intro/tree/main/lectures/_static/lecture_specific/inequality/data.ipynb) can be used to compute this information over the full dataset." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0a6804a1", + "metadata": {}, + "outputs": [], + "source": [ + "data_url = 'https://github.com/QuantEcon/lecture-python-intro/raw/main/lectures/_static/lecture_specific/inequality/usa-gini-nwealth-tincome-lincome.csv'\n", + "ginis = pd.read_csv(data_url, index_col='year')\n", + "ginis.head(n=5)" + ] + }, + { + "cell_type": "markdown", + "id": "e96a44d9", + "metadata": {}, + "source": [ + "Let's plot the Gini coefficients for net wealth." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4ec091fe", + "metadata": { + "mystnb": { + "figure": { + "caption": "Gini coefficients of US net wealth", + "name": "gini_wealth_us" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "ax.plot(years, ginis[\"n_wealth\"], marker='o')\n", + "ax.set_xlabel(\"year\")\n", + "ax.set_ylabel(\"Gini coefficient\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "3a4b01ed", + "metadata": {}, + "source": [ + "The time series for the wealth Gini exhibits a U-shape, falling until the early\n", + "1980s and then increasing rapidly.\n", + "\n", + "One possibility is that this change is mainly driven by technology.\n", + "\n", + "However, we will see below that not all advanced economies experienced similar growth of inequality.\n", + "\n", + "### Cross-country comparisons of income inequality\n", + "\n", + "Earlier in this lecture we used `wbgapi` to get Gini data across many countries\n", + "and saved it in a variable called `gini_all`\n", + "\n", + "In this section we will use this data to compare several advanced economies, and\n", + "to look at the evolution in their respective income Ginis." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e86e19cd", + "metadata": {}, + "outputs": [], + "source": [ + "data = gini_all.unstack()\n", + "data.columns" + ] + }, + { + "cell_type": "markdown", + "id": "946ba248", + "metadata": {}, + "source": [ + "There are 167 countries represented in this dataset. \n", + "\n", + "Let us compare three advanced economies: the US, the UK, and Norway" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c7f2b3a7", + "metadata": { + "mystnb": { + "figure": { + "caption": "Gini coefficients for income (USA, United Kingdom, and Norway)", + "name": "gini_usa_gbr_nor1" + } + } + }, + "outputs": [], + "source": [ + "ax = data[['USA','GBR', 'NOR']].plot()\n", + "ax.set_xlabel('year')\n", + "ax.set_ylabel('Gini coefficient')\n", + "ax.legend(title=\"\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "9f152a48", + "metadata": {}, + "source": [ + "We see that Norway has a shorter time series.\n", + "\n", + "Let us take a closer look at the underlying data and see if we can rectify this." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a2b3d2ba", + "metadata": {}, + "outputs": [], + "source": [ + "data[['NOR']].dropna().head(n=5)" + ] + }, + { + "cell_type": "markdown", + "id": "b67c5565", + "metadata": {}, + "source": [ + "The data for Norway in this dataset goes back to 1979 but there are gaps in the time series and matplotlib is not showing those data points. \n", + "\n", + "We can use the `.ffill()` method to copy and bring forward the last known value in a series to fill in these gaps" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4178a763", + "metadata": { + "mystnb": { + "figure": { + "caption": "Gini coefficients for income (USA, United Kingdom, and Norway)", + "name": "gini_usa_gbr_nor2" + } + } + }, + "outputs": [], + "source": [ + "data['NOR'] = data['NOR'].ffill()\n", + "ax = data[['USA','GBR', 'NOR']].plot()\n", + "ax.set_xlabel('year')\n", + "ax.set_ylabel('Gini coefficient')\n", + "ax.legend(title=\"\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "81eef9a7", + "metadata": {}, + "source": [ + "From this plot we can observe that the US has a higher Gini coefficient (i.e.\n", + "higher income inequality) when compared to the UK and Norway. \n", + "\n", + "Norway has the lowest Gini coefficient over the three economies and, moreover,\n", + "the Gini coefficient shows no upward trend.\n", + "\n", + "\n", + "\n", + "### Gini Coefficient and GDP per capita (over time)\n", + "\n", + "We can also look at how the Gini coefficient compares with GDP per capita (over time). \n", + "\n", + "Let's take another look at the US, Norway, and the UK." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d75c88d0", + "metadata": {}, + "outputs": [], + "source": [ + "countries = ['USA', 'NOR', 'GBR']\n", + "gdppc = wb.data.DataFrame(\"NY.GDP.PCAP.KD\", countries)\n", + "# remove 'YR' in index and convert to integer\n", + "gdppc.columns = gdppc.columns.map(lambda x: int(x.replace('YR',''))) \n", + "gdppc = gdppc.T" + ] + }, + { + "cell_type": "markdown", + "id": "657cf6a8", + "metadata": {}, + "source": [ + "We can rearrange the data so that we can plot GDP per capita and the Gini coefficient across years" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0d06056d", + "metadata": {}, + "outputs": [], + "source": [ + "plot_data = pd.DataFrame(data[countries].unstack())\n", + "plot_data.index.names = ['country', 'year']\n", + "plot_data.columns = ['gini']" + ] + }, + { + "cell_type": "markdown", + "id": "199ebadd", + "metadata": {}, + "source": [ + "Now we can get the GDP per capita data into a shape that can be merged with `plot_data`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2b988942", + "metadata": {}, + "outputs": [], + "source": [ + "pgdppc = pd.DataFrame(gdppc.unstack())\n", + "pgdppc.index.names = ['country', 'year']\n", + "pgdppc.columns = ['gdppc']\n", + "plot_data = plot_data.merge(pgdppc, left_index=True, right_index=True)\n", + "plot_data.reset_index(inplace=True)" + ] + }, + { + "cell_type": "markdown", + "id": "7eef3ba5", + "metadata": {}, + "source": [ + "Now we use Plotly to build a plot with GDP per capita on the y-axis and the Gini coefficient on the x-axis." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "85025e73", + "metadata": {}, + "outputs": [], + "source": [ + "min_year = plot_data.year.min()\n", + "max_year = plot_data.year.max()" + ] + }, + { + "cell_type": "markdown", + "id": "de0db116", + "metadata": {}, + "source": [ + "The time series for all three countries start and stop in different years. \n", + "\n", + "We will add a year mask to the data to improve clarity in the chart including the different end years associated with each country's time series." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cc4a95ab", + "metadata": {}, + "outputs": [], + "source": [ + "labels = [1979, 1986, 1991, 1995, 2000, 2020, 2021, 2022] + \\\n", + " list(range(min_year,max_year,5))\n", + "plot_data.year = plot_data.year.map(lambda x: x if x in labels else None)" + ] + }, + { + "cell_type": "markdown", + "id": "ec718cc5", + "metadata": {}, + "source": [ + "(fig:plotly-gini-gdppc-years)=" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8d0cf551", + "metadata": {}, + "outputs": [], + "source": [ + "fig = px.line(plot_data, \n", + " x = \"gini\", \n", + " y = \"gdppc\", \n", + " color = \"country\", \n", + " text = \"year\", \n", + " height = 800,\n", + " labels = {\"gini\" : \"Gini coefficient\", \"gdppc\" : \"GDP per capita\"}\n", + " )\n", + "fig.update_traces(textposition=\"bottom right\")\n", + "fig.show()" + ] + }, + { + "cell_type": "markdown", + "id": "ede8a3c0", + "metadata": {}, + "source": [ + "```{only} latex\n", + "This figure is built using `plotly` and is {ref}` available on the website `\n", + "```\n", + "\n", + "This plot shows that all three Western economies' GDP per capita has grown over\n", + "time with some fluctuations in the Gini coefficient. \n", + "\n", + "From the early 80's the United Kingdom and the US economies both saw increases\n", + "in income inequality. \n", + "\n", + "Interestingly, since the year 2000, the United Kingdom saw a decline in income inequality while\n", + "the US exhibits persistent but stable levels around a Gini coefficient of 40. \n", + "\n", + "\n", + "## Top shares\n", + "\n", + "Another popular measure of inequality is the top shares.\n", + "\n", + "In this section we show how to compute top shares.\n", + "\n", + "\n", + "### Definition\n", + "\n", + "As before, suppose that the sample $w_1, \\ldots, w_n$ has been sorted from smallest to largest.\n", + "\n", + "Given the Lorenz curve $y = L(x)$ defined above, the top $100 \\times p \\%$\n", + "share is defined as\n", + "\n", + "```{prf:definition}\n", + ":label: top-shares\n", + "\n", + "$$\n", + "T(p) = 1 - L (1-p) \n", + " \\approx \\frac{\\sum_{j\\geq i} w_j}{ \\sum_{j \\leq n} w_j}, \\quad i = \\lfloor n (1-p)\\rfloor\n", + "$$ (topshares)\n", + "```\n", + "\n", + "Here $\\lfloor \\cdot \\rfloor$ is the floor function, which rounds any\n", + "number down to the integer less than or equal to that number.\n", + "\n", + "The following code uses the data from dataframe `df_income_wealth` to generate another dataframe `df_topshares`.\n", + "\n", + "`df_topshares` stores the top 10 percent shares for the total income, the labor income and net wealth from 1950 to 2016 in US." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b4b546c1", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "# transfer the survey weights from absolute into relative values\n", + "df1 = df_income_wealth\n", + "df2 = df1.groupby('year').sum(numeric_only=True).reset_index()\n", + "df3 = df2[['year', 'weights']]\n", + "df3.columns = 'year', 'r_weights'\n", + "df4 = pd.merge(df3, df1, how=\"left\", on=[\"year\"])\n", + "df4['r_weights'] = df4['weights'] / df4['r_weights']\n", + "\n", + "# create weighted nw, ti, li\n", + "df4['weighted_n_wealth'] = df4['n_wealth'] * df4['r_weights']\n", + "df4['weighted_t_income'] = df4['t_income'] * df4['r_weights']\n", + "df4['weighted_l_income'] = df4['l_income'] * df4['r_weights']\n", + "\n", + "# extract two top 10% groups by net wealth and total income.\n", + "df6 = df4[df4['nw_groups'] == 'Top 10%']\n", + "df7 = df4[df4['ti_groups'] == 'Top 10%']\n", + "\n", + "# calculate the sum of weighted top 10% by net wealth,\n", + "# total income and labor income.\n", + "df5 = df4.groupby('year').sum(numeric_only=True).reset_index()\n", + "df8 = df6.groupby('year').sum(numeric_only=True).reset_index()\n", + "df9 = df7.groupby('year').sum(numeric_only=True).reset_index()\n", + "\n", + "df5['weighted_n_wealth_top10'] = df8['weighted_n_wealth']\n", + "df5['weighted_t_income_top10'] = df9['weighted_t_income']\n", + "df5['weighted_l_income_top10'] = df9['weighted_l_income']\n", + "\n", + "# calculate the top 10% shares of the three variables.\n", + "df5['topshare_n_wealth'] = df5['weighted_n_wealth_top10'] / \\\n", + " df5['weighted_n_wealth']\n", + "df5['topshare_t_income'] = df5['weighted_t_income_top10'] / \\\n", + " df5['weighted_t_income']\n", + "df5['topshare_l_income'] = df5['weighted_l_income_top10'] / \\\n", + " df5['weighted_l_income']\n", + "\n", + "# we only need these vars for top 10 percent shares\n", + "df_topshares = df5[['year', 'topshare_n_wealth',\n", + " 'topshare_t_income', 'topshare_l_income']]" + ] + }, + { + "cell_type": "markdown", + "id": "335fa3d6", + "metadata": {}, + "source": [ + "Then let's plot the top shares." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b6ad3898", + "metadata": { + "mystnb": { + "figure": { + "caption": "US top shares", + "name": "top_shares_us" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "ax.plot(years, df_topshares[\"topshare_l_income\"],\n", + " marker='o', label=\"labor income\")\n", + "ax.plot(years, df_topshares[\"topshare_n_wealth\"],\n", + " marker='o', label=\"net wealth\")\n", + "ax.plot(years, df_topshares[\"topshare_t_income\"],\n", + " marker='o', label=\"total income\")\n", + "ax.set_xlabel(\"year\")\n", + "ax.set_ylabel(\"top $10\\%$ share\")\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "4e2f5a80", + "metadata": {}, + "source": [ + "## Exercises\n", + "\n", + "```{exercise}\n", + ":label: inequality_ex1\n", + "\n", + "Using simulation, compute the top 10 percent shares for the collection of\n", + "lognormal distributions associated with the random variables $w_\\sigma =\n", + "\\exp(\\mu + \\sigma Z)$, where $Z \\sim N(0, 1)$ and $\\sigma$ varies over a\n", + "finite grid between $0.2$ and $4$. \n", + "\n", + "As $\\sigma$ increases, so does the variance of $w_\\sigma$. \n", + "\n", + "To focus on volatility, adjust $\\mu$ at each step to maintain the equality\n", + "$\\mu=-\\sigma^2/2$.\n", + "\n", + "For each $\\sigma$, generate 2,000 independent draws of $w_\\sigma$ and\n", + "calculate the Lorenz curve and Gini coefficient. \n", + "\n", + "Confirm that higher variance\n", + "generates more dispersion in the sample, and hence greater inequality.\n", + "```\n", + "\n", + "```{solution-start} inequality_ex1\n", + ":class: dropdown\n", + "```\n", + "\n", + "Here is one solution:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f2bd11b7", + "metadata": {}, + "outputs": [], + "source": [ + "def calculate_top_share(s, p=0.1):\n", + " \n", + " s = np.sort(s)\n", + " n = len(s)\n", + " index = int(n * (1 - p))\n", + " return s[index:].sum() / s.sum()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "683b28d1", + "metadata": {}, + "outputs": [], + "source": [ + "k = 5\n", + "σ_vals = np.linspace(0.2, 4, k)\n", + "n = 2_000\n", + "\n", + "topshares = []\n", + "ginis = []\n", + "f_vals = []\n", + "l_vals = []\n", + "\n", + "for σ in σ_vals:\n", + " μ = -σ ** 2 / 2\n", + " y = np.exp(μ + σ * np.random.randn(n))\n", + " f_val, l_val = lorenz_curve(y)\n", + " f_vals.append(f_val)\n", + " l_vals.append(l_val)\n", + " ginis.append(gini_coefficient(y))\n", + " topshares.append(calculate_top_share(y))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b36bba6a", + "metadata": { + "mystnb": { + "figure": { + "caption": "Top shares of simulated data", + "name": "top_shares_simulated" + }, + "image": { + "alt": "top_shares_simulated" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plot_inequality_measures(σ_vals, \n", + " topshares, \n", + " \"simulated data\", \n", + " \"$\\sigma$\", \n", + " \"top $10\\%$ share\") \n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "89c0e8c5", + "metadata": { + "mystnb": { + "figure": { + "caption": "Gini coefficients of simulated data", + "name": "gini_coef_simulated" + }, + "image": { + "alt": "gini_coef_simulated" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plot_inequality_measures(σ_vals, \n", + " ginis, \n", + " \"simulated data\", \n", + " \"$\\sigma$\", \n", + " \"gini coefficient\")\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "43551bce", + "metadata": { + "mystnb": { + "figure": { + "caption": "Lorenz curves for simulated data", + "name": "lorenz_curve_simulated" + }, + "image": { + "alt": "lorenz_curve_simulated" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "ax.plot([0,1],[0,1], label=f\"equality\")\n", + "for i in range(len(f_vals)):\n", + " ax.plot(f_vals[i], l_vals[i], label=f\"$\\sigma$ = {σ_vals[i]}\")\n", + "plt.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "c6356fd1", + "metadata": {}, + "source": [ + "```{solution-end}\n", + "```\n", + "\n", + "\n", + "```{exercise}\n", + ":label: inequality_ex2\n", + "\n", + "According to the definition of the top shares {eq}`topshares` we can also calculate the top percentile shares using the Lorenz curve.\n", + "\n", + "Compute the top shares of US net wealth using the corresponding Lorenz curves data: ``f_vals_nw, l_vals_nw`` and linear interpolation.\n", + "\n", + "Plot the top shares generated from Lorenz curve and the top shares approximated from data together.\n", + "\n", + "```\n", + "\n", + "```{solution-start} inequality_ex2\n", + ":class: dropdown\n", + "```\n", + "\n", + "Here is one solution:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bed1f7e4", + "metadata": {}, + "outputs": [], + "source": [ + "def lorenz2top(f_val, l_val, p=0.1):\n", + " t = lambda x: np.interp(x, f_val, l_val)\n", + " return 1- t(1 - p)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "91b52c0a", + "metadata": {}, + "outputs": [], + "source": [ + "top_shares_nw = []\n", + "for f_val, l_val in zip(f_vals_nw, l_vals_nw):\n", + " top_shares_nw.append(lorenz2top(f_val, l_val))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f516ced2", + "metadata": { + "mystnb": { + "figure": { + "caption": "US top shares: approximation vs Lorenz", + "name": "top_shares_us_al" + }, + "image": { + "alt": "top_shares_us_al" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "\n", + "ax.plot(years, df_topshares[\"topshare_n_wealth\"], marker='o',\\\n", + " label=\"net wealth-approx\")\n", + "ax.plot(years, top_shares_nw, marker='o', label=\"net wealth-lorenz\")\n", + "\n", + "ax.set_xlabel(\"year\")\n", + "ax.set_ylabel(\"top $10\\%$ share\")\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "86ea5494", + "metadata": {}, + "source": [ + "```{solution-end}\n", + "```\n", + "\n", + "```{exercise}\n", + ":label: inequality_ex3\n", + "\n", + "The {ref}`code to compute the Gini coefficient is listed in the lecture above `.\n", + "\n", + "This code uses loops to calculate the coefficient based on income or wealth data.\n", + "\n", + "This function can be re-written using vectorization which will greatly improve the computational efficiency when using `python`.\n", + "\n", + "Re-write the function `gini_coefficient` using `numpy` and vectorized code.\n", + "\n", + "You can compare the output of this new function with the one above, and note the speed differences. \n", + "```\n", + "\n", + "```{solution-start} inequality_ex3\n", + ":class: dropdown\n", + "```\n", + "\n", + "Let's take a look at some raw data for the US that is stored in `df_income_wealth`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a4534a25", + "metadata": {}, + "outputs": [], + "source": [ + "df_income_wealth.describe()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bb5cb25f", + "metadata": {}, + "outputs": [], + "source": [ + "df_income_wealth.head(n=4)" + ] + }, + { + "cell_type": "markdown", + "id": "624ae422", + "metadata": {}, + "source": [ + "We will focus on wealth variable `n_wealth` to compute a Gini coefficient for the year 2016." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d2b5dbca", + "metadata": {}, + "outputs": [], + "source": [ + "data = df_income_wealth[df_income_wealth.year == 2016].sample(3000, random_state=1)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6d5aa572", + "metadata": {}, + "outputs": [], + "source": [ + "data.head(n=2)" + ] + }, + { + "cell_type": "markdown", + "id": "e1304eb0", + "metadata": {}, + "source": [ + "We can first compute the Gini coefficient using the function defined in the lecture above." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c005e3cd", + "metadata": {}, + "outputs": [], + "source": [ + "gini_coefficient(data.n_wealth.values)" + ] + }, + { + "cell_type": "markdown", + "id": "0bb3d3ab", + "metadata": {}, + "source": [ + "Now we can write a vectorized version using `numpy`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0e196063", + "metadata": {}, + "outputs": [], + "source": [ + "def gini(y):\n", + " n = len(y)\n", + " y_1 = np.reshape(y, (n, 1))\n", + " y_2 = np.reshape(y, (1, n))\n", + " g_sum = np.sum(np.abs(y_1 - y_2))\n", + " return g_sum / (2 * n * np.sum(y))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1fa5b7fe", + "metadata": {}, + "outputs": [], + "source": [ + "gini(data.n_wealth.values)" + ] + }, + { + "cell_type": "markdown", + "id": "27d0d60c", + "metadata": {}, + "source": [ + "Let's simulate five populations by drawing from a lognormal distribution as before" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a77b8356", + "metadata": {}, + "outputs": [], + "source": [ + "k = 5\n", + "σ_vals = np.linspace(0.2, 4, k)\n", + "n = 2_000\n", + "σ_vals = σ_vals.reshape((k,1))\n", + "μ_vals = -σ_vals**2/2\n", + "y_vals = np.exp(μ_vals + σ_vals*np.random.randn(n))" + ] + }, + { + "cell_type": "markdown", + "id": "13d4228d", + "metadata": {}, + "source": [ + "We can compute the Gini coefficient for these five populations using the vectorized function, the computation time is shown below:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4009aa4a", + "metadata": {}, + "outputs": [], + "source": [ + "%%time\n", + "gini_coefficients =[]\n", + "for i in range(k):\n", + " gini_coefficients.append(gini(y_vals[i]))" + ] + }, + { + "cell_type": "markdown", + "id": "7adcd09e", + "metadata": {}, + "source": [ + "This shows the vectorized function is much faster.\n", + "This gives us the Gini coefficients for these five households." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "89bb1716", + "metadata": {}, + "outputs": [], + "source": [ + "gini_coefficients" + ] + }, + { + "cell_type": "markdown", + "id": "800dd7d5", + "metadata": {}, + "source": [ + "```{solution-end}\n", + "```" + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.15.1" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 81, + 85, + 89, + 96, + 158, + 203, + 216, + 240, + 253, + 259, + 261, + 268, + 307, + 316, + 334, + 377, + 396, + 407, + 428, + 444, + 472, + 489, + 501, + 505, + 515, + 528, + 541, + 543, + 551, + 571, + 577, + 582, + 587, + 590, + 594, + 607, + 622, + 624, + 628, + 632, + 636, + 648, + 665, + 668, + 674, + 686, + 692, + 694, + 700, + 713, + 729, + 735, + 739, + 743, + 747, + 753, + 757, + 760, + 766, + 770, + 774, + 785, + 831, + 872, + 876, + 894, + 924, + 933, + 953, + 970, + 987, + 1002, + 1025, + 1031, + 1037, + 1056, + 1081, + 1085, + 1087, + 1091, + 1095, + 1097, + 1101, + 1103, + 1107, + 1115, + 1117, + 1120, + 1127, + 1130, + 1135, + 1139, + 1141 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/inequality.md b/book/_build/html/_sources/inequality.md new file mode 100644 index 0000000..9344b70 --- /dev/null +++ b/book/_build/html/_sources/inequality.md @@ -0,0 +1,1146 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.15.1 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Income and Wealth Inequality + +## Overview + +In the lecture {doc}`long_run_growth` we studied how GDP per capita has changed +for certain countries and regions. + +Per capita GDP is important because it gives us an idea of average income for +households in a given country. + +However, when we study income and wealth, averages are only part of the story. + +```{prf:example} +:label: ie_ex_av + +For example, imagine two societies, each with one million people, where + +* in the first society, the yearly income of one man is $100,000,000 and the income of the + others are zero +* in the second society, the yearly income of everyone is $100 + +These countries have the same income per capita (average income is $100) but the lives of the people will be very different (e.g., almost everyone in the first society is +starving, even though one person is fabulously rich). +``` + +The example above suggests that we should go beyond simple averages when we study income and wealth. + +This leads us to the topic of economic inequality, which examines how income and wealth (and other quantities) are distributed across a population. + +In this lecture we study inequality, beginning with measures of inequality and +then applying them to wealth and income data from the US and other countries. + + + +### Some history + +Many historians argue that inequality played a role in the fall of the Roman Republic (see, e.g., {cite}`levitt2019did`). + +Following the defeat of Carthage and the invasion of Spain, money flowed into +Rome from across the empire, greatly enriched those in power. + +Meanwhile, ordinary citizens were taken from their farms to fight for long +periods, diminishing their wealth. + +The resulting growth in inequality was a driving factor behind political turmoil that shook the foundations of the republic. + +Eventually, the Roman Republic gave way to a series of dictatorships, starting with [Octavian](https://en.wikipedia.org/wiki/Augustus) (Augustus) in 27 BCE. + +This history tells us that inequality matters, in the sense that it can drive major world events. + +There are other reasons that inequality might matter, such as how it affects +human welfare. + +With this motivation, let us start to think about what inequality is and how we +can quantify and analyze it. + + +### Measurement + +In politics and popular media, the word "inequality" is often used quite loosely, without any firm definition. + +To bring a scientific perspective to the topic of inequality we must start with careful definitions. + +Hence we begin by discussing ways that inequality can be measured in economic research. + +We will need to install the following packages + +```{code-cell} ipython3 +:tags: [hide-output] + +%pip install wbgapi plotly +``` + +We will also use the following imports. + +```{code-cell} ipython3 +import pandas as pd +import numpy as np +import matplotlib.pyplot as plt +import random as rd +import wbgapi as wb +import plotly.express as px +``` + + + +## The Lorenz curve + +One popular measure of inequality is the Lorenz curve. + +In this section we define the Lorenz curve and examine its properties. + + +### Definition + +The Lorenz curve takes a sample $w_1, \ldots, w_n$ and produces a curve $L$. + +We suppose that the sample has been sorted from smallest to largest. + +To aid our interpretation, suppose that we are measuring wealth + +* $w_1$ is the wealth of the poorest member of the population, and +* $w_n$ is the wealth of the richest member of the population. + +The curve $L$ is just a function $y = L(x)$ that we can plot and interpret. + +To create it we first generate data points $(x_i, y_i)$ according to + +```{prf:definition} +:label: define-lorenz + +$$ +x_i = \frac{i}{n}, +\qquad +y_i = \frac{\sum_{j \leq i} w_j}{\sum_{j \leq n} w_j}, +\qquad i = 1, \ldots, n +$$ +``` + +Now the Lorenz curve $L$ is formed from these data points using interpolation. + +If we use a line plot in `matplotlib`, the interpolation will be done for us. + +The meaning of the statement $y = L(x)$ is that the lowest $(100 +\times x)$\% of people have $(100 \times y)$\% of all wealth. + +* if $x=0.5$ and $y=0.1$, then the bottom 50% of the population + owns 10% of the wealth. + +In the discussion above we focused on wealth but the same ideas apply to +income, consumption, etc. + + +### Lorenz curves of simulated data + +Let's look at some examples and try to build understanding. + +First let us construct a `lorenz_curve` function that we can +use in our simulations below. + +It is useful to construct a function that translates an array of +income or wealth data into the cumulative share +of individuals (or households) and the cumulative share of income (or wealth). + +```{code-cell} ipython3 +def lorenz_curve(y): + """ + Calculates the Lorenz Curve, a graphical representation of + the distribution of income or wealth. + + It returns the cumulative share of people (x-axis) and + the cumulative share of income earned. + + Parameters + ---------- + y : array_like(float or int, ndim=1) + Array of income/wealth for each individual. + Unordered or ordered is fine. + + Returns + ------- + cum_people : array_like(float, ndim=1) + Cumulative share of people for each person index (i/n) + cum_income : array_like(float, ndim=1) + Cumulative share of income for each person index + + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Lorenz_curve + + Examples + -------- + >>> a_val, n = 3, 10_000 + >>> y = np.random.pareto(a_val, size=n) + >>> f_vals, l_vals = lorenz(y) + + """ + + n = len(y) + y = np.sort(y) + s = np.zeros(n + 1) + s[1:] = np.cumsum(y) + cum_people = np.zeros(n + 1) + cum_income = np.zeros(n + 1) + for i in range(1, n + 1): + cum_people[i] = i / n + cum_income[i] = s[i] / s[n] + return cum_people, cum_income +``` + +In the next figure, we generate $n=2000$ draws from a lognormal +distribution and treat these draws as our population. + +The straight 45-degree line ($x=L(x)$ for all $x$) corresponds to perfect equality. + +The log-normal draws produce a less equal distribution. + +For example, if we imagine these draws as being observations of wealth across +a sample of households, then the dashed lines show that the bottom 80\% of +households own just over 40\% of total wealth. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Lorenz curve of simulated wealth data + name: lorenz_simulated +--- +n = 2000 +sample = np.exp(np.random.randn(n)) + +fig, ax = plt.subplots() + +f_vals, l_vals = lorenz_curve(sample) +ax.plot(f_vals, l_vals, label=f'lognormal sample', lw=2) +ax.plot(f_vals, f_vals, label='equality', lw=2) + +ax.vlines([0.8], [0.0], [0.43], alpha=0.5, colors='k', ls='--') +ax.hlines([0.43], [0], [0.8], alpha=0.5, colors='k', ls='--') +ax.set_xlim((0, 1)) +ax.set_xlabel("share of households") +ax.set_ylim((0, 1)) +ax.set_ylabel("share of wealth") +ax.legend() +plt.show() +``` + + + + +### Lorenz curves for US data + +Next let's look at US data for both income and wealth. + +(data:survey-consumer-finance)= +The following code block imports a subset of the dataset `SCF_plus` for 2016, +which is derived from the [Survey of Consumer Finances](https://en.wikipedia.org/wiki/Survey_of_Consumer_Finances) (SCF). + +```{code-cell} ipython3 +url = 'https://github.com/QuantEcon/high_dim_data/raw/main/SCF_plus/SCF_plus_mini.csv' +df = pd.read_csv(url) +df_income_wealth = df.dropna() +``` + +```{code-cell} ipython3 +df_income_wealth.head(n=5) +``` + +The next code block uses data stored in dataframe `df_income_wealth` to generate the Lorenz curves. + +(The code is somewhat complex because we need to adjust the data according to +population weights supplied by the SCF.) + +```{code-cell} ipython3 +:tags: [hide-input] + +df = df_income_wealth + +varlist = ['n_wealth', # net wealth + 't_income', # total income + 'l_income'] # labor income + +years = df.year.unique() + +# Create lists to store Lorenz data + +F_vals, L_vals = [], [] + +for var in varlist: + # create lists to store Lorenz curve data + f_vals = [] + l_vals = [] + for year in years: + + # Repeat the observations according to their weights + counts = list(round(df[df['year'] == year]['weights'] )) + y = df[df['year'] == year][var].repeat(counts) + y = np.asarray(y) + + # Shuffle the sequence to improve the plot + rd.shuffle(y) + + # calculate and store Lorenz curve data + f_val, l_val = lorenz_curve(y) + f_vals.append(f_val) + l_vals.append(l_val) + + F_vals.append(f_vals) + L_vals.append(l_vals) + +f_vals_nw, f_vals_ti, f_vals_li = F_vals +l_vals_nw, l_vals_ti, l_vals_li = L_vals +``` + +Now we plot Lorenz curves for net wealth, total income and labor income in the +US in 2016. + +Total income is the sum of households' all income sources, including labor income but excluding capital gains. + +(All income measures are pre-tax.) + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: 2016 US Lorenz curves + name: lorenz_us + image: + alt: lorenz_us +--- +fig, ax = plt.subplots() +ax.plot(f_vals_nw[-1], l_vals_nw[-1], label=f'net wealth') +ax.plot(f_vals_ti[-1], l_vals_ti[-1], label=f'total income') +ax.plot(f_vals_li[-1], l_vals_li[-1], label=f'labor income') +ax.plot(f_vals_nw[-1], f_vals_nw[-1], label=f'equality') +ax.set_xlabel("share of households") +ax.set_ylabel("share of income/wealth") +ax.legend() +plt.show() +``` + + +One key finding from this figure is that wealth inequality is more extreme than income inequality. + + + + + + +## The Gini coefficient + +The Lorenz curve provides a visual representation of inequality in a distribution. + +Another way to study income and wealth inequality is via the Gini coefficient. + +In this section we discuss the Gini coefficient and its relationship to the Lorenz curve. + + + +### Definition + +As before, suppose that the sample $w_1, \ldots, w_n$ has been sorted from smallest to largest. + +The Gini coefficient is defined for the sample above as + +```{prf:definition} +:label: define-gini + +$$ +G := +\frac{\sum_{i=1}^n \sum_{j = 1}^n |w_j - w_i|} + {2n\sum_{i=1}^n w_i}. +$$ +``` + +The Gini coefficient is closely related to the Lorenz curve. + +In fact, it can be shown that its value is twice the area between the line of +equality and the Lorenz curve (e.g., the shaded area in {numref}`lorenz_gini`). + +The idea is that $G=0$ indicates complete equality, while $G=1$ indicates complete inequality. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Gini coefficient (simulated wealth data) + name: lorenz_gini +--- +fig, ax = plt.subplots() +f_vals, l_vals = lorenz_curve(sample) +ax.plot(f_vals, l_vals, label=f'lognormal sample', lw=2) +ax.plot(f_vals, f_vals, label='equality', lw=2) +ax.fill_between(f_vals, l_vals, f_vals, alpha=0.06) +ax.set_ylim((0, 1)) +ax.set_xlim((0, 1)) +ax.text(0.04, 0.5, r'$G = 2 \times$ shaded area') +ax.set_xlabel("share of households (%)") +ax.set_ylabel("share of wealth (%)") +ax.legend() +plt.show() +``` + +In fact the Gini coefficient can also be expressed as + +$$ +G = \frac{A}{A+B} +$$ + +where $A$ is the area between the 45-degree line of +perfect equality and the Lorenz curve, while $B$ is the area below the Lorenze curve -- see {numref}`lorenz_gini2`. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Lorenz curve and Gini coefficient + name: lorenz_gini2 +--- +fig, ax = plt.subplots() +f_vals, l_vals = lorenz_curve(sample) +ax.plot(f_vals, l_vals, label='lognormal sample', lw=2) +ax.plot(f_vals, f_vals, label='equality', lw=2) +ax.fill_between(f_vals, l_vals, f_vals, alpha=0.06) +ax.fill_between(f_vals, l_vals, np.zeros_like(f_vals), alpha=0.06) +ax.set_ylim((0, 1)) +ax.set_xlim((0, 1)) +ax.text(0.55, 0.4, 'A') +ax.text(0.75, 0.15, 'B') +ax.set_xlabel("share of households") +ax.set_ylabel("share of wealth") +ax.legend() +plt.show() +``` + + + +```{seealso} +The World in Data project has a [graphical exploration of the Lorenz curve and the Gini coefficient](https://ourworldindata.org/what-is-the-gini-coefficient) +``` + +### Gini coefficient of simulated data + +Let's examine the Gini coefficient in some simulations. + +The code below computes the Gini coefficient from a sample. + +(code:gini-coefficient)= + +```{code-cell} ipython3 + +def gini_coefficient(y): + r""" + Implements the Gini inequality index + + Parameters + ---------- + y : array_like(float) + Array of income/wealth for each individual. + Ordered or unordered is fine + + Returns + ------- + Gini index: float + The gini index describing the inequality of the array of income/wealth + + References + ---------- + + https://en.wikipedia.org/wiki/Gini_coefficient + """ + n = len(y) + i_sum = np.zeros(n) + for i in range(n): + for j in range(n): + i_sum[i] += abs(y[i] - y[j]) + return np.sum(i_sum) / (2 * n * np.sum(y)) +``` + +Now we can compute the Gini coefficients for five different populations. + +Each of these populations is generated by drawing from a +lognormal distribution with parameters $\mu$ (mean) and $\sigma$ (standard deviation). + +To create the five populations, we vary $\sigma$ over a grid of length $5$ +between $0.2$ and $4$. + +In each case we set $\mu = - \sigma^2 / 2$. + +This implies that the mean of the distribution does not change with $\sigma$. + +You can check this by looking up the expression for the mean of a lognormal +distribution. + +```{code-cell} ipython3 +%%time +k = 5 +σ_vals = np.linspace(0.2, 4, k) +n = 2_000 + +ginis = [] + +for σ in σ_vals: + μ = -σ**2 / 2 + y = np.exp(μ + σ * np.random.randn(n)) + ginis.append(gini_coefficient(y)) +``` + +Let's build a function that returns a figure (so that we can use it later in the lecture). + +```{code-cell} ipython3 +def plot_inequality_measures(x, y, legend, xlabel, ylabel): + fig, ax = plt.subplots() + ax.plot(x, y, marker='o', label=legend) + ax.set_xlabel(xlabel) + ax.set_ylabel(ylabel) + ax.legend() + return fig, ax +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Gini coefficients of simulated data + name: gini_simulated +--- +fix, ax = plot_inequality_measures(σ_vals, + ginis, + 'simulated', + '$\sigma$', + 'Gini coefficients') +plt.show() +``` + +The plots show that inequality rises with $\sigma$, according to the Gini +coefficient. + +### Gini coefficient for income (US data) + +Let's look at the Gini coefficient for the distribution of income in the US. + +We will get pre-computed Gini coefficients (based on income) from the World Bank using the [wbgapi](https://blogs.worldbank.org/opendata/introducing-wbgapi-new-python-package-accessing-world-bank-data). + +Let's use the `wbgapi` package we imported earlier to search the World Bank data for Gini to find the Series ID. + +```{code-cell} ipython3 +wb.search("gini") +``` + +We now know the series ID is `SI.POV.GINI`. + +(Another way to find the series ID is to use the [World Bank data portal](https://data.worldbank.org) and then use `wbgapi` to fetch the data.) + +To get a quick overview, let's histogram Gini coefficients across all countries and all years in the World Bank dataset. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Histogram of Gini coefficients across countries + name: gini_histogram +--- +# Fetch gini data for all countries +gini_all = wb.data.DataFrame("SI.POV.GINI") +# remove 'YR' in index and convert to integer +gini_all.columns = gini_all.columns.map(lambda x: int(x.replace('YR',''))) + +# Create a long series with a multi-index of the data to get global min and max values +gini_all = gini_all.unstack(level='economy').dropna() + +# Build a histogram +ax = gini_all.plot(kind="hist", bins=20) +ax.set_xlabel("Gini coefficient") +ax.set_ylabel("frequency") +plt.show() +``` + +We can see in {numref}`gini_histogram` that across 50 years of data and all countries the measure varies between 20 and 65. + +Let us fetch the data `DataFrame` for the USA. + +```{code-cell} ipython3 +data = wb.data.DataFrame("SI.POV.GINI", "USA") +data.head(n=5) +# remove 'YR' in index and convert to integer +data.columns = data.columns.map(lambda x: int(x.replace('YR',''))) +``` + +(This package often returns data with year information contained in the columns. This is not always convenient for simple plotting with pandas so it can be useful to transpose the results before plotting.) + + +```{code-cell} ipython3 +data = data.T # Obtain years as rows +data_usa = data['USA'] # pd.Series of US data +``` + +Let us take a look at the data for the US. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Gini coefficients for income distribution (USA) + name: gini_usa1 +--- +fig, ax = plt.subplots() +ax = data_usa.plot(ax=ax) +ax.set_ylim(data_usa.min()-1, data_usa.max()+1) +ax.set_ylabel("Gini coefficient (income)") +ax.set_xlabel("year") +plt.show() +``` + +As can be seen in {numref}`gini_usa1`, the income Gini +trended upward from 1980 to 2020 and then dropped following at the start of the COVID pandemic. + +(compare-income-wealth-usa-over-time)= +### Gini coefficient for wealth + +In the previous section we looked at the Gini coefficient for income, focusing on using US data. + +Now let's look at the Gini coefficient for the distribution of wealth. + +We will use US data from the {ref}`Survey of Consumer Finances` + + +```{code-cell} ipython3 +df_income_wealth.year.describe() +``` + +[This notebook](https://github.com/QuantEcon/lecture-python-intro/tree/main/lectures/_static/lecture_specific/inequality/data.ipynb) can be used to compute this information over the full dataset. + +```{code-cell} ipython3 +data_url = 'https://github.com/QuantEcon/lecture-python-intro/raw/main/lectures/_static/lecture_specific/inequality/usa-gini-nwealth-tincome-lincome.csv' +ginis = pd.read_csv(data_url, index_col='year') +ginis.head(n=5) +``` + +Let's plot the Gini coefficients for net wealth. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Gini coefficients of US net wealth + name: gini_wealth_us +--- +fig, ax = plt.subplots() +ax.plot(years, ginis["n_wealth"], marker='o') +ax.set_xlabel("year") +ax.set_ylabel("Gini coefficient") +plt.show() +``` + +The time series for the wealth Gini exhibits a U-shape, falling until the early +1980s and then increasing rapidly. + +One possibility is that this change is mainly driven by technology. + +However, we will see below that not all advanced economies experienced similar growth of inequality. + +### Cross-country comparisons of income inequality + +Earlier in this lecture we used `wbgapi` to get Gini data across many countries +and saved it in a variable called `gini_all` + +In this section we will use this data to compare several advanced economies, and +to look at the evolution in their respective income Ginis. + +```{code-cell} ipython3 +data = gini_all.unstack() +data.columns +``` + +There are 167 countries represented in this dataset. + +Let us compare three advanced economies: the US, the UK, and Norway + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Gini coefficients for income (USA, United Kingdom, and Norway) + name: gini_usa_gbr_nor1 +--- +ax = data[['USA','GBR', 'NOR']].plot() +ax.set_xlabel('year') +ax.set_ylabel('Gini coefficient') +ax.legend(title="") +plt.show() +``` + +We see that Norway has a shorter time series. + +Let us take a closer look at the underlying data and see if we can rectify this. + +```{code-cell} ipython3 +data[['NOR']].dropna().head(n=5) +``` + +The data for Norway in this dataset goes back to 1979 but there are gaps in the time series and matplotlib is not showing those data points. + +We can use the `.ffill()` method to copy and bring forward the last known value in a series to fill in these gaps + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Gini coefficients for income (USA, United Kingdom, and Norway) + name: gini_usa_gbr_nor2 +--- +data['NOR'] = data['NOR'].ffill() +ax = data[['USA','GBR', 'NOR']].plot() +ax.set_xlabel('year') +ax.set_ylabel('Gini coefficient') +ax.legend(title="") +plt.show() +``` + +From this plot we can observe that the US has a higher Gini coefficient (i.e. +higher income inequality) when compared to the UK and Norway. + +Norway has the lowest Gini coefficient over the three economies and, moreover, +the Gini coefficient shows no upward trend. + + + +### Gini Coefficient and GDP per capita (over time) + +We can also look at how the Gini coefficient compares with GDP per capita (over time). + +Let's take another look at the US, Norway, and the UK. + +```{code-cell} ipython3 +countries = ['USA', 'NOR', 'GBR'] +gdppc = wb.data.DataFrame("NY.GDP.PCAP.KD", countries) +# remove 'YR' in index and convert to integer +gdppc.columns = gdppc.columns.map(lambda x: int(x.replace('YR',''))) +gdppc = gdppc.T +``` + +We can rearrange the data so that we can plot GDP per capita and the Gini coefficient across years + +```{code-cell} ipython3 +plot_data = pd.DataFrame(data[countries].unstack()) +plot_data.index.names = ['country', 'year'] +plot_data.columns = ['gini'] +``` + +Now we can get the GDP per capita data into a shape that can be merged with `plot_data` + +```{code-cell} ipython3 +pgdppc = pd.DataFrame(gdppc.unstack()) +pgdppc.index.names = ['country', 'year'] +pgdppc.columns = ['gdppc'] +plot_data = plot_data.merge(pgdppc, left_index=True, right_index=True) +plot_data.reset_index(inplace=True) +``` + +Now we use Plotly to build a plot with GDP per capita on the y-axis and the Gini coefficient on the x-axis. + +```{code-cell} ipython3 +min_year = plot_data.year.min() +max_year = plot_data.year.max() +``` + +The time series for all three countries start and stop in different years. + +We will add a year mask to the data to improve clarity in the chart including the different end years associated with each country's time series. + +```{code-cell} ipython3 +labels = [1979, 1986, 1991, 1995, 2000, 2020, 2021, 2022] + \ + list(range(min_year,max_year,5)) +plot_data.year = plot_data.year.map(lambda x: x if x in labels else None) +``` + +(fig:plotly-gini-gdppc-years)= + +```{code-cell} ipython3 +fig = px.line(plot_data, + x = "gini", + y = "gdppc", + color = "country", + text = "year", + height = 800, + labels = {"gini" : "Gini coefficient", "gdppc" : "GDP per capita"} + ) +fig.update_traces(textposition="bottom right") +fig.show() +``` + +```{only} latex +This figure is built using `plotly` and is {ref}` available on the website ` +``` + +This plot shows that all three Western economies' GDP per capita has grown over +time with some fluctuations in the Gini coefficient. + +From the early 80's the United Kingdom and the US economies both saw increases +in income inequality. + +Interestingly, since the year 2000, the United Kingdom saw a decline in income inequality while +the US exhibits persistent but stable levels around a Gini coefficient of 40. + + +## Top shares + +Another popular measure of inequality is the top shares. + +In this section we show how to compute top shares. + + +### Definition + +As before, suppose that the sample $w_1, \ldots, w_n$ has been sorted from smallest to largest. + +Given the Lorenz curve $y = L(x)$ defined above, the top $100 \times p \%$ +share is defined as + +```{prf:definition} +:label: top-shares + +$$ +T(p) = 1 - L (1-p) + \approx \frac{\sum_{j\geq i} w_j}{ \sum_{j \leq n} w_j}, \quad i = \lfloor n (1-p)\rfloor +$$ (topshares) +``` + +Here $\lfloor \cdot \rfloor$ is the floor function, which rounds any +number down to the integer less than or equal to that number. + +The following code uses the data from dataframe `df_income_wealth` to generate another dataframe `df_topshares`. + +`df_topshares` stores the top 10 percent shares for the total income, the labor income and net wealth from 1950 to 2016 in US. + +```{code-cell} ipython3 +:tags: [hide-input] + +# transfer the survey weights from absolute into relative values +df1 = df_income_wealth +df2 = df1.groupby('year').sum(numeric_only=True).reset_index() +df3 = df2[['year', 'weights']] +df3.columns = 'year', 'r_weights' +df4 = pd.merge(df3, df1, how="left", on=["year"]) +df4['r_weights'] = df4['weights'] / df4['r_weights'] + +# create weighted nw, ti, li +df4['weighted_n_wealth'] = df4['n_wealth'] * df4['r_weights'] +df4['weighted_t_income'] = df4['t_income'] * df4['r_weights'] +df4['weighted_l_income'] = df4['l_income'] * df4['r_weights'] + +# extract two top 10% groups by net wealth and total income. +df6 = df4[df4['nw_groups'] == 'Top 10%'] +df7 = df4[df4['ti_groups'] == 'Top 10%'] + +# calculate the sum of weighted top 10% by net wealth, +# total income and labor income. +df5 = df4.groupby('year').sum(numeric_only=True).reset_index() +df8 = df6.groupby('year').sum(numeric_only=True).reset_index() +df9 = df7.groupby('year').sum(numeric_only=True).reset_index() + +df5['weighted_n_wealth_top10'] = df8['weighted_n_wealth'] +df5['weighted_t_income_top10'] = df9['weighted_t_income'] +df5['weighted_l_income_top10'] = df9['weighted_l_income'] + +# calculate the top 10% shares of the three variables. +df5['topshare_n_wealth'] = df5['weighted_n_wealth_top10'] / \ + df5['weighted_n_wealth'] +df5['topshare_t_income'] = df5['weighted_t_income_top10'] / \ + df5['weighted_t_income'] +df5['topshare_l_income'] = df5['weighted_l_income_top10'] / \ + df5['weighted_l_income'] + +# we only need these vars for top 10 percent shares +df_topshares = df5[['year', 'topshare_n_wealth', + 'topshare_t_income', 'topshare_l_income']] +``` + +Then let's plot the top shares. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: US top shares + name: top_shares_us +--- +fig, ax = plt.subplots() +ax.plot(years, df_topshares["topshare_l_income"], + marker='o', label="labor income") +ax.plot(years, df_topshares["topshare_n_wealth"], + marker='o', label="net wealth") +ax.plot(years, df_topshares["topshare_t_income"], + marker='o', label="total income") +ax.set_xlabel("year") +ax.set_ylabel("top $10\%$ share") +ax.legend() +plt.show() +``` + +## Exercises + +```{exercise} +:label: inequality_ex1 + +Using simulation, compute the top 10 percent shares for the collection of +lognormal distributions associated with the random variables $w_\sigma = +\exp(\mu + \sigma Z)$, where $Z \sim N(0, 1)$ and $\sigma$ varies over a +finite grid between $0.2$ and $4$. + +As $\sigma$ increases, so does the variance of $w_\sigma$. + +To focus on volatility, adjust $\mu$ at each step to maintain the equality +$\mu=-\sigma^2/2$. + +For each $\sigma$, generate 2,000 independent draws of $w_\sigma$ and +calculate the Lorenz curve and Gini coefficient. + +Confirm that higher variance +generates more dispersion in the sample, and hence greater inequality. +``` + +```{solution-start} inequality_ex1 +:class: dropdown +``` + +Here is one solution: + +```{code-cell} ipython3 +def calculate_top_share(s, p=0.1): + + s = np.sort(s) + n = len(s) + index = int(n * (1 - p)) + return s[index:].sum() / s.sum() +``` + +```{code-cell} ipython3 +k = 5 +σ_vals = np.linspace(0.2, 4, k) +n = 2_000 + +topshares = [] +ginis = [] +f_vals = [] +l_vals = [] + +for σ in σ_vals: + μ = -σ ** 2 / 2 + y = np.exp(μ + σ * np.random.randn(n)) + f_val, l_val = lorenz_curve(y) + f_vals.append(f_val) + l_vals.append(l_val) + ginis.append(gini_coefficient(y)) + topshares.append(calculate_top_share(y)) +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Top shares of simulated data + name: top_shares_simulated + image: + alt: top_shares_simulated +--- +fig, ax = plot_inequality_measures(σ_vals, + topshares, + "simulated data", + "$\sigma$", + "top $10\%$ share") +plt.show() +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Gini coefficients of simulated data + name: gini_coef_simulated + image: + alt: gini_coef_simulated +--- +fig, ax = plot_inequality_measures(σ_vals, + ginis, + "simulated data", + "$\sigma$", + "gini coefficient") +plt.show() +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Lorenz curves for simulated data + name: lorenz_curve_simulated + image: + alt: lorenz_curve_simulated +--- +fig, ax = plt.subplots() +ax.plot([0,1],[0,1], label=f"equality") +for i in range(len(f_vals)): + ax.plot(f_vals[i], l_vals[i], label=f"$\sigma$ = {σ_vals[i]}") +plt.legend() +plt.show() +``` + +```{solution-end} +``` + + +```{exercise} +:label: inequality_ex2 + +According to the definition of the top shares {eq}`topshares` we can also calculate the top percentile shares using the Lorenz curve. + +Compute the top shares of US net wealth using the corresponding Lorenz curves data: ``f_vals_nw, l_vals_nw`` and linear interpolation. + +Plot the top shares generated from Lorenz curve and the top shares approximated from data together. + +``` + +```{solution-start} inequality_ex2 +:class: dropdown +``` + +Here is one solution: + +```{code-cell} ipython3 +def lorenz2top(f_val, l_val, p=0.1): + t = lambda x: np.interp(x, f_val, l_val) + return 1- t(1 - p) +``` + +```{code-cell} ipython3 +top_shares_nw = [] +for f_val, l_val in zip(f_vals_nw, l_vals_nw): + top_shares_nw.append(lorenz2top(f_val, l_val)) +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: 'US top shares: approximation vs Lorenz' + name: top_shares_us_al + image: + alt: top_shares_us_al +--- +fig, ax = plt.subplots() + +ax.plot(years, df_topshares["topshare_n_wealth"], marker='o',\ + label="net wealth-approx") +ax.plot(years, top_shares_nw, marker='o', label="net wealth-lorenz") + +ax.set_xlabel("year") +ax.set_ylabel("top $10\%$ share") +ax.legend() +plt.show() +``` + +```{solution-end} +``` + +```{exercise} +:label: inequality_ex3 + +The {ref}`code to compute the Gini coefficient is listed in the lecture above `. + +This code uses loops to calculate the coefficient based on income or wealth data. + +This function can be re-written using vectorization which will greatly improve the computational efficiency when using `python`. + +Re-write the function `gini_coefficient` using `numpy` and vectorized code. + +You can compare the output of this new function with the one above, and note the speed differences. +``` + +```{solution-start} inequality_ex3 +:class: dropdown +``` + +Let's take a look at some raw data for the US that is stored in `df_income_wealth` + +```{code-cell} ipython3 +df_income_wealth.describe() +``` + +```{code-cell} ipython3 +df_income_wealth.head(n=4) +``` + +We will focus on wealth variable `n_wealth` to compute a Gini coefficient for the year 2016. + +```{code-cell} ipython3 +data = df_income_wealth[df_income_wealth.year == 2016].sample(3000, random_state=1) +``` + +```{code-cell} ipython3 +data.head(n=2) +``` + +We can first compute the Gini coefficient using the function defined in the lecture above. + +```{code-cell} ipython3 +gini_coefficient(data.n_wealth.values) +``` + +Now we can write a vectorized version using `numpy` + +```{code-cell} ipython3 +def gini(y): + n = len(y) + y_1 = np.reshape(y, (n, 1)) + y_2 = np.reshape(y, (1, n)) + g_sum = np.sum(np.abs(y_1 - y_2)) + return g_sum / (2 * n * np.sum(y)) +``` +```{code-cell} ipython3 +gini(data.n_wealth.values) +``` +Let's simulate five populations by drawing from a lognormal distribution as before + +```{code-cell} ipython3 +k = 5 +σ_vals = np.linspace(0.2, 4, k) +n = 2_000 +σ_vals = σ_vals.reshape((k,1)) +μ_vals = -σ_vals**2/2 +y_vals = np.exp(μ_vals + σ_vals*np.random.randn(n)) +``` +We can compute the Gini coefficient for these five populations using the vectorized function, the computation time is shown below: + +```{code-cell} ipython3 +%%time +gini_coefficients =[] +for i in range(k): + gini_coefficients.append(gini(y_vals[i])) +``` +This shows the vectorized function is much faster. +This gives us the Gini coefficients for these five households. + +```{code-cell} ipython3 +gini_coefficients +``` +```{solution-end} +``` + + + diff --git a/book/_build/html/_sources/inflation_history.ipynb b/book/_build/html/_sources/inflation_history.ipynb new file mode 100644 index 0000000..4ace2be --- /dev/null +++ b/book/_build/html/_sources/inflation_history.ipynb @@ -0,0 +1,935 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "10129406", + "metadata": {}, + "source": [ + "# Price Level Histories \n", + "\n", + "This lecture offers some historical evidence about fluctuations in levels of aggregate price indexes. \n", + "\n", + "Let's start by installing the necessary Python packages.\n", + "\n", + "The `xlrd` package is used by `pandas` to perform operations on Excel files." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d12c840c", + "metadata": { + "tags": [ + "hide-output" + ] + }, + "outputs": [], + "source": [ + "%pip install xlrd" + ] + }, + { + "cell_type": "markdown", + "id": "3c58262f", + "metadata": {}, + "source": [ + "" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "091eebb7", + "metadata": { + "tags": [ + "hide-cell" + ] + }, + "outputs": [], + "source": [ + "from importlib.metadata import version\n", + "from packaging.version import Version\n", + "\n", + "if Version(version(\"pandas\")) < Version('2.1.4'):\n", + " %pip install \"pandas>=2.1.4\"" + ] + }, + { + "cell_type": "markdown", + "id": "4b320f04", + "metadata": {}, + "source": [ + "We can then import the Python modules we will use." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "001d00b2", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import matplotlib.dates as mdates" + ] + }, + { + "cell_type": "markdown", + "id": "3b59722b", + "metadata": {}, + "source": [ + "The rate of growth of the price level is called **inflation** in the popular press and in discussions among central bankers and treasury officials.\n", + "\n", + "The price level is measured in units of domestic currency per units of a representative bundle of consumption goods. \n", + "\n", + "Thus, in the US, the price level at $t$ is measured in dollars (month $t$ or year $t$) per unit of the consumption bundle.\n", + "\n", + "Until the early 20th century, in many western economies, price levels fluctuated from year to year but didn't have much of a trend. \n", + "\n", + "Often the price levels ended a century near where they started.\n", + "\n", + "Things were different in the 20th century, as we shall see in this lecture.\n", + "\n", + "A widely believed explanation of this big difference is that countries' abandoning gold and silver standards in the early twentieth century. \n", + "\n", + "```{tip}\n", + "This lecture sets the stage for some subsequent lectures about a theory that macro economists use to think about determinants of the price level, namely, {doc}`cagan_ree` and {doc}`cagan_adaptive`\n", + "```\n", + "\n", + "## Four centuries of price levels\n", + "\n", + "We begin by displaying data that originally appeared on page 35 of {cite}`sargent2002big` that show price levels for four \"hard currency\" countries from 1600 to 1914.\n", + "\n", + "* France \n", + "* Spain (Castile)\n", + "* United Kingdom\n", + "* United States\n", + "\n", + "In the present context, the phrase \"hard currency\" means that the countries were on a commodity-money standard: money consisted of gold and silver coins that circulated at values largely determined by the weights of their gold and silver contents.\n", + "\n", + "```{note}\n", + "Under a gold or silver standard, some money also consisted of \"warehouse certificates\" that represented paper claims on gold or silver coins. Bank notes issued by the government or private banks can be viewed as examples of such \"warehouse certificates\".\n", + "```\n", + "\n", + "Let us bring the data into pandas from a spreadsheet that is [hosted on github](https://github.com/QuantEcon/lecture-python-intro/tree/main/lectures/datasets)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2392f279", + "metadata": {}, + "outputs": [], + "source": [ + "# Import data and clean up the index\n", + "data_url = \"https://github.com/QuantEcon/lecture-python-intro/raw/main/lectures/datasets/longprices.xls\"\n", + "df_fig5 = pd.read_excel(data_url, \n", + " sheet_name='all', \n", + " header=2, \n", + " index_col=0).iloc[1:]\n", + "df_fig5.index = df_fig5.index.astype(int)" + ] + }, + { + "cell_type": "markdown", + "id": "3a157ece", + "metadata": {}, + "source": [ + "We first plot price levels over the period 1600-1914.\n", + "\n", + "During most years in this time interval, the countries were on a gold or silver standard." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "093fd306", + "metadata": { + "mystnb": { + "figure": { + "caption": "Long run time series of the price level", + "name": "lrpl" + } + } + }, + "outputs": [], + "source": [ + "df_fig5_befe1914 = df_fig5[df_fig5.index <= 1914]\n", + "\n", + "# Create plot\n", + "cols = ['UK', 'US', 'France', 'Castile']\n", + "\n", + "fig, ax = plt.subplots(figsize=(10,6))\n", + "\n", + "for col in cols:\n", + " ax.plot(df_fig5_befe1914.index, \n", + " df_fig5_befe1914[col], label=col, lw=2)\n", + "\n", + "ax.legend()\n", + "ax.set_ylabel('Index 1913 = 100')\n", + "ax.set_xlabel('Year')\n", + "ax.set_xlim(xmin=1600)\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "ded6c434", + "metadata": {}, + "source": [ + "We say \"most years\" because there were temporary lapses from the gold or silver standard.\n", + "\n", + "By staring at {numref}`lrpl` carefully, you might be able to guess when these temporary lapses occurred, because they were also times during which price levels temporarily rose markedly:\n", + "\n", + "* 1791-1797 in France (French Revolution)\n", + "* 1776-1790 in the US (War for Independence from Great Britain)\n", + "* 1861-1865 in the US (Civil War)\n", + "\n", + "During these episodes, the gold/silver standard was temporarily abandoned when a government printed paper money to pay for war expenditures.\n", + "\n", + "```{note}\n", + "This quantecon lecture {doc}`french_rev` describes circumstances leading up to and during the big inflation that occurred during the French Revolution.\n", + "```\n", + "\n", + "Despite these temporary lapses, a striking thing about the figure is that price levels were roughly constant over three centuries. \n", + "\n", + "In the early century, two other features of this data attracted the attention of [Irving Fisher](https://en.wikipedia.org/wiki/Irving_Fisher) of Yale University and [John Maynard Keynes](https://en.wikipedia.org/wiki/John_Maynard_Keynes) of Cambridge University.\n", + "\n", + "* Despite being anchored to the same average level over long time spans, there were considerable year-to-year variations in price levels\n", + "* While using valuable gold and silver as coins succeeded in anchoring the price level by limiting the supply of money, it cost real resources.\n", + "* a country paid a high \"opportunity cost\" for using gold and silver coins as money -- that gold and silver could instead have been made into valuable jewelry and other durable goods. \n", + "\n", + "Keynes and Fisher proposed what they claimed would be a more efficient way to achieve a price level that \n", + "\n", + "* would be at least as firmly anchored as achieved under a gold or silver standard, and\n", + "* would also exhibit less year-to-year short-term fluctuations. \n", + "\n", + "They said that central bank could achieve price level stability by\n", + "\n", + "* issuing **limited supplies** of paper currency\n", + "* refusing to print money to finance government expenditures\n", + "\n", + "This logic prompted John Maynard Keynes to call a commodity standard a \"barbarous relic.\"\n", + "\n", + "A paper currency or \"fiat money\" system disposes of all reserves behind a currency. \n", + "\n", + "But adhering to a gold or silver standard had provided an automatic mechanism for limiting the supply of money, thereby anchoring the price level.\n", + "\n", + "To anchor the price level, a pure paper or fiat money system replaces that automatic mechanism with a central bank with the authority and determination to limit the supply of money (and to deter counterfeiters!) \n", + "\n", + "Now let's see what happened to the price level in the four countries after 1914, when one after another of them left the gold/silver standard by showing the complete graph that originally appeared on page 35 of {cite}`sargent2002big`.\n", + "\n", + "{numref}`lrpl_lg` shows the logarithm of price levels over four \"hard currency\" countries from 1600 to 2000.\n", + "\n", + "```{note}\n", + "Although we didn't have to use logarithms in our earlier graphs that had stopped in 1914, we now choose to use logarithms because we want to fit observations after 1914 in the same graph as the earlier observations.\n", + "```\n", + "\n", + "After the outbreak of the Great War in 1914, the four countries left the gold standard and in so doing acquired the ability to print money to finance government expenditures." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e090f5b8", + "metadata": { + "mystnb": { + "figure": { + "caption": "Long run time series of the price level (log)", + "name": "lrpl_lg" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots(dpi=200)\n", + "\n", + "for col in cols:\n", + " ax.plot(df_fig5.index, df_fig5[col], lw=2)\n", + " ax.text(x=df_fig5.index[-1]+2, \n", + " y=df_fig5[col].iloc[-1], s=col)\n", + "\n", + "ax.set_yscale('log')\n", + "ax.set_ylabel('Logs of price levels (Index 1913 = 100)')\n", + "ax.set_ylim([10, 1e6])\n", + "ax.set_xlabel('year')\n", + "ax.set_xlim(xmin=1600)\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "e2e761dd", + "metadata": {}, + "source": [ + "{numref}`lrpl_lg` shows that paper-money-printing central banks didn't do as well as the gold and standard silver standard in anchoring price levels.\n", + "\n", + "That would probably have surprised or disappointed Irving Fisher and John Maynard Keynes.\n", + "\n", + "Actually, earlier economists and statesmen knew about the possibility of fiat money systems long before Keynes and Fisher advocated them in the early 20th century.\n", + "\n", + "Proponents of a commodity money system did not trust governments and central banks properly to manage a fiat money system.\n", + "\n", + "They were willing to pay the resource costs associated with setting up and maintaining a commodity money system.\n", + "\n", + "In light of the high and persistent inflation that many countries experienced after they abandoned commodity monies in the twentieth century, we hesitate to criticize advocates of a gold or silver standard for their preference to stay on the pre-1914 gold/silver standard. \n", + "\n", + "The breadth and lengths of the inflationary experiences of the twentieth century under paper money fiat standards are historically unprecedented.\n", + "\n", + "## Four big inflations\n", + "\n", + "In the wake of World War I, which ended in November 1918, monetary and fiscal authorities struggled to achieve price level stability without being on a gold or silver standard.\n", + "\n", + "We present four graphs from \"The Ends of Four Big Inflations\" from chapter 3 of {cite}`sargent2013rational`.\n", + "\n", + "The graphs depict logarithms of price levels during the early post World War I years for four countries:\n", + "\n", + "* Figure 3.1, Retail prices Austria, 1921-1924 (page 42)\n", + "* Figure 3.2, Wholesale prices Hungary, 1921-1924 (page 43)\n", + "* Figure 3.3, Wholesale prices, Poland, 1921-1924 (page 44)\n", + "* Figure 3.4, Wholesale prices, Germany, 1919-1924 (page 45)\n", + "\n", + "We have added logarithms of the exchange rates vis-à-vis the US dollar to each of the four graphs\n", + "from chapter 3 of {cite}`sargent2013rational`.\n", + "\n", + "Data underlying our graphs appear in tables in an appendix to chapter 3 of {cite}`sargent2013rational`.\n", + "We have transcribed all of these data into a spreadsheet {download}`chapter_3.xlsx ` that we read into pandas.\n", + "\n", + "In the code cell below we clean the data and build a `pandas.dataframe`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "15f78e0b", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "def process_entry(entry):\n", + " \"Clean each entry of a dataframe.\"\n", + " \n", + " if type(entry) == str:\n", + " # Remove leading and trailing whitespace\n", + " entry = entry.strip()\n", + " # Remove comma\n", + " entry = entry.replace(',', '')\n", + " \n", + " # Remove HTML markers\n", + " item_to_remove = ['a', 'c', \n", + " 'd', 'e']\n", + "\n", + " # b represents a billion\n", + " if 'b' in entry:\n", + " entry = entry.replace('b', '')\n", + " entry = float(entry) * 1e9\n", + " else:\n", + " for item in item_to_remove:\n", + " if item in entry:\n", + " entry = entry.replace(item, '')\n", + " return entry\n", + "\n", + "def process_df(df):\n", + " \"Clean and reorganize the entire dataframe.\"\n", + " \n", + " # Remove HTML markers from column names\n", + " for item in ['a', 'c', 'd', 'e']:\n", + " df.columns = df.columns.str.replace(item, '')\n", + " \n", + " # Convert years to int\n", + " df['Year'] = df['Year'].apply(lambda x: int(x))\n", + " \n", + " # Set index to datetime with year and month\n", + " df = df.set_index(\n", + " pd.to_datetime(\n", + " (df['Year'].astype(str) + \\\n", + " df['Month'].astype(str)), \n", + " format='%Y%B'))\n", + " df = df.drop(['Year', 'Month'], axis=1)\n", + " \n", + " # Handle duplicates by keeping the first\n", + " df = df[~df.index.duplicated(keep='first')]\n", + " \n", + " # Convert attribute values to numeric\n", + " df = df.map(lambda x: float(x) \\\n", + " if x != '—' else np.nan)\n", + " \n", + " # Finally, we only focus on data between 1919 and 1925\n", + " mask = (df.index >= '1919-01-01') & \\\n", + " (df.index < '1925-01-01')\n", + " df = df.loc[mask]\n", + "\n", + " return df" + ] + }, + { + "cell_type": "markdown", + "id": "56562523", + "metadata": {}, + "source": [ + "Now we write plotting functions `pe_plot` and `pr_plot` that will build figures that show the price level, exchange rates, \n", + "and inflation rates, for each country of interest." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d360a43a", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "def pe_plot(p_seq, e_seq, index, labs, ax):\n", + " \"Generate plots for price and exchange rates.\"\n", + "\n", + " p_lab, e_lab = labs\n", + " \n", + " # Plot price and exchange rates\n", + " ax.plot(index, p_seq, label=p_lab, color='tab:blue', lw=2)\n", + " \n", + " # Add a new axis\n", + " ax1 = ax.twinx()\n", + " ax1.plot([None], [None], label=p_lab, color='tab:blue', lw=2)\n", + " ax1.plot(index, e_seq, label=e_lab, color='tab:orange', lw=2)\n", + " \n", + " # Set log axes\n", + " ax.set_yscale('log')\n", + " ax1.set_yscale('log')\n", + " \n", + " # Define the axis label format\n", + " ax.xaxis.set_major_locator(\n", + " mdates.MonthLocator(interval=5))\n", + " ax.xaxis.set_major_formatter(\n", + " mdates.DateFormatter('%b %Y'))\n", + " for label in ax.get_xticklabels():\n", + " label.set_rotation(45)\n", + " \n", + " # Set labels\n", + " ax.set_ylabel('Price level')\n", + " ax1.set_ylabel('Exchange rate')\n", + " \n", + " ax1.legend(loc='upper left')\n", + " \n", + " return ax1\n", + "\n", + "def pr_plot(p_seq, index, ax):\n", + " \"Generate plots for inflation rates.\"\n", + "\n", + " # Calculate the difference of log p_seq\n", + " log_diff_p = np.diff(np.log(p_seq))\n", + " \n", + " # Calculate and plot moving average\n", + " diff_smooth = pd.DataFrame(log_diff_p).rolling(3, center=True).mean()\n", + " ax.plot(index[1:], diff_smooth, label='Moving average (3 period)', alpha=0.5, lw=2)\n", + " ax.set_ylabel('Inflation rate')\n", + " \n", + " ax.xaxis.set_major_locator(\n", + " mdates.MonthLocator(interval=5))\n", + " ax.xaxis.set_major_formatter(\n", + " mdates.DateFormatter('%b %Y'))\n", + " \n", + " for label in ax.get_xticklabels():\n", + " label.set_rotation(45)\n", + " \n", + " ax.legend()\n", + " \n", + " return ax" + ] + }, + { + "cell_type": "markdown", + "id": "34ff8a2c", + "metadata": {}, + "source": [ + "We prepare the data for each country" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4d0f80b0", + "metadata": {}, + "outputs": [], + "source": [ + "# Import data\n", + "data_url = \"https://github.com/QuantEcon/lecture-python-intro/raw/main/lectures/datasets/chapter_3.xlsx\"\n", + "xls = pd.ExcelFile(data_url)\n", + "\n", + "# Select relevant sheets\n", + "sheet_index = [(2, 3, 4), \n", + " (9, 10), \n", + " (14, 15, 16), \n", + " (21, 18, 19)]\n", + "\n", + "# Remove redundant rows\n", + "remove_row = [(-2, -2, -2), \n", + " (-7, -10), \n", + " (-6, -4, -3), \n", + " (-19, -3, -6)]\n", + "\n", + "# Unpack and combine series for each country\n", + "df_list = []\n", + "\n", + "for i in range(4):\n", + " \n", + " indices, rows = sheet_index[i], remove_row[i]\n", + " \n", + " # Apply process_entry on the selected sheet\n", + " sheet_list = [\n", + " pd.read_excel(xls, 'Table3.' + str(ind), \n", + " header=1).iloc[:row].map(process_entry)\n", + " for ind, row in zip(indices, rows)]\n", + " \n", + " sheet_list = [process_df(df) for df in sheet_list]\n", + " df_list.append(pd.concat(sheet_list, axis=1))\n", + "\n", + "df_aus, df_hun, df_pol, df_deu = df_list" + ] + }, + { + "cell_type": "markdown", + "id": "540c814f", + "metadata": {}, + "source": [ + "Now let's construct graphs for our four countries.\n", + "\n", + "For each country, we'll plot two graphs.\n", + "\n", + "The first graph plots logarithms of \n", + "\n", + "* price levels\n", + "* exchange rates vis-à-vis US dollars\n", + "\n", + "For each country, the scale on the right side of a graph will pertain to the price level while the scale on the left side of a graph will pertain to the exchange rate. \n", + "\n", + "For each country, the second graph plots a centered three-month moving average of the inflation rate defined as $\\frac{p_{t-1} + p_t + p_{t+1}}{3}$.\n", + "\n", + "### Austria\n", + "\n", + "The sources of our data are:\n", + "\n", + "* Table 3.3, retail price level $\\exp p$\n", + "* Table 3.4, exchange rate with US" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6d666d70", + "metadata": { + "mystnb": { + "figure": { + "caption": "Price index and exchange rate (Austria)", + "name": "pi_xrate_austria" + } + } + }, + "outputs": [], + "source": [ + "p_seq = df_aus['Retail price index, 52 commodities']\n", + "e_seq = df_aus['Exchange Rate']\n", + "\n", + "lab = ['Retail price index', \n", + " 'Austrian Krones (Crowns) per US cent']\n", + "\n", + "# Create plot\n", + "fig, ax = plt.subplots(dpi=200)\n", + "_ = pe_plot(p_seq, e_seq, df_aus.index, lab, ax)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ee2f7620", + "metadata": { + "mystnb": { + "figure": { + "caption": "Monthly inflation rate (Austria)", + "name": "inflationrate_austria" + } + } + }, + "outputs": [], + "source": [ + "# Plot moving average\n", + "fig, ax = plt.subplots(dpi=200)\n", + "_ = pr_plot(p_seq, df_aus.index, ax)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "adcafb1b", + "metadata": {}, + "source": [ + "Staring at {numref}`pi_xrate_austria` and {numref}`inflationrate_austria` conveys the following impressions to the authors of this lecture at QuantEcon.\n", + "\n", + "* an episode of \"hyperinflation\" with rapidly rising log price level and very high monthly inflation rates\n", + "* a sudden stop of the hyperinflation as indicated by the abrupt flattening of the log price level and a marked permanent drop in the three-month average of inflation\n", + "* a US dollar exchange rate that shadows the price level. \n", + " \n", + "We'll see similar patterns in the next three episodes that we'll study now.\n", + "\n", + "### Hungary\n", + "\n", + "The source of our data for Hungary is:\n", + "\n", + "* Table 3.10, price level $\\exp p$ and exchange rate" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "20c5f1fe", + "metadata": { + "mystnb": { + "figure": { + "caption": "Price index and exchange rate (Hungary)", + "name": "pi_xrate_hungary" + } + } + }, + "outputs": [], + "source": [ + "p_seq = df_hun['Hungarian index of prices']\n", + "e_seq = 1 / df_hun['Cents per crown in New York']\n", + "\n", + "lab = ['Hungarian index of prices', \n", + " 'Hungarian Koronas (Crowns) per US cent']\n", + "\n", + "# Create plot\n", + "fig, ax = plt.subplots(dpi=200)\n", + "_ = pe_plot(p_seq, e_seq, df_hun.index, lab, ax)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d4a063aa", + "metadata": { + "mystnb": { + "figure": { + "caption": "Monthly inflation rate (Hungary)", + "name": "inflationrate_hungary" + } + } + }, + "outputs": [], + "source": [ + "# Plot moving average\n", + "fig, ax = plt.subplots(dpi=200)\n", + "_ = pr_plot(p_seq, df_hun.index, ax)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "afe26e4c", + "metadata": {}, + "source": [ + "### Poland\n", + "\n", + "The sources of our data for Poland are:\n", + "\n", + "* Table 3.15, price level $\\exp p$ \n", + "* Table 3.15, exchange rate\n", + "\n", + "```{note}\n", + "To construct the price level series from the data in the spreadsheet, we instructed Pandas to follow the same procedures implemented in chapter 3 of {cite}`sargent2013rational`. We spliced together three series - Wholesale price index, Wholesale Price Index: On paper currency basis, and Wholesale Price Index: On zloty basis. We adjusted the sequence based on the price level ratio at the last period of the available previous series and glued them to construct a single series.\n", + "We dropped the exchange rate after June 1924, when the zloty was adopted. We did this because we don't have the price measured in zloty. We used the old currency in June to compute the exchange rate adjustment.\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8018a638", + "metadata": { + "mystnb": { + "figure": { + "caption": "Price index and exchange rate (Poland)", + "name": "pi_xrate_poland" + } + } + }, + "outputs": [], + "source": [ + "# Splice three price series in different units\n", + "p_seq1 = df_pol['Wholesale price index'].copy()\n", + "p_seq2 = df_pol['Wholesale Price Index: '\n", + " 'On paper currency basis'].copy()\n", + "p_seq3 = df_pol['Wholesale Price Index: ' \n", + " 'On zloty basis'].copy()\n", + "\n", + "# Non-nan part\n", + "mask_1 = p_seq1[~p_seq1.isna()].index[-1]\n", + "mask_2 = p_seq2[~p_seq2.isna()].index[-2]\n", + "\n", + "adj_ratio12 = (p_seq1[mask_1] / p_seq2[mask_1])\n", + "adj_ratio23 = (p_seq2[mask_2] / p_seq3[mask_2])\n", + "\n", + "# Glue three series\n", + "p_seq = pd.concat([p_seq1[:mask_1], \n", + " adj_ratio12 * p_seq2[mask_1:mask_2], \n", + " adj_ratio23 * p_seq3[mask_2:]])\n", + "p_seq = p_seq[~p_seq.index.duplicated(keep='first')]\n", + "\n", + "# Exchange rate\n", + "e_seq = 1/df_pol['Cents per Polish mark (zloty after May 1924)']\n", + "e_seq[e_seq.index > '05-01-1924'] = np.nan" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7a306afa", + "metadata": {}, + "outputs": [], + "source": [ + "lab = ['Wholesale price index', \n", + " 'Polish marks per US cent']\n", + "\n", + "# Create plot\n", + "fig, ax = plt.subplots(dpi=200)\n", + "ax1 = pe_plot(p_seq, e_seq, df_pol.index, lab, ax)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "678de7b1", + "metadata": { + "mystnb": { + "figure": { + "caption": "Monthly inflation rate (Poland)", + "name": "inflationrate_poland" + } + } + }, + "outputs": [], + "source": [ + "# Plot moving average\n", + "fig, ax = plt.subplots(dpi=200)\n", + "_ = pr_plot(p_seq, df_pol.index, ax)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "3443517b", + "metadata": {}, + "source": [ + "### Germany\n", + "\n", + "The sources of our data for Germany are the following tables from chapter 3 of {cite}`sargent2013rational`:\n", + "\n", + "* Table 3.18, wholesale price level $\\exp p$ \n", + "* Table 3.19, exchange rate" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d1925bf4", + "metadata": { + "mystnb": { + "figure": { + "caption": "Price index and exchange rate (Germany)", + "name": "pi_xrate_germany" + } + } + }, + "outputs": [], + "source": [ + "p_seq = df_deu['Price index (on basis of marks before July 1924,'\n", + " ' reichsmarks after)'].copy()\n", + "e_seq = 1/df_deu['Cents per mark']\n", + "\n", + "lab = ['Price index', \n", + " 'Marks per US cent']\n", + "\n", + "# Create plot\n", + "fig, ax = plt.subplots(dpi=200)\n", + "ax1 = pe_plot(p_seq, e_seq, df_deu.index, lab, ax)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3f7d80f3", + "metadata": { + "mystnb": { + "figure": { + "caption": "Price index (adjusted) and exchange rate (Germany)", + "name": "piadj_xrate_germany" + } + } + }, + "outputs": [], + "source": [ + "p_seq = df_deu['Price index (on basis of marks before July 1924,'\n", + " ' reichsmarks after)'].copy()\n", + "e_seq = 1/df_deu['Cents per mark'].copy()\n", + "\n", + "# Adjust the price level/exchange rate after the currency reform\n", + "p_seq[p_seq.index > '06-01-1924'] = p_seq[p_seq.index \n", + " > '06-01-1924'] * 1e12\n", + "e_seq[e_seq.index > '12-01-1923'] = e_seq[e_seq.index \n", + " > '12-01-1923'] * 1e12\n", + "\n", + "lab = ['Price index (marks or converted to marks)', \n", + " 'Marks per US cent(or reichsmark converted to mark)']\n", + "\n", + "# Create plot\n", + "fig, ax = plt.subplots(dpi=200)\n", + "ax1 = pe_plot(p_seq, e_seq, df_deu.index, lab, ax)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "16b1be86", + "metadata": { + "mystnb": { + "figure": { + "caption": "Monthly inflation rate (Germany)", + "name": "inflationrate_germany" + } + } + }, + "outputs": [], + "source": [ + "# Plot moving average\n", + "fig, ax = plt.subplots(dpi=200)\n", + "_ = pr_plot(p_seq, df_deu.index, ax)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "a83dfdcf", + "metadata": {}, + "source": [ + "## Starting and stopping big inflations\n", + "\n", + "It is striking how *quickly* (log) price levels in Austria, Hungary, Poland, and Germany leveled off after rising so quickly.\n", + "\n", + "These \"sudden stops\" are also revealed by the permanent drops in three-month moving averages of inflation for the four countries plotted above.\n", + "\n", + "In addition, the US dollar exchange rates for each of the four countries shadowed their price levels. \n", + "\n", + "```{note}\n", + "This pattern is an instance of a force featured in the [purchasing power parity](https://en.wikipedia.org/wiki/Purchasing_power_parity) theory of exchange rates. \n", + "```\n", + "\n", + "Each of these big inflations seemed to have \"stopped on a dime\".\n", + "\n", + "Chapter 3 of {cite}`sargent2002big` offers an explanation for this remarkable pattern.\n", + "\n", + "In a nutshell, here is the explanation offered there.\n", + "\n", + "After World War I, the United States was on a gold standard. \n", + "\n", + "The US government stood ready to convert a dollar into a specified amount of gold on demand.\n", + "\n", + "Immediately after World War I, Hungary, Austria, Poland, and Germany were not on the gold standard. \n", + "\n", + "Their currencies were \"fiat\" or \"unbacked\", meaning that they were not backed by credible government promises to convert them into gold or silver coins on demand.\n", + "\n", + "The governments printed new paper notes to pay for goods and services. \n", + "\n", + "```{note}\n", + "Technically the notes were \"backed\" mainly by treasury bills. But people could not expect that those treasury bills would be paid off by levying taxes, but instead by printing more notes or treasury bills.\n", + "```\n", + "\n", + "This was done on such a scale that it led to a depreciation of the currencies of spectacular proportions. \n", + " \n", + "In the end, the German mark stabilized at 1 trillion ($10^{12}$) paper marks to the prewar gold mark, the Polish mark at 1.8 million paper marks to the gold zloty, the Austrian crown at 14,400 paper crowns to the prewar Austro-Hungarian crown, and the Hungarian krone at 14,500 paper crowns to the prewar Austro-Hungarian crown.\n", + "\n", + "Chapter 3 of {cite}`sargent2002big` described deliberate changes in policy that Hungary, Austria, Poland, and Germany made to end their hyperinflations.\n", + "\n", + "Each government stopped printing money to pay for goods and services once again and made its currency convertible to the US dollar or the UK pound.\n", + "\n", + "The story told in {cite}`sargent2002big` is grounded in a *monetarist theory of the price level* described in {doc}`cagan_ree` and {doc}`cagan_adaptive`.\n", + "\n", + "Those lectures discuss theories about what owners of those rapidly depreciating currencies were thinking and how their beliefs shaped responses of inflation to government monetary and fiscal policies." + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.16.1" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 22, + 26, + 30, + 38, + 42, + 47, + 84, + 92, + 98, + 122, + 174, + 195, + 232, + 289, + 294, + 352, + 356, + 390, + 412, + 432, + 444, + 460, + 480, + 492, + 506, + 538, + 549, + 561, + 570, + 591, + 618, + 630 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/inflation_history.md b/book/_build/html/_sources/inflation_history.md new file mode 100644 index 0000000..1be6655 --- /dev/null +++ b/book/_build/html/_sources/inflation_history.md @@ -0,0 +1,674 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.16.1 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Price Level Histories + +This lecture offers some historical evidence about fluctuations in levels of aggregate price indexes. + +Let's start by installing the necessary Python packages. + +The `xlrd` package is used by `pandas` to perform operations on Excel files. + +```{code-cell} ipython3 +:tags: [hide-output] + +%pip install xlrd +``` + + + +```{code-cell} ipython3 +:tags: [hide-cell] + +from importlib.metadata import version +from packaging.version import Version + +if Version(version("pandas")) < Version('2.1.4'): + %pip install "pandas>=2.1.4" +``` + +We can then import the Python modules we will use. + +```{code-cell} ipython3 +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +import matplotlib.dates as mdates +``` + +The rate of growth of the price level is called **inflation** in the popular press and in discussions among central bankers and treasury officials. + +The price level is measured in units of domestic currency per units of a representative bundle of consumption goods. + +Thus, in the US, the price level at $t$ is measured in dollars (month $t$ or year $t$) per unit of the consumption bundle. + +Until the early 20th century, in many western economies, price levels fluctuated from year to year but didn't have much of a trend. + +Often the price levels ended a century near where they started. + +Things were different in the 20th century, as we shall see in this lecture. + +A widely believed explanation of this big difference is that countries' abandoning gold and silver standards in the early twentieth century. + +```{tip} +This lecture sets the stage for some subsequent lectures about a theory that macro economists use to think about determinants of the price level, namely, {doc}`cagan_ree` and {doc}`cagan_adaptive` +``` + +## Four centuries of price levels + +We begin by displaying data that originally appeared on page 35 of {cite}`sargent2002big` that show price levels for four "hard currency" countries from 1600 to 1914. + +* France +* Spain (Castile) +* United Kingdom +* United States + +In the present context, the phrase "hard currency" means that the countries were on a commodity-money standard: money consisted of gold and silver coins that circulated at values largely determined by the weights of their gold and silver contents. + +```{note} +Under a gold or silver standard, some money also consisted of "warehouse certificates" that represented paper claims on gold or silver coins. Bank notes issued by the government or private banks can be viewed as examples of such "warehouse certificates". +``` + +Let us bring the data into pandas from a spreadsheet that is [hosted on github](https://github.com/QuantEcon/lecture-python-intro/tree/main/lectures/datasets). + +```{code-cell} ipython3 +# Import data and clean up the index +data_url = "https://github.com/QuantEcon/lecture-python-intro/raw/main/lectures/datasets/longprices.xls" +df_fig5 = pd.read_excel(data_url, + sheet_name='all', + header=2, + index_col=0).iloc[1:] +df_fig5.index = df_fig5.index.astype(int) +``` + +We first plot price levels over the period 1600-1914. + +During most years in this time interval, the countries were on a gold or silver standard. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Long run time series of the price level + name: lrpl +--- +df_fig5_befe1914 = df_fig5[df_fig5.index <= 1914] + +# Create plot +cols = ['UK', 'US', 'France', 'Castile'] + +fig, ax = plt.subplots(figsize=(10,6)) + +for col in cols: + ax.plot(df_fig5_befe1914.index, + df_fig5_befe1914[col], label=col, lw=2) + +ax.legend() +ax.set_ylabel('Index 1913 = 100') +ax.set_xlabel('Year') +ax.set_xlim(xmin=1600) +plt.tight_layout() +plt.show() +``` + +We say "most years" because there were temporary lapses from the gold or silver standard. + +By staring at {numref}`lrpl` carefully, you might be able to guess when these temporary lapses occurred, because they were also times during which price levels temporarily rose markedly: + +* 1791-1797 in France (French Revolution) +* 1776-1790 in the US (War for Independence from Great Britain) +* 1861-1865 in the US (Civil War) + +During these episodes, the gold/silver standard was temporarily abandoned when a government printed paper money to pay for war expenditures. + +```{note} +This quantecon lecture {doc}`french_rev` describes circumstances leading up to and during the big inflation that occurred during the French Revolution. +``` + +Despite these temporary lapses, a striking thing about the figure is that price levels were roughly constant over three centuries. + +In the early century, two other features of this data attracted the attention of [Irving Fisher](https://en.wikipedia.org/wiki/Irving_Fisher) of Yale University and [John Maynard Keynes](https://en.wikipedia.org/wiki/John_Maynard_Keynes) of Cambridge University. + +* Despite being anchored to the same average level over long time spans, there were considerable year-to-year variations in price levels +* While using valuable gold and silver as coins succeeded in anchoring the price level by limiting the supply of money, it cost real resources. +* a country paid a high "opportunity cost" for using gold and silver coins as money -- that gold and silver could instead have been made into valuable jewelry and other durable goods. + +Keynes and Fisher proposed what they claimed would be a more efficient way to achieve a price level that + +* would be at least as firmly anchored as achieved under a gold or silver standard, and +* would also exhibit less year-to-year short-term fluctuations. + +They said that central bank could achieve price level stability by + +* issuing **limited supplies** of paper currency +* refusing to print money to finance government expenditures + +This logic prompted John Maynard Keynes to call a commodity standard a "barbarous relic." + +A paper currency or "fiat money" system disposes of all reserves behind a currency. + +But adhering to a gold or silver standard had provided an automatic mechanism for limiting the supply of money, thereby anchoring the price level. + +To anchor the price level, a pure paper or fiat money system replaces that automatic mechanism with a central bank with the authority and determination to limit the supply of money (and to deter counterfeiters!) + +Now let's see what happened to the price level in the four countries after 1914, when one after another of them left the gold/silver standard by showing the complete graph that originally appeared on page 35 of {cite}`sargent2002big`. + +{numref}`lrpl_lg` shows the logarithm of price levels over four "hard currency" countries from 1600 to 2000. + +```{note} +Although we didn't have to use logarithms in our earlier graphs that had stopped in 1914, we now choose to use logarithms because we want to fit observations after 1914 in the same graph as the earlier observations. +``` + +After the outbreak of the Great War in 1914, the four countries left the gold standard and in so doing acquired the ability to print money to finance government expenditures. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Long run time series of the price level (log) + name: lrpl_lg +--- +fig, ax = plt.subplots(dpi=200) + +for col in cols: + ax.plot(df_fig5.index, df_fig5[col], lw=2) + ax.text(x=df_fig5.index[-1]+2, + y=df_fig5[col].iloc[-1], s=col) + +ax.set_yscale('log') +ax.set_ylabel('Logs of price levels (Index 1913 = 100)') +ax.set_ylim([10, 1e6]) +ax.set_xlabel('year') +ax.set_xlim(xmin=1600) +plt.tight_layout() +plt.show() +``` + +{numref}`lrpl_lg` shows that paper-money-printing central banks didn't do as well as the gold and standard silver standard in anchoring price levels. + +That would probably have surprised or disappointed Irving Fisher and John Maynard Keynes. + +Actually, earlier economists and statesmen knew about the possibility of fiat money systems long before Keynes and Fisher advocated them in the early 20th century. + +Proponents of a commodity money system did not trust governments and central banks properly to manage a fiat money system. + +They were willing to pay the resource costs associated with setting up and maintaining a commodity money system. + +In light of the high and persistent inflation that many countries experienced after they abandoned commodity monies in the twentieth century, we hesitate to criticize advocates of a gold or silver standard for their preference to stay on the pre-1914 gold/silver standard. + +The breadth and lengths of the inflationary experiences of the twentieth century under paper money fiat standards are historically unprecedented. + +## Four big inflations + +In the wake of World War I, which ended in November 1918, monetary and fiscal authorities struggled to achieve price level stability without being on a gold or silver standard. + +We present four graphs from "The Ends of Four Big Inflations" from chapter 3 of {cite}`sargent2013rational`. + +The graphs depict logarithms of price levels during the early post World War I years for four countries: + +* Figure 3.1, Retail prices Austria, 1921-1924 (page 42) +* Figure 3.2, Wholesale prices Hungary, 1921-1924 (page 43) +* Figure 3.3, Wholesale prices, Poland, 1921-1924 (page 44) +* Figure 3.4, Wholesale prices, Germany, 1919-1924 (page 45) + +We have added logarithms of the exchange rates vis-à-vis the US dollar to each of the four graphs +from chapter 3 of {cite}`sargent2013rational`. + +Data underlying our graphs appear in tables in an appendix to chapter 3 of {cite}`sargent2013rational`. +We have transcribed all of these data into a spreadsheet {download}`chapter_3.xlsx ` that we read into pandas. + +In the code cell below we clean the data and build a `pandas.dataframe`. + +```{code-cell} ipython3 +:tags: [hide-input] + +def process_entry(entry): + "Clean each entry of a dataframe." + + if type(entry) == str: + # Remove leading and trailing whitespace + entry = entry.strip() + # Remove comma + entry = entry.replace(',', '') + + # Remove HTML markers + item_to_remove = ['a', 'c', + 'd', 'e'] + + # b represents a billion + if 'b' in entry: + entry = entry.replace('b', '') + entry = float(entry) * 1e9 + else: + for item in item_to_remove: + if item in entry: + entry = entry.replace(item, '') + return entry + +def process_df(df): + "Clean and reorganize the entire dataframe." + + # Remove HTML markers from column names + for item in ['a', 'c', 'd', 'e']: + df.columns = df.columns.str.replace(item, '') + + # Convert years to int + df['Year'] = df['Year'].apply(lambda x: int(x)) + + # Set index to datetime with year and month + df = df.set_index( + pd.to_datetime( + (df['Year'].astype(str) + \ + df['Month'].astype(str)), + format='%Y%B')) + df = df.drop(['Year', 'Month'], axis=1) + + # Handle duplicates by keeping the first + df = df[~df.index.duplicated(keep='first')] + + # Convert attribute values to numeric + df = df.map(lambda x: float(x) \ + if x != '—' else np.nan) + + # Finally, we only focus on data between 1919 and 1925 + mask = (df.index >= '1919-01-01') & \ + (df.index < '1925-01-01') + df = df.loc[mask] + + return df +``` + +Now we write plotting functions `pe_plot` and `pr_plot` that will build figures that show the price level, exchange rates, +and inflation rates, for each country of interest. + +```{code-cell} ipython3 +:tags: [hide-input] + +def pe_plot(p_seq, e_seq, index, labs, ax): + "Generate plots for price and exchange rates." + + p_lab, e_lab = labs + + # Plot price and exchange rates + ax.plot(index, p_seq, label=p_lab, color='tab:blue', lw=2) + + # Add a new axis + ax1 = ax.twinx() + ax1.plot([None], [None], label=p_lab, color='tab:blue', lw=2) + ax1.plot(index, e_seq, label=e_lab, color='tab:orange', lw=2) + + # Set log axes + ax.set_yscale('log') + ax1.set_yscale('log') + + # Define the axis label format + ax.xaxis.set_major_locator( + mdates.MonthLocator(interval=5)) + ax.xaxis.set_major_formatter( + mdates.DateFormatter('%b %Y')) + for label in ax.get_xticklabels(): + label.set_rotation(45) + + # Set labels + ax.set_ylabel('Price level') + ax1.set_ylabel('Exchange rate') + + ax1.legend(loc='upper left') + + return ax1 + +def pr_plot(p_seq, index, ax): + "Generate plots for inflation rates." + + # Calculate the difference of log p_seq + log_diff_p = np.diff(np.log(p_seq)) + + # Calculate and plot moving average + diff_smooth = pd.DataFrame(log_diff_p).rolling(3, center=True).mean() + ax.plot(index[1:], diff_smooth, label='Moving average (3 period)', alpha=0.5, lw=2) + ax.set_ylabel('Inflation rate') + + ax.xaxis.set_major_locator( + mdates.MonthLocator(interval=5)) + ax.xaxis.set_major_formatter( + mdates.DateFormatter('%b %Y')) + + for label in ax.get_xticklabels(): + label.set_rotation(45) + + ax.legend() + + return ax +``` + +We prepare the data for each country + +```{code-cell} ipython3 +# Import data +data_url = "https://github.com/QuantEcon/lecture-python-intro/raw/main/lectures/datasets/chapter_3.xlsx" +xls = pd.ExcelFile(data_url) + +# Select relevant sheets +sheet_index = [(2, 3, 4), + (9, 10), + (14, 15, 16), + (21, 18, 19)] + +# Remove redundant rows +remove_row = [(-2, -2, -2), + (-7, -10), + (-6, -4, -3), + (-19, -3, -6)] + +# Unpack and combine series for each country +df_list = [] + +for i in range(4): + + indices, rows = sheet_index[i], remove_row[i] + + # Apply process_entry on the selected sheet + sheet_list = [ + pd.read_excel(xls, 'Table3.' + str(ind), + header=1).iloc[:row].map(process_entry) + for ind, row in zip(indices, rows)] + + sheet_list = [process_df(df) for df in sheet_list] + df_list.append(pd.concat(sheet_list, axis=1)) + +df_aus, df_hun, df_pol, df_deu = df_list +``` + +Now let's construct graphs for our four countries. + +For each country, we'll plot two graphs. + +The first graph plots logarithms of + +* price levels +* exchange rates vis-à-vis US dollars + +For each country, the scale on the right side of a graph will pertain to the price level while the scale on the left side of a graph will pertain to the exchange rate. + +For each country, the second graph plots a centered three-month moving average of the inflation rate defined as $\frac{p_{t-1} + p_t + p_{t+1}}{3}$. + +### Austria + +The sources of our data are: + +* Table 3.3, retail price level $\exp p$ +* Table 3.4, exchange rate with US + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Price index and exchange rate (Austria) + name: pi_xrate_austria +--- +p_seq = df_aus['Retail price index, 52 commodities'] +e_seq = df_aus['Exchange Rate'] + +lab = ['Retail price index', + 'Austrian Krones (Crowns) per US cent'] + +# Create plot +fig, ax = plt.subplots(dpi=200) +_ = pe_plot(p_seq, e_seq, df_aus.index, lab, ax) + +plt.show() +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Monthly inflation rate (Austria) + name: inflationrate_austria +--- +# Plot moving average +fig, ax = plt.subplots(dpi=200) +_ = pr_plot(p_seq, df_aus.index, ax) + +plt.show() +``` + +Staring at {numref}`pi_xrate_austria` and {numref}`inflationrate_austria` conveys the following impressions to the authors of this lecture at QuantEcon. + +* an episode of "hyperinflation" with rapidly rising log price level and very high monthly inflation rates +* a sudden stop of the hyperinflation as indicated by the abrupt flattening of the log price level and a marked permanent drop in the three-month average of inflation +* a US dollar exchange rate that shadows the price level. + +We'll see similar patterns in the next three episodes that we'll study now. + +### Hungary + +The source of our data for Hungary is: + +* Table 3.10, price level $\exp p$ and exchange rate + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Price index and exchange rate (Hungary) + name: pi_xrate_hungary +--- +p_seq = df_hun['Hungarian index of prices'] +e_seq = 1 / df_hun['Cents per crown in New York'] + +lab = ['Hungarian index of prices', + 'Hungarian Koronas (Crowns) per US cent'] + +# Create plot +fig, ax = plt.subplots(dpi=200) +_ = pe_plot(p_seq, e_seq, df_hun.index, lab, ax) + +plt.show() +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Monthly inflation rate (Hungary) + name: inflationrate_hungary +--- +# Plot moving average +fig, ax = plt.subplots(dpi=200) +_ = pr_plot(p_seq, df_hun.index, ax) + +plt.show() +``` + +### Poland + +The sources of our data for Poland are: + +* Table 3.15, price level $\exp p$ +* Table 3.15, exchange rate + +```{note} +To construct the price level series from the data in the spreadsheet, we instructed Pandas to follow the same procedures implemented in chapter 3 of {cite}`sargent2013rational`. We spliced together three series - Wholesale price index, Wholesale Price Index: On paper currency basis, and Wholesale Price Index: On zloty basis. We adjusted the sequence based on the price level ratio at the last period of the available previous series and glued them to construct a single series. +We dropped the exchange rate after June 1924, when the zloty was adopted. We did this because we don't have the price measured in zloty. We used the old currency in June to compute the exchange rate adjustment. +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Price index and exchange rate (Poland) + name: pi_xrate_poland +--- +# Splice three price series in different units +p_seq1 = df_pol['Wholesale price index'].copy() +p_seq2 = df_pol['Wholesale Price Index: ' + 'On paper currency basis'].copy() +p_seq3 = df_pol['Wholesale Price Index: ' + 'On zloty basis'].copy() + +# Non-nan part +mask_1 = p_seq1[~p_seq1.isna()].index[-1] +mask_2 = p_seq2[~p_seq2.isna()].index[-2] + +adj_ratio12 = (p_seq1[mask_1] / p_seq2[mask_1]) +adj_ratio23 = (p_seq2[mask_2] / p_seq3[mask_2]) + +# Glue three series +p_seq = pd.concat([p_seq1[:mask_1], + adj_ratio12 * p_seq2[mask_1:mask_2], + adj_ratio23 * p_seq3[mask_2:]]) +p_seq = p_seq[~p_seq.index.duplicated(keep='first')] + +# Exchange rate +e_seq = 1/df_pol['Cents per Polish mark (zloty after May 1924)'] +e_seq[e_seq.index > '05-01-1924'] = np.nan +``` + +```{code-cell} ipython3 +lab = ['Wholesale price index', + 'Polish marks per US cent'] + +# Create plot +fig, ax = plt.subplots(dpi=200) +ax1 = pe_plot(p_seq, e_seq, df_pol.index, lab, ax) + +plt.show() +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Monthly inflation rate (Poland) + name: inflationrate_poland +--- +# Plot moving average +fig, ax = plt.subplots(dpi=200) +_ = pr_plot(p_seq, df_pol.index, ax) + +plt.show() +``` + +### Germany + +The sources of our data for Germany are the following tables from chapter 3 of {cite}`sargent2013rational`: + +* Table 3.18, wholesale price level $\exp p$ +* Table 3.19, exchange rate + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Price index and exchange rate (Germany) + name: pi_xrate_germany +--- +p_seq = df_deu['Price index (on basis of marks before July 1924,' + ' reichsmarks after)'].copy() +e_seq = 1/df_deu['Cents per mark'] + +lab = ['Price index', + 'Marks per US cent'] + +# Create plot +fig, ax = plt.subplots(dpi=200) +ax1 = pe_plot(p_seq, e_seq, df_deu.index, lab, ax) + +plt.show() +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Price index (adjusted) and exchange rate (Germany) + name: piadj_xrate_germany +--- +p_seq = df_deu['Price index (on basis of marks before July 1924,' + ' reichsmarks after)'].copy() +e_seq = 1/df_deu['Cents per mark'].copy() + +# Adjust the price level/exchange rate after the currency reform +p_seq[p_seq.index > '06-01-1924'] = p_seq[p_seq.index + > '06-01-1924'] * 1e12 +e_seq[e_seq.index > '12-01-1923'] = e_seq[e_seq.index + > '12-01-1923'] * 1e12 + +lab = ['Price index (marks or converted to marks)', + 'Marks per US cent(or reichsmark converted to mark)'] + +# Create plot +fig, ax = plt.subplots(dpi=200) +ax1 = pe_plot(p_seq, e_seq, df_deu.index, lab, ax) + +plt.show() +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Monthly inflation rate (Germany) + name: inflationrate_germany +--- +# Plot moving average +fig, ax = plt.subplots(dpi=200) +_ = pr_plot(p_seq, df_deu.index, ax) + +plt.show() +``` + +## Starting and stopping big inflations + +It is striking how *quickly* (log) price levels in Austria, Hungary, Poland, and Germany leveled off after rising so quickly. + +These "sudden stops" are also revealed by the permanent drops in three-month moving averages of inflation for the four countries plotted above. + +In addition, the US dollar exchange rates for each of the four countries shadowed their price levels. + +```{note} +This pattern is an instance of a force featured in the [purchasing power parity](https://en.wikipedia.org/wiki/Purchasing_power_parity) theory of exchange rates. +``` + +Each of these big inflations seemed to have "stopped on a dime". + +Chapter 3 of {cite}`sargent2002big` offers an explanation for this remarkable pattern. + +In a nutshell, here is the explanation offered there. + +After World War I, the United States was on a gold standard. + +The US government stood ready to convert a dollar into a specified amount of gold on demand. + +Immediately after World War I, Hungary, Austria, Poland, and Germany were not on the gold standard. + +Their currencies were "fiat" or "unbacked", meaning that they were not backed by credible government promises to convert them into gold or silver coins on demand. + +The governments printed new paper notes to pay for goods and services. + +```{note} +Technically the notes were "backed" mainly by treasury bills. But people could not expect that those treasury bills would be paid off by levying taxes, but instead by printing more notes or treasury bills. +``` + +This was done on such a scale that it led to a depreciation of the currencies of spectacular proportions. + +In the end, the German mark stabilized at 1 trillion ($10^{12}$) paper marks to the prewar gold mark, the Polish mark at 1.8 million paper marks to the gold zloty, the Austrian crown at 14,400 paper crowns to the prewar Austro-Hungarian crown, and the Hungarian krone at 14,500 paper crowns to the prewar Austro-Hungarian crown. + +Chapter 3 of {cite}`sargent2002big` described deliberate changes in policy that Hungary, Austria, Poland, and Germany made to end their hyperinflations. + +Each government stopped printing money to pay for goods and services once again and made its currency convertible to the US dollar or the UK pound. + +The story told in {cite}`sargent2002big` is grounded in a *monetarist theory of the price level* described in {doc}`cagan_ree` and {doc}`cagan_adaptive`. + +Those lectures discuss theories about what owners of those rapidly depreciating currencies were thinking and how their beliefs shaped responses of inflation to government monetary and fiscal policies. diff --git a/book/_build/html/_sources/input_output.ipynb b/book/_build/html/_sources/input_output.ipynb new file mode 100644 index 0000000..acdd240 --- /dev/null +++ b/book/_build/html/_sources/input_output.ipynb @@ -0,0 +1,950 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "00b8bb7f", + "metadata": {}, + "source": [ + "# Input-Output Models\n", + "\n", + "## Overview\n", + "\n", + "This lecture requires the following imports and installs before we proceed." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2afe9608", + "metadata": { + "tags": [ + "hide-output" + ] + }, + "outputs": [], + "source": [ + "%pip install quantecon_book_networks\n", + "%pip install quantecon\n", + "%pip install pandas-datareader" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "18203204", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import networkx as nx\n", + "import matplotlib.pyplot as plt\n", + "import quantecon_book_networks\n", + "import quantecon_book_networks.input_output as qbn_io\n", + "import quantecon_book_networks.plotting as qbn_plt\n", + "import quantecon_book_networks.data as qbn_data\n", + "import matplotlib as mpl\n", + "from matplotlib.patches import Polygon\n", + "\n", + "quantecon_book_networks.config(\"matplotlib\")\n", + "mpl.rcParams.update(mpl.rcParamsDefault)" + ] + }, + { + "cell_type": "markdown", + "id": "303ba736", + "metadata": {}, + "source": [ + "The following figure illustrates a network of linkages among 15 sectors\n", + "obtained from the US Bureau of Economic Analysis’s 2021 Input-Output Accounts\n", + "Data." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "303365c0", + "metadata": { + "tags": [ + "hide-cell" + ] + }, + "outputs": [], + "source": [ + "def build_coefficient_matrices(Z, X):\n", + " \"\"\"\n", + " Build coefficient matrices A and F from Z and X via\n", + "\n", + " A[i, j] = Z[i, j] / X[j]\n", + " F[i, j] = Z[i, j] / X[i]\n", + "\n", + " \"\"\"\n", + " A, F = np.empty_like(Z), np.empty_like(Z)\n", + " n = A.shape[0]\n", + " for i in range(n):\n", + " for j in range(n):\n", + " A[i, j] = Z[i, j] / X[j]\n", + " F[i, j] = Z[i, j] / X[i]\n", + "\n", + " return A, F\n", + "\n", + "ch2_data = qbn_data.production()\n", + "codes = ch2_data[\"us_sectors_15\"][\"codes\"]\n", + "Z = ch2_data[\"us_sectors_15\"][\"adjacency_matrix\"]\n", + "X = ch2_data[\"us_sectors_15\"][\"total_industry_sales\"]\n", + "A, F = build_coefficient_matrices(Z, X)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d3534d29", + "metadata": { + "mystnb": { + "figure": { + "caption": "US 15 sector production network", + "name": "us_15sectors" + } + }, + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "centrality = qbn_io.eigenvector_centrality(A)\n", + "\n", + "# Remove self-loops\n", + "for i in range(A.shape[0]):\n", + " A[i][i] = 0\n", + "\n", + "fig, ax = plt.subplots(figsize=(8, 10))\n", + "plt.axis(\"off\")\n", + "color_list = qbn_io.colorise_weights(centrality,beta=False)\n", + "\n", + "qbn_plt.plot_graph(A, X, ax, codes,\n", + " layout_type='spring',\n", + " layout_seed=5432167,\n", + " tol=0.0,\n", + " node_color_list=color_list)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "779c48f1", + "metadata": {}, + "source": [ + "|Label| Sector |Label| Sector |Label| Sector |\n", + "|:---:|:-------------:|:---:|:--------------:|:---:|:-------------------------:|\n", + "| ag | Agriculture | wh | Wholesale | pr | Professional Services |\n", + "| mi | Mining | re | Retail | ed | Education & Health |\n", + "| ut | Utilities | tr | Transportation | ar | Arts & Entertainment |\n", + "| co | Construction | in | Information | ot | Other Services (exc govt) |\n", + "| ma | Manufacturing | fi | Finance | go | Government |\n", + "\n", + "\n", + "An arrow from $i$ to $j$ means that some of sector $i$'s output serves as an input to production of sector $j$.\n", + "\n", + "Economies are characterised by many such links.\n", + "\n", + "A basic framework for their analysis is\n", + "[Leontief's](https://en.wikipedia.org/wiki/Wassily_Leontief) input-output model.\n", + "\n", + "\n", + "\n", + "After introducing the input-output model, we describe some of its connections to {doc}`linear programming lecture `.\n", + "\n", + "\n", + "## Input-output analysis\n", + "\n", + "Let\n", + "\n", + " * $x_0$ be the amount of a single exogenous input to production, say labor\n", + " * $x_j, j = 1,\\ldots n$ be the gross output of final good $j$\n", + " * $d_j, j = 1,\\ldots n$ be the net output of final good $j$ that is available for final consumption\n", + " * $z_{ij} $ be the quantity of good $i$ allocated to be an input to producing good $j$ for $i=1, \\ldots n$, $j = 1, \\ldots n$\n", + " * $z_{0j}$ be the quantity of labor allocated to producing good $j$.\n", + " * $a_{ij}$ be the number of units of good $i$ required to produce one unit of good $j$, $i=0, \\ldots, n, j= 1, \\ldots n$.\n", + " * $w >0$ be an exogenous wage of labor, denominated in dollars per unit of labor\n", + " * $p$ be an $n \\times 1$ vector of prices of produced goods $i = 1, \\ldots , n$.\n", + "\n", + "\n", + "\n", + "The technology for producing good $j \\in \\{1, \\ldots , n\\}$ is described by the **Leontief** function\n", + "\n", + "$$\n", + " x_j = \\min_{i \\in \\{0, \\ldots , n \\}} \\left( \\frac{z_{ij}}{a_{ij}}\\right)\n", + "$$\n", + "\n", + "### Two goods\n", + "\n", + "To illustrate, we begin by setting $n =2$ and formulating\n", + "the following network." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dc5fcab3", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "G = nx.DiGraph()\n", + "\n", + "nodes= (1, 2, 'c')\n", + "edges = ((1, 1), (1, 2), (2, 1), (2, 2), (1, 'c'), (2, 'c'))\n", + "edges1 = ((1, 1), (1, 2), (2, 1), (2, 2), (1, 'c'))\n", + "edges2 = [(2,'c')]\n", + "G.add_nodes_from(nodes)\n", + "G.add_edges_from(edges)\n", + "\n", + "pos_list = ([0, 0], [2, 0], [1, -1])\n", + "pos = dict(zip(G.nodes(), pos_list))\n", + "\n", + "fig, ax = plt.subplots()\n", + "plt.axis(\"off\")\n", + "\n", + "nx.draw_networkx_nodes(G, pos=pos, node_size=800,\n", + " node_color='white', edgecolors='black')\n", + "nx.draw_networkx_labels(G, pos=pos)\n", + "nx.draw_networkx_edges(G,pos=pos, edgelist=edges1,\n", + " node_size=300, connectionstyle='arc3,rad=0.2',\n", + " arrowsize=10, min_target_margin=15)\n", + "nx.draw_networkx_edges(G, pos=pos, edgelist=edges2,\n", + " node_size=300, connectionstyle='arc3,rad=-0.2',\n", + " arrowsize=10, min_target_margin=15)\n", + "\n", + "plt.text(0.055, 0.125, r'$z_{11}$')\n", + "plt.text(1.825, 0.125, r'$z_{22}$')\n", + "plt.text(0.955, 0.1, r'$z_{21}$')\n", + "plt.text(0.955, -0.125, r'$z_{12}$')\n", + "plt.text(0.325, -0.5, r'$d_{1}$')\n", + "plt.text(1.6, -0.5, r'$d_{2}$')\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "d5dbbeca", + "metadata": {}, + "source": [ + "*Feasible allocations must satisfy*\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "(1 - a_{11}) x_1 - a_{12} x_2 & \\geq d_1 \\cr\n", + "-a_{21} x_1 + (1 - a_{22}) x_2 & \\geq d_2 \\cr\n", + "a_{01} x_1 + a_{02} x_2 & \\leq x_0\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "This can be graphically represented as follows." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5231fc7c", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "ax.grid()\n", + "\n", + "# Draw constraint lines\n", + "ax.hlines(0, -1, 400)\n", + "ax.vlines(0, -1, 200)\n", + "\n", + "ax.plot(np.linspace(55, 380, 100), (50-0.9*np.linspace(55, 380, 100))/(-1.46), color=\"r\")\n", + "ax.plot(np.linspace(-1, 400, 100), (60+0.16*np.linspace(-1, 400, 100))/0.83, color=\"r\")\n", + "ax.plot(np.linspace(250, 395, 100), (62-0.04*np.linspace(250, 395, 100))/0.33, color=\"b\")\n", + "\n", + "ax.text(130, 38, \"$(1-a_{11})x_1 + a_{12}x_2 \\geq d_1$\", size=10)\n", + "ax.text(10, 105, \"$-a_{21}x_1 + (1-a_{22})x_2 \\geq d_2$\", size=10)\n", + "ax.text(150, 150, \"$a_{01}x_1 +a_{02}x_2 \\leq x_0$\", size=10)\n", + "\n", + "# Draw the feasible region\n", + "feasible_set = Polygon(np.array([[301, 151],\n", + " [368, 143],\n", + " [250, 120]]),\n", + " color=\"cyan\")\n", + "ax.add_patch(feasible_set)\n", + "\n", + "# Draw the optimal solution\n", + "ax.plot(250, 120, \"*\", color=\"black\")\n", + "ax.text(260, 115, \"solution\", size=10)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "e8d71912", + "metadata": { + "user_expressions": [] + }, + "source": [ + "More generally, constraints on production are\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "(I - A) x & \\geq d \\cr\n", + "a_0^\\top x & \\leq x_0\n", + "\\end{aligned}\n", + "$$ (eq:inout_1)\n", + "\n", + "where $A$ is the $n \\times n$ matrix with typical element $a_{ij}$ and $a_0^\\top = \\begin{bmatrix} a_{01} & \\cdots & a_{0n} \\end{bmatrix}$.\n", + "\n", + "\n", + "\n", + "If we solve the first block of equations of {eq}`eq:inout_1` for gross output $x$ we get\n", + "\n", + "$$\n", + "x = (I -A)^{-1} d \\equiv L d\n", + "$$ (eq:inout_2)\n", + "\n", + "where the matrix $L = (I-A)^{-1}$ is sometimes called a **Leontief Inverse**.\n", + "\n", + "\n", + "\n", + "To assure that the solution $X$ of {eq}`eq:inout_2` is a positive vector, the following **Hawkins-Simon conditions** suffice:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "\\det (I - A) > 0 \\text{ and} \\;\\;\\; \\\\\n", + "(I-A)_{ij} > 0 \\text{ for all } i=j\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "\n", + "```{prf:example}\n", + ":label: io_ex_tg\n", + "\n", + "For example a two-good economy described by\n", + "\n", + "$$\n", + "A =\n", + "\\begin{bmatrix}\n", + " 0.1 & 40 \\\\\n", + " 0.01 & 0\n", + "\\end{bmatrix}\n", + "\\text{ and }\n", + "d =\n", + "\\begin{bmatrix}\n", + " 50 \\\\\n", + " 2\n", + "\\end{bmatrix}\n", + "$$ (eq:inout_ex)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7d4d2345", + "metadata": {}, + "outputs": [], + "source": [ + "A = np.array([[0.1, 40],\n", + " [0.01, 0]])\n", + "d = np.array([50, 2]).reshape((2, 1))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "09b25681", + "metadata": {}, + "outputs": [], + "source": [ + "I = np.identity(2)\n", + "B = I - A\n", + "B" + ] + }, + { + "cell_type": "markdown", + "id": "6bbb3c48", + "metadata": {}, + "source": [ + "Let's check the **Hawkins-Simon conditions**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "84b25373", + "metadata": {}, + "outputs": [], + "source": [ + "np.linalg.det(B) > 0 # checking Hawkins-Simon conditions" + ] + }, + { + "cell_type": "markdown", + "id": "b4f874f2", + "metadata": {}, + "source": [ + "Now, let's compute the **Leontief inverse** matrix" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d4d9e7d1", + "metadata": {}, + "outputs": [], + "source": [ + "L = np.linalg.inv(B) # obtaining Leontief inverse matrix\n", + "L" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a73670f6", + "metadata": {}, + "outputs": [], + "source": [ + "x = L @ d # solving for gross output\n", + "x" + ] + }, + { + "cell_type": "markdown", + "id": "1704432c", + "metadata": { + "user_expressions": [] + }, + "source": [ + "## Production possibility frontier\n", + "\n", + "The second equation of {eq}`eq:inout_1` can be written\n", + "\n", + "$$\n", + "a_0^\\top x = x_0\n", + "$$\n", + "\n", + "or\n", + "\n", + "$$\n", + "A_0^\\top d = x_0\n", + "$$ (eq:inout_frontier)\n", + "\n", + "where\n", + "\n", + "$$\n", + "A_0^\\top = a_0^\\top (I - A)^{-1}\n", + "$$\n", + "\n", + " For $i \\in \\{1, \\ldots , n\\}$, the $i$th component of $A_0$ is the amount of labor that is required to produce one unit of final output of good $i$.\n", + "\n", + "Equation {eq}`eq:inout_frontier` sweeps out a **production possibility frontier** of final consumption bundles $d$ that can be produced with exogenous labor input $x_0$.\n", + "\n", + "```{prf:example}\n", + ":label: io_ex_ppf\n", + "\n", + "Consider the example in {eq}`eq:inout_ex`.\n", + "\n", + "Suppose we are now given\n", + "\n", + "$$\n", + "a_0^\\top = \\begin{bmatrix}\n", + "4 & 100\n", + "\\end{bmatrix}\n", + "$$\n", + "```\n", + "\n", + "Then we can find $A_0^\\top$ by" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "175e6808", + "metadata": {}, + "outputs": [], + "source": [ + "a0 = np.array([4, 100])\n", + "A0 = a0 @ L\n", + "A0" + ] + }, + { + "cell_type": "markdown", + "id": "56d5f5ce", + "metadata": { + "user_expressions": [] + }, + "source": [ + "Thus, the production possibility frontier for this economy is\n", + "\n", + "$$\n", + "10d_1 + 500d_2 = x_0\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "a8db3211", + "metadata": { + "user_expressions": [] + }, + "source": [ + "## Prices\n", + "\n", + "{cite}`DoSSo` argue that relative prices of the $n$ produced goods must satisfy\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "p_1 = a_{11}p_1 + a_{21}p_2 + a_{01}w \\\\\n", + "p_2 = a_{12}p_1 + a_{22}p_2 + a_{02}w\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "More generally,\n", + "\n", + "$$\n", + "p = A^\\top p + a_0 w\n", + "$$\n", + "\n", + "which states that the price of each final good equals the total cost\n", + "of production, which consists of costs of intermediate inputs $A^\\top p$\n", + "plus costs of labor $a_0 w$.\n", + "\n", + "This equation can be written as\n", + "\n", + "$$\n", + "(I - A^\\top) p = a_0 w\n", + "$$ (eq:inout_price)\n", + "\n", + "which implies\n", + "\n", + "$$\n", + "p = (I - A^\\top)^{-1} a_0 w\n", + "$$\n", + "\n", + "Notice how {eq}`eq:inout_price` with {eq}`eq:inout_1` forms a\n", + "**conjugate pair** through the appearance of operators\n", + "that are transposes of one another.\n", + "\n", + "This connection surfaces again in a classic linear program and its dual.\n", + "\n", + "\n", + "## Linear programs\n", + "\n", + "A **primal** problem is\n", + "\n", + "$$\n", + "\\min_{x} w a_0^\\top x\n", + "$$\n", + "\n", + "subject to\n", + "\n", + "$$\n", + "(I - A) x \\geq d\n", + "$$\n", + "\n", + "\n", + "The associated **dual** problem is\n", + "\n", + "$$\n", + "\\max_{p} p^\\top d\n", + "$$\n", + "\n", + "subject to\n", + "\n", + "$$\n", + "(I -A)^\\top p \\leq a_0 w\n", + "$$\n", + "\n", + "The primal problem chooses a feasible production plan to minimize costs for delivering a pre-assigned vector of final goods consumption $d$.\n", + "\n", + "The dual problem chooses prices to maximize the value of a pre-assigned vector of final goods $d$ subject to prices covering costs of production.\n", + "\n", + "By the [strong duality theorem](https://en.wikipedia.org/wiki/Dual_linear_program#Strong_duality),\n", + "optimal value of the primal and dual problems coincide:\n", + "\n", + "$$\n", + "w a_0^\\top x^* = p^* d\n", + "$$\n", + "\n", + "where $^*$'s denote optimal choices for the primal and dual problems.\n", + "\n", + "The dual problem can be graphically represented as follows." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1d008392", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "ax.grid()\n", + "\n", + "# Draw constraint lines\n", + "ax.hlines(0, -1, 50)\n", + "ax.vlines(0, -1, 250)\n", + "\n", + "ax.plot(np.linspace(4.75, 49, 100), (4-0.9*np.linspace(4.75, 49, 100))/(-0.16), color=\"r\")\n", + "ax.plot(np.linspace(0, 50, 100), (33+1.46*np.linspace(0, 50, 100))/0.83, color=\"r\")\n", + "\n", + "ax.text(15, 175, \"$(1-a_{11})p_1 - a_{21}p_2 \\leq a_{01}w$\", size=10)\n", + "ax.text(30, 85, \"$-a_{12}p_1 + (1-a_{22})p_2 \\leq a_{02}w$\", size=10)\n", + "\n", + "# Draw the feasible region\n", + "feasible_set = Polygon(np.array([[17, 69],\n", + " [4, 0],\n", + " [0,0],\n", + " [0, 40]]),\n", + " color=\"cyan\")\n", + "ax.add_patch(feasible_set)\n", + "\n", + "# Draw the optimal solution\n", + "ax.plot(17, 69, \"*\", color=\"black\")\n", + "ax.text(18, 60, \"dual solution\", size=10)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "b00ad9d0", + "metadata": { + "user_expressions": [] + }, + "source": [ + "## Leontief inverse\n", + "\n", + "We have discussed that gross output $x$ is given by {eq}`eq:inout_2`, where $L$ is called the Leontief Inverse.\n", + "\n", + "Recall the {doc}`Neumann Series Lemma ` which states that $L$ exists if the spectral radius $r(A)<1$.\n", + "\n", + "In fact\n", + "\n", + "$$\n", + "L = \\sum_{i=0}^{\\infty} A^i\n", + "$$\n", + "\n", + "### Demand shocks\n", + "\n", + "Consider the impact of a demand shock $\\Delta d$ which shifts demand from $d_0$ to $d_1 = d_0 + \\Delta d$.\n", + "\n", + "Gross output shifts from $x_0 = Ld_0$ to $x_1 = Ld_1$.\n", + "\n", + "If $r(A) < 1$ then a solution exists and\n", + "\n", + "$$\n", + "\\Delta x = L \\Delta d = \\Delta d + A(\\Delta d) + A^2 (\\Delta d) + \\cdots\n", + "$$\n", + "\n", + "This illustrates that an element $l_{ij}$ of $L$ shows the total impact on sector $i$ of a unit change in demand of good $j$.\n", + "\n", + "## Applications of graph theory\n", + "\n", + "We can further study input-output networks through applications of {doc}`graph theory `.\n", + "\n", + "An input-output network can be represented by a weighted directed graph induced by the adjacency matrix $A$.\n", + "\n", + "The set of nodes $V = [n]$ is the list of sectors and the set of edges is given by\n", + "\n", + "$$\n", + "E = \\{(i,j) \\in V \\times V : a_{ij}>0\\}\n", + "$$\n", + "\n", + "In {numref}`us_15sectors` weights are indicated by the widths of the arrows, which are proportional to the corresponding input-output coefficients.\n", + "\n", + "We can now use centrality measures to rank sectors and discuss their importance relative to the other sectors.\n", + "\n", + "### Eigenvector centrality\n", + "\n", + "Eigenvector centrality of a node $i$ is measured by\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + " e_i = \\frac{1}{r(A)} \\sum_{1 \\leq j \\leq n} a_{ij} e_j\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "We plot a bar graph of hub-based eigenvector centrality for the sectors represented in {numref}`us_15sectors`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d9122118", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "ax.bar(codes, centrality, color=color_list, alpha=0.6)\n", + "ax.set_ylabel(\"eigenvector centrality\", fontsize=12)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "2df1dc34", + "metadata": {}, + "source": [ + "A higher measure indicates higher importance as a supplier.\n", + "\n", + "As a result demand shocks in most sectors will significantly impact activity in sectors with high eigenvector centrality.\n", + "\n", + "The above figure indicates that manufacturing is the most dominant sector in the US economy.\n", + "\n", + "### Output multipliers\n", + "\n", + "Another way to rank sectors in input-output networks is via output multipliers.\n", + "\n", + "The **output multiplier** of sector $j$ denoted by $\\mu_j$ is usually defined as the\n", + "total sector-wide impact of a unit change of demand in sector $j$.\n", + "\n", + "Earlier when disussing demand shocks we concluded that for $L = (l_{ij})$ the element\n", + "$l_{ij}$ represents the impact on sector $i$ of a unit change in demand in sector $j$.\n", + "\n", + "Thus,\n", + "\n", + "$$\n", + "\\mu_j = \\sum_{j=1}^n l_{ij}\n", + "$$\n", + "\n", + "This can be written as $\\mu^\\top = \\mathbb{1}^\\top L$ or\n", + "\n", + "\n", + "$$\n", + "\\mu^\\top = \\mathbb{1}^\\top (I-A)^{-1}\n", + "$$\n", + "\n", + "Please note that here we use $\\mathbb{1}$ to represent a vector of ones.\n", + "\n", + "High ranking sectors within this measure are important buyers of intermediate goods.\n", + "\n", + "A demand shock in such sectors will cause a large impact on the whole production network.\n", + "\n", + "The following figure displays the output multipliers for the sectors represented\n", + "in {numref}`us_15sectors`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a22ef2d2", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "A, F = build_coefficient_matrices(Z, X)\n", + "omult = qbn_io.katz_centrality(A, authority=True)\n", + "\n", + "fig, ax = plt.subplots()\n", + "omult_color_list = qbn_io.colorise_weights(omult,beta=False)\n", + "ax.bar(codes, omult, color=omult_color_list, alpha=0.6)\n", + "ax.set_ylabel(\"Output multipliers\", fontsize=12)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "f5a790e0", + "metadata": {}, + "source": [ + "We observe that manufacturing and agriculture are highest ranking sectors.\n", + "\n", + "\n", + "## Exercises\n", + "\n", + "```{exercise-start}\n", + ":label: io_ex1\n", + "```\n", + "\n", + "{cite}`DoSSo` Chapter 9 discusses an example with the following\n", + "parameter settings:\n", + "\n", + "$$\n", + "A = \\begin{bmatrix}\n", + " 0.1 & 1.46 \\\\\n", + " 0.16 & 0.17\n", + " \\end{bmatrix}\n", + "\\text{ and }\n", + "a_0 = \\begin{bmatrix} .04 & .33 \\end{bmatrix}\n", + "$$\n", + "\n", + "$$\n", + "x = \\begin{bmatrix} 250 \\\\ 120 \\end{bmatrix}\n", + "\\text{ and }\n", + "x_0 = 50\n", + "$$\n", + "\n", + "$$\n", + "d = \\begin{bmatrix} 50 \\\\ 60 \\end{bmatrix}\n", + "$$\n", + "\n", + "Describe how they infer the input-output coefficients in $A$ and $a_0$ from the following hypothetical underlying \"data\" on agricultural and manufacturing industries:\n", + "\n", + "$$\n", + "z = \\begin{bmatrix} 25 & 175 \\\\\n", + " 40 & 20 \\end{bmatrix}\n", + "\\text{ and }\n", + "z_0 = \\begin{bmatrix} 10 & 40 \\end{bmatrix}\n", + "$$\n", + "\n", + "where $z_0$ is a vector of labor services used in each industry.\n", + "\n", + "```{exercise-end}\n", + "```\n", + "\n", + "```{solution-start} io_ex1\n", + ":class: dropdown\n", + "```\n", + "For each $i = 0,1,2$ and $j = 1,2$\n", + "\n", + "$$\n", + "a_{ij} = \\frac{z_{ij}}{x_j}\n", + "$$\n", + "\n", + "```{solution-end}\n", + "```\n", + "\n", + "```{exercise-start}\n", + ":label: io_ex2\n", + "```\n", + "\n", + "Derive the production possibility frontier for the economy characterized in the previous exercise.\n", + "\n", + "```{exercise-end}\n", + "```\n", + "\n", + "```{solution-start} io_ex2\n", + ":class: dropdown\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d10ac4a7", + "metadata": {}, + "outputs": [], + "source": [ + "A = np.array([[0.1, 1.46],\n", + " [0.16, 0.17]])\n", + "a_0 = np.array([0.04, 0.33])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9488db64", + "metadata": {}, + "outputs": [], + "source": [ + "I = np.identity(2)\n", + "B = I - A\n", + "L = np.linalg.inv(B)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c62626fc", + "metadata": {}, + "outputs": [], + "source": [ + "A_0 = a_0 @ L\n", + "A_0" + ] + }, + { + "cell_type": "markdown", + "id": "a01d4010", + "metadata": { + "user_expressions": [] + }, + "source": [ + "Thus the production possibility frontier is given by\n", + "\n", + "$$\n", + "0.17 d_1 + 0.69 d_2 = 50\n", + "$$\n", + "\n", + "```{solution-end}\n", + "```" + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.5" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 20, + 28, + 41, + 48, + 75, + 100, + 149, + 185, + 199, + 231, + 286, + 292, + 296, + 300, + 302, + 306, + 311, + 316, + 358, + 364, + 372, + 456, + 487, + 543, + 550, + 590, + 601, + 673, + 679, + 685, + 690 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/input_output.md b/book/_build/html/_sources/input_output.md new file mode 100644 index 0000000..e0996c6 --- /dev/null +++ b/book/_build/html/_sources/input_output.md @@ -0,0 +1,699 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.5 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Input-Output Models + +## Overview + +This lecture requires the following imports and installs before we proceed. + +```{code-cell} ipython3 +:tags: [hide-output] + +%pip install quantecon_book_networks +%pip install quantecon +%pip install pandas-datareader +``` + +```{code-cell} ipython3 +import numpy as np +import networkx as nx +import matplotlib.pyplot as plt +import quantecon_book_networks +import quantecon_book_networks.input_output as qbn_io +import quantecon_book_networks.plotting as qbn_plt +import quantecon_book_networks.data as qbn_data +import matplotlib as mpl +from matplotlib.patches import Polygon + +quantecon_book_networks.config("matplotlib") +mpl.rcParams.update(mpl.rcParamsDefault) +``` + +The following figure illustrates a network of linkages among 15 sectors +obtained from the US Bureau of Economic Analysis’s 2021 Input-Output Accounts +Data. + + +```{code-cell} ipython3 +:tags: [hide-cell] + +def build_coefficient_matrices(Z, X): + """ + Build coefficient matrices A and F from Z and X via + + A[i, j] = Z[i, j] / X[j] + F[i, j] = Z[i, j] / X[i] + + """ + A, F = np.empty_like(Z), np.empty_like(Z) + n = A.shape[0] + for i in range(n): + for j in range(n): + A[i, j] = Z[i, j] / X[j] + F[i, j] = Z[i, j] / X[i] + + return A, F + +ch2_data = qbn_data.production() +codes = ch2_data["us_sectors_15"]["codes"] +Z = ch2_data["us_sectors_15"]["adjacency_matrix"] +X = ch2_data["us_sectors_15"]["total_industry_sales"] +A, F = build_coefficient_matrices(Z, X) +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: US 15 sector production network + name: us_15sectors +tags: [hide-input] +--- +centrality = qbn_io.eigenvector_centrality(A) + +# Remove self-loops +for i in range(A.shape[0]): + A[i][i] = 0 + +fig, ax = plt.subplots(figsize=(8, 10)) +plt.axis("off") +color_list = qbn_io.colorise_weights(centrality,beta=False) + +qbn_plt.plot_graph(A, X, ax, codes, + layout_type='spring', + layout_seed=5432167, + tol=0.0, + node_color_list=color_list) + +plt.show() +``` + +|Label| Sector |Label| Sector |Label| Sector | +|:---:|:-------------:|:---:|:--------------:|:---:|:-------------------------:| +| ag | Agriculture | wh | Wholesale | pr | Professional Services | +| mi | Mining | re | Retail | ed | Education & Health | +| ut | Utilities | tr | Transportation | ar | Arts & Entertainment | +| co | Construction | in | Information | ot | Other Services (exc govt) | +| ma | Manufacturing | fi | Finance | go | Government | + + +An arrow from $i$ to $j$ means that some of sector $i$'s output serves as an input to production of sector $j$. + +Economies are characterised by many such links. + +A basic framework for their analysis is +[Leontief's](https://en.wikipedia.org/wiki/Wassily_Leontief) input-output model. + + + +After introducing the input-output model, we describe some of its connections to {doc}`linear programming lecture `. + + +## Input-output analysis + +Let + + * $x_0$ be the amount of a single exogenous input to production, say labor + * $x_j, j = 1,\ldots n$ be the gross output of final good $j$ + * $d_j, j = 1,\ldots n$ be the net output of final good $j$ that is available for final consumption + * $z_{ij} $ be the quantity of good $i$ allocated to be an input to producing good $j$ for $i=1, \ldots n$, $j = 1, \ldots n$ + * $z_{0j}$ be the quantity of labor allocated to producing good $j$. + * $a_{ij}$ be the number of units of good $i$ required to produce one unit of good $j$, $i=0, \ldots, n, j= 1, \ldots n$. + * $w >0$ be an exogenous wage of labor, denominated in dollars per unit of labor + * $p$ be an $n \times 1$ vector of prices of produced goods $i = 1, \ldots , n$. + + + +The technology for producing good $j \in \{1, \ldots , n\}$ is described by the **Leontief** function + +$$ + x_j = \min_{i \in \{0, \ldots , n \}} \left( \frac{z_{ij}}{a_{ij}}\right) +$$ + +### Two goods + +To illustrate, we begin by setting $n =2$ and formulating +the following network. + +```{code-cell} ipython3 +:tags: [hide-input] + +G = nx.DiGraph() + +nodes= (1, 2, 'c') +edges = ((1, 1), (1, 2), (2, 1), (2, 2), (1, 'c'), (2, 'c')) +edges1 = ((1, 1), (1, 2), (2, 1), (2, 2), (1, 'c')) +edges2 = [(2,'c')] +G.add_nodes_from(nodes) +G.add_edges_from(edges) + +pos_list = ([0, 0], [2, 0], [1, -1]) +pos = dict(zip(G.nodes(), pos_list)) + +fig, ax = plt.subplots() +plt.axis("off") + +nx.draw_networkx_nodes(G, pos=pos, node_size=800, + node_color='white', edgecolors='black') +nx.draw_networkx_labels(G, pos=pos) +nx.draw_networkx_edges(G,pos=pos, edgelist=edges1, + node_size=300, connectionstyle='arc3,rad=0.2', + arrowsize=10, min_target_margin=15) +nx.draw_networkx_edges(G, pos=pos, edgelist=edges2, + node_size=300, connectionstyle='arc3,rad=-0.2', + arrowsize=10, min_target_margin=15) + +plt.text(0.055, 0.125, r'$z_{11}$') +plt.text(1.825, 0.125, r'$z_{22}$') +plt.text(0.955, 0.1, r'$z_{21}$') +plt.text(0.955, -0.125, r'$z_{12}$') +plt.text(0.325, -0.5, r'$d_{1}$') +plt.text(1.6, -0.5, r'$d_{2}$') + +plt.show() +``` + +*Feasible allocations must satisfy* + +$$ +\begin{aligned} +(1 - a_{11}) x_1 - a_{12} x_2 & \geq d_1 \cr +-a_{21} x_1 + (1 - a_{22}) x_2 & \geq d_2 \cr +a_{01} x_1 + a_{02} x_2 & \leq x_0 +\end{aligned} +$$ + +This can be graphically represented as follows. + +```{code-cell} ipython3 +:tags: [hide-input] + +fig, ax = plt.subplots() +ax.grid() + +# Draw constraint lines +ax.hlines(0, -1, 400) +ax.vlines(0, -1, 200) + +ax.plot(np.linspace(55, 380, 100), (50-0.9*np.linspace(55, 380, 100))/(-1.46), color="r") +ax.plot(np.linspace(-1, 400, 100), (60+0.16*np.linspace(-1, 400, 100))/0.83, color="r") +ax.plot(np.linspace(250, 395, 100), (62-0.04*np.linspace(250, 395, 100))/0.33, color="b") + +ax.text(130, 38, "$(1-a_{11})x_1 + a_{12}x_2 \geq d_1$", size=10) +ax.text(10, 105, "$-a_{21}x_1 + (1-a_{22})x_2 \geq d_2$", size=10) +ax.text(150, 150, "$a_{01}x_1 +a_{02}x_2 \leq x_0$", size=10) + +# Draw the feasible region +feasible_set = Polygon(np.array([[301, 151], + [368, 143], + [250, 120]]), + color="cyan") +ax.add_patch(feasible_set) + +# Draw the optimal solution +ax.plot(250, 120, "*", color="black") +ax.text(260, 115, "solution", size=10) + +plt.show() +``` + ++++ {"user_expressions": []} + +More generally, constraints on production are + +$$ +\begin{aligned} +(I - A) x & \geq d \cr +a_0^\top x & \leq x_0 +\end{aligned} +$$ (eq:inout_1) + +where $A$ is the $n \times n$ matrix with typical element $a_{ij}$ and $a_0^\top = \begin{bmatrix} a_{01} & \cdots & a_{0n} \end{bmatrix}$. + + + +If we solve the first block of equations of {eq}`eq:inout_1` for gross output $x$ we get + +$$ +x = (I -A)^{-1} d \equiv L d +$$ (eq:inout_2) + +where the matrix $L = (I-A)^{-1}$ is sometimes called a **Leontief Inverse**. + + + +To assure that the solution $X$ of {eq}`eq:inout_2` is a positive vector, the following **Hawkins-Simon conditions** suffice: + +$$ +\begin{aligned} +\det (I - A) > 0 \text{ and} \;\;\; \\ +(I-A)_{ij} > 0 \text{ for all } i=j +\end{aligned} +$$ + + +```{prf:example} +:label: io_ex_tg + +For example a two-good economy described by + +$$ +A = +\begin{bmatrix} + 0.1 & 40 \\ + 0.01 & 0 +\end{bmatrix} +\text{ and } +d = +\begin{bmatrix} + 50 \\ + 2 +\end{bmatrix} +$$ (eq:inout_ex) +``` + +```{code-cell} ipython3 +A = np.array([[0.1, 40], + [0.01, 0]]) +d = np.array([50, 2]).reshape((2, 1)) +``` + +```{code-cell} ipython3 +I = np.identity(2) +B = I - A +B +``` + +Let's check the **Hawkins-Simon conditions** + +```{code-cell} ipython3 +np.linalg.det(B) > 0 # checking Hawkins-Simon conditions +``` + +Now, let's compute the **Leontief inverse** matrix + +```{code-cell} ipython3 +L = np.linalg.inv(B) # obtaining Leontief inverse matrix +L +``` + +```{code-cell} ipython3 +x = L @ d # solving for gross output +x +``` + ++++ {"user_expressions": []} + +## Production possibility frontier + +The second equation of {eq}`eq:inout_1` can be written + +$$ +a_0^\top x = x_0 +$$ + +or + +$$ +A_0^\top d = x_0 +$$ (eq:inout_frontier) + +where + +$$ +A_0^\top = a_0^\top (I - A)^{-1} +$$ + + For $i \in \{1, \ldots , n\}$, the $i$th component of $A_0$ is the amount of labor that is required to produce one unit of final output of good $i$. + +Equation {eq}`eq:inout_frontier` sweeps out a **production possibility frontier** of final consumption bundles $d$ that can be produced with exogenous labor input $x_0$. + +```{prf:example} +:label: io_ex_ppf + +Consider the example in {eq}`eq:inout_ex`. + +Suppose we are now given + +$$ +a_0^\top = \begin{bmatrix} +4 & 100 +\end{bmatrix} +$$ +``` + +Then we can find $A_0^\top$ by + +```{code-cell} ipython3 +a0 = np.array([4, 100]) +A0 = a0 @ L +A0 +``` + ++++ {"user_expressions": []} + +Thus, the production possibility frontier for this economy is + +$$ +10d_1 + 500d_2 = x_0 +$$ + ++++ {"user_expressions": []} + +## Prices + +{cite}`DoSSo` argue that relative prices of the $n$ produced goods must satisfy + +$$ +\begin{aligned} +p_1 = a_{11}p_1 + a_{21}p_2 + a_{01}w \\ +p_2 = a_{12}p_1 + a_{22}p_2 + a_{02}w +\end{aligned} +$$ + +More generally, + +$$ +p = A^\top p + a_0 w +$$ + +which states that the price of each final good equals the total cost +of production, which consists of costs of intermediate inputs $A^\top p$ +plus costs of labor $a_0 w$. + +This equation can be written as + +$$ +(I - A^\top) p = a_0 w +$$ (eq:inout_price) + +which implies + +$$ +p = (I - A^\top)^{-1} a_0 w +$$ + +Notice how {eq}`eq:inout_price` with {eq}`eq:inout_1` forms a +**conjugate pair** through the appearance of operators +that are transposes of one another. + +This connection surfaces again in a classic linear program and its dual. + + +## Linear programs + +A **primal** problem is + +$$ +\min_{x} w a_0^\top x +$$ + +subject to + +$$ +(I - A) x \geq d +$$ + + +The associated **dual** problem is + +$$ +\max_{p} p^\top d +$$ + +subject to + +$$ +(I -A)^\top p \leq a_0 w +$$ + +The primal problem chooses a feasible production plan to minimize costs for delivering a pre-assigned vector of final goods consumption $d$. + +The dual problem chooses prices to maximize the value of a pre-assigned vector of final goods $d$ subject to prices covering costs of production. + +By the [strong duality theorem](https://en.wikipedia.org/wiki/Dual_linear_program#Strong_duality), +optimal value of the primal and dual problems coincide: + +$$ +w a_0^\top x^* = p^* d +$$ + +where $^*$'s denote optimal choices for the primal and dual problems. + +The dual problem can be graphically represented as follows. + +```{code-cell} ipython3 +:tags: [hide-input] + +fig, ax = plt.subplots() +ax.grid() + +# Draw constraint lines +ax.hlines(0, -1, 50) +ax.vlines(0, -1, 250) + +ax.plot(np.linspace(4.75, 49, 100), (4-0.9*np.linspace(4.75, 49, 100))/(-0.16), color="r") +ax.plot(np.linspace(0, 50, 100), (33+1.46*np.linspace(0, 50, 100))/0.83, color="r") + +ax.text(15, 175, "$(1-a_{11})p_1 - a_{21}p_2 \leq a_{01}w$", size=10) +ax.text(30, 85, "$-a_{12}p_1 + (1-a_{22})p_2 \leq a_{02}w$", size=10) + +# Draw the feasible region +feasible_set = Polygon(np.array([[17, 69], + [4, 0], + [0,0], + [0, 40]]), + color="cyan") +ax.add_patch(feasible_set) + +# Draw the optimal solution +ax.plot(17, 69, "*", color="black") +ax.text(18, 60, "dual solution", size=10) + +plt.show() +``` + ++++ {"user_expressions": []} + +## Leontief inverse + +We have discussed that gross output $x$ is given by {eq}`eq:inout_2`, where $L$ is called the Leontief Inverse. + +Recall the {doc}`Neumann Series Lemma ` which states that $L$ exists if the spectral radius $r(A)<1$. + +In fact + +$$ +L = \sum_{i=0}^{\infty} A^i +$$ + +### Demand shocks + +Consider the impact of a demand shock $\Delta d$ which shifts demand from $d_0$ to $d_1 = d_0 + \Delta d$. + +Gross output shifts from $x_0 = Ld_0$ to $x_1 = Ld_1$. + +If $r(A) < 1$ then a solution exists and + +$$ +\Delta x = L \Delta d = \Delta d + A(\Delta d) + A^2 (\Delta d) + \cdots +$$ + +This illustrates that an element $l_{ij}$ of $L$ shows the total impact on sector $i$ of a unit change in demand of good $j$. + +## Applications of graph theory + +We can further study input-output networks through applications of {doc}`graph theory `. + +An input-output network can be represented by a weighted directed graph induced by the adjacency matrix $A$. + +The set of nodes $V = [n]$ is the list of sectors and the set of edges is given by + +$$ +E = \{(i,j) \in V \times V : a_{ij}>0\} +$$ + +In {numref}`us_15sectors` weights are indicated by the widths of the arrows, which are proportional to the corresponding input-output coefficients. + +We can now use centrality measures to rank sectors and discuss their importance relative to the other sectors. + +### Eigenvector centrality + +Eigenvector centrality of a node $i$ is measured by + +$$ +\begin{aligned} + e_i = \frac{1}{r(A)} \sum_{1 \leq j \leq n} a_{ij} e_j +\end{aligned} +$$ + +We plot a bar graph of hub-based eigenvector centrality for the sectors represented in {numref}`us_15sectors`. + +```{code-cell} ipython3 +:tags: [hide-input] + +fig, ax = plt.subplots() +ax.bar(codes, centrality, color=color_list, alpha=0.6) +ax.set_ylabel("eigenvector centrality", fontsize=12) +plt.show() +``` + +A higher measure indicates higher importance as a supplier. + +As a result demand shocks in most sectors will significantly impact activity in sectors with high eigenvector centrality. + +The above figure indicates that manufacturing is the most dominant sector in the US economy. + +### Output multipliers + +Another way to rank sectors in input-output networks is via output multipliers. + +The **output multiplier** of sector $j$ denoted by $\mu_j$ is usually defined as the +total sector-wide impact of a unit change of demand in sector $j$. + +Earlier when disussing demand shocks we concluded that for $L = (l_{ij})$ the element +$l_{ij}$ represents the impact on sector $i$ of a unit change in demand in sector $j$. + +Thus, + +$$ +\mu_j = \sum_{j=1}^n l_{ij} +$$ + +This can be written as $\mu^\top = \mathbb{1}^\top L$ or + + +$$ +\mu^\top = \mathbb{1}^\top (I-A)^{-1} +$$ + +Please note that here we use $\mathbb{1}$ to represent a vector of ones. + +High ranking sectors within this measure are important buyers of intermediate goods. + +A demand shock in such sectors will cause a large impact on the whole production network. + +The following figure displays the output multipliers for the sectors represented +in {numref}`us_15sectors`. + +```{code-cell} ipython3 +:tags: [hide-input] + +A, F = build_coefficient_matrices(Z, X) +omult = qbn_io.katz_centrality(A, authority=True) + +fig, ax = plt.subplots() +omult_color_list = qbn_io.colorise_weights(omult,beta=False) +ax.bar(codes, omult, color=omult_color_list, alpha=0.6) +ax.set_ylabel("Output multipliers", fontsize=12) +plt.show() +``` + +We observe that manufacturing and agriculture are highest ranking sectors. + + +## Exercises + +```{exercise-start} +:label: io_ex1 +``` + +{cite}`DoSSo` Chapter 9 discusses an example with the following +parameter settings: + +$$ +A = \begin{bmatrix} + 0.1 & 1.46 \\ + 0.16 & 0.17 + \end{bmatrix} +\text{ and } +a_0 = \begin{bmatrix} .04 & .33 \end{bmatrix} +$$ + +$$ +x = \begin{bmatrix} 250 \\ 120 \end{bmatrix} +\text{ and } +x_0 = 50 +$$ + +$$ +d = \begin{bmatrix} 50 \\ 60 \end{bmatrix} +$$ + +Describe how they infer the input-output coefficients in $A$ and $a_0$ from the following hypothetical underlying "data" on agricultural and manufacturing industries: + +$$ +z = \begin{bmatrix} 25 & 175 \\ + 40 & 20 \end{bmatrix} +\text{ and } +z_0 = \begin{bmatrix} 10 & 40 \end{bmatrix} +$$ + +where $z_0$ is a vector of labor services used in each industry. + +```{exercise-end} +``` + +```{solution-start} io_ex1 +:class: dropdown +``` +For each $i = 0,1,2$ and $j = 1,2$ + +$$ +a_{ij} = \frac{z_{ij}}{x_j} +$$ + +```{solution-end} +``` + +```{exercise-start} +:label: io_ex2 +``` + +Derive the production possibility frontier for the economy characterized in the previous exercise. + +```{exercise-end} +``` + +```{solution-start} io_ex2 +:class: dropdown +``` + +```{code-cell} ipython3 +A = np.array([[0.1, 1.46], + [0.16, 0.17]]) +a_0 = np.array([0.04, 0.33]) +``` + +```{code-cell} ipython3 +I = np.identity(2) +B = I - A +L = np.linalg.inv(B) +``` + +```{code-cell} ipython3 +A_0 = a_0 @ L +A_0 +``` + ++++ {"user_expressions": []} + +Thus the production possibility frontier is given by + +$$ +0.17 d_1 + 0.69 d_2 = 50 +$$ + +```{solution-end} +``` diff --git a/book/_build/html/_sources/intro.ipynb b/book/_build/html/_sources/intro.ipynb new file mode 100644 index 0000000..d94cabd --- /dev/null +++ b/book/_build/html/_sources/intro.ipynb @@ -0,0 +1,35 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "d40d5968", + "metadata": {}, + "source": [ + "# A First Course in Quantitative Economics with Python\n", + "\n", + "This lecture series provides an introduction to quantitative economics using Python. \n", + "\n", + "```{tableofcontents}\n", + "```" + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst" + } + }, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "source_map": [ + 10 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/intro.md b/book/_build/html/_sources/intro.md new file mode 100644 index 0000000..d0bfe9a --- /dev/null +++ b/book/_build/html/_sources/intro.md @@ -0,0 +1,18 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst +kernelspec: + display_name: Python 3 + language: python + name: python3 +--- + +# A First Course in Quantitative Economics with Python + +This lecture series provides an introduction to quantitative economics using Python. + +```{tableofcontents} +``` + diff --git a/book/_build/html/_sources/intro_supply_demand.ipynb b/book/_build/html/_sources/intro_supply_demand.ipynb new file mode 100644 index 0000000..544bf16 --- /dev/null +++ b/book/_build/html/_sources/intro_supply_demand.ipynb @@ -0,0 +1,1260 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "48cd0bbd", + "metadata": {}, + "source": [ + "# Introduction to Supply and Demand\n", + "\n", + "## Overview\n", + "\n", + "This lecture is about some models of equilibrium prices and quantities, one of\n", + "the core topics of elementary microeconomics.\n", + "\n", + "Throughout the lecture, we focus on models with one good and one price.\n", + "\n", + "```{seealso}\n", + "In a {doc}`subsequent lecture ` we will investigate settings with\n", + "many goods.\n", + "```\n", + "\n", + "### Why does this model matter?\n", + "\n", + "In the 15th, 16th, 17th and 18th centuries, mercantilist ideas held sway among most rulers of European countries.\n", + "\n", + "Exports were regarded as good because they brought in bullion (gold flowed into the country).\n", + "\n", + "Imports were regarded as bad because bullion was required to pay for them (gold flowed out).\n", + "\n", + "This [zero-sum](https://en.wikipedia.org/wiki/Zero-sum_game) view of economics was eventually overturned by the work of the classical economists such as [Adam Smith](https://en.wikipedia.org/wiki/Adam_Smith) and [David Ricardo](https://en.wikipedia.org/wiki/David_Ricardo), who showed how freeing domestic and international trade can enhance welfare.\n", + "\n", + "There are many different expressions of this idea in economics.\n", + "\n", + "This lecture discusses one of the simplest: how free adjustment of prices can maximize a measure of social welfare in the market for a single good.\n", + "\n", + "\n", + "### Topics and infrastructure\n", + "\n", + "Key infrastructure concepts that we will encounter in this lecture are:\n", + "\n", + "* inverse demand curves\n", + "* inverse supply curves\n", + "* consumer surplus\n", + "* producer surplus\n", + "* integration\n", + "* social welfare as the sum of consumer and producer surpluses\n", + "* the relationship between equilibrium quantity and social welfare optimum\n", + "\n", + "In our exposition we will use the following Python imports." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a4b9cfc0", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from collections import namedtuple" + ] + }, + { + "cell_type": "markdown", + "id": "084d9a19", + "metadata": {}, + "source": [ + "## Consumer surplus\n", + "\n", + "Before we look at the model of supply and demand, it will be helpful to have some background on (a) consumer and producer surpluses and (b) integration.\n", + "\n", + "(If you are comfortable with both topics you can jump to the {ref}`next section `.)\n", + "\n", + "### A discrete example\n", + "\n", + "```{prf:example}\n", + ":label: isd_ex_cs\n", + "\n", + "Regarding consumer surplus, suppose that we have a single good and 10 consumers.\n", + "\n", + "These 10 consumers have different preferences; in particular, the amount they would be willing to pay for one unit of the good differs.\n", + "\n", + "Suppose that the willingness to pay for each of the 10 consumers is as follows:\n", + "\n", + "| consumer | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |\n", + "|----------------|----|----|----|----|----|----|----|----|----|-----|\n", + "| willing to pay | 98 | 72 | 41 | 38 | 29 | 21 | 17 | 12 | 11 | 10 |\n", + "\n", + "(We have ordered consumers by willingness to pay, in descending order.)\n", + "```\n", + "\n", + "If $p$ is the price of the good and $w_i$ is the amount that consumer $i$ is willing to pay, then $i$ buys when $w_i \\geq p$.\n", + "\n", + "```{note}\n", + "If $p=w_i$ the consumer is indifferent between buying and not buying; we arbitrarily assume that they buy.\n", + "```\n", + "\n", + "The **consumer surplus** of the $i$-th consumer is $\\max\\{w_i - p, 0\\}$\n", + "\n", + "* if $w_i \\geq p$, then the consumer buys and gets surplus $w_i - p$\n", + "* if $w_i < p$, then the consumer does not buy and gets surplus $0$\n", + "\n", + "For example, if the price is $p=40$, then consumer 1 gets surplus $98-40=58$.\n", + "\n", + "The bar graph below shows the surplus of each consumer when $p=25$.\n", + "\n", + "The total height of each bar $i$ is willingness to pay by consumer $i$.\n", + "\n", + "The orange portion of some of the bars shows consumer surplus." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "34d071de", + "metadata": { + "mystnb": { + "figure": { + "caption": "Willingness to pay (discrete)", + "name": "wpdisc" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "consumers = range(1, 11) # consumers 1,..., 10\n", + "# willingness to pay for each consumer\n", + "wtp = (98, 72, 41, 38, 29, 21, 17, 12, 11, 10)\n", + "price = 25\n", + "ax.bar(consumers, wtp, label=\"consumer surplus\", color=\"darkorange\", alpha=0.8)\n", + "ax.plot((0, 12), (price, price), lw=2, label=\"price $p$\")\n", + "ax.bar(consumers, [min(w, price) for w in wtp], color=\"black\", alpha=0.6)\n", + "ax.set_xlim(0, 12)\n", + "ax.set_xticks(consumers)\n", + "ax.set_ylabel(\"willingness to pay, price\")\n", + "ax.set_xlabel(\"consumer, quantity\")\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "f00090f6", + "metadata": {}, + "source": [ + "The total consumer surplus in this market is \n", + "\n", + "$$ \n", + "\\sum_{i=1}^{10} \\max\\{w_i - p, 0\\}\n", + "= \\sum_{w_i \\geq p} (w_i - p)\n", + "$$\n", + "\n", + "Since consumer surplus $\\max\\{w_i-p,0\\}$ of consumer $i$ is a measure of her gains from trade (i.e., extent to which the good is valued over and above the amount the consumer had to pay), it is reasonable to consider total consumer surplus as a measurement of consumer welfare.\n", + "\n", + "Later we will pursue this idea further, considering how different prices lead to different welfare outcomes for consumers and producers.\n", + "\n", + "### A comment on quantity.\n", + "\n", + "Notice that in the figure, the horizontal axis is labeled \"consumer, quantity\".\n", + "\n", + "We have added \"quantity\" here because we can read the number of units sold from this axis, assuming for now that there are sellers who are willing to sell as many units as the consumers demand, given the current market price $p$.\n", + "\n", + "In this example, consumers 1 to 5 buy, and the quantity sold is 5.\n", + "\n", + "Below we drop the assumption that sellers will provide any amount at a given price and study how this changes outcomes.\n", + "\n", + "### A continuous approximation\n", + "\n", + "It is often convenient to assume that there is a \"very large number\" of consumers, so that willingness to pay becomes a continuous curve.\n", + "\n", + "As before, the vertical axis measures willingness to pay, while the horizontal axis measures quantity.\n", + "\n", + "This kind of curve is called an **inverse demand curve**\n", + "\n", + "An example is provided below, showing both an inverse demand curve and a set price.\n", + "\n", + "The inverse demand curve is given by \n", + "\n", + "$$\n", + "p = 100 e^{-q} \n", + "$$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "14e201b5", + "metadata": { + "mystnb": { + "figure": { + "caption": "Willingness to pay (continuous)", + "name": "wpcont" + } + } + }, + "outputs": [], + "source": [ + "def inverse_demand(q):\n", + " return 100 * np.exp(- q)\n", + "\n", + "# build a grid to evaluate the function at different values of q\n", + "q_min, q_max = 0, 5\n", + "q_grid = np.linspace(q_min, q_max, 1000)\n", + "\n", + "# plot the inverse demand curve\n", + "fig, ax = plt.subplots()\n", + "ax.plot((q_min, q_max), (price, price), lw=2, label=\"price\")\n", + "ax.plot(q_grid, inverse_demand(q_grid), \n", + " color=\"orange\", label=\"inverse demand curve\")\n", + "ax.set_ylabel(\"willingness to pay, price\")\n", + "ax.set_xlabel(\"quantity\")\n", + "ax.set_xlim(q_min, q_max)\n", + "ax.set_ylim(0, 110)\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "3dbeea6b", + "metadata": {}, + "source": [ + "Reasoning by analogy with the discrete case, the area under the demand curve and above the price is called the **consumer surplus**, and is a measure of total gains from trade on the part of consumers.\n", + "\n", + "The consumer surplus is shaded in the figure below." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "63ee4831", + "metadata": { + "mystnb": { + "figure": { + "caption": "Willingness to pay (continuous) with consumer surplus", + "name": "wpcont_cs" + } + } + }, + "outputs": [], + "source": [ + "# solve for the value of q where demand meets price\n", + "q_star = np.log(100) - np.log(price)\n", + "\n", + "fig, ax = plt.subplots()\n", + "ax.plot((q_min, q_max), (price, price), lw=2, label=\"price\")\n", + "ax.plot(q_grid, inverse_demand(q_grid), \n", + " color=\"orange\", label=\"inverse demand curve\")\n", + "small_grid = np.linspace(0, q_star, 500)\n", + "ax.fill_between(small_grid, np.full(len(small_grid), price),\n", + " inverse_demand(small_grid), color=\"orange\",\n", + " alpha=0.5, label=\"consumer surplus\")\n", + "ax.vlines(q_star, 0, price, ls=\"--\")\n", + "ax.set_ylabel(\"willingness to pay, price\")\n", + "ax.set_xlabel(\"quantity\")\n", + "ax.set_xlim(q_min, q_max)\n", + "ax.set_ylim(0, 110)\n", + "ax.text(q_star, -10, \"$q^*$\")\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "b97a1603", + "metadata": {}, + "source": [ + "The value $q^*$ is where the inverse demand curve meets price.\n", + "\n", + "## Producer surplus\n", + "\n", + "Having discussed demand, let's now switch over to the supply side of the market.\n", + "\n", + "### The discrete case\n", + "\n", + "The figure below shows the price at which a collection of producers, also numbered 1 to 10, are willing to sell one unit of the good in question" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ea31f3c1", + "metadata": { + "mystnb": { + "figure": { + "caption": "Willingness to sell (discrete)", + "name": "wsdisc" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "producers = range(1, 11) # producers 1,..., 10\n", + "# willingness to sell for each producer\n", + "wts = (5, 8, 17, 22, 35, 39, 46, 57, 88, 91)\n", + "price = 25\n", + "ax.bar(producers, wts, label=\"willingness to sell\", color=\"green\", alpha=0.5)\n", + "ax.set_xlim(0, 12)\n", + "ax.set_xticks(producers)\n", + "ax.set_ylabel(\"willingness to sell\")\n", + "ax.set_xlabel(\"producer\")\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "d26a5eab", + "metadata": {}, + "source": [ + "Let $v_i$ be the price at which producer $i$ is willing to sell the good.\n", + "\n", + "When the price is $p$, producer surplus for producer $i$ is $\\max\\{p - v_i, 0\\}$.\n", + "\n", + "```{prf:example}\n", + ":label: isd_ex_dc\n", + "\n", + "For example, a producer willing to sell at \\$10 and selling at price \\$20 makes a surplus of \\$10. \n", + "\n", + "Total producer surplus is given by\n", + "\n", + "$$\n", + "\\sum_{i=1}^{10} \\max\\{p - v_i, 0\\}\n", + "= \\sum_{p \\geq v_i} (p - v_i)\n", + "$$\n", + "\n", + "As for the consumer case, it can be helpful for analysis if we approximate producer willingness to sell into a continuous curve.\n", + "\n", + "This curve is called the **inverse supply curve**\n", + "\n", + "We show an example below where the inverse supply curve is\n", + "\n", + "$$\n", + "p = 2 q^2\n", + "$$\n", + "\n", + "The shaded area is the total producer surplus in this continuous model.\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "94558e05", + "metadata": { + "mystnb": { + "figure": { + "caption": "Willingness to sell (continuous) with producer surplus", + "name": "wscont" + } + } + }, + "outputs": [], + "source": [ + "def inverse_supply(q):\n", + " return 2 * q**2\n", + "\n", + "# solve for the value of q where supply meets price\n", + "q_star = (price / 2)**(1/2)\n", + "\n", + "# plot the inverse supply curve\n", + "fig, ax = plt.subplots()\n", + "ax.plot((q_min, q_max), (price, price), lw=2, label=\"price\")\n", + "ax.plot(q_grid, inverse_supply(q_grid), \n", + " color=\"green\", label=\"inverse supply curve\")\n", + "small_grid = np.linspace(0, q_star, 500)\n", + "ax.fill_between(small_grid, inverse_supply(small_grid), \n", + " np.full(len(small_grid), price), \n", + " color=\"green\",\n", + " alpha=0.5, label=\"producer surplus\")\n", + "ax.vlines(q_star, 0, price, ls=\"--\")\n", + "ax.set_ylabel(\"willingness to sell, price\")\n", + "ax.set_xlabel(\"quantity\")\n", + "ax.set_xlim(q_min, q_max)\n", + "ax.set_ylim(0, 60)\n", + "ax.text(q_star, -10, \"$q^*$\")\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "2652e4bb", + "metadata": {}, + "source": [ + "(integration)=\n", + "## Integration\n", + "\n", + "How can we calculate the consumer and producer surplus in the continuous case?\n", + "\n", + "The short answer is: by using [integration](https://en.wikipedia.org/wiki/Integral).\n", + "\n", + "Some readers will already be familiar with the basics of integration.\n", + "\n", + "For those who are not, here is a quick introduction.\n", + "\n", + "In general, for a function $f$, the **integral** of $f$ over the interval $[a, b]$ is the area under the curve $f$ between $a$ and $b$.\n", + "\n", + "This value is written as $\\int_a^b f(x) \\mathrm{d} x$ and illustrated in the figure below when $f(x) = \\cos(x/2) + 1$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b592b682", + "metadata": { + "mystnb": { + "figure": { + "caption": "Area under the curve", + "name": "integrate" + } + } + }, + "outputs": [], + "source": [ + "def f(x):\n", + " return np.cos(x/2) + 1\n", + "\n", + "xmin, xmax = 0, 5\n", + "a, b = 1, 3\n", + "x_grid = np.linspace(xmin, xmax, 1000)\n", + "ab_grid = np.linspace(a, b, 400)\n", + "\n", + "fig, ax = plt.subplots()\n", + "ax.plot(x_grid, f(x_grid), label=\"$f$\", color=\"k\")\n", + "ax.fill_between(ab_grid, [0] * len(ab_grid), f(ab_grid), \n", + " label=\"$\\int_a^b f(x) dx$\")\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "9b7bea8f", + "metadata": {}, + "source": [ + "There are many rules for calculating integrals, with different rules applying to different choices of $f$.\n", + "\n", + "Many of these rules relate to one of the most beautiful and powerful results in all of mathematics: the [fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus).\n", + "\n", + "We will not try to cover these ideas here, partly because the subject is too big, and partly because you only need to know one rule for this lecture, stated below.\n", + "\n", + "If $f(x) = c + dx$, then \n", + "\n", + "$$ \n", + "\\int_a^b f(x) \\mathrm{d} x = c (b - a) + \\frac{d}{2}(b^2 - a^2) \n", + "$$\n", + "\n", + "In fact this rule is so simple that it can be calculated from elementary geometry -- you might like to try by graphing $f$ and calculating the area under the curve between $a$ and $b$.\n", + "\n", + "We use this rule repeatedly in what follows.\n", + "\n", + "## Supply and demand\n", + "\n", + "Let's now put supply and demand together.\n", + "\n", + "This leads us to the all important notion of market equilibrium, and from there onto a discussion of equilibria and welfare.\n", + "\n", + "For most of this discussion, we'll assume that inverse demand and supply curves are **affine** functions of quantity.\n", + "\n", + "```{note}\n", + "\"Affine\" means \"linear plus a constant\" and [here](https://math.stackexchange.com/questions/275310/what-is-the-difference-between-linear-and-affine-function) is a nice discussion about it.\n", + "```\n", + "\n", + "We'll also assume affine inverse supply and demand functions when we study models with multiple consumption goods in our {doc}`subsequent lecture `.\n", + "\n", + "We do this in order to simplify the exposition and enable us to use just a few tools from linear algebra, namely, matrix multiplication and matrix inversion.\n", + "\n", + "We study a market for a single good in which buyers and sellers exchange a quantity $q$ for a price $p$.\n", + "\n", + "Quantity $q$ and price $p$ are both scalars.\n", + "\n", + "We assume that inverse demand and supply curves for the good are:\n", + "\n", + "$$\n", + "p = d_0 - d_1 q, \\quad d_0, d_1 > 0\n", + "$$\n", + "\n", + "$$\n", + "p = s_0 + s_1 q , \\quad s_0, s_1 > 0\n", + "$$\n", + "\n", + "We call them inverse demand and supply curves because price is on the left side of the equation rather than on the right side as it would be in a direct demand or supply function.\n", + "\n", + "We can use a [namedtuple](https://docs.python.org/3/library/collections.html#collections.namedtuple) to store the parameters for our single good market." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5eb95a97", + "metadata": {}, + "outputs": [], + "source": [ + "Market = namedtuple('Market', ['d_0', # demand intercept\n", + " 'd_1', # demand slope\n", + " 's_0', # supply intercept\n", + " 's_1'] # supply slope\n", + " )" + ] + }, + { + "cell_type": "markdown", + "id": "34810ab0", + "metadata": {}, + "source": [ + "The function below creates an instance of a Market namedtuple with default values." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "85c8fbd3", + "metadata": {}, + "outputs": [], + "source": [ + "def create_market(d_0=1.0, d_1=0.6, s_0=0.1, s_1=0.4):\n", + " return Market(d_0=d_0, d_1=d_1, s_0=s_0, s_1=s_1)" + ] + }, + { + "cell_type": "markdown", + "id": "63832538", + "metadata": {}, + "source": [ + "This `market` can then be used by our `inverse_demand` and `inverse_supply` functions." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "604a4e8d", + "metadata": {}, + "outputs": [], + "source": [ + "def inverse_demand(q, model):\n", + " return model.d_0 - model.d_1 * q\n", + "\n", + "def inverse_supply(q, model):\n", + " return model.s_0 + model.s_1 * q" + ] + }, + { + "cell_type": "markdown", + "id": "470fba0a", + "metadata": {}, + "source": [ + "Here is a plot of these two functions using `market`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f3308e15", + "metadata": { + "mystnb": { + "figure": { + "caption": "Supply and demand", + "name": "supply_demand" + } + } + }, + "outputs": [], + "source": [ + "market = create_market()\n", + "\n", + "grid_min, grid_max, grid_size = 0, 1.5, 200\n", + "q_grid = np.linspace(grid_min, grid_max, grid_size)\n", + "supply_curve = inverse_supply(q_grid, market)\n", + "demand_curve = inverse_demand(q_grid, market)\n", + "\n", + "fig, ax = plt.subplots()\n", + "ax.plot(q_grid, supply_curve, label='supply', color='green')\n", + "ax.plot(q_grid, demand_curve, label='demand', color='orange')\n", + "ax.legend(loc='upper center', frameon=False)\n", + "ax.set_ylim(0, 1.2)\n", + "ax.set_xticks((0, 1))\n", + "ax.set_yticks((0, 1))\n", + "ax.set_xlabel('quantity')\n", + "ax.set_ylabel('price')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "31787cfd", + "metadata": {}, + "source": [ + "In the above graph, an **equilibrium** price-quantity pair occurs at the intersection of the supply and demand curves. \n", + "\n", + "### Consumer surplus\n", + "\n", + "Let a quantity $q$ be given and let $p := d_0 - d_1 q$ be the\n", + "corresponding price on the inverse demand curve.\n", + "\n", + "We define **consumer surplus** $S_c(q)$ as the area under an inverse demand\n", + "curve minus $p q$:\n", + "\n", + "$$\n", + "S_c(q) := \n", + "\\int_0^{q} (d_0 - d_1 x) \\mathrm{d} x - p q \n", + "$$ (eq:cstm_spls)\n", + "\n", + "The next figure illustrates" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "45f68a71", + "metadata": { + "mystnb": { + "figure": { + "caption": "Supply and demand (consumer surplus)", + "name": "supply_demand_cs" + } + }, + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "q = 1.25\n", + "p = inverse_demand(q, market)\n", + "ps = np.ones_like(q_grid) * p\n", + "\n", + "fig, ax = plt.subplots()\n", + "ax.plot(q_grid, demand_curve, label='demand', color='orange')\n", + "ax.fill_between(q_grid[q_grid <= q],\n", + " demand_curve[q_grid <= q],\n", + " ps[q_grid <= q],\n", + " label='consumer surplus',\n", + " color=\"orange\", \n", + " alpha=0.5)\n", + "ax.vlines(q, 0, p, linestyle=\"dashed\", color='black', alpha=0.7)\n", + "ax.hlines(p, 0, q, linestyle=\"dashed\", color='black', alpha=0.7)\n", + "\n", + "ax.legend(loc='upper center', frameon=False)\n", + "ax.set_ylim(0, 1.2)\n", + "ax.set_xticks((q,))\n", + "ax.set_xticklabels((\"$q$\",))\n", + "ax.set_yticks((p,))\n", + "ax.set_yticklabels((\"$p$\",))\n", + "ax.set_xlabel('quantity')\n", + "ax.set_ylabel('price')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "46758c91", + "metadata": {}, + "source": [ + "Consumer surplus provides a measure of total consumer welfare at quantity $q$.\n", + "\n", + "The idea is that the inverse demand curve $d_0 - d_1 q$ shows a consumer's willingness to \n", + "pay for an additional increment of the good at a given quantity $q$.\n", + "\n", + "The difference between willingness to pay and the actual price is consumer surplus.\n", + "\n", + "The value $S_c(q)$ is the \"sum\" (i.e., integral) of these surpluses when the total\n", + "quantity purchased is $q$ and the purchase price is $p$.\n", + "\n", + "Evaluating the integral in the definition of consumer surplus {eq}`eq:cstm_spls` gives\n", + "\n", + "$$\n", + "S_c(q) \n", + "= d_0 q - \\frac{1}{2} d_1 q^2 - p q\n", + "$$\n", + "\n", + "### Producer surplus\n", + "\n", + "Let a quantity $q$ be given and let $p := s_0 + s_1 q$ be the\n", + "corresponding price on the inverse supply curve.\n", + "\n", + "We define **producer surplus** as $p q$ minus the area under an inverse supply curve\n", + "\n", + "$$\n", + "S_p(q) \n", + ":= p q - \\int_0^q (s_0 + s_1 x) \\mathrm{d} x \n", + "$$ (eq:pdcr_spls)\n", + "\n", + "The next figure illustrates" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bb31f82b", + "metadata": { + "mystnb": { + "figure": { + "caption": "Supply and demand (producer surplus)", + "name": "supply_demand_ps" + } + }, + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "q = 0.75\n", + "p = inverse_supply(q, market)\n", + "ps = np.ones_like(q_grid) * p\n", + "\n", + "fig, ax = plt.subplots()\n", + "ax.plot(q_grid, supply_curve, label='supply', color='green')\n", + "ax.fill_between(q_grid[q_grid <= q],\n", + " supply_curve[q_grid <= q],\n", + " ps[q_grid <= q],\n", + " label='producer surplus',\n", + " color=\"green\",\n", + " alpha=0.5)\n", + "ax.vlines(q, 0, p, linestyle=\"dashed\", color='black', alpha=0.7)\n", + "ax.hlines(p, 0, q, linestyle=\"dashed\", color='black', alpha=0.7)\n", + "\n", + "ax.legend(loc='upper center', frameon=False)\n", + "ax.set_ylim(0, 1.2)\n", + "ax.set_xticks((q,))\n", + "ax.set_xticklabels((\"$q$\",))\n", + "ax.set_yticks((p,))\n", + "ax.set_yticklabels((\"$p$\",))\n", + "ax.set_xlabel('quantity')\n", + "ax.set_ylabel('price')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "4bebfb75", + "metadata": {}, + "source": [ + "Producer surplus measures total producer welfare at quantity $q$ \n", + "\n", + "The idea is similar to that of consumer surplus.\n", + "\n", + "The inverse supply curve $s_0 + s_1 q$ shows the price at which producers are\n", + "prepared to sell, given quantity $q$.\n", + "\n", + "The difference between willingness to sell and the actual price is producer surplus.\n", + "\n", + "The value $S_p(q)$ is the integral of these surpluses.\n", + "\n", + "Evaluating the integral in the definition of producer surplus {eq}`eq:pdcr_spls` gives\n", + "\n", + "$$\n", + "S_p(q) = pq - s_0 q - \\frac{1}{2} s_1 q^2\n", + "$$\n", + "\n", + "\n", + "### Social welfare\n", + "\n", + "Sometimes economists measure social welfare by a **welfare criterion** that\n", + "equals consumer surplus plus producer surplus, assuming that consumers and\n", + "producers pay the same price:\n", + "\n", + "$$\n", + "W(q)\n", + "= \\int_0^q (d_0 - d_1 x) dx - \\int_0^q (s_0 + s_1 x) \\mathrm{d} x \n", + "$$\n", + "\n", + "Evaluating the integrals gives\n", + "\n", + "$$\n", + "W(q) = (d_0 - s_0) q - \\frac{1}{2} (d_1 + s_1) q^2\n", + "$$\n", + "\n", + "Here is a Python function that evaluates this social welfare at a given\n", + "quantity $q$ and a fixed set of parameters." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c33f9ef7", + "metadata": {}, + "outputs": [], + "source": [ + "def W(q, market):\n", + " # Compute and return welfare\n", + " return (market.d_0 - market.s_0) * q - 0.5 * (market.d_1 + market.s_1) * q**2" + ] + }, + { + "cell_type": "markdown", + "id": "2aea8ee8", + "metadata": {}, + "source": [ + "The next figure plots welfare as a function of $q$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e773a54e", + "metadata": { + "mystnb": { + "figure": { + "caption": "Welfare", + "name": "wf" + } + }, + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "q_vals = np.linspace(0, 1.78, 200)\n", + "fig, ax = plt.subplots()\n", + "ax.plot(q_vals, W(q_vals, market), label='welfare', color='brown')\n", + "ax.legend(frameon=False)\n", + "ax.set_xlabel('quantity')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "b2f3567d", + "metadata": {}, + "source": [ + "Let's now give a social planner the task of maximizing social welfare.\n", + "\n", + "To compute a quantity that maximizes the welfare criterion, we differentiate\n", + "$W$ with respect to $q$ and then set the derivative to zero.\n", + "\n", + "$$\n", + "\\frac{\\mathrm{d} W(q)}{\\mathrm{d} q} = d_0 - s_0 - (d_1 + s_1) q = 0\n", + "$$\n", + "\n", + "Solving for $q$ yields\n", + "\n", + "$$\n", + "q = \\frac{ d_0 - s_0}{s_1 + d_1}\n", + "$$ (eq:old1)\n", + "\n", + "Let's remember the quantity $q$ given by equation {eq}`eq:old1` that a social planner would choose to maximize consumer surplus plus producer surplus.\n", + "\n", + "We'll compare it to the quantity that emerges in a competitive equilibrium that equates supply to demand.\n", + "\n", + "### Competitive equilibrium\n", + "\n", + "Instead of equating quantities supplied and demanded, we can accomplish the\n", + "same thing by equating demand price to supply price:\n", + "\n", + "$$\n", + "p = d_0 - d_1 q = s_0 + s_1 q \n", + "$$\n", + "\n", + "If we solve the equation defined by the second equality in the above line for\n", + "$q$, we obtain \n", + "\n", + "$$\n", + "q = \\frac{ d_0 - s_0}{s_1 + d_1}\n", + "$$ (eq:equilib_q)\n", + "\n", + "\n", + "This is the competitive equilibrium quantity. \n", + "\n", + "Observe that the equilibrium quantity equals the same $q$ given by equation {eq}`eq:old1`.\n", + "\n", + "The outcome that the quantity determined by equation {eq}`eq:old1` equates\n", + "supply to demand brings us a *key finding*:\n", + "\n", + "* a competitive equilibrium quantity maximizes our welfare criterion\n", + "\n", + "This is a version of the [first fundamental welfare theorem](https://en.wikipedia.org/wiki/Fundamental_theorems_of_welfare_economics), \n", + "\n", + "It also brings a useful **competitive equilibrium computation strategy:**\n", + "\n", + "* after solving the welfare problem for an optimal quantity, we can read a competitive equilibrium price from either supply price or demand price at the competitive equilibrium quantity\n", + "\n", + "## Generalizations\n", + "\n", + "In a {doc}`later lecture `, we'll derive\n", + "generalizations of the above demand and supply curves from other objects.\n", + "\n", + "Our generalizations will extend the preceding analysis of a market for a single good to the analysis of $n$ simultaneous markets in $n$ goods.\n", + "\n", + "In addition\n", + "\n", + "* we'll derive *demand curves* from a consumer problem that maximizes a\n", + " *utility function* subject to a *budget constraint*.\n", + "\n", + "* we'll derive *supply curves* from the problem of a producer who is price\n", + " taker and maximizes his profits minus total costs that are described by a *cost function*.\n", + "\n", + "## Exercises\n", + "\n", + "Suppose now that the inverse demand and supply curves are modified to take the\n", + "form\n", + "\n", + "$$\n", + "p = i_d(q) := d_0 - d_1 q^{0.6} \n", + "$$\n", + "\n", + "$$\n", + "p = i_s(q) := s_0 + s_1 q^{1.8} \n", + "$$\n", + "\n", + "All parameters are positive, as before.\n", + "\n", + "```{exercise}\n", + ":label: isd_ex1\n", + "\n", + "Use the same `Market` namedtuple that holds the parameter values as before but\n", + "make new `inverse_demand` and `inverse_supply` functions to match these new definitions.\n", + "\n", + "Then plot the inverse demand and supply curves $i_d$ and $i_s$.\n", + "\n", + "```\n", + "\n", + "```{solution-start} isd_ex1\n", + ":class: dropdown\n", + "```\n", + "\n", + "Let's update the `inverse_demand` and `inverse_supply` functions, as defined above." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4f465315", + "metadata": {}, + "outputs": [], + "source": [ + "def inverse_demand(q, model):\n", + " return model.d_0 - model.d_1 * q**0.6\n", + "\n", + "def inverse_supply(q, model):\n", + " return model.s_0 + model.s_1 * q**1.8" + ] + }, + { + "cell_type": "markdown", + "id": "7913ba89", + "metadata": {}, + "source": [ + "Here is a plot of inverse supply and demand." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6f179398", + "metadata": {}, + "outputs": [], + "source": [ + "grid_min, grid_max, grid_size = 0, 1.5, 200\n", + "q_grid = np.linspace(grid_min, grid_max, grid_size)\n", + "market = create_market()\n", + "supply_curve = inverse_supply(q_grid, market)\n", + "demand_curve = inverse_demand(q_grid, market)\n", + "\n", + "fig, ax = plt.subplots()\n", + "ax.plot(q_grid, supply_curve, label='supply', color='green')\n", + "ax.plot(q_grid, demand_curve, label='demand', color='orange')\n", + "ax.legend(loc='upper center', frameon=False)\n", + "ax.set_ylim(0, 1.2)\n", + "ax.set_xticks((0, 1))\n", + "ax.set_yticks((0, 1))\n", + "ax.set_xlabel('quantity')\n", + "ax.set_ylabel('price')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "c9d84de8", + "metadata": {}, + "source": [ + "```{solution-end}\n", + "```\n", + "\n", + "\n", + "```{exercise}\n", + ":label: isd_ex2\n", + "\n", + "As before, consumer surplus at $q$ is the area under the demand curve minus\n", + "price times quantity:\n", + "\n", + "$$\n", + "S_c(q) = \\int_0^{q} i_d(x) dx - p q \n", + "$$\n", + "\n", + "Here $p$ is set to $i_d(q)$\n", + "\n", + "Producer surplus is price times quantity minus the area under the inverse\n", + "supply curve:\n", + "\n", + "$$\n", + "S_p(q) \n", + "= p q - \\int_0^q i_s(x) \\mathrm{d} x \n", + "$$\n", + "\n", + "Here $p$ is set to $i_s(q)$.\n", + "\n", + "Social welfare is the sum of consumer and producer surplus under the\n", + "assumption that the price is the same for buyers and sellers:\n", + "\n", + "$$\n", + "W(q)\n", + "= \\int_0^q i_d(x) dx - \\int_0^q i_s(x) \\mathrm{d} x \n", + "$$\n", + "\n", + "Solve the integrals and write a function to compute this quantity numerically\n", + "at given $q$. \n", + "\n", + "Plot welfare as a function of $q$.\n", + "```\n", + "\n", + "\n", + "```{solution-start} isd_ex2\n", + ":class: dropdown\n", + "```\n", + "\n", + "Solving the integrals gives \n", + "\n", + "$$\n", + "W(q) \n", + "= d_0 q - \\frac{d_1 q^{1.6}}{1.6}\n", + " - \\left( s_0 q + \\frac{s_1 q^{2.8}}{2.8} \\right)\n", + "$$\n", + "\n", + "Here's a Python function that computes this value:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b41e025c", + "metadata": {}, + "outputs": [], + "source": [ + "def W(q, market):\n", + " # Compute and return welfare\n", + " S_c = market.d_0 * q - market.d_1 * q**1.6 / 1.6\n", + " S_p = market.s_0 * q + market.s_1 * q**2.8 / 2.8\n", + " return S_c - S_p" + ] + }, + { + "cell_type": "markdown", + "id": "61de3441", + "metadata": {}, + "source": [ + "The next figure plots welfare as a function of $q$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6138bc5c", + "metadata": {}, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "ax.plot(q_vals, W(q_vals, market), label='welfare', color='brown')\n", + "ax.legend(frameon=False)\n", + "ax.set_xlabel('quantity')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "952d2c36", + "metadata": {}, + "source": [ + "```{solution-end}\n", + "```\n", + "\n", + "\n", + "````{exercise}\n", + ":label: isd_ex3\n", + "\n", + "Due to non-linearities, the new welfare function is not easy to maximize with\n", + "pencil and paper.\n", + "\n", + "Maximize it using `scipy.optimize.minimize_scalar` instead.\n", + "\n", + "```{seealso}\n", + "Our [SciPy](https://python-programming.quantecon.org/scipy.html) lecture has\n", + "a section on [Optimization](https://python-programming.quantecon.org/scipy.html#optimization)\n", + "is a useful resource to find out more. \n", + "```\n", + "\n", + "````\n", + "\n", + "\n", + "```{solution-start} isd_ex3\n", + ":class: dropdown\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4a643441", + "metadata": {}, + "outputs": [], + "source": [ + "from scipy.optimize import minimize_scalar\n", + "\n", + "def objective(q):\n", + " return -W(q, market)\n", + "\n", + "result = minimize_scalar(objective, bounds=(0, 10))\n", + "print(result.message)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "73155c9b", + "metadata": {}, + "outputs": [], + "source": [ + "maximizing_q = result.x\n", + "print(f\"{maximizing_q: .5f}\")" + ] + }, + { + "cell_type": "markdown", + "id": "d5fd755d", + "metadata": {}, + "source": [ + "```{solution-end}\n", + "```\n", + "\n", + "\n", + "````{exercise}\n", + ":label: isd_ex4\n", + "\n", + "Now compute the equilibrium quantity by finding the price that equates supply\n", + "and demand.\n", + "\n", + "You can do this numerically by finding the root of the excess demand function\n", + "\n", + "$$\n", + "e_d(q) := i_d(q) - i_s(q) \n", + "$$\n", + "\n", + "You can use `scipy.optimize.newton` to compute the root.\n", + "\n", + "```{seealso}\n", + "Our [SciPy](https://python-programming.quantecon.org/scipy.html) lecture has\n", + "a section on [Roots and Fixed Points](https://python-programming.quantecon.org/scipy.html#roots-and-fixed-points)\n", + "is a useful resource to find out more. \n", + "```\n", + "\n", + "Initialize `newton` with a starting guess somewhere close to 1.0.\n", + "\n", + "(Similar initial conditions will give the same result.)\n", + "\n", + "You should find that the equilibrium price agrees with the welfare maximizing\n", + "price, in line with the first fundamental welfare theorem.\n", + "\n", + "````\n", + "\n", + "\n", + "```{solution-start} isd_ex4\n", + ":class: dropdown\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "14d49dd0", + "metadata": {}, + "outputs": [], + "source": [ + "from scipy.optimize import newton\n", + "\n", + "def excess_demand(q):\n", + " return inverse_demand(q, market) - inverse_supply(q, market)\n", + "\n", + "equilibrium_q = newton(excess_demand, 0.99)\n", + "print(f\"{equilibrium_q: .5f}\")" + ] + }, + { + "cell_type": "markdown", + "id": "375c2790", + "metadata": {}, + "source": [ + "```{solution-end}\n", + "```" + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.15.1" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 57, + 61, + 106, + 127, + 166, + 191, + 197, + 223, + 235, + 254, + 285, + 316, + 333, + 354, + 406, + 412, + 416, + 419, + 423, + 429, + 433, + 457, + 476, + 509, + 542, + 575, + 615, + 619, + 623, + 638, + 737, + 743, + 747, + 764, + 821, + 827, + 831, + 837, + 864, + 874, + 877, + 917, + 925 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/intro_supply_demand.md b/book/_build/html/_sources/intro_supply_demand.md new file mode 100644 index 0000000..aea36eb --- /dev/null +++ b/book/_build/html/_sources/intro_supply_demand.md @@ -0,0 +1,928 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.15.1 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Introduction to Supply and Demand + +## Overview + +This lecture is about some models of equilibrium prices and quantities, one of +the core topics of elementary microeconomics. + +Throughout the lecture, we focus on models with one good and one price. + +```{seealso} +In a {doc}`subsequent lecture ` we will investigate settings with +many goods. +``` + +### Why does this model matter? + +In the 15th, 16th, 17th and 18th centuries, mercantilist ideas held sway among most rulers of European countries. + +Exports were regarded as good because they brought in bullion (gold flowed into the country). + +Imports were regarded as bad because bullion was required to pay for them (gold flowed out). + +This [zero-sum](https://en.wikipedia.org/wiki/Zero-sum_game) view of economics was eventually overturned by the work of the classical economists such as [Adam Smith](https://en.wikipedia.org/wiki/Adam_Smith) and [David Ricardo](https://en.wikipedia.org/wiki/David_Ricardo), who showed how freeing domestic and international trade can enhance welfare. + +There are many different expressions of this idea in economics. + +This lecture discusses one of the simplest: how free adjustment of prices can maximize a measure of social welfare in the market for a single good. + + +### Topics and infrastructure + +Key infrastructure concepts that we will encounter in this lecture are: + +* inverse demand curves +* inverse supply curves +* consumer surplus +* producer surplus +* integration +* social welfare as the sum of consumer and producer surpluses +* the relationship between equilibrium quantity and social welfare optimum + +In our exposition we will use the following Python imports. + +```{code-cell} ipython3 +import numpy as np +import matplotlib.pyplot as plt +from collections import namedtuple +``` + +## Consumer surplus + +Before we look at the model of supply and demand, it will be helpful to have some background on (a) consumer and producer surpluses and (b) integration. + +(If you are comfortable with both topics you can jump to the {ref}`next section `.) + +### A discrete example + +```{prf:example} +:label: isd_ex_cs + +Regarding consumer surplus, suppose that we have a single good and 10 consumers. + +These 10 consumers have different preferences; in particular, the amount they would be willing to pay for one unit of the good differs. + +Suppose that the willingness to pay for each of the 10 consumers is as follows: + +| consumer | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | +|----------------|----|----|----|----|----|----|----|----|----|-----| +| willing to pay | 98 | 72 | 41 | 38 | 29 | 21 | 17 | 12 | 11 | 10 | + +(We have ordered consumers by willingness to pay, in descending order.) +``` + +If $p$ is the price of the good and $w_i$ is the amount that consumer $i$ is willing to pay, then $i$ buys when $w_i \geq p$. + +```{note} +If $p=w_i$ the consumer is indifferent between buying and not buying; we arbitrarily assume that they buy. +``` + +The **consumer surplus** of the $i$-th consumer is $\max\{w_i - p, 0\}$ + +* if $w_i \geq p$, then the consumer buys and gets surplus $w_i - p$ +* if $w_i < p$, then the consumer does not buy and gets surplus $0$ + +For example, if the price is $p=40$, then consumer 1 gets surplus $98-40=58$. + +The bar graph below shows the surplus of each consumer when $p=25$. + +The total height of each bar $i$ is willingness to pay by consumer $i$. + +The orange portion of some of the bars shows consumer surplus. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Willingness to pay (discrete)" + name: wpdisc +--- +fig, ax = plt.subplots() +consumers = range(1, 11) # consumers 1,..., 10 +# willingness to pay for each consumer +wtp = (98, 72, 41, 38, 29, 21, 17, 12, 11, 10) +price = 25 +ax.bar(consumers, wtp, label="consumer surplus", color="darkorange", alpha=0.8) +ax.plot((0, 12), (price, price), lw=2, label="price $p$") +ax.bar(consumers, [min(w, price) for w in wtp], color="black", alpha=0.6) +ax.set_xlim(0, 12) +ax.set_xticks(consumers) +ax.set_ylabel("willingness to pay, price") +ax.set_xlabel("consumer, quantity") +ax.legend() +plt.show() +``` + +The total consumer surplus in this market is + +$$ +\sum_{i=1}^{10} \max\{w_i - p, 0\} += \sum_{w_i \geq p} (w_i - p) +$$ + +Since consumer surplus $\max\{w_i-p,0\}$ of consumer $i$ is a measure of her gains from trade (i.e., extent to which the good is valued over and above the amount the consumer had to pay), it is reasonable to consider total consumer surplus as a measurement of consumer welfare. + +Later we will pursue this idea further, considering how different prices lead to different welfare outcomes for consumers and producers. + +### A comment on quantity. + +Notice that in the figure, the horizontal axis is labeled "consumer, quantity". + +We have added "quantity" here because we can read the number of units sold from this axis, assuming for now that there are sellers who are willing to sell as many units as the consumers demand, given the current market price $p$. + +In this example, consumers 1 to 5 buy, and the quantity sold is 5. + +Below we drop the assumption that sellers will provide any amount at a given price and study how this changes outcomes. + +### A continuous approximation + +It is often convenient to assume that there is a "very large number" of consumers, so that willingness to pay becomes a continuous curve. + +As before, the vertical axis measures willingness to pay, while the horizontal axis measures quantity. + +This kind of curve is called an **inverse demand curve** + +An example is provided below, showing both an inverse demand curve and a set price. + +The inverse demand curve is given by + +$$ +p = 100 e^{-q} +$$ + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Willingness to pay (continuous)" + name: wpcont +--- +def inverse_demand(q): + return 100 * np.exp(- q) + +# build a grid to evaluate the function at different values of q +q_min, q_max = 0, 5 +q_grid = np.linspace(q_min, q_max, 1000) + +# plot the inverse demand curve +fig, ax = plt.subplots() +ax.plot((q_min, q_max), (price, price), lw=2, label="price") +ax.plot(q_grid, inverse_demand(q_grid), + color="orange", label="inverse demand curve") +ax.set_ylabel("willingness to pay, price") +ax.set_xlabel("quantity") +ax.set_xlim(q_min, q_max) +ax.set_ylim(0, 110) +ax.legend() +plt.show() +``` + +Reasoning by analogy with the discrete case, the area under the demand curve and above the price is called the **consumer surplus**, and is a measure of total gains from trade on the part of consumers. + +The consumer surplus is shaded in the figure below. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Willingness to pay (continuous) with consumer surplus" + name: wpcont_cs +--- +# solve for the value of q where demand meets price +q_star = np.log(100) - np.log(price) + +fig, ax = plt.subplots() +ax.plot((q_min, q_max), (price, price), lw=2, label="price") +ax.plot(q_grid, inverse_demand(q_grid), + color="orange", label="inverse demand curve") +small_grid = np.linspace(0, q_star, 500) +ax.fill_between(small_grid, np.full(len(small_grid), price), + inverse_demand(small_grid), color="orange", + alpha=0.5, label="consumer surplus") +ax.vlines(q_star, 0, price, ls="--") +ax.set_ylabel("willingness to pay, price") +ax.set_xlabel("quantity") +ax.set_xlim(q_min, q_max) +ax.set_ylim(0, 110) +ax.text(q_star, -10, "$q^*$") +ax.legend() +plt.show() +``` + +The value $q^*$ is where the inverse demand curve meets price. + +## Producer surplus + +Having discussed demand, let's now switch over to the supply side of the market. + +### The discrete case + +The figure below shows the price at which a collection of producers, also numbered 1 to 10, are willing to sell one unit of the good in question + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Willingness to sell (discrete)" + name: wsdisc +--- +fig, ax = plt.subplots() +producers = range(1, 11) # producers 1,..., 10 +# willingness to sell for each producer +wts = (5, 8, 17, 22, 35, 39, 46, 57, 88, 91) +price = 25 +ax.bar(producers, wts, label="willingness to sell", color="green", alpha=0.5) +ax.set_xlim(0, 12) +ax.set_xticks(producers) +ax.set_ylabel("willingness to sell") +ax.set_xlabel("producer") +ax.legend() +plt.show() +``` + +Let $v_i$ be the price at which producer $i$ is willing to sell the good. + +When the price is $p$, producer surplus for producer $i$ is $\max\{p - v_i, 0\}$. + +```{prf:example} +:label: isd_ex_dc + +For example, a producer willing to sell at \$10 and selling at price \$20 makes a surplus of \$10. + +Total producer surplus is given by + +$$ +\sum_{i=1}^{10} \max\{p - v_i, 0\} += \sum_{p \geq v_i} (p - v_i) +$$ + +As for the consumer case, it can be helpful for analysis if we approximate producer willingness to sell into a continuous curve. + +This curve is called the **inverse supply curve** + +We show an example below where the inverse supply curve is + +$$ +p = 2 q^2 +$$ + +The shaded area is the total producer surplus in this continuous model. +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Willingness to sell (continuous) with producer surplus" + name: wscont +--- +def inverse_supply(q): + return 2 * q**2 + +# solve for the value of q where supply meets price +q_star = (price / 2)**(1/2) + +# plot the inverse supply curve +fig, ax = plt.subplots() +ax.plot((q_min, q_max), (price, price), lw=2, label="price") +ax.plot(q_grid, inverse_supply(q_grid), + color="green", label="inverse supply curve") +small_grid = np.linspace(0, q_star, 500) +ax.fill_between(small_grid, inverse_supply(small_grid), + np.full(len(small_grid), price), + color="green", + alpha=0.5, label="producer surplus") +ax.vlines(q_star, 0, price, ls="--") +ax.set_ylabel("willingness to sell, price") +ax.set_xlabel("quantity") +ax.set_xlim(q_min, q_max) +ax.set_ylim(0, 60) +ax.text(q_star, -10, "$q^*$") +ax.legend() +plt.show() +``` + +(integration)= +## Integration + +How can we calculate the consumer and producer surplus in the continuous case? + +The short answer is: by using [integration](https://en.wikipedia.org/wiki/Integral). + +Some readers will already be familiar with the basics of integration. + +For those who are not, here is a quick introduction. + +In general, for a function $f$, the **integral** of $f$ over the interval $[a, b]$ is the area under the curve $f$ between $a$ and $b$. + +This value is written as $\int_a^b f(x) \mathrm{d} x$ and illustrated in the figure below when $f(x) = \cos(x/2) + 1$. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Area under the curve" + name: integrate +--- +def f(x): + return np.cos(x/2) + 1 + +xmin, xmax = 0, 5 +a, b = 1, 3 +x_grid = np.linspace(xmin, xmax, 1000) +ab_grid = np.linspace(a, b, 400) + +fig, ax = plt.subplots() +ax.plot(x_grid, f(x_grid), label="$f$", color="k") +ax.fill_between(ab_grid, [0] * len(ab_grid), f(ab_grid), + label="$\int_a^b f(x) dx$") +ax.legend() +plt.show() +``` + +There are many rules for calculating integrals, with different rules applying to different choices of $f$. + +Many of these rules relate to one of the most beautiful and powerful results in all of mathematics: the [fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus). + +We will not try to cover these ideas here, partly because the subject is too big, and partly because you only need to know one rule for this lecture, stated below. + +If $f(x) = c + dx$, then + +$$ +\int_a^b f(x) \mathrm{d} x = c (b - a) + \frac{d}{2}(b^2 - a^2) +$$ + +In fact this rule is so simple that it can be calculated from elementary geometry -- you might like to try by graphing $f$ and calculating the area under the curve between $a$ and $b$. + +We use this rule repeatedly in what follows. + +## Supply and demand + +Let's now put supply and demand together. + +This leads us to the all important notion of market equilibrium, and from there onto a discussion of equilibria and welfare. + +For most of this discussion, we'll assume that inverse demand and supply curves are **affine** functions of quantity. + +```{note} +"Affine" means "linear plus a constant" and [here](https://math.stackexchange.com/questions/275310/what-is-the-difference-between-linear-and-affine-function) is a nice discussion about it. +``` + +We'll also assume affine inverse supply and demand functions when we study models with multiple consumption goods in our {doc}`subsequent lecture `. + +We do this in order to simplify the exposition and enable us to use just a few tools from linear algebra, namely, matrix multiplication and matrix inversion. + +We study a market for a single good in which buyers and sellers exchange a quantity $q$ for a price $p$. + +Quantity $q$ and price $p$ are both scalars. + +We assume that inverse demand and supply curves for the good are: + +$$ +p = d_0 - d_1 q, \quad d_0, d_1 > 0 +$$ + +$$ +p = s_0 + s_1 q , \quad s_0, s_1 > 0 +$$ + +We call them inverse demand and supply curves because price is on the left side of the equation rather than on the right side as it would be in a direct demand or supply function. + +We can use a [namedtuple](https://docs.python.org/3/library/collections.html#collections.namedtuple) to store the parameters for our single good market. + +```{code-cell} ipython3 +Market = namedtuple('Market', ['d_0', # demand intercept + 'd_1', # demand slope + 's_0', # supply intercept + 's_1'] # supply slope + ) +``` + +The function below creates an instance of a Market namedtuple with default values. + +```{code-cell} ipython3 +def create_market(d_0=1.0, d_1=0.6, s_0=0.1, s_1=0.4): + return Market(d_0=d_0, d_1=d_1, s_0=s_0, s_1=s_1) +``` + +This `market` can then be used by our `inverse_demand` and `inverse_supply` functions. + +```{code-cell} ipython3 +def inverse_demand(q, model): + return model.d_0 - model.d_1 * q + +def inverse_supply(q, model): + return model.s_0 + model.s_1 * q +``` + +Here is a plot of these two functions using `market`. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Supply and demand" + name: supply_demand +--- +market = create_market() + +grid_min, grid_max, grid_size = 0, 1.5, 200 +q_grid = np.linspace(grid_min, grid_max, grid_size) +supply_curve = inverse_supply(q_grid, market) +demand_curve = inverse_demand(q_grid, market) + +fig, ax = plt.subplots() +ax.plot(q_grid, supply_curve, label='supply', color='green') +ax.plot(q_grid, demand_curve, label='demand', color='orange') +ax.legend(loc='upper center', frameon=False) +ax.set_ylim(0, 1.2) +ax.set_xticks((0, 1)) +ax.set_yticks((0, 1)) +ax.set_xlabel('quantity') +ax.set_ylabel('price') +plt.show() +``` + +In the above graph, an **equilibrium** price-quantity pair occurs at the intersection of the supply and demand curves. + +### Consumer surplus + +Let a quantity $q$ be given and let $p := d_0 - d_1 q$ be the +corresponding price on the inverse demand curve. + +We define **consumer surplus** $S_c(q)$ as the area under an inverse demand +curve minus $p q$: + +$$ +S_c(q) := +\int_0^{q} (d_0 - d_1 x) \mathrm{d} x - p q +$$ (eq:cstm_spls) + +The next figure illustrates + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Supply and demand (consumer surplus)" + name: supply_demand_cs +tags: [hide-input] +--- + +q = 1.25 +p = inverse_demand(q, market) +ps = np.ones_like(q_grid) * p + +fig, ax = plt.subplots() +ax.plot(q_grid, demand_curve, label='demand', color='orange') +ax.fill_between(q_grid[q_grid <= q], + demand_curve[q_grid <= q], + ps[q_grid <= q], + label='consumer surplus', + color="orange", + alpha=0.5) +ax.vlines(q, 0, p, linestyle="dashed", color='black', alpha=0.7) +ax.hlines(p, 0, q, linestyle="dashed", color='black', alpha=0.7) + +ax.legend(loc='upper center', frameon=False) +ax.set_ylim(0, 1.2) +ax.set_xticks((q,)) +ax.set_xticklabels(("$q$",)) +ax.set_yticks((p,)) +ax.set_yticklabels(("$p$",)) +ax.set_xlabel('quantity') +ax.set_ylabel('price') +plt.show() +``` + +Consumer surplus provides a measure of total consumer welfare at quantity $q$. + +The idea is that the inverse demand curve $d_0 - d_1 q$ shows a consumer's willingness to +pay for an additional increment of the good at a given quantity $q$. + +The difference between willingness to pay and the actual price is consumer surplus. + +The value $S_c(q)$ is the "sum" (i.e., integral) of these surpluses when the total +quantity purchased is $q$ and the purchase price is $p$. + +Evaluating the integral in the definition of consumer surplus {eq}`eq:cstm_spls` gives + +$$ +S_c(q) += d_0 q - \frac{1}{2} d_1 q^2 - p q +$$ + +### Producer surplus + +Let a quantity $q$ be given and let $p := s_0 + s_1 q$ be the +corresponding price on the inverse supply curve. + +We define **producer surplus** as $p q$ minus the area under an inverse supply curve + +$$ +S_p(q) +:= p q - \int_0^q (s_0 + s_1 x) \mathrm{d} x +$$ (eq:pdcr_spls) + +The next figure illustrates + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Supply and demand (producer surplus)" + name: supply_demand_ps +tags: [hide-input] +--- + +q = 0.75 +p = inverse_supply(q, market) +ps = np.ones_like(q_grid) * p + +fig, ax = plt.subplots() +ax.plot(q_grid, supply_curve, label='supply', color='green') +ax.fill_between(q_grid[q_grid <= q], + supply_curve[q_grid <= q], + ps[q_grid <= q], + label='producer surplus', + color="green", + alpha=0.5) +ax.vlines(q, 0, p, linestyle="dashed", color='black', alpha=0.7) +ax.hlines(p, 0, q, linestyle="dashed", color='black', alpha=0.7) + +ax.legend(loc='upper center', frameon=False) +ax.set_ylim(0, 1.2) +ax.set_xticks((q,)) +ax.set_xticklabels(("$q$",)) +ax.set_yticks((p,)) +ax.set_yticklabels(("$p$",)) +ax.set_xlabel('quantity') +ax.set_ylabel('price') +plt.show() +``` + +Producer surplus measures total producer welfare at quantity $q$ + +The idea is similar to that of consumer surplus. + +The inverse supply curve $s_0 + s_1 q$ shows the price at which producers are +prepared to sell, given quantity $q$. + +The difference between willingness to sell and the actual price is producer surplus. + +The value $S_p(q)$ is the integral of these surpluses. + +Evaluating the integral in the definition of producer surplus {eq}`eq:pdcr_spls` gives + +$$ +S_p(q) = pq - s_0 q - \frac{1}{2} s_1 q^2 +$$ + + +### Social welfare + +Sometimes economists measure social welfare by a **welfare criterion** that +equals consumer surplus plus producer surplus, assuming that consumers and +producers pay the same price: + +$$ +W(q) += \int_0^q (d_0 - d_1 x) dx - \int_0^q (s_0 + s_1 x) \mathrm{d} x +$$ + +Evaluating the integrals gives + +$$ +W(q) = (d_0 - s_0) q - \frac{1}{2} (d_1 + s_1) q^2 +$$ + +Here is a Python function that evaluates this social welfare at a given +quantity $q$ and a fixed set of parameters. + +```{code-cell} ipython3 +def W(q, market): + # Compute and return welfare + return (market.d_0 - market.s_0) * q - 0.5 * (market.d_1 + market.s_1) * q**2 +``` + +The next figure plots welfare as a function of $q$. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Welfare" + name: wf +tags: [hide-input] +--- + +q_vals = np.linspace(0, 1.78, 200) +fig, ax = plt.subplots() +ax.plot(q_vals, W(q_vals, market), label='welfare', color='brown') +ax.legend(frameon=False) +ax.set_xlabel('quantity') +plt.show() +``` + +Let's now give a social planner the task of maximizing social welfare. + +To compute a quantity that maximizes the welfare criterion, we differentiate +$W$ with respect to $q$ and then set the derivative to zero. + +$$ +\frac{\mathrm{d} W(q)}{\mathrm{d} q} = d_0 - s_0 - (d_1 + s_1) q = 0 +$$ + +Solving for $q$ yields + +$$ +q = \frac{ d_0 - s_0}{s_1 + d_1} +$$ (eq:old1) + +Let's remember the quantity $q$ given by equation {eq}`eq:old1` that a social planner would choose to maximize consumer surplus plus producer surplus. + +We'll compare it to the quantity that emerges in a competitive equilibrium that equates supply to demand. + +### Competitive equilibrium + +Instead of equating quantities supplied and demanded, we can accomplish the +same thing by equating demand price to supply price: + +$$ +p = d_0 - d_1 q = s_0 + s_1 q +$$ + +If we solve the equation defined by the second equality in the above line for +$q$, we obtain + +$$ +q = \frac{ d_0 - s_0}{s_1 + d_1} +$$ (eq:equilib_q) + + +This is the competitive equilibrium quantity. + +Observe that the equilibrium quantity equals the same $q$ given by equation {eq}`eq:old1`. + +The outcome that the quantity determined by equation {eq}`eq:old1` equates +supply to demand brings us a *key finding*: + +* a competitive equilibrium quantity maximizes our welfare criterion + +This is a version of the [first fundamental welfare theorem](https://en.wikipedia.org/wiki/Fundamental_theorems_of_welfare_economics), + +It also brings a useful **competitive equilibrium computation strategy:** + +* after solving the welfare problem for an optimal quantity, we can read a competitive equilibrium price from either supply price or demand price at the competitive equilibrium quantity + +## Generalizations + +In a {doc}`later lecture `, we'll derive +generalizations of the above demand and supply curves from other objects. + +Our generalizations will extend the preceding analysis of a market for a single good to the analysis of $n$ simultaneous markets in $n$ goods. + +In addition + +* we'll derive *demand curves* from a consumer problem that maximizes a + *utility function* subject to a *budget constraint*. + +* we'll derive *supply curves* from the problem of a producer who is price + taker and maximizes his profits minus total costs that are described by a *cost function*. + +## Exercises + +Suppose now that the inverse demand and supply curves are modified to take the +form + +$$ +p = i_d(q) := d_0 - d_1 q^{0.6} +$$ + +$$ +p = i_s(q) := s_0 + s_1 q^{1.8} +$$ + +All parameters are positive, as before. + +```{exercise} +:label: isd_ex1 + +Use the same `Market` namedtuple that holds the parameter values as before but +make new `inverse_demand` and `inverse_supply` functions to match these new definitions. + +Then plot the inverse demand and supply curves $i_d$ and $i_s$. + +``` + +```{solution-start} isd_ex1 +:class: dropdown +``` + +Let's update the `inverse_demand` and `inverse_supply` functions, as defined above. + +```{code-cell} ipython3 +def inverse_demand(q, model): + return model.d_0 - model.d_1 * q**0.6 + +def inverse_supply(q, model): + return model.s_0 + model.s_1 * q**1.8 +``` + +Here is a plot of inverse supply and demand. + +```{code-cell} ipython3 +grid_min, grid_max, grid_size = 0, 1.5, 200 +q_grid = np.linspace(grid_min, grid_max, grid_size) +market = create_market() +supply_curve = inverse_supply(q_grid, market) +demand_curve = inverse_demand(q_grid, market) + +fig, ax = plt.subplots() +ax.plot(q_grid, supply_curve, label='supply', color='green') +ax.plot(q_grid, demand_curve, label='demand', color='orange') +ax.legend(loc='upper center', frameon=False) +ax.set_ylim(0, 1.2) +ax.set_xticks((0, 1)) +ax.set_yticks((0, 1)) +ax.set_xlabel('quantity') +ax.set_ylabel('price') +plt.show() +``` + +```{solution-end} +``` + + +```{exercise} +:label: isd_ex2 + +As before, consumer surplus at $q$ is the area under the demand curve minus +price times quantity: + +$$ +S_c(q) = \int_0^{q} i_d(x) dx - p q +$$ + +Here $p$ is set to $i_d(q)$ + +Producer surplus is price times quantity minus the area under the inverse +supply curve: + +$$ +S_p(q) += p q - \int_0^q i_s(x) \mathrm{d} x +$$ + +Here $p$ is set to $i_s(q)$. + +Social welfare is the sum of consumer and producer surplus under the +assumption that the price is the same for buyers and sellers: + +$$ +W(q) += \int_0^q i_d(x) dx - \int_0^q i_s(x) \mathrm{d} x +$$ + +Solve the integrals and write a function to compute this quantity numerically +at given $q$. + +Plot welfare as a function of $q$. +``` + + +```{solution-start} isd_ex2 +:class: dropdown +``` + +Solving the integrals gives + +$$ +W(q) += d_0 q - \frac{d_1 q^{1.6}}{1.6} + - \left( s_0 q + \frac{s_1 q^{2.8}}{2.8} \right) +$$ + +Here's a Python function that computes this value: + +```{code-cell} ipython3 +def W(q, market): + # Compute and return welfare + S_c = market.d_0 * q - market.d_1 * q**1.6 / 1.6 + S_p = market.s_0 * q + market.s_1 * q**2.8 / 2.8 + return S_c - S_p +``` + +The next figure plots welfare as a function of $q$. + +```{code-cell} ipython3 +fig, ax = plt.subplots() +ax.plot(q_vals, W(q_vals, market), label='welfare', color='brown') +ax.legend(frameon=False) +ax.set_xlabel('quantity') +plt.show() +``` + +```{solution-end} +``` + + +````{exercise} +:label: isd_ex3 + +Due to non-linearities, the new welfare function is not easy to maximize with +pencil and paper. + +Maximize it using `scipy.optimize.minimize_scalar` instead. + +```{seealso} +Our [SciPy](https://python-programming.quantecon.org/scipy.html) lecture has +a section on [Optimization](https://python-programming.quantecon.org/scipy.html#optimization) +is a useful resource to find out more. +``` + +```` + + +```{solution-start} isd_ex3 +:class: dropdown +``` + +```{code-cell} ipython3 +from scipy.optimize import minimize_scalar + +def objective(q): + return -W(q, market) + +result = minimize_scalar(objective, bounds=(0, 10)) +print(result.message) +``` + +```{code-cell} ipython3 +maximizing_q = result.x +print(f"{maximizing_q: .5f}") +``` + +```{solution-end} +``` + + +````{exercise} +:label: isd_ex4 + +Now compute the equilibrium quantity by finding the price that equates supply +and demand. + +You can do this numerically by finding the root of the excess demand function + +$$ +e_d(q) := i_d(q) - i_s(q) +$$ + +You can use `scipy.optimize.newton` to compute the root. + +```{seealso} +Our [SciPy](https://python-programming.quantecon.org/scipy.html) lecture has +a section on [Roots and Fixed Points](https://python-programming.quantecon.org/scipy.html#roots-and-fixed-points) +is a useful resource to find out more. +``` + +Initialize `newton` with a starting guess somewhere close to 1.0. + +(Similar initial conditions will give the same result.) + +You should find that the equilibrium price agrees with the welfare maximizing +price, in line with the first fundamental welfare theorem. + +```` + + +```{solution-start} isd_ex4 +:class: dropdown +``` + +```{code-cell} ipython3 +from scipy.optimize import newton + +def excess_demand(q): + return inverse_demand(q, market) - inverse_supply(q, market) + +equilibrium_q = newton(excess_demand, 0.99) +print(f"{equilibrium_q: .5f}") +``` + +```{solution-end} +``` diff --git a/book/_build/html/_sources/laffer_adaptive.ipynb b/book/_build/html/_sources/laffer_adaptive.ipynb new file mode 100644 index 0000000..4c8da62 --- /dev/null +++ b/book/_build/html/_sources/laffer_adaptive.ipynb @@ -0,0 +1,570 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "b50b5f56", + "metadata": {}, + "source": [ + "# Laffer Curves with Adaptive Expectations \n", + "\n", + "## Overview\n", + "\n", + "This lecture studies stationary and dynamic **Laffer curves** in the inflation tax rate in a non-linear version of the model studied in this lecture {doc}`money_inflation`.\n", + "\n", + "As in the lecture {doc}`money_inflation`, this lecture uses the log-linear version of the demand function for money that {cite}`Cagan` used in his classic paper in place of the linear demand function used in this lecture {doc}`money_inflation`.\n", + "\n", + "But now, instead of assuming ''rational expectations'' in the form of ''perfect foresight'',\n", + "we'll adopt the ''adaptive expectations'' assumption used by {cite}`Cagan` and {cite}`Friedman1956`.\n", + "\n", + "This means that instead of assuming that expected inflation $\\pi_t^*$ is described by the \"perfect foresight\" or \"rational expectations\" hypothesis \n", + "\n", + "$$\n", + "\\pi_t^* = p_{t+1} - p_t\n", + "$$ \n", + "\n", + "that we adopted in lectures {doc}`money_inflation` and lectures {doc}`money_inflation_nonlinear`, we'll now assume that $\\pi_t^*$ is determined by the adaptive expectations hypothesis described in equation {eq}`eq:adaptex` reported below. \n", + "\n", + "We shall discover that changing our hypothesis about expectations formation in this way will change some our findings and leave others intact. In particular, we shall discover that\n", + "\n", + "* replacing rational expectations with adaptive expectations leaves the two stationary inflation rates unchanged, but that $\\ldots$ \n", + "* it reverses the perverse dynamics by making the **lower** stationary inflation rate the one to which the system typically converges\n", + "* a more plausible comparative dynamic outcome emerges in which now inflation can be **reduced** by running **lower** government deficits\n", + "\n", + "These more plausible comparative dynamics underlie the \"old time religion\" that states that \n", + "\"inflation is always and everywhere caused by government deficits\".\n", + "\n", + "These issues were studied by {cite}`bruno1990seigniorage`.\n", + "\n", + "Their purpose was to reverse what they thought were counter intuitive\n", + "predictions of their model under rational expectations (i.e., perfect foresight in this context)\n", + "by dropping rational expectations and instead assuming that people form expectations about future inflation rates according to the \"adaptive expectations\" scheme {eq}`eq:adaptex` described below.\n", + "\n", + "```{note}\n", + "{cite}`sargent1989least` had studied another way of selecting stationary equilibrium that involved replacing rational expectations with a model of learning via least squares regression. \n", + " {cite}`marcet2003recurrent` and {cite}`sargent2009conquest` extended that work and applied it to study recurrent high-inflation episodes in Latin America.\n", + "``` \n", + "\n", + "## The model\n", + "\n", + "Let \n", + "\n", + "* $m_t$ be the log of the money supply at the beginning of time $t$\n", + "* $p_t$ be the log of the price level at time $t$\n", + "* $\\pi_t^*$ be the public's expectation of the rate of inflation between $t$ and $t+1$ \n", + " \n", + "The law of motion of the money supply is\n", + "\n", + "$$ \n", + "\\exp(m_{t+1}) - \\exp(m_t) = g \\exp(p_t) \n", + "$$ (eq:ada_msupply)\n", + "\n", + "where $g$ is the part of government expenditures financed by printing money.\n", + "\n", + "Notice that equation {eq}`eq:ada_msupply` implies that\n", + "\n", + "$$\n", + "m_{t+1} = \\log[ \\exp(m_t) + g \\exp(p_t)]\n", + "$$ (eq:ada_msupply2)\n", + "\n", + "The demand function for money is \n", + "\n", + "$$\n", + "m_{t+1} - p_t = -\\alpha \\pi_t^* \n", + "$$ (eq:ada_mdemand)\n", + "\n", + "where $\\alpha \\geq 0$. \n", + "\n", + "Expectations of inflation are governed by \n", + "\n", + "$$\n", + "\\pi_{t}^* = (1-\\delta) (p_t - p_{t-1}) + \\delta \\pi_{t-1}^*\n", + "$$ (eq:adaptex)\n", + "\n", + "where $\\delta \\in (0,1)$\n", + "\n", + "## Computing an equilibrium sequence \n", + "\n", + "Equation the expressions for $m_{t+1}$ provided by {eq}`eq:ada_mdemand` and {eq}`eq:ada_msupply2` and use equation {eq}`eq:adaptex` to eliminate $\\pi_t^*$ to obtain\n", + "the following equation for $p_t$:\n", + "\n", + "$$\n", + "\\log[ \\exp(m_t) + g \\exp(p_t)] - p_t = -\\alpha [(1-\\delta) (p_t - p_{t-1}) + \\delta \\pi_{t-1}^*]\n", + "$$ (eq:pequation)\n", + "\n", + "**Pseudo-code**\n", + "\n", + "Here is the pseudo-code for our algorithm.\n", + "\n", + "Starting at time $0$ with initial conditions $(m_0, \\pi_{-1}^*, p_{-1})$, for each $t \\geq 0$\n", + "deploy the following steps in order:\n", + "\n", + "* solve {eq}`eq:pequation` for $p_t$\n", + "* solve equation {eq}`eq:adaptex` for $\\pi_t^*$ \n", + "* solve equation {eq}`eq:ada_msupply2` for $m_{t+1}$\n", + "\n", + "This completes the algorithm.\n", + "\n", + "\n", + "## Claims or conjectures\n", + " \n", + " \n", + "It will turn out that \n", + "\n", + "* if they exist, limiting values $\\overline \\pi$ and $\\overline \\mu$ will be equal\n", + "\n", + "* if limiting values exist, there are two possible limiting values, one high, one low\n", + "\n", + "* unlike the outcome in lecture {doc}`money_inflation_nonlinear`, for almost all initial log price levels and expected inflation rates $p_0, \\pi_{t}^*$, the limiting $\\overline \\pi = \\overline \\mu$ is the **lower** steady state value\n", + "\n", + "* for each of the two possible limiting values $\\bar \\pi$ ,there is a unique initial log price level $p_0$ that implies that $\\pi_t = \\mu_t = \\bar \\mu$ for all $t \\geq 0$\n", + "\n", + " * this unique initial log price level solves $\\log(\\exp(m_0) + g \\exp(p_0)) - p_0 = - \\alpha \\bar \\pi $\n", + " \n", + " * the preceding equation for $p_0$ comes from $m_1 - p_0 = - \\alpha \\bar \\pi$\n", + "\n", + "## Limiting values of inflation rate\n", + "\n", + "As in our earlier lecture {doc}`money_inflation_nonlinear`, we can compute the two prospective limiting values for $\\bar \\pi$ by studying the steady-state Laffer curve.\n", + "\n", + "Thus, in a **steady state** \n", + "\n", + "$$\n", + "m_{t+1} - m_t = p_{t+1} - p_t = x \\quad \\forall t ,\n", + "$$\n", + "\n", + "where $x > 0 $ is a common rate of growth of logarithms of the money supply and price level.\n", + "\n", + "A few lines of algebra yields the following equation that $x$ satisfies\n", + "\n", + "$$\n", + "\\exp(-\\alpha x) - \\exp(-(1 + \\alpha) x) = g \n", + "$$ (eq:ada_steadypi)\n", + "\n", + "where we require that\n", + "\n", + "$$\n", + "g \\leq \\max_{x: x \\geq 0} \\exp(-\\alpha x) - \\exp(-(1 + \\alpha) x) , \n", + "$$ (eq:ada_revmax)\n", + "\n", + "so that it is feasible to finance $g$ by printing money.\n", + "\n", + "The left side of {eq}`eq:ada_steadypi` is steady state revenue raised by printing money.\n", + "\n", + "The right side of {eq}`eq:ada_steadypi` is the quantity of time $t$ goods that the government raises by printing money. \n", + "\n", + "Soon we'll plot the left and right sides of equation {eq}`eq:ada_steadypi`.\n", + "\n", + "But first we'll write code that computes a steady-state\n", + "$\\bar \\pi$.\n", + "\n", + "Let's start by importing some libraries" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "76711606", + "metadata": {}, + "outputs": [], + "source": [ + "from collections import namedtuple\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from matplotlib.ticker import MaxNLocator\n", + "from matplotlib.cm import get_cmap\n", + "from matplotlib.colors import to_rgba\n", + "import matplotlib\n", + "from scipy.optimize import root, fsolve" + ] + }, + { + "cell_type": "markdown", + "id": "8fa98f64", + "metadata": { + "user_expressions": [] + }, + "source": [ + "Let's create a `namedtuple` to store the parameters of the model" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0806dca2", + "metadata": {}, + "outputs": [], + "source": [ + "LafferAdaptive = namedtuple('LafferAdaptive', \n", + " [\"m0\", # log of the money supply at t=0\n", + " \"α\", # sensitivity of money demand\n", + " \"g\", # government expenditure\n", + " \"δ\"])\n", + "\n", + "# Create a Cagan Laffer model\n", + "def create_model(α=0.5, m0=np.log(100), g=0.35, δ=0.9):\n", + " return LafferAdaptive(α=α, m0=m0, g=g, δ=δ)\n", + "\n", + "model = create_model()" + ] + }, + { + "cell_type": "markdown", + "id": "3ea2571e", + "metadata": {}, + "source": [ + "Now we write code that computes steady-state $\\bar \\pi$s." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "985a4e1e", + "metadata": {}, + "outputs": [], + "source": [ + "# Define formula for π_bar\n", + "def solve_π(x, α, g):\n", + " return np.exp(-α * x) - np.exp(-(1 + α) * x) - g\n", + "\n", + "def solve_π_bar(model, x0):\n", + " π_bar = fsolve(solve_π, x0=x0, xtol=1e-10, args=(model.α, model.g))[0]\n", + " return π_bar\n", + "\n", + "# Solve for the two steady state of π\n", + "π_l = solve_π_bar(model, x0=0.6)\n", + "π_u = solve_π_bar(model, x0=3.0)\n", + "print(f'The two steady state of π are: {π_l, π_u}')" + ] + }, + { + "cell_type": "markdown", + "id": "48a1d8a3", + "metadata": {}, + "source": [ + "We find two steady state $\\bar \\pi$ values\n", + "\n", + "## Steady-state Laffer curve\n", + "\n", + "The following figure plots the steady-state Laffer curve together with the two stationary inflation rates." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "30579960", + "metadata": { + "mystnb": { + "figure": { + "caption": "Seigniorage as function of steady-state inflation. The dashed brown lines indicate $\\pi_l$ and $\\pi_u$.", + "name": "laffer_curve_adaptive", + "width": "500px" + } + } + }, + "outputs": [], + "source": [ + "def compute_seign(x, α):\n", + " return np.exp(-α * x) - np.exp(-(1 + α) * x) \n", + "\n", + "def plot_laffer(model, πs):\n", + " α, g = model.α, model.g\n", + " \n", + " # Generate π values\n", + " x_values = np.linspace(0, 5, 1000)\n", + "\n", + " # Compute corresponding seigniorage values for the function\n", + " y_values = compute_seign(x_values, α)\n", + "\n", + " # Plot the function\n", + " plt.plot(x_values, y_values, \n", + " label=f'$exp((-{α})x) - exp(- (1- {α}) x)$')\n", + " for π, label in zip(πs, ['$\\pi_l$', '$\\pi_u$']):\n", + " plt.text(π, plt.gca().get_ylim()[0]*2, \n", + " label, horizontalalignment='center',\n", + " color='brown', size=10)\n", + " plt.axvline(π, color='brown', linestyle='--')\n", + " plt.axhline(g, color='red', linewidth=0.5, \n", + " linestyle='--', label='g')\n", + " plt.xlabel('$\\pi$')\n", + " plt.ylabel('seigniorage')\n", + " plt.legend()\n", + " plt.grid(True)\n", + " plt.show()\n", + "\n", + "# Steady state Laffer curve\n", + "plot_laffer(model, (π_l, π_u))" + ] + }, + { + "cell_type": "markdown", + "id": "88fc79c1", + "metadata": {}, + "source": [ + "## Associated initial price levels\n", + "\n", + "Now that we have our hands on the two possible steady states, we can compute two initial log price levels $p_{-1}$, which as initial conditions, imply that $\\pi_t = \\bar \\pi $ for all $t \\geq 0$.\n", + "\n", + "In particular, to initiate a fixed point of the dynamic Laffer curve dynamics, we set \n", + "\n", + "$$\n", + "p_{-1} = m_0 + \\alpha \\pi^*\n", + "$$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "08e82f7a", + "metadata": {}, + "outputs": [], + "source": [ + "def solve_p_init(model, π_star):\n", + " m0, α = model.m0, model.α\n", + " return m0 + α*π_star\n", + "\n", + "\n", + "# Compute two initial price levels associated with π_l and π_u\n", + "p_l, p_u = map(lambda π: solve_p_init(model, π), (π_l, π_u))\n", + "print('Associated initial p_{-1}s', f'are: {p_l, p_u}')" + ] + }, + { + "cell_type": "markdown", + "id": "5915231f", + "metadata": {}, + "source": [ + "### Verification \n", + "\n", + "To start, let's write some code to verify that if we initial $\\pi_{-1}^*,p_{-1}$ appropriately, the inflation rate $\\pi_t$ will be constant for all $t \\geq 0$ (at either $\\pi_u$ or $\\pi_l$ depending on the initial condition)\n", + "\n", + "The following code verifies this." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "90ca4e37", + "metadata": {}, + "outputs": [], + "source": [ + "def solve_laffer_adapt(p_init, π_init, model, num_steps):\n", + " m0, α, δ, g = model.m0, model.α, model.δ, model.g\n", + " \n", + " m_seq = np.nan * np.ones(num_steps+1) \n", + " π_seq = np.nan * np.ones(num_steps) \n", + " p_seq = np.nan * np.ones(num_steps)\n", + " μ_seq = np.nan * np.ones(num_steps) \n", + " \n", + " m_seq[1] = m0\n", + " π_seq[0] = π_init\n", + " p_seq[0] = p_init\n", + " \n", + " for t in range(1, num_steps):\n", + " # Solve p_t\n", + " def p_t(pt):\n", + " return np.log(np.exp(m_seq[t]) + g * np.exp(pt)) \\\n", + " - pt + α * ((1-δ)*(pt - p_seq[t-1]) + δ*π_seq[t-1])\n", + " \n", + " p_seq[t] = root(fun=p_t, x0=p_seq[t-1]).x[0]\n", + " \n", + " # Solve π_t\n", + " π_seq[t] = (1-δ) * (p_seq[t]-p_seq[t-1]) + δ*π_seq[t-1]\n", + " \n", + " # Solve m_t\n", + " m_seq[t+1] = np.log(np.exp(m_seq[t]) + g*np.exp(p_seq[t]))\n", + " \n", + " # Solve μ_t\n", + " μ_seq[t] = m_seq[t+1] - m_seq[t]\n", + " \n", + " return π_seq, μ_seq, m_seq, p_seq" + ] + }, + { + "cell_type": "markdown", + "id": "c02384b8", + "metadata": {}, + "source": [ + "Compute limiting values starting from $p_{-1}$ associated with $\\pi_l$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "419aa321", + "metadata": {}, + "outputs": [], + "source": [ + "π_seq, μ_seq, m_seq, p_seq = solve_laffer_adapt(p_l, π_l, model, 50)\n", + "\n", + "# Check steady state m_{t+1} - m_t and p_{t+1} - p_t \n", + "print('m_{t+1} - m_t:', m_seq[-1] - m_seq[-2])\n", + "print('p_{t+1} - p_t:', p_seq[-1] - p_seq[-2])\n", + "\n", + "# Check if exp(-αx) - exp(-(1 + α)x) = g\n", + "eq_g = lambda x: np.exp(-model.α * x) - np.exp(-(1 + model.α) * x)\n", + "\n", + "print('eq_g == g:', np.isclose(eq_g(m_seq[-1] - m_seq[-2]), model.g))" + ] + }, + { + "cell_type": "markdown", + "id": "bf1ea1a9", + "metadata": {}, + "source": [ + "Compute limiting values starting from $p_{-1}$ associated with $\\pi_u$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f219aeba", + "metadata": {}, + "outputs": [], + "source": [ + "π_seq, μ_seq, m_seq, p_seq = solve_laffer_adapt(p_u, π_u, model, 50)\n", + "\n", + "# Check steady state m_{t+1} - m_t and p_{t+1} - p_t \n", + "print('m_{t+1} - m_t:', m_seq[-1] - m_seq[-2])\n", + "print('p_{t+1} - p_t:', p_seq[-1] - p_seq[-2])\n", + "\n", + "# Check if exp(-αx) - exp(-(1 + α)x) = g\n", + "eq_g = lambda x: np.exp(-model.α * x) - np.exp(-(1 + model.α) * x)\n", + "\n", + "print('eq_g == g:', np.isclose(eq_g(m_seq[-1] - m_seq[-2]), model.g))" + ] + }, + { + "cell_type": "markdown", + "id": "2c43a987", + "metadata": {}, + "source": [ + "## Slippery side of Laffer curve dynamics\n", + "\n", + "We are now equipped to compute time series starting from different $p_{-1}, \\pi_{-1}^*$ settings, analogous to those in this lecture {doc}`money_inflation` and this lecture {doc}`money_inflation_nonlinear`. \n", + "\n", + "Now we'll study how outcomes unfold when we start $p_{-1}, \\pi_{-1}^*$ away from a stationary point of the dynamic Laffer curve, i.e., away from either $\\pi_u$ or $ \\pi_l$.\n", + "\n", + "To construct a perturbation pair $\\check p_{-1}, \\check \\pi_{-1}^*$we'll implement the following pseudo code:\n", + "\n", + "* set $\\check \\pi_{-1}^* $ not equal to one of the stationary points $\\pi_u$ or $ \\pi_l$.\n", + "* set $\\check p_{-1} = m_0 + \\alpha \\check \\pi_{-1}^*$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "291446ad", + "metadata": { + "tags": [ + "hide-cell" + ] + }, + "outputs": [], + "source": [ + "def draw_iterations(π0s, model, line_params, π_bars, num_steps):\n", + " fig, axes = plt.subplots(4, 1, figsize=(8, 12), sharex=True)\n", + "\n", + " for ax in axes[:2]:\n", + " ax.set_yscale('log')\n", + " \n", + " for i, π0 in enumerate(π0s):\n", + " p0 = model.m0 + model.α*π0\n", + " π_seq, μ_seq, m_seq, p_seq = solve_laffer_adapt(p0, π0, model, num_steps)\n", + "\n", + " axes[0].plot(np.arange(num_steps), m_seq[1:], **line_params)\n", + " axes[1].plot(np.arange(-1, num_steps-1), p_seq, **line_params)\n", + " axes[2].plot(np.arange(-1, num_steps-1), π_seq, **line_params)\n", + " axes[3].plot(np.arange(num_steps), μ_seq, **line_params)\n", + " \n", + " axes[2].axhline(y=π_bars[0], color='grey', linestyle='--', lw=1.5, alpha=0.6)\n", + " axes[2].axhline(y=π_bars[1], color='grey', linestyle='--', lw=1.5, alpha=0.6)\n", + " axes[2].text(num_steps * 1.07, π_bars[0], '$\\pi_l$', verticalalignment='center', \n", + " color='grey', size=10)\n", + " axes[2].text(num_steps * 1.07, π_bars[1], '$\\pi_u$', verticalalignment='center', \n", + " color='grey', size=10)\n", + "\n", + " axes[0].set_ylabel('$m_t$')\n", + " axes[1].set_ylabel('$p_t$')\n", + " axes[2].set_ylabel('$\\pi_t$')\n", + " axes[3].set_ylabel('$\\mu_t$')\n", + " axes[3].set_xlabel('timestep')\n", + " axes[3].xaxis.set_major_locator(MaxNLocator(integer=True))\n", + "\n", + " plt.tight_layout()\n", + " plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "4e695b9a", + "metadata": {}, + "source": [ + "Let's simulate the result generated by varying the initial $\\pi_{-1}$ and corresponding $p_{-1}$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ca010585", + "metadata": { + "mystnb": { + "figure": { + "caption": "Starting from different initial values of $\\pi_0$, paths of $m_t$ (top panel, log scale for $m$), $p_t$ (second panel, log scale for $p$), $\\pi_t$ (third panel), and $\\mu_t$ (bottom panel)", + "name": "pi0_path", + "width": "500px" + } + } + }, + "outputs": [], + "source": [ + "πs = np.linspace(π_l, π_u, 10)\n", + "\n", + "line_params = {'lw': 1.5, \n", + " 'marker': 'o',\n", + " 'markersize': 3}\n", + " \n", + "π_bars = (π_l, π_u)\n", + "draw_iterations(πs, model, line_params, π_bars, num_steps=80)" + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.5" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 168, + 179, + 183, + 195, + 199, + 212, + 220, + 259, + 271, + 280, + 288, + 319, + 323, + 334, + 338, + 349, + 362, + 396, + 400 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/laffer_adaptive.md b/book/_build/html/_sources/laffer_adaptive.md new file mode 100644 index 0000000..684f2e6 --- /dev/null +++ b/book/_build/html/_sources/laffer_adaptive.md @@ -0,0 +1,418 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.5 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Laffer Curves with Adaptive Expectations + +## Overview + +This lecture studies stationary and dynamic **Laffer curves** in the inflation tax rate in a non-linear version of the model studied in this lecture {doc}`money_inflation`. + +As in the lecture {doc}`money_inflation`, this lecture uses the log-linear version of the demand function for money that {cite}`Cagan` used in his classic paper in place of the linear demand function used in this lecture {doc}`money_inflation`. + +But now, instead of assuming ''rational expectations'' in the form of ''perfect foresight'', +we'll adopt the ''adaptive expectations'' assumption used by {cite}`Cagan` and {cite}`Friedman1956`. + +This means that instead of assuming that expected inflation $\pi_t^*$ is described by the "perfect foresight" or "rational expectations" hypothesis + +$$ +\pi_t^* = p_{t+1} - p_t +$$ + +that we adopted in lectures {doc}`money_inflation` and lectures {doc}`money_inflation_nonlinear`, we'll now assume that $\pi_t^*$ is determined by the adaptive expectations hypothesis described in equation {eq}`eq:adaptex` reported below. + +We shall discover that changing our hypothesis about expectations formation in this way will change some our findings and leave others intact. In particular, we shall discover that + +* replacing rational expectations with adaptive expectations leaves the two stationary inflation rates unchanged, but that $\ldots$ +* it reverses the perverse dynamics by making the **lower** stationary inflation rate the one to which the system typically converges +* a more plausible comparative dynamic outcome emerges in which now inflation can be **reduced** by running **lower** government deficits + +These more plausible comparative dynamics underlie the "old time religion" that states that +"inflation is always and everywhere caused by government deficits". + +These issues were studied by {cite}`bruno1990seigniorage`. + +Their purpose was to reverse what they thought were counter intuitive +predictions of their model under rational expectations (i.e., perfect foresight in this context) +by dropping rational expectations and instead assuming that people form expectations about future inflation rates according to the "adaptive expectations" scheme {eq}`eq:adaptex` described below. + +```{note} +{cite}`sargent1989least` had studied another way of selecting stationary equilibrium that involved replacing rational expectations with a model of learning via least squares regression. + {cite}`marcet2003recurrent` and {cite}`sargent2009conquest` extended that work and applied it to study recurrent high-inflation episodes in Latin America. +``` + +## The model + +Let + +* $m_t$ be the log of the money supply at the beginning of time $t$ +* $p_t$ be the log of the price level at time $t$ +* $\pi_t^*$ be the public's expectation of the rate of inflation between $t$ and $t+1$ + +The law of motion of the money supply is + +$$ +\exp(m_{t+1}) - \exp(m_t) = g \exp(p_t) +$$ (eq:ada_msupply) + +where $g$ is the part of government expenditures financed by printing money. + +Notice that equation {eq}`eq:ada_msupply` implies that + +$$ +m_{t+1} = \log[ \exp(m_t) + g \exp(p_t)] +$$ (eq:ada_msupply2) + +The demand function for money is + +$$ +m_{t+1} - p_t = -\alpha \pi_t^* +$$ (eq:ada_mdemand) + +where $\alpha \geq 0$. + +Expectations of inflation are governed by + +$$ +\pi_{t}^* = (1-\delta) (p_t - p_{t-1}) + \delta \pi_{t-1}^* +$$ (eq:adaptex) + +where $\delta \in (0,1)$ + +## Computing an equilibrium sequence + +Equation the expressions for $m_{t+1}$ provided by {eq}`eq:ada_mdemand` and {eq}`eq:ada_msupply2` and use equation {eq}`eq:adaptex` to eliminate $\pi_t^*$ to obtain +the following equation for $p_t$: + +$$ +\log[ \exp(m_t) + g \exp(p_t)] - p_t = -\alpha [(1-\delta) (p_t - p_{t-1}) + \delta \pi_{t-1}^*] +$$ (eq:pequation) + +**Pseudo-code** + +Here is the pseudo-code for our algorithm. + +Starting at time $0$ with initial conditions $(m_0, \pi_{-1}^*, p_{-1})$, for each $t \geq 0$ +deploy the following steps in order: + +* solve {eq}`eq:pequation` for $p_t$ +* solve equation {eq}`eq:adaptex` for $\pi_t^*$ +* solve equation {eq}`eq:ada_msupply2` for $m_{t+1}$ + +This completes the algorithm. + + +## Claims or conjectures + + +It will turn out that + +* if they exist, limiting values $\overline \pi$ and $\overline \mu$ will be equal + +* if limiting values exist, there are two possible limiting values, one high, one low + +* unlike the outcome in lecture {doc}`money_inflation_nonlinear`, for almost all initial log price levels and expected inflation rates $p_0, \pi_{t}^*$, the limiting $\overline \pi = \overline \mu$ is the **lower** steady state value + +* for each of the two possible limiting values $\bar \pi$ ,there is a unique initial log price level $p_0$ that implies that $\pi_t = \mu_t = \bar \mu$ for all $t \geq 0$ + + * this unique initial log price level solves $\log(\exp(m_0) + g \exp(p_0)) - p_0 = - \alpha \bar \pi $ + + * the preceding equation for $p_0$ comes from $m_1 - p_0 = - \alpha \bar \pi$ + +## Limiting values of inflation rate + +As in our earlier lecture {doc}`money_inflation_nonlinear`, we can compute the two prospective limiting values for $\bar \pi$ by studying the steady-state Laffer curve. + +Thus, in a **steady state** + +$$ +m_{t+1} - m_t = p_{t+1} - p_t = x \quad \forall t , +$$ + +where $x > 0 $ is a common rate of growth of logarithms of the money supply and price level. + +A few lines of algebra yields the following equation that $x$ satisfies + +$$ +\exp(-\alpha x) - \exp(-(1 + \alpha) x) = g +$$ (eq:ada_steadypi) + +where we require that + +$$ +g \leq \max_{x: x \geq 0} \exp(-\alpha x) - \exp(-(1 + \alpha) x) , +$$ (eq:ada_revmax) + +so that it is feasible to finance $g$ by printing money. + +The left side of {eq}`eq:ada_steadypi` is steady state revenue raised by printing money. + +The right side of {eq}`eq:ada_steadypi` is the quantity of time $t$ goods that the government raises by printing money. + +Soon we'll plot the left and right sides of equation {eq}`eq:ada_steadypi`. + +But first we'll write code that computes a steady-state +$\bar \pi$. + +Let's start by importing some libraries + +```{code-cell} ipython3 +from collections import namedtuple +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.ticker import MaxNLocator +from matplotlib.cm import get_cmap +from matplotlib.colors import to_rgba +import matplotlib +from scipy.optimize import root, fsolve +``` + ++++ {"user_expressions": []} + +Let's create a `namedtuple` to store the parameters of the model + +```{code-cell} ipython3 +LafferAdaptive = namedtuple('LafferAdaptive', + ["m0", # log of the money supply at t=0 + "α", # sensitivity of money demand + "g", # government expenditure + "δ"]) + +# Create a Cagan Laffer model +def create_model(α=0.5, m0=np.log(100), g=0.35, δ=0.9): + return LafferAdaptive(α=α, m0=m0, g=g, δ=δ) + +model = create_model() +``` + +Now we write code that computes steady-state $\bar \pi$s. + +```{code-cell} ipython3 +# Define formula for π_bar +def solve_π(x, α, g): + return np.exp(-α * x) - np.exp(-(1 + α) * x) - g + +def solve_π_bar(model, x0): + π_bar = fsolve(solve_π, x0=x0, xtol=1e-10, args=(model.α, model.g))[0] + return π_bar + +# Solve for the two steady state of π +π_l = solve_π_bar(model, x0=0.6) +π_u = solve_π_bar(model, x0=3.0) +print(f'The two steady state of π are: {π_l, π_u}') +``` + +We find two steady state $\bar \pi$ values + +## Steady-state Laffer curve + +The following figure plots the steady-state Laffer curve together with the two stationary inflation rates. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Seigniorage as function of steady-state inflation. The dashed brown lines + indicate $\pi_l$ and $\pi_u$. + name: laffer_curve_adaptive + width: 500px +--- +def compute_seign(x, α): + return np.exp(-α * x) - np.exp(-(1 + α) * x) + +def plot_laffer(model, πs): + α, g = model.α, model.g + + # Generate π values + x_values = np.linspace(0, 5, 1000) + + # Compute corresponding seigniorage values for the function + y_values = compute_seign(x_values, α) + + # Plot the function + plt.plot(x_values, y_values, + label=f'$exp((-{α})x) - exp(- (1- {α}) x)$') + for π, label in zip(πs, ['$\pi_l$', '$\pi_u$']): + plt.text(π, plt.gca().get_ylim()[0]*2, + label, horizontalalignment='center', + color='brown', size=10) + plt.axvline(π, color='brown', linestyle='--') + plt.axhline(g, color='red', linewidth=0.5, + linestyle='--', label='g') + plt.xlabel('$\pi$') + plt.ylabel('seigniorage') + plt.legend() + plt.grid(True) + plt.show() + +# Steady state Laffer curve +plot_laffer(model, (π_l, π_u)) +``` + +## Associated initial price levels + +Now that we have our hands on the two possible steady states, we can compute two initial log price levels $p_{-1}$, which as initial conditions, imply that $\pi_t = \bar \pi $ for all $t \geq 0$. + +In particular, to initiate a fixed point of the dynamic Laffer curve dynamics, we set + +$$ +p_{-1} = m_0 + \alpha \pi^* +$$ + +```{code-cell} ipython3 +def solve_p_init(model, π_star): + m0, α = model.m0, model.α + return m0 + α*π_star + + +# Compute two initial price levels associated with π_l and π_u +p_l, p_u = map(lambda π: solve_p_init(model, π), (π_l, π_u)) +print('Associated initial p_{-1}s', f'are: {p_l, p_u}') +``` + +### Verification + +To start, let's write some code to verify that if we initial $\pi_{-1}^*,p_{-1}$ appropriately, the inflation rate $\pi_t$ will be constant for all $t \geq 0$ (at either $\pi_u$ or $\pi_l$ depending on the initial condition) + +The following code verifies this. + +```{code-cell} ipython3 +def solve_laffer_adapt(p_init, π_init, model, num_steps): + m0, α, δ, g = model.m0, model.α, model.δ, model.g + + m_seq = np.nan * np.ones(num_steps+1) + π_seq = np.nan * np.ones(num_steps) + p_seq = np.nan * np.ones(num_steps) + μ_seq = np.nan * np.ones(num_steps) + + m_seq[1] = m0 + π_seq[0] = π_init + p_seq[0] = p_init + + for t in range(1, num_steps): + # Solve p_t + def p_t(pt): + return np.log(np.exp(m_seq[t]) + g * np.exp(pt)) \ + - pt + α * ((1-δ)*(pt - p_seq[t-1]) + δ*π_seq[t-1]) + + p_seq[t] = root(fun=p_t, x0=p_seq[t-1]).x[0] + + # Solve π_t + π_seq[t] = (1-δ) * (p_seq[t]-p_seq[t-1]) + δ*π_seq[t-1] + + # Solve m_t + m_seq[t+1] = np.log(np.exp(m_seq[t]) + g*np.exp(p_seq[t])) + + # Solve μ_t + μ_seq[t] = m_seq[t+1] - m_seq[t] + + return π_seq, μ_seq, m_seq, p_seq +``` + +Compute limiting values starting from $p_{-1}$ associated with $\pi_l$ + +```{code-cell} ipython3 +π_seq, μ_seq, m_seq, p_seq = solve_laffer_adapt(p_l, π_l, model, 50) + +# Check steady state m_{t+1} - m_t and p_{t+1} - p_t +print('m_{t+1} - m_t:', m_seq[-1] - m_seq[-2]) +print('p_{t+1} - p_t:', p_seq[-1] - p_seq[-2]) + +# Check if exp(-αx) - exp(-(1 + α)x) = g +eq_g = lambda x: np.exp(-model.α * x) - np.exp(-(1 + model.α) * x) + +print('eq_g == g:', np.isclose(eq_g(m_seq[-1] - m_seq[-2]), model.g)) +``` + +Compute limiting values starting from $p_{-1}$ associated with $\pi_u$ + +```{code-cell} ipython3 +π_seq, μ_seq, m_seq, p_seq = solve_laffer_adapt(p_u, π_u, model, 50) + +# Check steady state m_{t+1} - m_t and p_{t+1} - p_t +print('m_{t+1} - m_t:', m_seq[-1] - m_seq[-2]) +print('p_{t+1} - p_t:', p_seq[-1] - p_seq[-2]) + +# Check if exp(-αx) - exp(-(1 + α)x) = g +eq_g = lambda x: np.exp(-model.α * x) - np.exp(-(1 + model.α) * x) + +print('eq_g == g:', np.isclose(eq_g(m_seq[-1] - m_seq[-2]), model.g)) +``` + +## Slippery side of Laffer curve dynamics + +We are now equipped to compute time series starting from different $p_{-1}, \pi_{-1}^*$ settings, analogous to those in this lecture {doc}`money_inflation` and this lecture {doc}`money_inflation_nonlinear`. + +Now we'll study how outcomes unfold when we start $p_{-1}, \pi_{-1}^*$ away from a stationary point of the dynamic Laffer curve, i.e., away from either $\pi_u$ or $ \pi_l$. + +To construct a perturbation pair $\check p_{-1}, \check \pi_{-1}^*$we'll implement the following pseudo code: + +* set $\check \pi_{-1}^* $ not equal to one of the stationary points $\pi_u$ or $ \pi_l$. +* set $\check p_{-1} = m_0 + \alpha \check \pi_{-1}^*$ + +```{code-cell} ipython3 +:tags: [hide-cell] + +def draw_iterations(π0s, model, line_params, π_bars, num_steps): + fig, axes = plt.subplots(4, 1, figsize=(8, 12), sharex=True) + + for ax in axes[:2]: + ax.set_yscale('log') + + for i, π0 in enumerate(π0s): + p0 = model.m0 + model.α*π0 + π_seq, μ_seq, m_seq, p_seq = solve_laffer_adapt(p0, π0, model, num_steps) + + axes[0].plot(np.arange(num_steps), m_seq[1:], **line_params) + axes[1].plot(np.arange(-1, num_steps-1), p_seq, **line_params) + axes[2].plot(np.arange(-1, num_steps-1), π_seq, **line_params) + axes[3].plot(np.arange(num_steps), μ_seq, **line_params) + + axes[2].axhline(y=π_bars[0], color='grey', linestyle='--', lw=1.5, alpha=0.6) + axes[2].axhline(y=π_bars[1], color='grey', linestyle='--', lw=1.5, alpha=0.6) + axes[2].text(num_steps * 1.07, π_bars[0], '$\pi_l$', verticalalignment='center', + color='grey', size=10) + axes[2].text(num_steps * 1.07, π_bars[1], '$\pi_u$', verticalalignment='center', + color='grey', size=10) + + axes[0].set_ylabel('$m_t$') + axes[1].set_ylabel('$p_t$') + axes[2].set_ylabel('$\pi_t$') + axes[3].set_ylabel('$\mu_t$') + axes[3].set_xlabel('timestep') + axes[3].xaxis.set_major_locator(MaxNLocator(integer=True)) + + plt.tight_layout() + plt.show() +``` + +Let's simulate the result generated by varying the initial $\pi_{-1}$ and corresponding $p_{-1}$ + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Starting from different initial values of $\pi_0$, paths of $m_t$ (top + panel, log scale for $m$), $p_t$ (second panel, log scale for $p$), $\pi_t$ (third panel), and $\mu_t$ (bottom + panel) + name: pi0_path + width: 500px +--- +πs = np.linspace(π_l, π_u, 10) + +line_params = {'lw': 1.5, + 'marker': 'o', + 'markersize': 3} + +π_bars = (π_l, π_u) +draw_iterations(πs, model, line_params, π_bars, num_steps=80) +``` diff --git a/content/lectures/lake_model.ipynb b/book/_build/html/_sources/lake_model.ipynb similarity index 91% rename from content/lectures/lake_model.ipynb rename to book/_build/html/_sources/lake_model.ipynb index 75f1f2c..87906cf 100644 --- a/content/lectures/lake_model.ipynb +++ b/book/_build/html/_sources/lake_model.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "8bd960f9", + "id": "6a162d7a", "metadata": {}, "source": [ "# A Lake Model of Employment\n", @@ -15,50 +15,17 @@ { "cell_type": "code", "execution_count": null, - "id": "c3e7ee3e", - "metadata": { - "tags": [ - "hide-output" - ] - }, - "outputs": [], - "source": [ - "%pip install graphviz" - ] - }, - { - "cell_type": "markdown", - "id": "e9e548cd", - "metadata": {}, - "source": [ - "```{admonition} graphviz\n", - ":class: warning\n", - "If you are running this lecture locally it requires [graphviz](https://www.graphviz.org)\n", - "to be installed on your computer. Installation instructions for graphviz can be found\n", - "[here](https://www.graphviz.org/download/) \n", - "```\n", - "\n", - "This lecture studies a model of employment and unemployment flows in a large\n", - "population called the **lake model**.\n", - "\n", - "We will use the following imports in this lecture." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "82614325", + "id": "fbb191ba", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from graphviz import Digraph" + "import matplotlib.pyplot as plt" ] }, { "cell_type": "markdown", - "id": "78a8d489", + "id": "f3a2b73f", "metadata": {}, "source": [ "## The Lake model\n", @@ -75,42 +42,14 @@ "3. employed workers separate from their jobs at rate $\\alpha$.\n", "4. unemployed workers find jobs at rate $\\lambda$.\n", "\n", - "The below graph illustrates the lake model." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6284d477", - "metadata": {}, - "outputs": [], - "source": [ - "# Create Digraph object\n", - "G = Digraph()\n", - "G.attr(rankdir='LR')\n", - "\n", - "# Add nodes\n", - "G.attr('node', shape='circle')\n", - "G.node('1', 'New entrants', color='blue')\n", - "G.node('2', 'Unemployed')\n", - "G.node('3', 'Employed')\n", - "\n", - "# Add edges\n", - "G.edge('1', '2', label='b')\n", - "G.edge('2', '3', label='λ(1-d)')\n", - "G.edge('3', '2', label='α(1-d)')\n", - "G.edge('2', '2', label='(1-λ)(1-d)')\n", - "G.edge('3', '3', label='(1-α)(1-d)')\n", - "\n", - "# Show graphviz\n", - "G" - ] - }, - { - "cell_type": "markdown", - "id": "d72d6501", - "metadata": {}, - "source": [ + "The graph below illustrates the lake model.\n", + "\n", + "```{figure} /_static/lecture_specific/lake_model/lake_model_worker.png\n", + ":name: lake_model_graphviz\n", + "\n", + "An illustration of the lake model\n", + "```\n", + "\n", "## Dynamics\n", "\n", "Let $e_t$ and $u_t$ be the number of employed and unemployed workers at time $t$ respectively.\n", @@ -170,7 +109,7 @@ { "cell_type": "code", "execution_count": null, - "id": "301b8022", + "id": "d0a2ae6f", "metadata": {}, "outputs": [], "source": [ @@ -234,7 +173,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8680dad0", + "id": "22b9eb48", "metadata": {}, "outputs": [], "source": [ @@ -269,7 +208,7 @@ }, { "cell_type": "markdown", - "id": "10271fdd", + "id": "d0be15d1", "metadata": {}, "source": [ "Not surprisingly, we observe that labor force $n_t$ increases at a constant rate.\n", @@ -297,11 +236,11 @@ "\n", "Moreover, the times series of unemployment and employment seems to grow at some stable rates in the long run.\n", "\n", - "### The application of erron-Frobenius theorem\n", + "### The application of Perron-Frobenius theorem\n", "\n", "Since by intuition if we consider unemployment pool and employment pool as a closed system, the growth should be similar to the labor force.\n", "\n", - "We next ask whether the long run growth rates of $e_t$ and $u_t$\n", + "We next ask whether the long-run growth rates of $e_t$ and $u_t$\n", "also dominated by $1+b-d$ as labor force.\n", "\n", "The answer will be clearer if we appeal to {ref}`Perron-Frobenius theorem`.\n", @@ -379,7 +318,7 @@ { "cell_type": "code", "execution_count": null, - "id": "13aae7b4", + "id": "febbe1c7", "metadata": {}, "outputs": [], "source": [ @@ -458,7 +397,7 @@ { "cell_type": "code", "execution_count": null, - "id": "14362075", + "id": "c3989e5c", "metadata": {}, "outputs": [], "source": [ @@ -469,7 +408,7 @@ }, { "cell_type": "markdown", - "id": "416dd638", + "id": "b48998f2", "metadata": {}, "source": [ "Since $\\bar{x}$ is an eigenvector corresponding to the eigenvalue $r(A)$, all the vectors in the set\n", @@ -498,7 +437,7 @@ { "cell_type": "code", "execution_count": null, - "id": "2013610b", + "id": "fd26850c", "metadata": {}, "outputs": [], "source": [ @@ -508,7 +447,7 @@ }, { "cell_type": "markdown", - "id": "c90709ff", + "id": "b502c931", "metadata": {}, "source": [ "Thus, while the sequence of iterates still moves towards the dominant eigenvector $\\bar{x}$, in this case\n", @@ -575,7 +514,7 @@ { "cell_type": "code", "execution_count": null, - "id": "d39deb7d", + "id": "32bf2828", "metadata": {}, "outputs": [], "source": [ @@ -615,7 +554,7 @@ }, { "cell_type": "markdown", - "id": "ca9f5572", + "id": "3d56faff", "metadata": {}, "source": [ "To provide more intuition for convergence, we further explain the convergence below without the Perron-Frobenius theorem.\n", @@ -681,7 +620,7 @@ { "cell_type": "code", "execution_count": null, - "id": "09f35e55", + "id": "4843df8a", "metadata": {}, "outputs": [], "source": [ @@ -702,7 +641,7 @@ }, { "cell_type": "markdown", - "id": "7a4a0fc9", + "id": "196e7f9e", "metadata": {}, "source": [ "```{solution-end}\n", @@ -711,12 +650,37 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.4" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 12, + 20, + 23, + 102, + 160, + 188, + 293, + 366, + 370, + 394, + 397, + 459, + 492, + 553, + 567 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/lake_model.md b/book/_build/html/_sources/lake_model.md new file mode 100644 index 0000000..f70da94 --- /dev/null +++ b/book/_build/html/_sources/lake_model.md @@ -0,0 +1,570 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.4 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# A Lake Model of Employment + +## Outline + +In addition to what's in Anaconda, this lecture will need the following libraries: + +```{code-cell} ipython3 +import numpy as np +import matplotlib.pyplot as plt +``` + +## The Lake model + +This model is sometimes called the **lake model** because there are two pools of workers: + +1. those who are currently employed. +2. those who are currently unemployed but are seeking employment. + +The "flows" between the two lakes are as follows: + +1. workers exit the labor market at rate $d$. +2. new workers enter the labor market at rate $b$. +3. employed workers separate from their jobs at rate $\alpha$. +4. unemployed workers find jobs at rate $\lambda$. + +The graph below illustrates the lake model. + +```{figure} /_static/lecture_specific/lake_model/lake_model_worker.png +:name: lake_model_graphviz + +An illustration of the lake model +``` + +## Dynamics + +Let $e_t$ and $u_t$ be the number of employed and unemployed workers at time $t$ respectively. + +The total population of workers is $n_t = e_t + u_t$. + +The number of unemployed and employed workers thus evolves according to: + +```{math} +:label: lake_model +\begin{aligned} + u_{t+1} &= (1-d)(1-\lambda)u_t + \alpha(1-d)e_t + bn_t \\ + &= ((1-d)(1-\lambda) + b)u_t + (\alpha(1-d) + b)e_t \\ + e_{t+1} &= (1-d)\lambda u_t + (1 - \alpha)(1-d)e_t +\end{aligned} +``` + +We can arrange {eq}`lake_model` as a linear system of equations in matrix form $x_{t+1} = Ax_t$ where + +$$ +x_{t+1} = +\begin{bmatrix} + u_{t+1} \\ + e_{t+1} +\end{bmatrix} +\quad +A = +\begin{bmatrix} + (1-d)(1-\lambda) + b & \alpha(1-d) + b \\ + (1-d)\lambda & (1 - \alpha)(1-d) +\end{bmatrix} +\quad \text{and} \quad +x_t = +\begin{bmatrix} + u_t \\ + e_t +\end{bmatrix}. +$$ + +Suppose at $t=0$ we have $x_0 = \begin{bmatrix} u_0 & e_0 \end{bmatrix}^\top$. + +Then, $x_1=Ax_0$, $x_2=Ax_1=A^2x_0$ and thus $x_t = A^tx_0$. + +Thus the long-run outcomes of this system may depend on the initial condition $x_0$ and the matrix $A$. + +We are interested in how $u_t$ and $e_t$ evolve over time. + +What long-run unemployment rate and employment rate should we expect? + +Do long-run outcomes depend on the initial values $(u_0, e_o)$? + +### Visualising the long-run outcomes + +Let us first plot the time series of unemployment $u_t$, employment $e_t$, and labor force $n_t$. + +```{code-cell} ipython3 +class LakeModel: + """ + Solves the lake model and computes dynamics of the unemployment stocks and + rates. + + Parameters: + ------------ + λ : scalar + The job finding rate for currently unemployed workers + α : scalar + The dismissal rate for currently employed workers + b : scalar + Entry rate into the labor force + d : scalar + Exit rate from the labor force + + """ + def __init__(self, λ=0.1, α=0.013, b=0.0124, d=0.00822): + self.λ, self.α, self.b, self.d = λ, α, b, d + + λ, α, b, d = self.λ, self.α, self.b, self.d + self.g = b - d + g = self.g + + self.A = np.array([[(1-d)*(1-λ) + b, α*(1-d) + b], + [ (1-d)*λ, (1-α)*(1-d)]]) + + + self.ū = (1 + g - (1 - d) * (1 - α)) / (1 + g - (1 - d) * (1 - α) + (1 - d) * λ) + self.ē = 1 - self.ū + + + def simulate_path(self, x0, T=1000): + """ + Simulates the sequence of employment and unemployment + + Parameters + ---------- + x0 : array + Contains initial values (u0,e0) + T : int + Number of periods to simulate + + Returns + ---------- + x : iterator + Contains sequence of employment and unemployment rates + + """ + x0 = np.atleast_1d(x0) # Recast as array just in case + x_ts= np.zeros((2, T)) + x_ts[:, 0] = x0 + for t in range(1, T): + x_ts[:, t] = self.A @ x_ts[:, t-1] + return x_ts +``` + +```{code-cell} ipython3 +lm = LakeModel() +e_0 = 0.92 # Initial employment +u_0 = 1 - e_0 # Initial unemployment, given initial n_0 = 1 + +lm = LakeModel() +T = 100 # Simulation length + +x_0 = (u_0, e_0) +x_path = lm.simulate_path(x_0, T) + +fig, axes = plt.subplots(3, 1, figsize=(10, 8)) + + +axes[0].plot(x_path[0, :], lw=2) +axes[0].set_title('Unemployment') + +axes[1].plot(x_path[1, :], lw=2) +axes[1].set_title('Employment') + +axes[2].plot(x_path.sum(0), lw=2) +axes[2].set_title('Labor force') + +for ax in axes: + ax.grid() + +plt.tight_layout() +plt.show() +``` + +Not surprisingly, we observe that labor force $n_t$ increases at a constant rate. + +This coincides with the fact there is only one inflow source (new entrants pool) to unemployment and employment pools. + +The inflow and outflow of labor market system +is determined by constant exit rate and entry rate of labor market in the long run. + +In detail, let $\mathbb{1}=[1, 1]^\top$ be a vector of ones. + +Observe that + +$$ + \begin{aligned} + n_{t+1} &= u_{t+1} + e_{t+1} \\ + &= \mathbb{1}^\top x_{t+1} \\ + &= \mathbb{1}^\top A x_t \\ + &= (1 + b - d) (u_t + e_t) \\ + &= (1 + b - d) n_t. + \end{aligned} +$$ + +Hence, the growth rate of $n_t$ is fixed at $1 + b - d$. + +Moreover, the times series of unemployment and employment seems to grow at some stable rates in the long run. + +### The application of Perron-Frobenius theorem + +Since by intuition if we consider unemployment pool and employment pool as a closed system, the growth should be similar to the labor force. + +We next ask whether the long-run growth rates of $e_t$ and $u_t$ +also dominated by $1+b-d$ as labor force. + +The answer will be clearer if we appeal to {ref}`Perron-Frobenius theorem`. + +The importance of the Perron-Frobenius theorem stems from the fact that +firstly in the real world most matrices we encounter are nonnegative matrices. + +Secondly, many important models are simply linear iterative models that +begin with an initial condition $x_0$ and then evolve recursively by the rule +$x_{t+1} = Ax_t$ or in short $x_t = A^tx_0$. + +This theorem helps characterise the dominant eigenvalue $r(A)$ which +determines the behavior of this iterative process. + +#### Dominant eigenvector + +We now illustrate the power of the Perron-Frobenius theorem by showing how it +helps us to analyze the lake model. + +Since $A$ is a nonnegative and irreducible matrix, the Perron-Frobenius theorem implies that: + +- the spectral radius $r(A)$ is an eigenvalue of $A$, where + +$$ + r(A) := \max\{|\lambda|: \lambda \text{ is an eigenvalue of } A \} +$$ + +- any other eigenvalue $\lambda$ in absolute value is strictly smaller than $r(A)$: $|\lambda|< r(A)$, + +- there exist unique and everywhere positive right eigenvector $\phi$ (column vector) and left eigenvector $\psi$ (row vector): + +$$ + A \phi = r(A) \phi, \quad \psi A = r(A) \psi +$$ + +- if further $A$ is positive, then with $<\psi, \phi> = \psi \phi=1$ we have + +$$ + r(A)^{-t} A^t \to \phi \psi +$$ + +The last statement implies that the magnitude of $A^t$ is identical to the magnitude of $r(A)^t$ in the long run, where $r(A)$ can be considered as the dominant eigenvalue in this lecture. + +Therefore, the magnitude $x_t = A^t x_0$ is also dominated by $r(A)^t$ in the long run. + +Recall that the spectral radius is bounded by column sums: for $A \geq 0$, we have + +```{math} +:label: PF_bounds +\min_j \text{colsum}_j (A) \leq r(A) \leq \max_j \text{colsum}_j (A) +``` + +Note that $\text{colsum}_j(A) = 1 + b - d$ for $j=1,2$ and by {eq}`PF_bounds` we can thus conclude that the dominant eigenvalue +is $r(A) = 1 + b - d$. + +Denote $g = b - d$ as the overall growth rate of the total labor force, so that $r(A) = 1 + g$. + +The Perron-Frobenius implies that there is a unique positive eigenvector $\bar{x} = \begin{bmatrix} \bar{u} \\ \bar{e} \end{bmatrix}$ +such that $A\bar{x} = r(A)\bar{x}$ and $\begin{bmatrix} 1 & 1 \end{bmatrix} \bar{x} = 1$: + +```{math} +:label: steady_x + +\begin{aligned} + \bar{u} & = \frac{b + \alpha (1-d)}{b + (\alpha+\lambda)(1-d)} \\ + \bar{e} & = \frac{\lambda(1-d)}{b + (\alpha+\lambda)(1-d)} +\end{aligned} +``` + +Since $\bar{x}$ is the eigenvector corresponding to the dominant eigenvalue $r(A)$, we call $\bar{x}$ the dominant eigenvector. + +This dominant eigenvector plays an important role in determining long-run outcomes as illustrated below. + +```{code-cell} ipython3 +def plot_time_paths(lm, x0=None, T=1000, ax=None): + """ + Plots the simulated time series. + + Parameters + ---------- + lm : class + Lake Model + x0 : array + Contains some different initial values. + T : int + Number of periods to simulate + + """ + + + if x0 is None: + x0 = np.array([[5.0, 0.1]]) + + ū, ē = lm.ū, lm.ē + + x0 = np.atleast_2d(x0) + + if ax is None: + fig, ax = plt.subplots(figsize=(10, 8)) + # Plot line D + s = 10 + ax.plot([0, s * ū], [0, s * ē], "k--", lw=1, label='set $D$') + + # Set the axes through the origin + for spine in ["left", "bottom"]: + ax.spines[spine].set_position("zero") + for spine in ["right", "top"]: + ax.spines[spine].set_color("none") + + ax.set_xlim(-2, 6) + ax.set_ylim(-2, 6) + ax.set_xlabel("unemployed workforce") + ax.set_ylabel("employed workforce") + ax.set_xticks((0, 6)) + ax.set_yticks((0, 6)) + + + + + # Plot time series + for x in x0: + x_ts = lm.simulate_path(x0=x) + + ax.scatter(x_ts[0, :], x_ts[1, :], s=4,) + + u0, e0 = x + ax.plot([u0], [e0], "ko", ms=2, alpha=0.6) + ax.annotate(f'$x_0 = ({u0},{e0})$', + xy=(u0, e0), + xycoords="data", + xytext=(0, 20), + textcoords="offset points", + arrowprops=dict(arrowstyle = "->")) + + ax.plot([ū], [ē], "ko", ms=4, alpha=0.6) + ax.annotate(r'$\bar{x}$', + xy=(ū, ē), + xycoords="data", + xytext=(20, -20), + textcoords="offset points", + arrowprops=dict(arrowstyle = "->")) + + if ax is None: + plt.show() +``` + +```{code-cell} ipython3 +lm = LakeModel(α=0.01, λ=0.1, d=0.02, b=0.025) +x0 = ((5.0, 0.1), (0.1, 4.0), (2.0, 1.0)) +plot_time_paths(lm, x0=x0) +``` + +Since $\bar{x}$ is an eigenvector corresponding to the eigenvalue $r(A)$, all the vectors in the set +$D := \{ x \in \mathbb{R}^2 : x = \alpha \bar{x} \; \text{for some} \; \alpha >0 \}$ are also eigenvectors corresponding +to $r(A)$. + +This set $D$ is represented by a dashed line in the above figure. + +The graph illustrates that for two distinct initial conditions $x_0$ the sequences of iterates $(A^t x_0)_{t \geq 0}$ move towards $D$ over time. + +This suggests that all such sequences share strong similarities in the long run, determined by the dominant eigenvector $\bar{x}$. + +#### Negative growth rate + +In the example illustrated above we considered parameters such that overall growth rate of the labor force $g>0$. + +Suppose now we are faced with a situation where the $g<0$, i.e., negative growth in the labor force. + +This means that $b-d<0$, i.e., workers exit the market faster than they enter. + +What would the behavior of the iterative sequence $x_{t+1} = Ax_t$ be now? + +This is visualised below. + +```{code-cell} ipython3 +lm = LakeModel(α=0.01, λ=0.1, d=0.025, b=0.02) +plot_time_paths(lm, x0=x0) +``` + +Thus, while the sequence of iterates still moves towards the dominant eigenvector $\bar{x}$, in this case +they converge to the origin. + +This is a result of the fact that $r(A)<1$, which ensures that the iterative sequence $(A^t x_0)_{t \geq 0}$ will converge +to some point, in this case to $(0,0)$. + +This leads us to the next result. + +### Properties + +Since the column sums of $A$ are $r(A)=1$, the left eigenvector is $\mathbb{1}^\top=[1, 1]$. + +Perron-Frobenius theory implies that + +$$ +r(A)^{-t} A^{t} \approx \bar{x} \mathbb{1}^\top = \begin{bmatrix} \bar{u} & \bar{u} \\ \bar{e} & \bar{e} \end{bmatrix}. +$$ + +As a result, for any $x_0 = (u_0, e_0)^\top$, we have + +$$ +\begin{aligned} +x_t = A^t x_0 &\approx r(A)^t \begin{bmatrix} \bar{u} & \bar{u} \\ \bar{e} & \bar{e} \end{bmatrix} \begin{bmatrix}u_0 \\ e_0 \end{bmatrix} \\ +&= (1+g)^t(u_0 + e_0) \begin{bmatrix}\bar{u} \\ \bar{e} \end{bmatrix} \\ +&= (1 + g)^t n_0 \bar{x} \\ +&= n_t \bar{x}. +\end{aligned} +$$ + +as $t$ is large enough. + +We see that the growth of $u_t$ and $e_t$ also dominated by $r(A) = 1+g$ in the long run: $x_t$ grows along $D$ as $r(A) > 1$ and converges to $(0, 0)$ as $r(A) < 1$. + +Moreover, the long-run unemployment and employment are steady fractions of $n_t$. + +The latter implies that $\bar{u}$ and $\bar{e}$ are long-run unemployment rate and employment rate, respectively. + +In detail, we have the unemployment rates and employment rates: $x_t / n_t = A^t n_0 / n_t \to \bar{x}$ as $t \to \infty$. + +To illustrate the dynamics of the rates, let $\hat{A} := A / (1+g)$ be the transition matrix of $r_t := x_t/ n_t$. + +The dynamics of the rates follow + +$$ +r_{t+1} = \frac{x_{t+1}}{n_{t+1}} = \frac{x_{t+1}}{(1+g) n_{t}} = \frac{A x_t}{(1+g)n_t} = \hat{A} \frac{x_t}{n_t} +=\hat{A} r_t. +$$ + +Observe that the column sums of $\hat{A}$ are all one so that $r(\hat{A})=1$. + +One can check that $\bar{x}$ is also the right eigenvector of $\hat{A}$ corresponding to $r(\hat{A})$ that $\bar{x} = \hat{A} \bar{x}$. + +Moreover, $\hat{A}^t r_0 \to \bar{x}$ as $t \to \infty$ for any $r_0 = x_0 / n_0$, since the above discussion implies + +$$ +r_t = \hat{A}^t r_0 = (1+g)^{-t} A^t r_0 = r(A)^{-t} A^t r_0 \to \begin{bmatrix} \bar{u} & \bar{u} \\ \bar{e} & \bar{e} \end{bmatrix} r_0 = \begin{bmatrix} \bar{u} \\ \bar{e} \end{bmatrix}. +$$ + +This is illustrated below. + +```{code-cell} ipython3 +lm = LakeModel() +e_0 = 0.92 # Initial employment +u_0 = 1 - e_0 # Initial unemployment, given initial n_0 = 1 + +lm = LakeModel() +T = 100 # Simulation length + +x_0 = (u_0, e_0) + +x_path = lm.simulate_path(x_0, T) + +rate_path = x_path / x_path.sum(0) + +fig, axes = plt.subplots(2, 1, figsize=(10, 8)) + +# Plot steady ū and ē +axes[0].hlines(lm.ū, 0, T, 'r', '--', lw=2, label='ū') +axes[1].hlines(lm.ē, 0, T, 'r', '--', lw=2, label='ē') + +titles = ['Unemployment rate', 'Employment rate'] +locations = ['lower right', 'upper right'] + +# Plot unemployment rate and employment rate +for i, ax in enumerate(axes): + ax.plot(rate_path[i, :], lw=2, alpha=0.6) + ax.set_title(titles[i]) + ax.grid() + ax.legend(loc=locations[i]) + + +plt.tight_layout() +plt.show() +``` + +To provide more intuition for convergence, we further explain the convergence below without the Perron-Frobenius theorem. + +Suppose that $\hat{A} = P D P^{-1}$ is diagonalizable, where $P = [v_1, v_2]$ consists of eigenvectors $v_1$ and $v_2$ of $\hat{A}$ +corresponding to eigenvalues $\gamma_1$ and $\gamma_2$ respectively, +and $D = \text{diag}(\gamma_1, \gamma_2)$. + +Let $\gamma_1 = r(\hat{A})=1$ and $|\gamma_2| < \gamma_1$, so that the spectral radius is a dominant eigenvalue. + +The dynamics of the rates follow $r_{t+1} = \hat{A} r_t$, where $r_0$ is a probability vector: $\sum_j r_{0,j}=1$. + +Consider $z_t = P^{-1} r_t $. + +Then, we have $z_{t+1} = P^{-1} r_{t+1} = P^{-1} \hat{A} r_t = P^{-1} \hat{A} P z_t = D z_t$. + +Hence, we obtain $z_t = D^t z_0$, and for some $z_0 = (c_1, c_2)^\top$ we have + +$$ +r_t = P z_t = \begin{bmatrix} v_1 & v_2 \end{bmatrix} \begin{bmatrix} \gamma_1^t & 0 \\ 0 & \gamma_2^t \end{bmatrix} +\begin{bmatrix} c_1 \\ c_2 \end{bmatrix} = c_1 \gamma_1^t v_1 + c_2 \gamma_2^t v_2. +$$ + +Since $|\gamma_2| < |\gamma_1|=1$, the second term in the right hand side converges to zero. + +Therefore, the convergence follows $r_t \to c_1 v_1$. + +Since the column sums of $\hat{A}$ are one and $r_0$ is a probability vector, $r_t$ must be a probability vector. + +In this case, $c_1 v_1$ must be a normalized eigenvector, so $c_1 v_1 = \bar{x}$ and then $r_t \to \bar{x}$. + +## Exercise + +```{exercise-start} Evolution of unemployment and employment rate +:label: lake_model_ex1 +``` + +How do the long-run unemployment rate and employment rate evolve if there is an increase in the separation rate $\alpha$ +or a decrease in job finding rate $\lambda$? + +Is the result compatible with your intuition? + +Plot the graph to illustrate how the line $D := \{ x \in \mathbb{R}^2 : x = \alpha \bar{x} \; \text{for some} \; \alpha >0 \}$ +shifts in the unemployment-employment space. + +```{exercise-end} +``` + +```{solution-start} lake_model_ex1 +:class: dropdown +``` + +Eq. {eq}`steady_x` implies that the long-run unemployment rate will increase, and the employment rate will decrease +if $\alpha$ increases or $\lambda$ decreases. + +Suppose first that $\alpha=0.01, \lambda=0.1, d=0.02, b=0.025$. +Assume that $\alpha$ increases to $0.04$. + +The below graph illustrates that the line $D$ shifts clockwise downward, which indicates that +the fraction of unemployment rises as the separation rate increases. + +```{code-cell} ipython3 +fig, ax = plt.subplots(figsize=(10, 8)) + +lm = LakeModel(α=0.01, λ=0.1, d=0.02, b=0.025) +plot_time_paths(lm, ax=ax) +s=10 +ax.plot([0, s * lm.ū], [0, s * lm.ē], "k--", lw=1, label='set $D$, α=0.01') + +lm = LakeModel(α=0.04, λ=0.1, d=0.02, b=0.025) +plot_time_paths(lm, ax=ax) +ax.plot([0, s * lm.ū], [0, s * lm.ē], "r--", lw=1, label='set $D$, α=0.04') + +ax.legend(loc='best') +plt.show() +``` + +```{solution-end} +``` diff --git a/content/lectures/linear_equations.ipynb b/book/_build/html/_sources/linear_equations.ipynb similarity index 83% rename from content/lectures/linear_equations.ipynb rename to book/_build/html/_sources/linear_equations.ipynb index 966873c..3ea226b 100644 --- a/content/lectures/linear_equations.ipynb +++ b/book/_build/html/_sources/linear_equations.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "eba361dc", + "id": "d7f9baa3", "metadata": {}, "source": [ "# Linear Equations and Matrix Algebra\n", @@ -10,10 +10,6 @@ "```{index} single: Linear Equations and Matrix Algebra\n", "```\n", "\n", - "```{contents} Contents\n", - ":depth: 2\n", - "```\n", - "\n", "## Overview\n", "\n", "Many problems in economics and finance require solving linear equations.\n", @@ -27,7 +23,7 @@ "\n", "But often we need to consider markets containing many goods.\n", "\n", - "In this case we face large systems of linear equations, with many equations\n", + "In the multiple goods case we face large systems of linear equations, with many equations\n", "and unknowns.\n", "\n", "To handle such systems we need two things:\n", @@ -37,27 +33,26 @@ "\n", "This lecture covers these steps.\n", "\n", - "We will use the following imports:" + "We will use the following packages:" ] }, { "cell_type": "code", "execution_count": null, - "id": "abca3d1f", + "id": "458c223d", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "plt.rcParams[\"figure.figsize\"] = (11, 5) # set default figure size" + "import matplotlib.pyplot as plt" ] }, { "cell_type": "markdown", - "id": "21be7499", + "id": "cfa7456d", "metadata": {}, "source": [ - "## A Two Good Example\n", + "## A two good example\n", "\n", "In this section we discuss a simple two good example and solve it by\n", "\n", @@ -67,11 +62,11 @@ "The second method is more general, as we will see.\n", "\n", "\n", - "### Pencil and Paper Methods\n", + "### Pencil and paper methods\n", "\n", "Suppose that we have two related goods, such as \n", "\n", - "* propane and ethanol \n", + "* propane and ethanol, and\n", "* rice and wheat, etc. \n", "\n", "To keep things simple, we label them as good 0 and good 1.\n", @@ -82,7 +77,7 @@ ":label: two_eq_demand\n", "\\begin{aligned}\n", " q_0^d = 100 - 10 p_0 - 5 p_1 \\\\\n", - " q_1^d = 50 - p_0 - 10 p_1 \n", + " q_1^d = 50 - p_0 - 10 p_1\n", "\\end{aligned}\n", "```\n", "\n", @@ -95,7 +90,7 @@ ":label: two_eq_supply\n", "\\begin{aligned}\n", " q_0^s = 10 p_0 + 5 p_1 \\\\\n", - " q_1^s = 5 p_0 + 10 p_1 \n", + " q_1^s = 5 p_0 + 10 p_1\n", "\\end{aligned}\n", "```\n", "\n", @@ -107,25 +102,25 @@ ":label: two_equilibrium\n", "\\begin{aligned}\n", " 100 - 10 p_0 - 5 p_1 = 10 p_0 + 5 p_1 \\\\\n", - " 50 - p_0 - 10 p_1 = 5 p_0 + 10 p_1 \n", + " 50 - p_0 - 10 p_1 = 5 p_0 + 10 p_1\n", "\\end{aligned}\n", "```\n", "\n", "We can solve this with pencil and paper to get\n", "\n", "$$\n", - " p_0 = 4.41 \\quad \\text{and} \\quad p_1 = 1.18\n", + " p_0 = 4.41 \\quad \\text{and} \\quad p_1 = 1.18.\n", "$$ \n", "\n", "Inserting these results into either {eq}`two_eq_demand` or {eq}`two_eq_supply` yields the\n", "equilibrium quantities \n", "\n", "$$\n", - " q_0 = 50 \\quad \\text{and} \\quad q_1 = 33.82\n", + " q_0 = 50 \\quad \\text{and} \\quad q_1 = 33.82.\n", "$$\n", "\n", "\n", - "### Looking Forward\n", + "### Looking forward\n", "\n", "Pencil and paper methods are easy in the two good case.\n", "\n", @@ -140,10 +135,10 @@ "\n", "## {index}`Vectors `\n", "\n", - "```{index} single: Linear Algebra; Vectors\n", - "```\n", + " ```{index} single: Linear Algebra; Vectors\n", + " ```\n", "\n", - "A **vector** of length $n$ is just a sequence (or array, or tuple) of $n$ numbers, which we write as $x = (x_1, \\ldots, x_n)$.\n", + "A **vector** of length $n$ is just a sequence (or array, or tuple) of $n$ numbers, which we write as $x = (x_1, \\ldots, x_n)$ or $x = \\begin{bmatrix}x_1, \\ldots, x_n\\end{bmatrix}$.\n", "\n", "We can write these sequences either horizontally or vertically.\n", "\n", @@ -152,10 +147,12 @@ "\n", "The set of all $n$-vectors is denoted by $\\mathbb R^n$.\n", "\n", - "For example, \n", + "```{prf:example}\n", + ":label: le_ex_dim\n", "\n", - "* $\\mathbb R^2$ is the plane --- the set of pairs $(x_1, x_2)$\n", - "* $\\mathbb R^3$ is 3 dimensional space --- the set of vectors $(x_1, x_2, x_3)$\n", + "* $\\mathbb R^2$ is the plane --- the set of pairs $(x_1, x_2)$.\n", + "* $\\mathbb R^3$ is 3 dimensional space --- the set of vectors $(x_1, x_2, x_3)$.\n", + "```\n", "\n", "Often vectors are represented visually as arrows from the origin to the point.\n", "\n", @@ -165,10 +162,10 @@ { "cell_type": "code", "execution_count": null, - "id": "932a13fd", + "id": "d33b10d3", "metadata": { "tags": [ - "hide_input" + "hide-input" ] }, "outputs": [], @@ -195,10 +192,10 @@ }, { "cell_type": "markdown", - "id": "848aecac", + "id": "aa9fadfe", "metadata": {}, "source": [ - "### Vector Operations\n", + "### Vector operations\n", "\n", "```{index} single: Vectors; Operations\n", "```\n", @@ -210,7 +207,8 @@ "\n", "When we add two vectors, we add them element-by-element.\n", "\n", - "For example,\n", + "```{prf:example}\n", + ":label: le_ex_add\n", "\n", "$$\n", "\\begin{bmatrix}\n", @@ -231,8 +229,9 @@ "\\begin{bmatrix}\n", " 7 \\\\\n", " 1\n", - "\\end{bmatrix}\n", + "\\end{bmatrix}.\n", "$$\n", + "```\n", "\n", "In general,\n", "\n", @@ -255,7 +254,7 @@ " x_2 + y_2 \\\\\n", " \\vdots \\\\\n", " x_n + y_n\n", - "\\end{bmatrix}\n", + "\\end{bmatrix}.\n", "$$\n", "\n", "We can visualise vector addition in $\\mathbb{R}^2$ as follows." @@ -264,10 +263,10 @@ { "cell_type": "code", "execution_count": null, - "id": "7b15d3ea", + "id": "b29d2111", "metadata": { "tags": [ - "hide_input" + "hide-input" ] }, "outputs": [], @@ -280,13 +279,13 @@ " ax.spines[spine].set_color('none')\n", "\n", "ax.set(xlim=(-2, 10), ylim=(-4, 4))\n", - "#ax.grid()\n", - "vecs = ((4, -2), (3, 3),(7,1))\n", - "tags = ('(x1, x2)','(y1, y2)','(x1+x2, y1+y2)')\n", - "colors = ('blue','green','red')\n", + "# ax.grid()\n", + "vecs = ((4, -2), (3, 3), (7, 1))\n", + "tags = ('(x1, x2)', '(y1, y2)', '(x1+x2, y1+y2)')\n", + "colors = ('blue', 'green', 'red')\n", "for i, v in enumerate(vecs):\n", " ax.annotate('', xy=v, xytext=(0, 0),\n", - " arrowprops=dict(color = colors[i],\n", + " arrowprops=dict(color=colors[i],\n", " shrink=0,\n", " alpha=0.7,\n", " width=0.5,\n", @@ -294,9 +293,9 @@ " headlength=15))\n", " ax.text(v[0] + 0.2, v[1] + 0.1, tags[i])\n", "\n", - "for i,v in enumerate(vecs):\n", - " ax.annotate('', xy=(7,1), xytext=v,\n", - " arrowprops=dict(color = 'gray',\n", + "for i, v in enumerate(vecs):\n", + " ax.annotate('', xy=(7, 1), xytext=v,\n", + " arrowprops=dict(color='gray',\n", " shrink=0,\n", " alpha=0.3,\n", " width=0.5,\n", @@ -307,12 +306,13 @@ }, { "cell_type": "markdown", - "id": "eb91fbbd", + "id": "0c408cd5", "metadata": {}, "source": [ "Scalar multiplication is an operation that multiplies a vector $x$ with a scalar elementwise.\n", "\n", - "For example,\n", + "```{prf:example}\n", + ":label: le_ex_mul\n", "\n", "$$\n", "-2\n", @@ -329,8 +329,9 @@ "\\begin{bmatrix}\n", " -6 \\\\\n", " 14\n", - "\\end{bmatrix}\n", + "\\end{bmatrix}.\n", "$$\n", + "```\n", "\n", "More generally, it takes a number $\\gamma$ and a vector $x$ and produces\n", "\n", @@ -341,7 +342,7 @@ " \\gamma x_2 \\\\\n", " \\vdots \\\\\n", " \\gamma x_n\n", - "\\end{bmatrix}\n", + "\\end{bmatrix}.\n", "$$\n", "\n", "Scalar multiplication is illustrated in the next figure." @@ -350,10 +351,10 @@ { "cell_type": "code", "execution_count": null, - "id": "6806458b", + "id": "56e30b91", "metadata": { "tags": [ - "hide_input" + "hide-input" ] }, "outputs": [], @@ -390,7 +391,7 @@ }, { "cell_type": "markdown", - "id": "930b3d7c", + "id": "f0d4c9ca", "metadata": {}, "source": [ "In Python, a vector can be represented as a list or tuple, \n", @@ -406,7 +407,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b1c5d496", + "id": "381ceff7", "metadata": {}, "outputs": [], "source": [ @@ -418,7 +419,7 @@ { "cell_type": "code", "execution_count": null, - "id": "993a2986", + "id": "0938f18e", "metadata": {}, "outputs": [], "source": [ @@ -427,10 +428,10 @@ }, { "cell_type": "markdown", - "id": "be0f7c86", + "id": "b6caaef4", "metadata": {}, "source": [ - "### Inner Product and Norm\n", + "### Inner product and norm\n", "\n", "```{index} single: Vectors; Inner Product\n", "```\n", @@ -441,7 +442,7 @@ "The **inner product** of vectors $x,y \\in \\mathbb R^n$ is defined as\n", "\n", "$$\n", - "x' y = \n", + "x^\\top y = \n", "\\begin{bmatrix}\n", " \\color{red}{x_1} & \\color{blue}{x_2} & \\cdots & x_n\n", "\\end{bmatrix}\n", @@ -452,14 +453,14 @@ " y_n\n", "\\end{bmatrix}\n", "= {\\color{red}{x_1 y_1}} + {\\color{blue}{x_2 y_2}} + \\cdots + x_n y_n\n", - ":= \\sum_{i=1}^n x_i y_i\n", + ":= \\sum_{i=1}^n x_i y_i.\n", "$$\n", "\n", "The **norm** of a vector $x$ represents its \"length\" (i.e., its distance from\n", "the zero vector) and is defined as\n", "\n", "$$\n", - " \\| x \\| := \\sqrt{x' x} := \\left( \\sum_{i=1}^n x_i^2 \\right)^{1/2}\n", + " \\| x \\| := \\sqrt{x^\\top x} := \\left( \\sum_{i=1}^n x_i^2 \\right)^{1/2}.\n", "$$\n", "\n", "The expression $\\| x - y\\|$ can be thought of as the \"distance\" between $x$ and $y$.\n", @@ -470,7 +471,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9c5eb25a", + "id": "85e0b34f", "metadata": {}, "outputs": [], "source": [ @@ -480,7 +481,7 @@ { "cell_type": "code", "execution_count": null, - "id": "48284855", + "id": "08ed72bc", "metadata": {}, "outputs": [], "source": [ @@ -490,29 +491,29 @@ { "cell_type": "code", "execution_count": null, - "id": "9e453e21", + "id": "4b73ccfa", "metadata": {}, "outputs": [], "source": [ - "np.sqrt(np.sum(x**2)) # Norm of x, take one" + "np.sqrt(np.sum(x**2)) # Norm of x, method one" ] }, { "cell_type": "code", "execution_count": null, - "id": "99e64205", + "id": "c14c753e", "metadata": {}, "outputs": [], "source": [ - "np.linalg.norm(x) # Norm of x, take two" + "np.linalg.norm(x) # Norm of x, method two" ] }, { "cell_type": "markdown", - "id": "b813f255", + "id": "3373ce91", "metadata": {}, "source": [ - "## Matrix Operations\n", + "## Matrix operations\n", "\n", "```{index} single: Matrix; Operations\n", "```\n", @@ -523,14 +524,15 @@ "\n", "Let's review some details.\n", "\n", - "### Addition and Scalar Multiplication\n", + "### Addition and scalar multiplication\n", "\n", "Just as was the case for vectors, we can add, subtract and scalar multiply\n", "matrices.\n", "\n", "Scalar multiplication and addition are generalizations of the vector case:\n", "\n", - "Here is an example of scalar multiplication\n", + "```{prf:example}\n", + ":label: le_ex_asm\n", "\n", "$$\n", "3\n", @@ -542,8 +544,9 @@ "\\begin{bmatrix}\n", " 6 & -39 \\\\\n", " 0 & 15\n", - "\\end{bmatrix}\n", + "\\end{bmatrix}.\n", "$$\n", + "```\n", "\n", "In general for a number $\\gamma$ and any matrix $A$,\n", "\n", @@ -559,9 +562,12 @@ " \\gamma a_{11} & \\cdots & \\gamma a_{1k} \\\\\n", " \\vdots & \\vdots & \\vdots \\\\\n", " \\gamma a_{n1} & \\cdots & \\gamma a_{nk}\n", - "\\end{bmatrix}\n", + "\\end{bmatrix}.\n", "$$\n", "\n", + "```{prf:example}\n", + ":label: le_ex_ma\n", + "\n", "Consider this example of matrix addition,\n", "\n", "$$\n", @@ -578,8 +584,9 @@ "\\begin{bmatrix}\n", " 13 & 4 \\\\\n", " 7 & 12\n", - "\\end{bmatrix}\n", + "\\end{bmatrix}.\n", "$$\n", + "```\n", "\n", "In general,\n", "\n", @@ -599,13 +606,13 @@ " a_{11} + b_{11} & \\cdots & a_{1k} + b_{1k} \\\\\n", " \\vdots & \\vdots & \\vdots \\\\\n", " a_{n1} + b_{n1} & \\cdots & a_{nk} + b_{nk}\n", - "\\end{bmatrix}\n", + "\\end{bmatrix}.\n", "$$\n", "\n", "In the latter case, the matrices must have the same shape in order for the\n", "definition to make sense.\n", "\n", - "### Matrix Multiplication\n", + "### Matrix multiplication\n", "\n", "We also have a convention for *multiplying* two matrices.\n", "\n", @@ -619,6 +626,9 @@ "If $A$ is $n \\times k$ and $B$ is $j \\times m$, then to multiply $A$ and $B$\n", "we require $k = j$, and the resulting matrix $A B$ is $n \\times m$.\n", "\n", + "```{prf:example}\n", + ":label: le_ex_2dmul\n", + "\n", "Here's an example of a $2 \\times 2$ matrix multiplied by a $2 \\times 1$ vector.\n", "\n", "$$\n", @@ -637,6 +647,7 @@ " a_{21}x_1 + a_{22}x_2\n", "\\end{bmatrix}\n", "$$\n", + "```\n", "\n", "As an important special case, consider multiplying $n \\times k$\n", "matrix $A$ and $k \\times 1$ column vector $x$.\n", @@ -690,7 +701,7 @@ "\n", "There are many tutorials to help you further visualize this operation, such as \n", "\n", - "* [this one](http://www.mathsisfun.com/algebra/matrix-multiplying.html), or \n", + "* [this one](http://www.mathsisfun.com/algebra/matrix-multiplying.html), or\n", "* the discussion on the [Wikipedia page](https://en.wikipedia.org/wiki/Matrix_multiplication).\n", "\n", "\n", @@ -698,7 +709,7 @@ "Unlike number products, $A B$ and $B A$ are not generally the same thing.\n", "```\n", "\n", - "ONe important special case is the [identity matrix](https://en.wikipedia.org/wiki/Identity_matrix), which has ones on the principal diagonal and zero elsewhere:\n", + "One important special case is the [identity matrix](https://en.wikipedia.org/wiki/Identity_matrix), which has ones on the principal diagonal and zero elsewhere:\n", "\n", "$$\n", " I = \n", @@ -711,8 +722,8 @@ "\n", "It is a useful exercise to check the following:\n", "\n", - "* If $A$ is $n \\times k$ and $I$ is the $k \\times k$ identity matrix, then $AI = A$.\n", - "* If $I$ is the $n \\times n$ identity matrix, then $IA = A$.\n", + "* if $A$ is $n \\times k$ and $I$ is the $k \\times k$ identity matrix, then $AI = A$, and\n", + "* if $I$ is the $n \\times n$ identity matrix, then $IA = A$.\n", "\n", "\n", "\n", @@ -729,7 +740,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1856df24", + "id": "ad59d382", "metadata": {}, "outputs": [], "source": [ @@ -742,7 +753,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5d8e87ba", + "id": "a8f4494b", "metadata": {}, "outputs": [], "source": [ @@ -754,7 +765,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5a0a1885", + "id": "83d99679", "metadata": {}, "outputs": [], "source": [ @@ -763,7 +774,7 @@ }, { "cell_type": "markdown", - "id": "318d8f43", + "id": "04363894", "metadata": {}, "source": [ "The `shape` attribute is a tuple giving the number of rows and columns ---\n", @@ -775,13 +786,13 @@ "There are many convenient functions for creating common matrices (matrices of zeros,\n", "ones, etc.) --- see [here](https://python-programming.quantecon.org/numpy.html#creating-arrays).\n", "\n", - "Since operations are performed elementwise by default, scalar multiplication and addition have very natural syntax" + "Since operations are performed elementwise by default, scalar multiplication and addition have very natural syntax." ] }, { "cell_type": "code", "execution_count": null, - "id": "2d522671", + "id": "ea561767", "metadata": {}, "outputs": [], "source": [ @@ -793,7 +804,7 @@ { "cell_type": "code", "execution_count": null, - "id": "7b386a55", + "id": "d4ee709f", "metadata": {}, "outputs": [], "source": [ @@ -802,7 +813,7 @@ }, { "cell_type": "markdown", - "id": "d23a3078", + "id": "7483572e", "metadata": {}, "source": [ "To multiply matrices we use the `@` symbol.\n", @@ -812,7 +823,7 @@ "In particular, `A @ B` is matrix multiplication, whereas `A * B` is element-by-element multiplication.\n", "```\n", "\n", - "### Two Good Model in Matrix Form\n", + "### Two good model in matrix form\n", "\n", "We can now revisit the two good model and solve {eq}`two_equilibrium`\n", "numerically via matrix algebra.\n", @@ -842,9 +853,11 @@ " \\begin{bmatrix}\n", " 100 \\\\\n", " 50\n", - " \\end{bmatrix}\n", + " \\end{bmatrix}.\n", "```\n", "\n", + "Recall that $p \\in \\mathbb{R}^{2}$ is the price of two goods.\n", + "\n", "(Please check that $q^d = D p + h$ represents the same equations as {eq}`two_eq_demand`.)\n", "\n", "We rewrite {eq}`two_eq_supply` as\n", @@ -863,19 +876,19 @@ " \\begin{bmatrix}\n", " 10 & 5 \\\\\n", " 5 & 10 \n", - " \\end{bmatrix}\n", + " \\end{bmatrix}.\n", "```\n", "\n", "Now equality of supply and demand can be expressed as $q^s = q^d$, or\n", "\n", "$$\n", - " C p = D p + h\n", + " C p = D p + h.\n", "$$\n", "\n", "We can rearrange the terms to get \n", "\n", "$$\n", - " (C - D) p = h\n", + " (C - D) p = h.\n", "$$\n", "\n", "If all of the terms were numbers, we could solve for prices as $p = h /\n", @@ -886,54 +899,54 @@ "\n", "```{math}\n", ":label: two_matrix\n", - " p = (C - D)^{-1} h\n", + " p = (C - D)^{-1} h.\n", "```\n", "\n", "Before we implement the solution let us consider a more general setting.\n", "\n", "\n", "\n", - "### More Goods\n", + "### More goods\n", "\n", "It is natural to think about demand systems with more goods.\n", "\n", "For example, even within energy commodities there are many different goods,\n", - "including crude oil, gasoline, coal, natural gas, ethanol and uranium.\n", + "including crude oil, gasoline, coal, natural gas, ethanol, and uranium.\n", "\n", "The prices of these goods are related, so it makes sense to study them\n", "together.\n", "\n", - "Pencil and paper solutions become very time consuming with large systems.\n", + "Pencil and paper methods become very time consuming with large systems.\n", "\n", "But fortunately the matrix methods described above are essentially unchanged.\n", "\n", "In general, we can write the demand equation as $q^d = Dp + h$, where\n", "\n", - "* $q^d$ is an $n \\times 1$ vector of demand quantities for $n$ different goods\n", - "* $D$ is an $n \\times n$ \"coefficient\" matrix\n", - "* $h$ is an $n \\times 1$ vector of constant values\n", + "* $q^d$ is an $n \\times 1$ vector of demand quantities for $n$ different goods.\n", + "* $D$ is an $n \\times n$ \"coefficient\" matrix.\n", + "* $h$ is an $n \\times 1$ vector of constant values.\n", "\n", "Similarly, we can write the supply equation as $q^s = Cp + e$, where\n", "\n", - "* $q^d$ is an $n \\times 1$ vector of supply quantities for the same goods\n", - "* $C$ is an $n \\times n$ \"coefficient\" matrix\n", - "* $e$ is an $n \\times 1$ vector of constant values\n", + "* $q^s$ is an $n \\times 1$ vector of supply quantities for the same goods.\n", + "* $C$ is an $n \\times n$ \"coefficient\" matrix.\n", + "* $e$ is an $n \\times 1$ vector of constant values.\n", "\n", "To find an equilibrium, we solve $Dp + h = Cp + e$, or\n", "\n", "```{math}\n", ":label: n_eq_sys_la\n", - " (D- C)p = e - h \n", + " (D- C)p = e - h.\n", "```\n", "\n", - "The solution is\n", + "Then the price vector of the n different goods is\n", "\n", "$$ \n", - " p = (D- C)^{-1}(e - h) \n", + " p = (D- C)^{-1}(e - h).\n", "$$\n", "\n", "\n", - "### General Linear Systems\n", + "### General linear systems\n", "\n", "A more general version of the problem described above looks as follows.\n", "\n", @@ -947,7 +960,7 @@ "\\end{matrix}\n", "```\n", "\n", - "The objective here is to solve for the \"unknowns\" $x_1, \\ldots, x_n$ \n", + "The objective here is to solve for the \"unknowns\" $x_1, \\ldots, x_n$.\n", "\n", "We take as given the coefficients $a_{11}, \\ldots, a_{nn}$ and constants $b_1, \\ldots, b_n$.\n", "\n", @@ -977,9 +990,11 @@ " b_1 \\\\\n", " \\vdots \\\\\n", " b_n\n", - " \\end{bmatrix}\n", + " \\end{bmatrix}.\n", "```\n", "\n", + "```{prf:example}\n", + ":label: le_ex_gls\n", "For example, {eq}`n_eq_sys_la` has this form with \n", "\n", "$$ \n", @@ -987,9 +1002,9 @@ " \\quad\n", " b = e - h\n", " \\quad \\text{and} \\quad\n", - " x = p\n", + " x = p.\n", "$$\n", - "\n", + "```\n", "\n", "When considering problems such as {eq}`la_gf`, we need to ask at least some of\n", "the following questions\n", @@ -999,7 +1014,7 @@ "\n", "\n", "\n", - "## Solving Systems of Equations\n", + "## Solving systems of equations\n", "\n", "```{index} single: Matrix; Solving Systems of Equations\n", "```\n", @@ -1008,7 +1023,7 @@ "\n", "```{math}\n", ":label: la_se2\n", - " A x = b\n", + " A x = b.\n", "```\n", "\n", "The problem we face is to find a vector $x \\in \\mathbb R^n$ that solves\n", @@ -1018,14 +1033,14 @@ "\n", "We illustrate two such cases below.\n", "\n", - "### No Solution\n", + "### No solution\n", "\n", "Consider the system of equations given by,\n", "\n", "$$\n", "\\begin{aligned}\n", - " x + 3y = 3 \\\\\n", - " 2x + 6y = -8\n", + " x + 3y &= 3 \\\\\n", + " 2x + 6y &= -8.\n", "\\end{aligned}\n", "$$\n", "\n", @@ -1037,12 +1052,12 @@ { "cell_type": "code", "execution_count": null, - "id": "e8bce3a7", + "id": "36eabd11", "metadata": {}, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", - "x = np.linspace(-10,10)\n", + "x = np.linspace(-10, 10)\n", "plt.plot(x, (3-x)/3, label=f'$x + 3y = 3$')\n", "plt.plot(x, (-8-2*x)/6, label=f'$2x + 6y = -8$')\n", "plt.legend()\n", @@ -1051,7 +1066,7 @@ }, { "cell_type": "markdown", - "id": "ebf74edd", + "id": "e80b913b", "metadata": { "tags": [] }, @@ -1077,7 +1092,7 @@ " \\begin{bmatrix}\n", " 3 \\\\\n", " -8\n", - " \\end{bmatrix}\n", + " \\end{bmatrix}.\n", "```\n", "\n", "It can be noted that the $2^{nd}$ row of matrix $A = (2, 6)$ is just a scalar multiple of the $1^{st}$ row of matrix $A = (1, 3)$.\n", @@ -1096,14 +1111,14 @@ "\n", "\n", "\n", - "### Many Solutions\n", + "### Many solutions\n", "\n", "Now consider,\n", "\n", "$$\n", "\\begin{aligned}\n", - " x - 2y = -4 \\\\\n", - " -2x + 4y = 8\n", + " x - 2y &= -4 \\\\\n", + " -2x + 4y &= 8.\n", "\\end{aligned}\n", "$$\n", "\n", @@ -1119,7 +1134,7 @@ " \\begin{bmatrix}\n", " 1 & -2 \\\\\n", " -2 & 4\n", - " \\end{bmatrix}\n", + " \\end{bmatrix}.\n", "```\n", "\n", "are linearly dependent --- can you see why?\n", @@ -1127,7 +1142,7 @@ "We now impose conditions on $A$ in {eq}`la_se2` that rule out these problems.\n", "\n", "\n", - "### Nonsingular Matrices\n", + "### Nonsingular matrices\n", "\n", "To every square matrix we can assign a unique number called the\n", "[determinant](https://en.wikipedia.org/wiki/Determinant).\n", @@ -1140,7 +1155,7 @@ " \\color{blue}{c} & \\color{red}{d}\n", "\\end{bmatrix}\n", "=\n", - "{\\color{red}{ad}} - {\\color{blue}{bc}}\n", + "{\\color{red}{ad}} - {\\color{blue}{bc}}.\n", "$$\n", "\n", "If the determinant of $A$ is not zero, then we say that $A$ is *nonsingular*.\n", @@ -1148,8 +1163,10 @@ "A square matrix $A$ is nonsingular if and only if the rows and columns of $A$\n", "are linearly independent.\n", "\n", + "A more detailed explanation of matrix inverse can be found [here](https://www.mathsisfun.com/algebra/matrix-inverse.html).\n", + "\n", "You can check yourself that the in {eq}`no_soln` and {eq}`many_solns` with\n", - "linearly dependent rows are singular matrices as well.\n", + "linearly dependent rows are singular matrices.\n", "\n", "This gives us a useful one-number summary of whether or not a square matrix\n", "can be inverted.\n", @@ -1170,7 +1187,7 @@ "\n", "\n", "\n", - "### Linear Equations with NumPy\n", + "### Linear equations with NumPy\n", "\n", "```{index} single: Linear Algebra; SciPy\n", "```\n", @@ -1178,7 +1195,7 @@ "In the two good example we obtained the matrix equation,\n", "\n", "$$\n", - "p = (C-D)^{-1} h\n", + "p = (C-D)^{-1} h.\n", "$$\n", "\n", "where $C$, $D$ and $h$ are given by {eq}`two_eq_demand_mat` and {eq}`two_eq_supply_mat`.\n", @@ -1193,17 +1210,17 @@ { "cell_type": "code", "execution_count": null, - "id": "9fca60b9", + "id": "7992fd22", "metadata": {}, "outputs": [], "source": [ - "C = ((10, 5), #matrix C\n", + "C = ((10, 5), # Matrix C\n", " (5, 10))" ] }, { "cell_type": "markdown", - "id": "5abb2c75", + "id": "06e8cae4", "metadata": {}, "source": [ "Now we change this to a NumPy array." @@ -1212,7 +1229,7 @@ { "cell_type": "code", "execution_count": null, - "id": "bd295aca", + "id": "d486647b", "metadata": {}, "outputs": [], "source": [ @@ -1222,11 +1239,11 @@ { "cell_type": "code", "execution_count": null, - "id": "0cf323b6", + "id": "71ebc6f1", "metadata": {}, "outputs": [], "source": [ - "D = ((-10, -5), #matrix D\n", + "D = ((-10, -5), # Matrix D\n", " (-1, -10))\n", "D = np.array(D)" ] @@ -1234,62 +1251,63 @@ { "cell_type": "code", "execution_count": null, - "id": "7c33226d", + "id": "4e9287be", "metadata": {}, "outputs": [], "source": [ - "h = np.array((100, 50)) #vector h\n", - "h.shape = 2,1 #transforming h to a column vector" + "h = np.array((100, 50)) # Vector h\n", + "h.shape = 2,1 # Transforming h to a column vector" ] }, { "cell_type": "code", "execution_count": null, - "id": "8b4c3579", + "id": "2f8607f8", "metadata": {}, "outputs": [], "source": [ "from numpy.linalg import det, inv\n", "A = C - D\n", - "det(A) # check that A is nonsingular (non-zero determinant), and hence invertible" + "# Check that A is nonsingular (non-zero determinant), and hence invertible\n", + "det(A)" ] }, { "cell_type": "code", "execution_count": null, - "id": "8471f6d8", + "id": "c9c9822c", "metadata": {}, "outputs": [], "source": [ - "A_inv = inv(A) # Compute the inverse\n", + "A_inv = inv(A) # compute the inverse\n", "A_inv" ] }, { "cell_type": "code", "execution_count": null, - "id": "ef928962", + "id": "ceb99627", "metadata": {}, "outputs": [], "source": [ - "p = A_inv @ h # equilibrium prices\n", + "p = A_inv @ h # equilibrium prices\n", "p" ] }, { "cell_type": "code", "execution_count": null, - "id": "6ed6fa27", + "id": "571b1366", "metadata": {}, "outputs": [], "source": [ - "q = C @ p # equilibrium quantities\n", + "q = C @ p # equilibrium quantities\n", "q" ] }, { "cell_type": "markdown", - "id": "dead7953", + "id": "85ead17b", "metadata": {}, "source": [ "Notice that we get the same solutions as the pencil and paper case.\n", @@ -1300,29 +1318,29 @@ { "cell_type": "code", "execution_count": null, - "id": "8a6b8e22", + "id": "7bb3aac1", "metadata": {}, "outputs": [], "source": [ "from numpy.linalg import solve\n", - "p = solve(A, h) # equilibrium prices\n", + "p = solve(A, h) # equilibrium prices\n", "p" ] }, { "cell_type": "code", "execution_count": null, - "id": "a75766b3", + "id": "5e224a04", "metadata": {}, "outputs": [], "source": [ - "q = C @ p # equilibrium quantities\n", + "q = C @ p # equilibrium quantities\n", "q" ] }, { "cell_type": "markdown", - "id": "4e899a8d", + "id": "b3784bc1", "metadata": {}, "source": [ "Observe how we can solve for $x = A^{-1} y$ by either via `inv(A) @ y`, or using `solve(A, y)`.\n", @@ -1413,31 +1431,31 @@ { "cell_type": "code", "execution_count": null, - "id": "3c37c31c", + "id": "7f45e633", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "from numpy.linalg import det\n", "\n", - "A = np.array([[35, -5, -5], #matrix A\n", + "A = np.array([[35, -5, -5], # matrix A\n", " [-5, 25, -10],\n", " [-5, -5, 15]])\n", "\n", - "b = np.array((100, 75, 55)) #column vector b\n", - "b.shape = (3,1)\n", + "b = np.array((100, 75, 55)) # column vector b\n", + "b.shape = (3, 1)\n", "\n", - "det(A) #check if A is nonsingular" + "det(A) # check if A is nonsingular" ] }, { "cell_type": "code", "execution_count": null, - "id": "27769af1", + "id": "805698e6", "metadata": {}, "outputs": [], "source": [ - "#using inverse\n", + "# Using inverse\n", "from numpy.linalg import det\n", "\n", "A_inv = inv(A)\n", @@ -1449,19 +1467,19 @@ { "cell_type": "code", "execution_count": null, - "id": "fbf3dd1e", + "id": "2d97f520", "metadata": {}, "outputs": [], "source": [ - "#using numpy.linalg.solve\n", + "# Using numpy.linalg.solve\n", "from numpy.linalg import solve\n", - "p = solve(A,b)\n", + "p = solve(A, b)\n", "p" ] }, { "cell_type": "markdown", - "id": "5d50b6ab", + "id": "a2e8c95f", "metadata": {}, "source": [ "The solution is given by:\n", @@ -1511,15 +1529,15 @@ "Now consider the general equation of a linear demand curve of a good given by:\n", "\n", "$$\n", - " p = a - bq\n", + " p = m - nq\n", "$$\n", "\n", "where $p$ is the price of the good and $q$ is the quantity demanded.\n", "\n", - "Suppose we are trying to *estimate* the values of $a$ and $b$.\n", + "Suppose we are trying to *estimate* the values of $m$ and $n$.\n", "\n", "We do this by repeatedly observing the price and quantity (for example, each\n", - "month) and then choosing $a$ and $b$ to fit the relationship between $p$ and\n", + "month) and then choosing $m$ and $n$ to fit the relationship between $p$ and\n", "$q$.\n", "\n", "We have the following observations:\n", @@ -1531,19 +1549,19 @@ "| 8 | 3 |\n", "\n", "\n", - "Requiring the demand curve $p = a - b q$ to pass through all these points leads to the\n", + "Requiring the demand curve $p = m - nq$ to pass through all these points leads to the\n", "following three equations:\n", "\n", "$$\n", "\\begin{aligned}\n", - " 1 = a - 9b \\\\\n", - " 3 = a - 7b \\\\\n", - " 8 = a - 3b\n", + " 1 = m - 9n \\\\\n", + " 3 = m - 7n \\\\\n", + " 8 = m - 3n\n", "\\end{aligned}\n", "$$\n", "\n", "Thus we obtain a system of equations $Ax = b$ where $A = \\begin{bmatrix} 1 & -9 \\\\ 1 & -7 \\\\ 1 & -3 \\end{bmatrix}$,\n", - "$x = \\begin{bmatrix} a \\\\ b \\end{bmatrix}$ and $b = \\begin{bmatrix} 1 \\\\ 3 \\\\ 8 \\end{bmatrix}$.\n", + "$x = \\begin{bmatrix} m \\\\ n \\end{bmatrix}$ and $b = \\begin{bmatrix} 1 \\\\ 3 \\\\ 8 \\end{bmatrix}$.\n", "\n", "It can be verified that this system has no solutions.\n", "\n", @@ -1565,7 +1583,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5dda4918", + "id": "c05e803b", "metadata": {}, "outputs": [], "source": [ @@ -1576,19 +1594,19 @@ { "cell_type": "code", "execution_count": null, - "id": "8b345c29", + "id": "24ef5237", "metadata": {}, "outputs": [], "source": [ - "#using matrix algebra\n", - "A = np.array([[1, -9], #matrix A\n", + "# Using matrix algebra\n", + "A = np.array([[1, -9], # matrix A\n", " [1, -7],\n", " [1, -3]])\n", "\n", - "A_T = np.transpose(A) #transpose of matrix A\n", + "A_T = np.transpose(A) # transpose of matrix A\n", "\n", - "b = np.array((1, 3, 8)) #column vector b\n", - "b.shape = (3,1)\n", + "b = np.array((1, 3, 8)) # column vector b\n", + "b.shape = (3, 1)\n", "\n", "x = inv(A_T @ A) @ A_T @ b\n", "x" @@ -1597,18 +1615,32 @@ { "cell_type": "code", "execution_count": null, - "id": "b7996085", + "id": "5451c4a1", "metadata": {}, "outputs": [], "source": [ - "#using numpy.linalg.lstsq\n", - "x = np.linalg.lstsq(A, b, rcond = None)\n", - "x" + "# Using numpy.linalg.lstsq\n", + "x, res, _, _ = np.linalg.lstsq(A, b, rcond=None)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f61fe7ea", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "print(f\"x\\u0302 = {x}\")\n", + "print(f\"\\u2016Ax\\u0302 - b\\u2016\\u00B2 = {res[0]}\")" ] }, { "cell_type": "markdown", - "id": "afdf949f", + "id": "db6a5f06", "metadata": {}, "source": [ "Here is a visualization of how the least squares method approximates the equation of a line connecting a set of points.\n", @@ -1619,18 +1651,18 @@ { "cell_type": "code", "execution_count": null, - "id": "21cdff78", + "id": "1f3edd96", "metadata": {}, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", "p = np.array((1, 3, 8))\n", - "q = np.array((9, 7 ,3))\n", + "q = np.array((9, 7, 3))\n", "\n", - "a, b = x[0]\n", + "a, b = x\n", "\n", - "plt.plot(q, p, 'o', label='observations', markersize=5)\n", - "plt.plot(q, a - b*q, 'r', label='Fitted line')\n", + "ax.plot(q, p, 'o', label='observations', markersize=5)\n", + "ax.plot(q, a - b*q, 'r', label='Fitted line')\n", "plt.xlabel('quantity demanded')\n", "plt.ylabel('price')\n", "plt.legend()\n", @@ -1639,14 +1671,14 @@ }, { "cell_type": "markdown", - "id": "04c27015", + "id": "0724768b", "metadata": {}, "source": [ "```{solution-end}\n", "```\n", "\n", "\n", - "### Further Reading\n", + "### Further reading\n", "\n", "The documentation of the `numpy.linalg` submodule can be found [here](https://numpy.org/devdocs/reference/routines.linalg.html).\n", "\n", @@ -1655,12 +1687,72 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.4" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 12, + 44, + 47, + 155, + 176, + 242, + 276, + 316, + 347, + 358, + 364, + 366, + 404, + 408, + 412, + 416, + 418, + 643, + 650, + 656, + 658, + 671, + 677, + 679, + 913, + 922, + 1059, + 1062, + 1066, + 1070, + 1076, + 1081, + 1088, + 1093, + 1098, + 1101, + 1107, + 1113, + 1116, + 1202, + 1216, + 1226, + 1231, + 1330, + 1335, + 1350, + 1355, + 1360, + 1366, + 1379 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/linear_equations.md b/book/_build/html/_sources/linear_equations.md new file mode 100644 index 0000000..4b9ccb0 --- /dev/null +++ b/book/_build/html/_sources/linear_equations.md @@ -0,0 +1,1389 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.4 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Linear Equations and Matrix Algebra + +```{index} single: Linear Equations and Matrix Algebra +``` + +## Overview + +Many problems in economics and finance require solving linear equations. + +In this lecture we discuss linear equations and their applications. + +To illustrate the importance of linear equations, we begin with a two good +model of supply and demand. + +The two good case is so simple that solutions can be calculated by hand. + +But often we need to consider markets containing many goods. + +In the multiple goods case we face large systems of linear equations, with many equations +and unknowns. + +To handle such systems we need two things: + +* matrix algebra (and the knowledge of how to use it) plus +* computer code to apply matrix algebra to the problems of interest. + +This lecture covers these steps. + +We will use the following packages: + +```{code-cell} ipython3 +import numpy as np +import matplotlib.pyplot as plt +``` + +## A two good example + +In this section we discuss a simple two good example and solve it by + +1. pencil and paper +2. matrix algebra + +The second method is more general, as we will see. + + +### Pencil and paper methods + +Suppose that we have two related goods, such as + +* propane and ethanol, and +* rice and wheat, etc. + +To keep things simple, we label them as good 0 and good 1. + +The demand for each good depends on the price of both goods: + +```{math} +:label: two_eq_demand +\begin{aligned} + q_0^d = 100 - 10 p_0 - 5 p_1 \\ + q_1^d = 50 - p_0 - 10 p_1 +\end{aligned} +``` + +(We are assuming demand decreases when the price of either good goes up, but +other cases are also possible.) + +Let's suppose that supply is given by + +```{math} +:label: two_eq_supply +\begin{aligned} + q_0^s = 10 p_0 + 5 p_1 \\ + q_1^s = 5 p_0 + 10 p_1 +\end{aligned} +``` + +Equilibrium holds when supply equals demand ($q_0^s = q_0^d$ and $q_1^s = q_1^d$). + +This yields the linear system + +```{math} +:label: two_equilibrium +\begin{aligned} + 100 - 10 p_0 - 5 p_1 = 10 p_0 + 5 p_1 \\ + 50 - p_0 - 10 p_1 = 5 p_0 + 10 p_1 +\end{aligned} +``` + +We can solve this with pencil and paper to get + +$$ + p_0 = 4.41 \quad \text{and} \quad p_1 = 1.18. +$$ + +Inserting these results into either {eq}`two_eq_demand` or {eq}`two_eq_supply` yields the +equilibrium quantities + +$$ + q_0 = 50 \quad \text{and} \quad q_1 = 33.82. +$$ + + +### Looking forward + +Pencil and paper methods are easy in the two good case. + +But what if there are many goods? + +For such problems we need matrix algebra. + +Before solving problems with matrix algebra, let's first recall the +basics of vectors and matrices, in both theory and computation. + + + +## {index}`Vectors ` + + ```{index} single: Linear Algebra; Vectors + ``` + +A **vector** of length $n$ is just a sequence (or array, or tuple) of $n$ numbers, which we write as $x = (x_1, \ldots, x_n)$ or $x = \begin{bmatrix}x_1, \ldots, x_n\end{bmatrix}$. + +We can write these sequences either horizontally or vertically. + +But when we use matrix operations, our default assumption is that vectors are +column vectors. + +The set of all $n$-vectors is denoted by $\mathbb R^n$. + +```{prf:example} +:label: le_ex_dim + +* $\mathbb R^2$ is the plane --- the set of pairs $(x_1, x_2)$. +* $\mathbb R^3$ is 3 dimensional space --- the set of vectors $(x_1, x_2, x_3)$. +``` + +Often vectors are represented visually as arrows from the origin to the point. + +Here's a visualization. + +```{code-cell} ipython3 +:tags: [hide-input] + +fig, ax = plt.subplots() +# Set the axes through the origin +for spine in ['left', 'bottom']: + ax.spines[spine].set_position('zero') +for spine in ['right', 'top']: + ax.spines[spine].set_color('none') + +ax.set(xlim=(-5, 5), ylim=(-5, 5)) + +vecs = ((2, 4), (-3, 3), (-4, -3.5)) +for v in vecs: + ax.annotate('', xy=v, xytext=(0, 0), + arrowprops=dict(facecolor='blue', + shrink=0, + alpha=0.7, + width=0.5)) + ax.text(1.1 * v[0], 1.1 * v[1], str(v)) +plt.show() +``` + +### Vector operations + +```{index} single: Vectors; Operations +``` + +Sometimes we want to modify vectors. + +The two most common operators on vectors are addition and scalar +multiplication, which we now describe. + +When we add two vectors, we add them element-by-element. + +```{prf:example} +:label: le_ex_add + +$$ +\begin{bmatrix} + 4 \\ + -2 +\end{bmatrix} ++ +\begin{bmatrix} + 3 \\ + 3 +\end{bmatrix} += +\begin{bmatrix} + 4 & + & 3 \\ + -2 & + & 3 +\end{bmatrix} += +\begin{bmatrix} + 7 \\ + 1 +\end{bmatrix}. +$$ +``` + +In general, + +$$ +x + y = +\begin{bmatrix} + x_1 \\ + x_2 \\ + \vdots \\ + x_n +\end{bmatrix} + +\begin{bmatrix} + y_1 \\ + y_2 \\ + \vdots \\ + y_n +\end{bmatrix} := +\begin{bmatrix} + x_1 + y_1 \\ + x_2 + y_2 \\ + \vdots \\ + x_n + y_n +\end{bmatrix}. +$$ + +We can visualise vector addition in $\mathbb{R}^2$ as follows. + +```{code-cell} ipython3 +:tags: [hide-input] + +fig, ax = plt.subplots() +# Set the axes through the origin +for spine in ['left', 'bottom']: + ax.spines[spine].set_position('zero') +for spine in ['right', 'top']: + ax.spines[spine].set_color('none') + +ax.set(xlim=(-2, 10), ylim=(-4, 4)) +# ax.grid() +vecs = ((4, -2), (3, 3), (7, 1)) +tags = ('(x1, x2)', '(y1, y2)', '(x1+x2, y1+y2)') +colors = ('blue', 'green', 'red') +for i, v in enumerate(vecs): + ax.annotate('', xy=v, xytext=(0, 0), + arrowprops=dict(color=colors[i], + shrink=0, + alpha=0.7, + width=0.5, + headwidth=8, + headlength=15)) + ax.text(v[0] + 0.2, v[1] + 0.1, tags[i]) + +for i, v in enumerate(vecs): + ax.annotate('', xy=(7, 1), xytext=v, + arrowprops=dict(color='gray', + shrink=0, + alpha=0.3, + width=0.5, + headwidth=5, + headlength=20)) +plt.show() +``` + +Scalar multiplication is an operation that multiplies a vector $x$ with a scalar elementwise. + +```{prf:example} +:label: le_ex_mul + +$$ +-2 +\begin{bmatrix} + 3 \\ + -7 +\end{bmatrix} += +\begin{bmatrix} + -2 & \times & 3 \\ + -2 & \times & -7 +\end{bmatrix} += +\begin{bmatrix} + -6 \\ + 14 +\end{bmatrix}. +$$ +``` + +More generally, it takes a number $\gamma$ and a vector $x$ and produces + +$$ +\gamma x := +\begin{bmatrix} + \gamma x_1 \\ + \gamma x_2 \\ + \vdots \\ + \gamma x_n +\end{bmatrix}. +$$ + +Scalar multiplication is illustrated in the next figure. + +```{code-cell} ipython3 +:tags: [hide-input] + +fig, ax = plt.subplots() +# Set the axes through the origin +for spine in ['left', 'bottom']: + ax.spines[spine].set_position('zero') +for spine in ['right', 'top']: + ax.spines[spine].set_color('none') + +ax.set(xlim=(-5, 5), ylim=(-5, 5)) +x = (2, 2) +ax.annotate('', xy=x, xytext=(0, 0), + arrowprops=dict(facecolor='blue', + shrink=0, + alpha=1, + width=0.5)) +ax.text(x[0] + 0.4, x[1] - 0.2, '$x$', fontsize='16') + +scalars = (-2, 2) +x = np.array(x) + +for s in scalars: + v = s * x + ax.annotate('', xy=v, xytext=(0, 0), + arrowprops=dict(facecolor='red', + shrink=0, + alpha=0.5, + width=0.5)) + ax.text(v[0] + 0.4, v[1] - 0.2, f'${s} x$', fontsize='16') +plt.show() +``` + +In Python, a vector can be represented as a list or tuple, +such as `x = [2, 4, 6]` or `x = (2, 4, 6)`. + +However, it is more common to represent vectors with +[NumPy arrays](https://python-programming.quantecon.org/numpy.html#numpy-arrays). + +One advantage of NumPy arrays is that scalar multiplication and addition have +very natural syntax. + +```{code-cell} ipython3 +x = np.ones(3) # Vector of three ones +y = np.array((2, 4, 6)) # Converts tuple (2, 4, 6) into a NumPy array +x + y # Add (element-by-element) +``` + +```{code-cell} +4 * x # Scalar multiply +``` + +### Inner product and norm + +```{index} single: Vectors; Inner Product +``` + +```{index} single: Vectors; Norm +``` + +The **inner product** of vectors $x,y \in \mathbb R^n$ is defined as + +$$ +x^\top y = +\begin{bmatrix} + \color{red}{x_1} & \color{blue}{x_2} & \cdots & x_n +\end{bmatrix} +\begin{bmatrix} + \color{red}{y_1} \\ + \color{blue}{y_2} \\ + \vdots \\ + y_n +\end{bmatrix} += {\color{red}{x_1 y_1}} + {\color{blue}{x_2 y_2}} + \cdots + x_n y_n +:= \sum_{i=1}^n x_i y_i. +$$ + +The **norm** of a vector $x$ represents its "length" (i.e., its distance from +the zero vector) and is defined as + +$$ + \| x \| := \sqrt{x^\top x} := \left( \sum_{i=1}^n x_i^2 \right)^{1/2}. +$$ + +The expression $\| x - y\|$ can be thought of as the "distance" between $x$ and $y$. + +The inner product and norm can be computed as follows + +```{code-cell} ipython3 +np.sum(x*y) # Inner product of x and y +``` + +```{code-cell} ipython3 +x @ y # Another way to compute the inner product +``` + +```{code-cell} ipython3 +np.sqrt(np.sum(x**2)) # Norm of x, method one +``` + +```{code-cell} ipython3 +np.linalg.norm(x) # Norm of x, method two +``` + +## Matrix operations + +```{index} single: Matrix; Operations +``` + +When we discussed linear price systems, we mentioned using matrix algebra. + +Matrix algebra is similar to algebra for numbers. + +Let's review some details. + +### Addition and scalar multiplication + +Just as was the case for vectors, we can add, subtract and scalar multiply +matrices. + +Scalar multiplication and addition are generalizations of the vector case: + +```{prf:example} +:label: le_ex_asm + +$$ +3 +\begin{bmatrix} + 2 & -13 \\ + 0 & 5 +\end{bmatrix} += +\begin{bmatrix} + 6 & -39 \\ + 0 & 15 +\end{bmatrix}. +$$ +``` + +In general for a number $\gamma$ and any matrix $A$, + +$$ +\gamma A = +\gamma +\begin{bmatrix} + a_{11} & \cdots & a_{1k} \\ + \vdots & \vdots & \vdots \\ + a_{n1} & \cdots & a_{nk} +\end{bmatrix} := +\begin{bmatrix} + \gamma a_{11} & \cdots & \gamma a_{1k} \\ + \vdots & \vdots & \vdots \\ + \gamma a_{n1} & \cdots & \gamma a_{nk} +\end{bmatrix}. +$$ + +```{prf:example} +:label: le_ex_ma + +Consider this example of matrix addition, + +$$ +\begin{bmatrix} + 1 & 5 \\ + 7 & 3 \\ +\end{bmatrix} ++ +\begin{bmatrix} + 12 & -1 \\ + 0 & 9 +\end{bmatrix} += +\begin{bmatrix} + 13 & 4 \\ + 7 & 12 +\end{bmatrix}. +$$ +``` + +In general, + +$$ +A + B = +\begin{bmatrix} + a_{11} & \cdots & a_{1k} \\ + \vdots & \vdots & \vdots \\ + a_{n1} & \cdots & a_{nk} +\end{bmatrix} + +\begin{bmatrix} + b_{11} & \cdots & b_{1k} \\ + \vdots & \vdots & \vdots \\ + b_{n1} & \cdots & b_{nk} +\end{bmatrix} := +\begin{bmatrix} + a_{11} + b_{11} & \cdots & a_{1k} + b_{1k} \\ + \vdots & \vdots & \vdots \\ + a_{n1} + b_{n1} & \cdots & a_{nk} + b_{nk} +\end{bmatrix}. +$$ + +In the latter case, the matrices must have the same shape in order for the +definition to make sense. + +### Matrix multiplication + +We also have a convention for *multiplying* two matrices. + +The rule for matrix multiplication generalizes the idea of inner products +discussed above. + +If $A$ and $B$ are two matrices, then their product $A B$ is formed by taking +as its $i,j$-th element the inner product of the $i$-th row of $A$ and the +$j$-th column of $B$. + +If $A$ is $n \times k$ and $B$ is $j \times m$, then to multiply $A$ and $B$ +we require $k = j$, and the resulting matrix $A B$ is $n \times m$. + +```{prf:example} +:label: le_ex_2dmul + +Here's an example of a $2 \times 2$ matrix multiplied by a $2 \times 1$ vector. + +$$ +Ax = +\begin{bmatrix} + \color{red}{a_{11}} & \color{red}{a_{12}} \\ + a_{21} & a_{22} +\end{bmatrix} +\begin{bmatrix} + \color{red}{x_1} \\ + \color{red}{x_2} +\end{bmatrix} += +\begin{bmatrix} + \color{red}{a_{11}x_1 + a_{12}x_2} \\ + a_{21}x_1 + a_{22}x_2 +\end{bmatrix} +$$ +``` + +As an important special case, consider multiplying $n \times k$ +matrix $A$ and $k \times 1$ column vector $x$. + +According to the preceding rule, this gives us an $n \times 1$ column vector. + +```{math} +:label: la_atx + +A x = +{\begin{bmatrix} + a_{11} & a_{12} & \cdots & a_{1k} \\ + \vdots & \vdots & & \vdots \\ + \color{red}{a_{i1}} & \color{red}{a_{i2}} & \color{red}{\cdots} & \color{red}{a_{i}k} \\ + \vdots & \vdots & & \vdots \\ + a_{n1} & a_{n2} & \cdots & a_{nk} +\end{bmatrix}}_{n \times k} +{\begin{bmatrix} + \color{red}{x_{1}} \\ + \color{red}{x_{2}} \\ + \color{red}{\vdots} \\ + \color{red}{\vdots} \\ + \color{red}{x_{k}} +\end{bmatrix}}_{k \times 1} := +{\begin{bmatrix} + a_{11} x_1 + a_{22} x_2 + \cdots + a_{1k} x_k \\ + \vdots \\ + \color{red}{a_{i1} x_1 + a_{i2} x_2 + \cdots + a_{ik} x_k} \\ + \vdots \\ + a_{n1} x_1 + a_{n2} x_2 + \cdots + a_{nk} x_k +\end{bmatrix}}_{n \times 1} +``` + +Here is a simple illustration of multiplication of two matrices. + +$$ +AB = +\begin{bmatrix} + a_{11} & a_{12} \\ + \color{red}{a_{21}} & \color{red}{a_{22}} \\ +\end{bmatrix} +\begin{bmatrix} + b_{11} & \color{red}{b_{12}} \\ + b_{21} & \color{red}{b_{22}} \\ +\end{bmatrix} := +\begin{bmatrix} + a_{11}b_{11} + a_{12}b_{21} & a_{11}b_{12} + a_{12}b_{22} \\ + a_{21}b_{11} + a_{22}b_{21} & \color{red}{a_{21}b_{12} + a_{22}b_{22}} +\end{bmatrix} +$$ + +There are many tutorials to help you further visualize this operation, such as + +* [this one](http://www.mathsisfun.com/algebra/matrix-multiplying.html), or +* the discussion on the [Wikipedia page](https://en.wikipedia.org/wiki/Matrix_multiplication). + + +```{note} +Unlike number products, $A B$ and $B A$ are not generally the same thing. +``` + +One important special case is the [identity matrix](https://en.wikipedia.org/wiki/Identity_matrix), which has ones on the principal diagonal and zero elsewhere: + +$$ + I = + \begin{bmatrix} + 1 & \cdots & 0 \\ + \vdots & \ddots & \vdots \\ + 0 & \cdots & 1 + \end{bmatrix} +$$ + +It is a useful exercise to check the following: + +* if $A$ is $n \times k$ and $I$ is the $k \times k$ identity matrix, then $AI = A$, and +* if $I$ is the $n \times n$ identity matrix, then $IA = A$. + + + +### Matrices in NumPy + +```{index} single: Matrix; Numpy +``` + +NumPy arrays are also used as matrices, and have fast, efficient functions and methods for all the standard matrix operations. + +You can create them manually from tuples of tuples (or lists of lists) as follows + +```{code-cell} ipython3 +A = ((1, 2), + (3, 4)) + +type(A) +``` + +```{code-cell} ipython3 +A = np.array(A) + +type(A) +``` + +```{code-cell} ipython3 +A.shape +``` + +The `shape` attribute is a tuple giving the number of rows and columns --- +see [here](https://python-programming.quantecon.org/numpy.html#shape-and-dimension) +for more discussion. + +To get the transpose of `A`, use `A.transpose()` or, more simply, `A.T`. + +There are many convenient functions for creating common matrices (matrices of zeros, +ones, etc.) --- see [here](https://python-programming.quantecon.org/numpy.html#creating-arrays). + +Since operations are performed elementwise by default, scalar multiplication and addition have very natural syntax. + +```{code-cell} ipython3 +A = np.identity(3) # 3 x 3 identity matrix +B = np.ones((3, 3)) # 3 x 3 matrix of ones +2 * A +``` + +```{code-cell} ipython3 +A + B +``` + +To multiply matrices we use the `@` symbol. + + +```{note} +In particular, `A @ B` is matrix multiplication, whereas `A * B` is element-by-element multiplication. +``` + +### Two good model in matrix form + +We can now revisit the two good model and solve {eq}`two_equilibrium` +numerically via matrix algebra. + +This involves some extra steps but the method is widely applicable --- as we +will see when we include more goods. + +First we rewrite {eq}`two_eq_demand` as + +```{math} +:label: two_eq_demand_mat + q^d = D p + h + \quad \text{where} \quad + q^d = + \begin{bmatrix} + q_0^d \\ + q_1^d + \end{bmatrix} + \quad + D = + \begin{bmatrix} + -10 & - 5 \\ + - 1 & - 10 + \end{bmatrix} + \quad \text{and} \quad + h = + \begin{bmatrix} + 100 \\ + 50 + \end{bmatrix}. +``` + +Recall that $p \in \mathbb{R}^{2}$ is the price of two goods. + +(Please check that $q^d = D p + h$ represents the same equations as {eq}`two_eq_demand`.) + +We rewrite {eq}`two_eq_supply` as + +```{math} +:label: two_eq_supply_mat + q^s = C p + \quad \text{where} \quad + q^s = + \begin{bmatrix} + q_0^s \\ + q_1^s + \end{bmatrix} + \quad \text{and} \quad + C = + \begin{bmatrix} + 10 & 5 \\ + 5 & 10 + \end{bmatrix}. +``` + +Now equality of supply and demand can be expressed as $q^s = q^d$, or + +$$ + C p = D p + h. +$$ + +We can rearrange the terms to get + +$$ + (C - D) p = h. +$$ + +If all of the terms were numbers, we could solve for prices as $p = h / +(C-D)$. + +Matrix algebra allows us to do something similar: we can solve for equilibrium +prices using the inverse of $C - D$: + +```{math} +:label: two_matrix + p = (C - D)^{-1} h. +``` + +Before we implement the solution let us consider a more general setting. + + + +### More goods + +It is natural to think about demand systems with more goods. + +For example, even within energy commodities there are many different goods, +including crude oil, gasoline, coal, natural gas, ethanol, and uranium. + +The prices of these goods are related, so it makes sense to study them +together. + +Pencil and paper methods become very time consuming with large systems. + +But fortunately the matrix methods described above are essentially unchanged. + +In general, we can write the demand equation as $q^d = Dp + h$, where + +* $q^d$ is an $n \times 1$ vector of demand quantities for $n$ different goods. +* $D$ is an $n \times n$ "coefficient" matrix. +* $h$ is an $n \times 1$ vector of constant values. + +Similarly, we can write the supply equation as $q^s = Cp + e$, where + +* $q^s$ is an $n \times 1$ vector of supply quantities for the same goods. +* $C$ is an $n \times n$ "coefficient" matrix. +* $e$ is an $n \times 1$ vector of constant values. + +To find an equilibrium, we solve $Dp + h = Cp + e$, or + +```{math} +:label: n_eq_sys_la + (D- C)p = e - h. +``` + +Then the price vector of the n different goods is + +$$ + p = (D- C)^{-1}(e - h). +$$ + + +### General linear systems + +A more general version of the problem described above looks as follows. + +```{math} +:label: la_se + +\begin{matrix} + a_{11} x_1 & + & a_{12} x_2 & + & \cdots & + & a_{1n} x_n & = & b_1 \\ + \vdots & & \vdots & & & & \vdots & & \vdots \\ + a_{n1} x_1 & + & a_{n2} x_2 & + & \cdots & + & a_{nn} x_n & = & b_n +\end{matrix} +``` + +The objective here is to solve for the "unknowns" $x_1, \ldots, x_n$. + +We take as given the coefficients $a_{11}, \ldots, a_{nn}$ and constants $b_1, \ldots, b_n$. + +Notice that we are treating a setting where the number of unknowns equals the +number of equations. + +This is the case where we are most likely to find a well-defined solution. + +(The other cases are referred to as [overdetermined](https://en.wikipedia.org/wiki/Overdetermined_system) and [underdetermined](https://en.wikipedia.org/wiki/Underdetermined_system) systems +of equations --- we defer discussion of these cases until later lectures.) + +In matrix form, the system {eq}`la_se` becomes + +```{math} +:label: la_gf + A x = b + \quad \text{where} \quad + A = + \begin{bmatrix} + a_{11} & \cdots & a_{1n} \\ + \vdots & \vdots & \vdots \\ + a_{n1} & \cdots & a_{nn} + \end{bmatrix} + \quad \text{and} \quad + b = + \begin{bmatrix} + b_1 \\ + \vdots \\ + b_n + \end{bmatrix}. +``` + +```{prf:example} +:label: le_ex_gls +For example, {eq}`n_eq_sys_la` has this form with + +$$ + A = D - C, + \quad + b = e - h + \quad \text{and} \quad + x = p. +$$ +``` + +When considering problems such as {eq}`la_gf`, we need to ask at least some of +the following questions + +* Does a solution actually exist? +* If a solution exists, how should we compute it? + + + +## Solving systems of equations + +```{index} single: Matrix; Solving Systems of Equations +``` + +Recall again the system of equations {eq}`la_se`, which we write here again as + +```{math} +:label: la_se2 + A x = b. +``` + +The problem we face is to find a vector $x \in \mathbb R^n$ that solves +{eq}`la_se2`, taking $b$ and $A$ as given. + +We may not always find a unique vector $x$ that solves {eq}`la_se2`. + +We illustrate two such cases below. + +### No solution + +Consider the system of equations given by, + +$$ +\begin{aligned} + x + 3y &= 3 \\ + 2x + 6y &= -8. +\end{aligned} +$$ + +It can be verified manually that this system has no possible solution. + +To illustrate why this situation arises let's plot the two lines. + +```{code-cell} ipython3 +fig, ax = plt.subplots() +x = np.linspace(-10, 10) +plt.plot(x, (3-x)/3, label=f'$x + 3y = 3$') +plt.plot(x, (-8-2*x)/6, label=f'$2x + 6y = -8$') +plt.legend() +plt.show() +``` + ++++ {"tags": []} + +Clearly, these are parallel lines and hence we will never find a point $x \in \mathbb{R}^2$ +such that these lines intersect. + +Thus, this system has no possible solution. + +We can rewrite this system in matrix form as + +```{math} +:label: no_soln + A x = b + \quad \text{where} \quad + A = + \begin{bmatrix} + 1 & 3 \\ + 2 & 6 + \end{bmatrix} + \quad \text{and} \quad + b = + \begin{bmatrix} + 3 \\ + -8 + \end{bmatrix}. +``` + +It can be noted that the $2^{nd}$ row of matrix $A = (2, 6)$ is just a scalar multiple of the $1^{st}$ row of matrix $A = (1, 3)$. + +The rows of matrix $A$ in this case are called **linearly dependent.** + + + +```{note} +Advanced readers can find a detailed explanation of linear dependence and +independence [here](https://python.quantecon.org/linear_algebra.html#linear-independence). + +But these details are not needed in what follows. + +``` + + + +### Many solutions + +Now consider, + +$$ +\begin{aligned} + x - 2y &= -4 \\ + -2x + 4y &= 8. +\end{aligned} +$$ + +Any vector $v = (x,y)$ such that $x = 2y - 4$ will solve the above system. + +Since we can find infinite such vectors this system has infinitely many solutions. + +This is because the rows of the corresponding matrix + +```{math} +:label: many_solns + A = + \begin{bmatrix} + 1 & -2 \\ + -2 & 4 + \end{bmatrix}. +``` + +are linearly dependent --- can you see why? + +We now impose conditions on $A$ in {eq}`la_se2` that rule out these problems. + + +### Nonsingular matrices + +To every square matrix we can assign a unique number called the +[determinant](https://en.wikipedia.org/wiki/Determinant). + +For $2 \times 2$ matrices, the determinant is given by, + +$$ +\begin{bmatrix} + \color{red}{a} & \color{blue}{b} \\ + \color{blue}{c} & \color{red}{d} +\end{bmatrix} += +{\color{red}{ad}} - {\color{blue}{bc}}. +$$ + +If the determinant of $A$ is not zero, then we say that $A$ is *nonsingular*. + +A square matrix $A$ is nonsingular if and only if the rows and columns of $A$ +are linearly independent. + +A more detailed explanation of matrix inverse can be found [here](https://www.mathsisfun.com/algebra/matrix-inverse.html). + +You can check yourself that the in {eq}`no_soln` and {eq}`many_solns` with +linearly dependent rows are singular matrices. + +This gives us a useful one-number summary of whether or not a square matrix +can be inverted. + +In particular, a square matrix $A$ has a nonzero determinant, if and only if +it possesses an *inverse matrix* $A^{-1}$, with the property that $A A^{-1} = +A^{-1} A = I$. + +As a consequence, if we pre-multiply both sides of $Ax = b$ by $A^{-1}$, we +get + +```{math} +:label: la_se_inv + x = A^{-1} b. +``` + +This is the solution to $Ax = b$ --- the solution we are looking for. + + + +### Linear equations with NumPy + +```{index} single: Linear Algebra; SciPy +``` + +In the two good example we obtained the matrix equation, + +$$ +p = (C-D)^{-1} h. +$$ + +where $C$, $D$ and $h$ are given by {eq}`two_eq_demand_mat` and {eq}`two_eq_supply_mat`. + +This equation is analogous to {eq}`la_se_inv` with $A = (C-D)^{-1}$, $b = h$, and $x = p$. + +We can now solve for equilibrium prices with NumPy's `linalg` submodule. + +All of these routines are Python front ends to time-tested and highly optimized FORTRAN code. + +```{code-cell} ipython3 +C = ((10, 5), # Matrix C + (5, 10)) +``` + +Now we change this to a NumPy array. + +```{code-cell} ipython3 +C = np.array(C) +``` + +```{code-cell} ipython3 +D = ((-10, -5), # Matrix D + (-1, -10)) +D = np.array(D) +``` + +```{code-cell} ipython3 +h = np.array((100, 50)) # Vector h +h.shape = 2,1 # Transforming h to a column vector +``` + +```{code-cell} ipython3 +from numpy.linalg import det, inv +A = C - D +# Check that A is nonsingular (non-zero determinant), and hence invertible +det(A) +``` + +```{code-cell} ipython3 +A_inv = inv(A) # compute the inverse +A_inv +``` + +```{code-cell} ipython3 +p = A_inv @ h # equilibrium prices +p +``` + +```{code-cell} ipython3 +q = C @ p # equilibrium quantities +q +``` + +Notice that we get the same solutions as the pencil and paper case. + +We can also solve for $p$ using `solve(A, h)` as follows. + +```{code-cell} ipython3 +from numpy.linalg import solve +p = solve(A, h) # equilibrium prices +p +``` + +```{code-cell} ipython3 +q = C @ p # equilibrium quantities +q +``` + +Observe how we can solve for $x = A^{-1} y$ by either via `inv(A) @ y`, or using `solve(A, y)`. + +The latter method uses a different algorithm that is numerically more stable and hence should be the default option. + + + +## Exercises + +```{exercise-start} +:label: lin_eqs_ex1 +``` + +Let's consider a market with 3 commodities - good 0, good 1 and good 2. + +The demand for each good depends on the price of the other two goods and is given by: + +$$ +\begin{aligned} + q_0^d & = 90 - 15p_0 + 5p_1 + 5p_2 \\ + q_1^d & = 60 + 5p_0 - 10p_1 + 10p_2 \\ + q_2^d & = 50 + 5p_0 + 5p_1 - 5p_2 +\end{aligned} +$$ + +(Here demand decreases when own price increases but increases when prices of other goods increase.) + +The supply of each good is given by: + +$$ +\begin{aligned} + q_0^s & = -10 + 20p_0 \\ + q_1^s & = -15 + 15p_1 \\ + q_2^s & = -5 + 10p_2 +\end{aligned} +$$ + +Equilibrium holds when supply equals demand, i.e, $q_0^d = q_0^s$, $q_1^d = q_1^s$ and $q_2^d = q_2^s$. + +1. Set up the market as a system of linear equations. +2. Use matrix algebra to solve for equilibrium prices. Do this using both the `numpy.linalg.solve` + and `inv(A)` methods. Compare the solutions. + +```{exercise-end} +``` +```{solution-start} lin_eqs_ex1 +:class: dropdown +``` + +The generated system would be: + +$$ +\begin{aligned} + 35p_0 - 5p_1 - 5p_2 = 100 \\ + -5p_0 + 25p_1 - 10p_2 = 75 \\ + -5p_0 - 5p_1 + 15p_2 = 55 +\end{aligned} +$$ + +In matrix form we will write this as: + +$$ +Ap = b +\quad \text{where} \quad +A = +\begin{bmatrix} + 35 & -5 & -5 \\ + -5 & 25 & -10 \\ + -5 & -5 & 15 +\end{bmatrix} +, \quad p = +\begin{bmatrix} + p_0 \\ + p_1 \\ + p_2 +\end{bmatrix} +\quad \text{and} \quad +b = +\begin{bmatrix} + 100 \\ + 75 \\ + 55 +\end{bmatrix} +$$ + +```{code-cell} +import numpy as np +from numpy.linalg import det + +A = np.array([[35, -5, -5], # matrix A + [-5, 25, -10], + [-5, -5, 15]]) + +b = np.array((100, 75, 55)) # column vector b +b.shape = (3, 1) + +det(A) # check if A is nonsingular +``` + +```{code-cell} +# Using inverse +from numpy.linalg import det + +A_inv = inv(A) + +p = A_inv @ b +p +``` + +```{code-cell} +# Using numpy.linalg.solve +from numpy.linalg import solve +p = solve(A, b) +p +``` + +The solution is given by: +$$ +p_0 = 4.6925, \; p_1 = 7.0625 \;\; \text{and} \;\; p_2 = 7.675 +$$ + +```{solution-end} +``` + +```{exercise-start} +:label: lin_eqs_ex2 +``` +Earlier in the lecture we discussed cases where the system of equations given by $Ax = b$ has no solution. + +In this case $Ax = b$ is called an _inconsistent_ system of equations. + +When faced with an inconsistent system we try to find the best "approximate" solution. + +There are various methods to do this, one such method is the **method of least squares.** + +Suppose we have an inconsistent system + +```{math} +:label: inconsistent + Ax = b +``` +where $A$ is an $m \times n$ matrix and $b$ is an $m \times 1$ column vector. + +A **least squares solution** to {eq}`inconsistent` is an $n \times 1$ column vector $\hat{x}$ such that, for all other vectors $x \in \mathbb{R}^n$, the distance from $A\hat{x}$ to $b$ +is less than the distance from $Ax$ to $b$. + +That is, + +$$ + \|A\hat{x} - b\| \leq \|Ax - b\| +$$ + +It can be shown that, for the system of equations $Ax = b$, the least squares +solution $\hat{x}$ is + +```{math} +:label: least_squares + \hat{x} = (A^T A)^{-1} A^T b +``` + +Now consider the general equation of a linear demand curve of a good given by: + +$$ + p = m - nq +$$ + +where $p$ is the price of the good and $q$ is the quantity demanded. + +Suppose we are trying to *estimate* the values of $m$ and $n$. + +We do this by repeatedly observing the price and quantity (for example, each +month) and then choosing $m$ and $n$ to fit the relationship between $p$ and +$q$. + +We have the following observations: + +| Price | Quantity Demanded | +|:-----:|:-----------------:| +| 1 | 9 | +| 3 | 7 | +| 8 | 3 | + + +Requiring the demand curve $p = m - nq$ to pass through all these points leads to the +following three equations: + +$$ +\begin{aligned} + 1 = m - 9n \\ + 3 = m - 7n \\ + 8 = m - 3n +\end{aligned} +$$ + +Thus we obtain a system of equations $Ax = b$ where $A = \begin{bmatrix} 1 & -9 \\ 1 & -7 \\ 1 & -3 \end{bmatrix}$, +$x = \begin{bmatrix} m \\ n \end{bmatrix}$ and $b = \begin{bmatrix} 1 \\ 3 \\ 8 \end{bmatrix}$. + +It can be verified that this system has no solutions. + +(The problem is that we have three equations and only two unknowns.) + +We will thus try to find the best approximate solution for $x$. + +1. Use {eq}`least_squares` and matrix algebra to find the least squares solution $\hat{x}$. +2. Find the least squares solution using `numpy.linalg.lstsq` and compare the results. + +```{exercise-end} +``` + +```{solution-start} lin_eqs_ex2 +:class: dropdown +``` + +```{code-cell} ipython3 +import numpy as np +from numpy.linalg import inv +``` + +```{code-cell} ipython3 +# Using matrix algebra +A = np.array([[1, -9], # matrix A + [1, -7], + [1, -3]]) + +A_T = np.transpose(A) # transpose of matrix A + +b = np.array((1, 3, 8)) # column vector b +b.shape = (3, 1) + +x = inv(A_T @ A) @ A_T @ b +x +``` + +```{code-cell} ipython3 +# Using numpy.linalg.lstsq +x, res, _, _ = np.linalg.lstsq(A, b, rcond=None) +``` + +```{code-cell} ipython3 +:tags: [hide-input] + +print(f"x\u0302 = {x}") +print(f"\u2016Ax\u0302 - b\u2016\u00B2 = {res[0]}") +``` + +Here is a visualization of how the least squares method approximates the equation of a line connecting a set of points. + +We can also describe this as "fitting" a line between a set of points. + +```{code-cell} ipython3 +fig, ax = plt.subplots() +p = np.array((1, 3, 8)) +q = np.array((9, 7, 3)) + +a, b = x + +ax.plot(q, p, 'o', label='observations', markersize=5) +ax.plot(q, a - b*q, 'r', label='Fitted line') +plt.xlabel('quantity demanded') +plt.ylabel('price') +plt.legend() +plt.show() +``` + +```{solution-end} +``` + + +### Further reading + +The documentation of the `numpy.linalg` submodule can be found [here](https://numpy.org/devdocs/reference/routines.linalg.html). + +More advanced topics in linear algebra can be found [here](https://python.quantecon.org/linear_algebra.html#id5). diff --git a/content/lectures/lln_clt.ipynb b/book/_build/html/_sources/lln_clt.ipynb similarity index 92% rename from content/lectures/lln_clt.ipynb rename to book/_build/html/_sources/lln_clt.ipynb index 630def6..b6dd100 100644 --- a/content/lectures/lln_clt.ipynb +++ b/book/_build/html/_sources/lln_clt.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "a1a541e9", + "id": "77b86da4", "metadata": {}, "source": [ "# LLN and CLT\n", @@ -30,23 +30,22 @@ { "cell_type": "code", "execution_count": null, - "id": "84030d84", + "id": "f6687e8d", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", - "import random\n", "import numpy as np\n", "import scipy.stats as st" ] }, { "cell_type": "markdown", - "id": "9277a25b", + "id": "13a69b90", "metadata": {}, "source": [ "(lln_mr)=\n", - "## The Law of Large Numbers\n", + "## The law of large numbers\n", "\n", "```{index} single: Law of Large Numbers\n", "```\n", @@ -54,10 +53,13 @@ "We begin with the law of large numbers, which tells us when sample averages\n", "will converge to their population means.\n", "\n", - "### The LLN in Action\n", + "### The LLN in action\n", "\n", "Let's see an example of the LLN in action before we go further.\n", "\n", + "```{prf:example}\n", + ":label: lln_ex_ber\n", + "\n", "Consider a [Bernoulli random variable](https://en.wikipedia.org/wiki/Bernoulli_distribution) $X$ with parameter $p$.\n", "\n", "This means that $X$ takes values in $\\{0,1\\}$ and $\\mathbb P\\{X=1\\} = p$.\n", @@ -75,6 +77,7 @@ " \\mathbb E X \n", " = 0 \\cdot \\mathbb P\\{X=0\\} + 1 \\cdot \\mathbb P\\{X=1\\} = \\mathbb P\\{X=1\\} = p\n", "$$\n", + "```\n", "\n", "We can generate a draw of $X$ with `scipy.stats` (imported as `st`) as follows:" ] @@ -82,7 +85,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8c7c7d66", + "id": "0ace2b8b", "metadata": {}, "outputs": [], "source": [ @@ -93,11 +96,13 @@ }, { "cell_type": "markdown", - "id": "4618597a", + "id": "d5882c51", "metadata": {}, "source": [ "In this setting, the LLN tells us if we flip the coin many times, the fraction\n", - "of heads that we see will be close to the mean $p$.\n", + "of heads that we see will be close to the mean $p$. \n", + "\n", + "We use $n$ to represent the number of times the coin is flipped.\n", "\n", "Let's check this:" ] @@ -105,7 +110,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c555cfef", + "id": "6ce6408f", "metadata": {}, "outputs": [], "source": [ @@ -116,7 +121,7 @@ }, { "cell_type": "markdown", - "id": "465bffeb", + "id": "9d627ea3", "metadata": {}, "source": [ "If we change $p$ the claim still holds:" @@ -125,7 +130,7 @@ { "cell_type": "code", "execution_count": null, - "id": "d5907fb3", + "id": "70be71ca", "metadata": {}, "outputs": [], "source": [ @@ -136,7 +141,7 @@ }, { "cell_type": "markdown", - "id": "f0484a0c", + "id": "a8237c72", "metadata": {}, "source": [ "Let's connect this to the discussion above, where we said the sample average\n", @@ -208,6 +213,7 @@ "\n", "The next theorem is called Kolmogorov's strong law of large numbers.\n", "\n", + "(iid-theorem)=\n", "````{prf:theorem}\n", "If $X_1, \\ldots, X_n$ are IID and $\\mathbb E |X|$ is finite, then\n", "\n", @@ -226,7 +232,7 @@ "\n", "\n", "\n", - "### Comments on the Theorem\n", + "### Comments on the theorem\n", "\n", "What does the probability one statement in the theorem mean?\n", "\n", @@ -282,7 +288,7 @@ { "cell_type": "code", "execution_count": null, - "id": "cd55402a", + "id": "8dc5a039", "metadata": {}, "outputs": [], "source": [ @@ -298,7 +304,7 @@ }, { "cell_type": "markdown", - "id": "de558038", + "id": "eb56ca66", "metadata": {}, "source": [ "Now we write a function to generate $m$ sample means and histogram them." @@ -307,7 +313,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a907b545", + "id": "15548034", "metadata": {}, "outputs": [], "source": [ @@ -336,7 +342,7 @@ }, { "cell_type": "markdown", - "id": "39fd7df8", + "id": "41472767", "metadata": {}, "source": [ "Now we call the function." @@ -345,7 +351,7 @@ { "cell_type": "code", "execution_count": null, - "id": "48375bf4", + "id": "609627a6", "metadata": {}, "outputs": [], "source": [ @@ -357,7 +363,7 @@ }, { "cell_type": "markdown", - "id": "a9791c16", + "id": "66e1c64b", "metadata": {}, "source": [ "We can see that the distribution of $\\bar X$ is clustered around $\\mathbb E X$\n", @@ -365,7 +371,7 @@ "\n", "Let's vary `n` to see how the distribution of the sample mean changes.\n", "\n", - "We will use a violin plot to show the different distributions.\n", + "We will use a [violin plot](https://intro.quantecon.org/prob_dist.html#violin-plots) to show the different distributions.\n", "\n", "Each distribution in the violin plot represents the distribution of $X_n$ for some $n$, calculated by simulation." ] @@ -373,7 +379,7 @@ { "cell_type": "code", "execution_count": null, - "id": "329ef9c2", + "id": "aeee25b0", "metadata": {}, "outputs": [], "source": [ @@ -407,7 +413,7 @@ }, { "cell_type": "markdown", - "id": "bbe8b4a7", + "id": "9b71ed78", "metadata": {}, "source": [ "Let's try with a normal distribution." @@ -416,7 +422,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b0445b64", + "id": "15bf32d8", "metadata": {}, "outputs": [], "source": [ @@ -425,7 +431,7 @@ }, { "cell_type": "markdown", - "id": "6d485da3", + "id": "3ed95e36", "metadata": {}, "source": [ "As $n$ gets large, more probability mass clusters around the population mean $\\mu$.\n", @@ -436,7 +442,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3fd2a554", + "id": "f399568d", "metadata": {}, "outputs": [], "source": [ @@ -445,7 +451,7 @@ }, { "cell_type": "markdown", - "id": "14883965", + "id": "abbb3e31", "metadata": {}, "source": [ "We get a similar result." @@ -453,7 +459,7 @@ }, { "cell_type": "markdown", - "id": "b1a90945", + "id": "d0f49c78", "metadata": {}, "source": [ "## Breaking the LLN\n", @@ -462,7 +468,7 @@ "\n", "If these assumptions do not hold, then the LLN might fail.\n", "\n", - "### Infinite First Moment\n", + "### Infinite first moment\n", "\n", "As indicated by the theorem, the LLN can break when $\\mathbb E |X|$ is not finite.\n", "\n", @@ -476,19 +482,20 @@ "\n", "Hence the LLN does not hold.\n", "\n", - "The LLN fails to hold here because the assumption $\\mathbb E|X| = \\infty$ is violated by the Cauchy distribution." + "The LLN fails to hold here because the assumption $\\mathbb E|X| < \\infty$ is violated by the Cauchy distribution." ] }, { "cell_type": "markdown", - "id": "ad15936a", + "id": "8e6b3598", "metadata": {}, "source": [ - "### Failure of the IID Condition\n", + "### Failure of the IID condition\n", "\n", "The LLN can also fail to hold when the IID assumption is violated.\n", "\n", - "For example, suppose that\n", + "```{prf:example}\n", + ":label: lln_ex_fail\n", "\n", "$$\n", " X_0 \\sim N(0,1)\n", @@ -503,6 +510,7 @@ "$$\n", "\n", "Therefore, the distribution of $\\bar X_n$ is $N(0,1)$ for all $n$!\n", + "```\n", "\n", "Does this contradict the LLN, which says that the distribution of $\\bar X_n$\n", "collapses to the single point $\\mu$?\n", @@ -525,10 +533,10 @@ }, { "cell_type": "markdown", - "id": "62521ff1", + "id": "d03eae26", "metadata": {}, "source": [ - "## Central Limit Theorem\n", + "## Central limit theorem\n", "\n", "```{index} single: Central Limit Theorem\n", "```\n", @@ -537,7 +545,7 @@ "distribution of the deviation between sample averages and population means.\n", "\n", "\n", - "### Statement of the Theorem\n", + "### Statement of the theorem\n", "\n", "The central limit theorem is one of the most remarkable results in all of mathematics.\n", "\n", @@ -562,9 +570,9 @@ "Here $\\stackrel { d } {\\to} N(0, \\sigma^2)$ indicates [convergence in distribution](https://en.wikipedia.org/wiki/Convergence_of_random_variables#Convergence_in_distribution) to a centered (i.e., zero mean) normal with standard deviation $\\sigma$.\n", "\n", "\n", - "The striking implication of the CLT is that for **any** distribution with\n", + "The striking implication of the CLT is that for any distribution with\n", "finite [second moment](https://en.wikipedia.org/wiki/Moment_(mathematics)), the simple operation of adding independent\n", - "copies **always** leads to a Gaussian curve.\n", + "copies always leads to a Gaussian(Normal) curve.\n", "\n", "\n", "\n", @@ -591,7 +599,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a6fd63fc", + "id": "64db9c1c", "metadata": {}, "outputs": [], "source": [ @@ -626,7 +634,7 @@ }, { "cell_type": "markdown", - "id": "a6b5c6a1", + "id": "fbd6f308", "metadata": {}, "source": [ "(Notice the absence of for loops --- every operation is vectorized, meaning that the major calculations are all shifted to fast C code.)\n", @@ -641,7 +649,7 @@ "```{exercise} \n", ":label: lln_ex1\n", "\n", - "Repeat the simulation [above1](sim_one) with the [Beta distribution](https://en.wikipedia.org/wiki/Beta_distribution).\n", + "Repeat the simulation [above](sim_one) with the [Beta distribution](https://en.wikipedia.org/wiki/Beta_distribution).\n", "\n", "You can choose any $\\alpha > 0$ and $\\beta > 0$.\n", "```\n", @@ -654,7 +662,7 @@ { "cell_type": "code", "execution_count": null, - "id": "34db1fc7", + "id": "f013bb68", "metadata": {}, "outputs": [], "source": [ @@ -687,7 +695,7 @@ }, { "cell_type": "markdown", - "id": "823e687a", + "id": "0b9996c7", "metadata": {}, "source": [ "```{solution-end}\n", @@ -746,7 +754,7 @@ "$$\n", "\n", "where $\\alpha, \\beta, \\sigma$ are constants and $\\epsilon_1, \\epsilon_2,\n", - "\\ldots$ is IID and standard norma.\n", + "\\ldots$ are IID and standard normal.\n", "\n", "Suppose that\n", "\n", @@ -818,7 +826,7 @@ { "cell_type": "code", "execution_count": null, - "id": "92cd610f", + "id": "591a1b8f", "metadata": {}, "outputs": [], "source": [ @@ -853,7 +861,7 @@ }, { "cell_type": "markdown", - "id": "7a665dfe", + "id": "c1a96039", "metadata": {}, "source": [ "We see the convergence of $\\bar x$ around $\\mu$ even when the independence assumption is violated.\n", @@ -865,12 +873,52 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.1" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 12, + 35, + 39, + 78, + 82, + 91, + 95, + 99, + 103, + 245, + 254, + 258, + 280, + 284, + 289, + 300, + 327, + 331, + 333, + 339, + 341, + 345, + 369, + 412, + 473, + 501, + 524, + 550, + 676, + 704 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/lln_clt.md b/book/_build/html/_sources/lln_clt.md new file mode 100644 index 0000000..83f21d4 --- /dev/null +++ b/book/_build/html/_sources/lln_clt.md @@ -0,0 +1,710 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.1 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# LLN and CLT + +## Overview + +This lecture illustrates two of the most important results in probability and statistics: + +1. the law of large numbers (LLN) and +2. the central limit theorem (CLT). + +These beautiful theorems lie behind many of the most fundamental results in +econometrics and quantitative economic modeling. + +The lecture is based around simulations that show the LLN and CLT in action. + +We also demonstrate how the LLN and CLT break down when the assumptions they +are based on do not hold. + +This lecture will focus on the univariate case (the multivariate case is treated [in a more advanced lecture](https://python.quantecon.org/lln_clt.html#the-multivariate-case)). + +We'll need the following imports: + +```{code-cell} ipython3 +import matplotlib.pyplot as plt +import numpy as np +import scipy.stats as st +``` + +(lln_mr)= +## The law of large numbers + +```{index} single: Law of Large Numbers +``` + +We begin with the law of large numbers, which tells us when sample averages +will converge to their population means. + +### The LLN in action + +Let's see an example of the LLN in action before we go further. + +```{prf:example} +:label: lln_ex_ber + +Consider a [Bernoulli random variable](https://en.wikipedia.org/wiki/Bernoulli_distribution) $X$ with parameter $p$. + +This means that $X$ takes values in $\{0,1\}$ and $\mathbb P\{X=1\} = p$. + +We can think of drawing $X$ as tossing a biased coin where + +* the coin falls on "heads" with probability $p$ and +* the coin falls on "tails" with probability $1-p$ + +We set $X=1$ if the coin is "heads" and zero otherwise. + +The (population) mean of $X$ is + +$$ + \mathbb E X + = 0 \cdot \mathbb P\{X=0\} + 1 \cdot \mathbb P\{X=1\} = \mathbb P\{X=1\} = p +$$ +``` + +We can generate a draw of $X$ with `scipy.stats` (imported as `st`) as follows: + +```{code-cell} ipython3 +p = 0.8 +X = st.bernoulli.rvs(p) +print(X) +``` + +In this setting, the LLN tells us if we flip the coin many times, the fraction +of heads that we see will be close to the mean $p$. + +We use $n$ to represent the number of times the coin is flipped. + +Let's check this: + +```{code-cell} ipython3 +n = 1_000_000 +X_draws = st.bernoulli.rvs(p, size=n) +print(X_draws.mean()) # count the number of 1's and divide by n +``` + +If we change $p$ the claim still holds: + +```{code-cell} ipython3 +p = 0.3 +X_draws = st.bernoulli.rvs(p, size=n) +print(X_draws.mean()) +``` + +Let's connect this to the discussion above, where we said the sample average +converges to the "population mean". + +Think of $X_1, \ldots, X_n$ as independent flips of the coin. + +The population mean is the mean in an infinite sample, which equals the +expectation $\mathbb E X$. + +The sample mean of the draws $X_1, \ldots, X_n$ is + +$$ + \bar X_n := \frac{1}{n} \sum_{i=1}^n X_i +$$ + +In this case, it is the fraction of draws that equal one (the number of heads divided by $n$). + +Thus, the LLN tells us that for the Bernoulli trials above + +```{math} +:label: exp + \bar X_n \to \mathbb E X = p + \qquad (n \to \infty) +``` + +This is exactly what we illustrated in the code. + + +(lln_ksl)= +### Statement of the LLN + +Let's state the LLN more carefully. + +Let $X_1, \ldots, X_n$ be random variables, all of which have the same +distribution. + +These random variables can be continuous or discrete. + +For simplicity we will + +* assume they are continuous and +* let $f$ denote their common density function + +The last statement means that for any $i$ in $\{1, \ldots, n\}$ and any +numbers $a, b$, + + +$$ + \mathbb P\{a \leq X_i \leq b\} = \int_a^b f(x) dx +$$ + +(For the discrete case, we need to replace densities with probability mass +functions and integrals with sums.) + +Let $\mu$ denote the common mean of this sample. + +Thus, for each $i$, + +$$ + \mu := \mathbb E X_i = \int_{-\infty}^{\infty} x f(x) dx +$$ + +The sample mean is + +$$ + \bar X_n := \frac{1}{n} \sum_{i=1}^n X_i +$$ + +The next theorem is called Kolmogorov's strong law of large numbers. + +(iid-theorem)= +````{prf:theorem} +If $X_1, \ldots, X_n$ are IID and $\mathbb E |X|$ is finite, then + +```{math} +:label: lln_as + +\mathbb P \left\{ \bar X_n \to \mu \text{ as } n \to \infty \right\} = 1 +``` +```` + +Here + +* IID means independent and identically distributed and +* $\mathbb E |X| = \int_{-\infty}^\infty |x| f(x) dx$ + + + + +### Comments on the theorem + +What does the probability one statement in the theorem mean? + +Let's think about it from a simulation perspective, imagining for a moment that +our computer can generate perfect random samples (although this [isn't strictly true](https://en.wikipedia.org/wiki/Pseudorandom_number_generator)). + +Let's also imagine that we can generate infinite sequences so that the +statement $\bar X_n \to \mu$ can be evaluated. + +In this setting, {eq}`lln_as` should be interpreted as meaning that the +probability of the computer producing a sequence where $\bar X_n \to \mu$ +fails to occur is zero. + +### Illustration + +```{index} single: Law of Large Numbers; Illustration +``` + +Let's illustrate the LLN using simulation. + +When we illustrate it, we will use a key idea: the sample mean $\bar X_n$ is +itself a random variable. + +The reason $\bar X_n$ is a random variable is that it's a function of the +random variables $X_1, \ldots, X_n$. + +What we are going to do now is + +1. pick some fixed distribution to draw each $X_i$ from +1. set $n$ to some large number + +and then repeat the following three instructions. + +1. generate the draws $X_1, \ldots, X_n$ +1. calculate the sample mean $\bar X_n$ and record its value in an array `sample_means` +1. go to step 1. + +We will loop over these three steps $m$ times, where $m$ is some large integer. + +The array `sample_means` will now contain $m$ draws of the random variable $\bar X_n$. + +If we histogram these observations of $\bar X_n$, we should see that they are clustered around the population mean $\mathbb E X$. + +Moreover, if we repeat the exercise with a larger value of $n$, we should see that the observations are even more tightly clustered around the population mean. + +This is, in essence, what the LLN is telling us. + +To implement these steps, we will use functions. + +Our first function generates a sample mean of size $n$ given a distribution. + +```{code-cell} ipython3 +def draw_means(X_distribution, # The distribution of each X_i + n): # The size of the sample mean + + # Generate n draws: X_1, ..., X_n + X_samples = X_distribution.rvs(size=n) + + # Return the sample mean + return np.mean(X_samples) +``` + +Now we write a function to generate $m$ sample means and histogram them. + +```{code-cell} ipython3 +def generate_histogram(X_distribution, n, m): + + # Compute m sample means + + sample_means = np.empty(m) + for j in range(m): + sample_means[j] = draw_means(X_distribution, n) + + # Generate a histogram + + fig, ax = plt.subplots() + ax.hist(sample_means, bins=30, alpha=0.5, density=True) + μ = X_distribution.mean() # Get the population mean + σ = X_distribution.std() # and the standard deviation + ax.axvline(x=μ, ls="--", c="k", label=fr"$\mu = {μ}$") + + ax.set_xlim(μ - σ, μ + σ) + ax.set_xlabel(r'$\bar X_n$', size=12) + ax.set_ylabel('density', size=12) + ax.legend() + plt.show() +``` + +Now we call the function. + +```{code-cell} ipython3 +# pick a distribution to draw each $X_i$ from +X_distribution = st.norm(loc=5, scale=2) +# Call the function +generate_histogram(X_distribution, n=1_000, m=1000) +``` + +We can see that the distribution of $\bar X$ is clustered around $\mathbb E X$ +as expected. + +Let's vary `n` to see how the distribution of the sample mean changes. + +We will use a [violin plot](https://intro.quantecon.org/prob_dist.html#violin-plots) to show the different distributions. + +Each distribution in the violin plot represents the distribution of $X_n$ for some $n$, calculated by simulation. + +```{code-cell} ipython3 +def means_violin_plot(distribution, + ns = [1_000, 10_000, 100_000], + m = 10_000): + + data = [] + for n in ns: + sample_means = [draw_means(distribution, n) for i in range(m)] + data.append(sample_means) + + fig, ax = plt.subplots() + + ax.violinplot(data) + μ = distribution.mean() + ax.axhline(y=μ, ls="--", c="k", label=fr"$\mu = {μ}$") + + labels=[fr'$n = {n}$' for n in ns] + + ax.set_xticks(np.arange(1, len(labels) + 1), labels=labels) + ax.set_xlim(0.25, len(labels) + 0.75) + + + plt.subplots_adjust(bottom=0.15, wspace=0.05) + + ax.set_ylabel('density', size=12) + ax.legend() + plt.show() +``` + +Let's try with a normal distribution. + +```{code-cell} ipython3 +means_violin_plot(st.norm(loc=5, scale=2)) +``` + +As $n$ gets large, more probability mass clusters around the population mean $\mu$. + +Now let's try with a Beta distribution. + +```{code-cell} ipython3 +means_violin_plot(st.beta(6, 6)) +``` + +We get a similar result. + ++++ + +## Breaking the LLN + +We have to pay attention to the assumptions in the statement of the LLN. + +If these assumptions do not hold, then the LLN might fail. + +### Infinite first moment + +As indicated by the theorem, the LLN can break when $\mathbb E |X|$ is not finite. + +We can demonstrate this using the [Cauchy distribution](https://en.wikipedia.org/wiki/Cauchy_distribution). + +The Cauchy distribution has the following property: + +If $X_1, \ldots, X_n$ are IID and Cauchy, then so is $\bar X_n$. + +This means that the distribution of $\bar X_n$ does not eventually concentrate on a single number. + +Hence the LLN does not hold. + +The LLN fails to hold here because the assumption $\mathbb E|X| < \infty$ is violated by the Cauchy distribution. + ++++ + + +### Failure of the IID condition + +The LLN can also fail to hold when the IID assumption is violated. + +```{prf:example} +:label: lln_ex_fail + +$$ + X_0 \sim N(0,1) + \quad \text{and} \quad + X_i = X_{i-1} \quad \text{for} \quad i = 1, ..., n +$$ + +In this case, + +$$ + \bar X_n = \frac{1}{n} \sum_{i=1}^n X_i = X_0 \sim N(0,1) +$$ + +Therefore, the distribution of $\bar X_n$ is $N(0,1)$ for all $n$! +``` + +Does this contradict the LLN, which says that the distribution of $\bar X_n$ +collapses to the single point $\mu$? + +No, the LLN is correct --- the issue is that its assumptions are not +satisfied. + +In particular, the sequence $X_1, \ldots, X_n$ is not independent. + + +```{note} +:name: iid_violation + +Although in this case the violation of IID breaks the LLN, there *are* situations +where IID fails but the LLN still holds. + +We will show an example in the [exercise](lln_ex3). +``` + ++++ + +## Central limit theorem + +```{index} single: Central Limit Theorem +``` + +Next, we turn to the central limit theorem (CLT), which tells us about the +distribution of the deviation between sample averages and population means. + + +### Statement of the theorem + +The central limit theorem is one of the most remarkable results in all of mathematics. + +In the IID setting, it tells us the following: + + +````{prf:theorem} +:label: statement_clt + +If $X_1, \ldots, X_n$ is IID with common mean $\mu$ and common variance +$\sigma^2 \in (0, \infty)$, then + +```{math} +:label: lln_clt + +\sqrt{n} ( \bar X_n - \mu ) \stackrel { d } {\to} N(0, \sigma^2) +\quad \text{as} \quad +n \to \infty +``` +```` + +Here $\stackrel { d } {\to} N(0, \sigma^2)$ indicates [convergence in distribution](https://en.wikipedia.org/wiki/Convergence_of_random_variables#Convergence_in_distribution) to a centered (i.e., zero mean) normal with standard deviation $\sigma$. + + +The striking implication of the CLT is that for any distribution with +finite [second moment](https://en.wikipedia.org/wiki/Moment_(mathematics)), the simple operation of adding independent +copies always leads to a Gaussian(Normal) curve. + + + + +### Simulation 1 + +Since the CLT seems almost magical, running simulations that verify its implications is one good way to build understanding. + +To this end, we now perform the following simulation + +1. Choose an arbitrary distribution $F$ for the underlying observations $X_i$. +1. Generate independent draws of $Y_n := \sqrt{n} ( \bar X_n - \mu )$. +1. Use these draws to compute some measure of their distribution --- such as a histogram. +1. Compare the latter to $N(0, \sigma^2)$. + +Here's some code that does exactly this for the exponential distribution +$F(x) = 1 - e^{- \lambda x}$. + +(Please experiment with other choices of $F$, but remember that, to conform with the conditions of the CLT, the distribution must have a finite second moment.) + +(sim_one)= + +```{code-cell} ipython3 +# Set parameters +n = 250 # Choice of n +k = 1_000_000 # Number of draws of Y_n +distribution = st.expon(2) # Exponential distribution, λ = 1/2 +μ, σ = distribution.mean(), distribution.std() + +# Draw underlying RVs. Each row contains a draw of X_1,..,X_n +data = distribution.rvs((k, n)) +# Compute mean of each row, producing k draws of \bar X_n +sample_means = data.mean(axis=1) +# Generate observations of Y_n +Y = np.sqrt(n) * (sample_means - μ) + +# Plot +fig, ax = plt.subplots(figsize=(10, 6)) +xmin, xmax = -3 * σ, 3 * σ +ax.set_xlim(xmin, xmax) +ax.hist(Y, bins=60, alpha=0.4, density=True) +xgrid = np.linspace(xmin, xmax, 200) +ax.plot(xgrid, st.norm.pdf(xgrid, scale=σ), + 'k-', lw=2, label='$N(0, \sigma^2)$') +ax.set_xlabel(r"$Y_n$", size=12) +ax.set_ylabel(r"$density$", size=12) + +ax.legend() + +plt.show() +``` + +(Notice the absence of for loops --- every operation is vectorized, meaning that the major calculations are all shifted to fast C code.) + +The fit to the normal density is already tight and can be further improved by increasing `n`. + + +## Exercises + + + +```{exercise} +:label: lln_ex1 + +Repeat the simulation [above](sim_one) with the [Beta distribution](https://en.wikipedia.org/wiki/Beta_distribution). + +You can choose any $\alpha > 0$ and $\beta > 0$. +``` + +```{solution-start} lln_ex1 +:class: dropdown +``` + +```{code-cell} ipython3 +# Set parameters +n = 250 # Choice of n +k = 1_000_000 # Number of draws of Y_n +distribution = st.beta(2,2) # We chose Beta(2, 2) as an example +μ, σ = distribution.mean(), distribution.std() + +# Draw underlying RVs. Each row contains a draw of X_1,..,X_n +data = distribution.rvs((k, n)) +# Compute mean of each row, producing k draws of \bar X_n +sample_means = data.mean(axis=1) +# Generate observations of Y_n +Y = np.sqrt(n) * (sample_means - μ) + +# Plot +fig, ax = plt.subplots(figsize=(10, 6)) +xmin, xmax = -3 * σ, 3 * σ +ax.set_xlim(xmin, xmax) +ax.hist(Y, bins=60, alpha=0.4, density=True) +ax.set_xlabel(r"$Y_n$", size=12) +ax.set_ylabel(r"$density$", size=12) +xgrid = np.linspace(xmin, xmax, 200) +ax.plot(xgrid, st.norm.pdf(xgrid, scale=σ), 'k-', lw=2, label='$N(0, \sigma^2)$') +ax.legend() + +plt.show() +``` + +```{solution-end} +``` + +````{exercise} +:label: lln_ex2 + +At the start of this lecture we discussed Bernoulli random variables. + +NumPy doesn't provide a `bernoulli` function that we can sample from. + +However, we can generate a draw of Bernoulli $X$ using NumPy via + +```python3 +U = np.random.rand() +X = 1 if U < p else 0 +print(X) +``` + +Explain why this provides a random variable $X$ with the right distribution. +```` + +```{solution-start} lln_ex2 +:class: dropdown +``` + +We can write $X$ as $X = \mathbf 1\{U < p\}$ where $\mathbf 1$ is the +[indicator function](https://en.wikipedia.org/wiki/Indicator_function) (i.e., +1 if the statement is true and zero otherwise). + +Here we generated a uniform draw $U$ on $[0,1]$ and then used the fact that + +$$ +\mathbb P\{0 \leq U < p\} = p - 0 = p +$$ + +This means that $X = \mathbf 1\{U < p\}$ has the right distribution. + +```{solution-end} +``` + + + +```{exercise} +:label: lln_ex3 + +We mentioned above that LLN can still hold sometimes when IID is violated. + +Let's investigate this claim further. + +Consider the AR(1) process + +$$ + X_{t+1} = \alpha + \beta X_t + \sigma \epsilon _{t+1} +$$ + +where $\alpha, \beta, \sigma$ are constants and $\epsilon_1, \epsilon_2, +\ldots$ are IID and standard normal. + +Suppose that + +$$ + X_0 \sim N \left(\frac{\alpha}{1-\beta}, \frac{\sigma^2}{1-\beta^2}\right) +$$ + +This process violates the independence assumption of the LLN +(since $X_{t+1}$ depends on the value of $X_t$). + +However, the next exercise teaches us that LLN type convergence of the sample +mean to the population mean still occurs. + +1. Prove that the sequence $X_1, X_2, \ldots$ is identically distributed. +2. Show that LLN convergence holds using simulations with $\alpha = 0.8$, $\beta = 0.2$. + +``` + +```{solution-start} lln_ex3 +:class: dropdown +``` + +**Q1 Solution** + +Regarding part 1, we claim that $X_t$ has the same distribution as $X_0$ for +all $t$. + +To construct a proof, we suppose that the claim is true for $X_t$. + +Now we claim it is also true for $X_{t+1}$. + +Observe that we have the correct mean: + +$$ +\begin{aligned} + \mathbb E X_{t+1} &= \alpha + \beta \mathbb E X_t \\ + &= \alpha + \beta \frac{\alpha}{1-\beta} \\ + &= \frac{\alpha}{1-\beta} +\end{aligned} +$$ + +We also have the correct variance: + +$$ +\begin{aligned} + \mathrm{Var}(X_{t+1}) &= \beta^2 \mathrm{Var}(X_{t}) + \sigma^2\\ + &= \frac{\beta^2\sigma^2}{1-\beta^2} + \sigma^2 \\ + &= \frac{\sigma^2}{1-\beta^2} +\end{aligned} +$$ + +Finally, since both $X_t$ and $\epsilon_0$ are normally distributed and +independent from each other, any linear combination of these two variables is +also normally distributed. + +We have now shown that + +$$ + X_{t+1} \sim + N \left(\frac{\alpha}{1-\beta}, \frac{\sigma^2}{1-\beta^2}\right) +$$ + +We can conclude this AR(1) process violates the independence assumption but is +identically distributed. + +**Q2 Solution** + +```{code-cell} ipython3 +σ = 10 +α = 0.8 +β = 0.2 +n = 100_000 + +fig, ax = plt.subplots(figsize=(10, 6)) +x = np.ones(n) +x[0] = st.norm.rvs(α/(1-β), α**2/(1-β**2)) +ϵ = st.norm.rvs(size=n+1) +means = np.ones(n) +means[0] = x[0] +for t in range(n-1): + x[t+1] = α + β * x[t] + σ * ϵ[t+1] + means[t+1] = np.mean(x[:t+1]) + + +ax.scatter(range(100, n), means[100:n], s=10, alpha=0.5) + +ax.set_xlabel(r"$n$", size=12) +ax.set_ylabel(r"$\bar X_n$", size=12) +yabs_max = max(ax.get_ylim(), key=abs) +ax.axhline(y=α/(1-β), ls="--", lw=3, + label=r"$\mu = \frac{\alpha}{1-\beta}$", + color = 'black') + +plt.legend() +plt.show() +``` + +We see the convergence of $\bar x$ around $\mu$ even when the independence assumption is violated. + + +```{solution-end} +``` diff --git a/book/_build/html/_sources/long_run_growth.ipynb b/book/_build/html/_sources/long_run_growth.ipynb new file mode 100644 index 0000000..3892863 --- /dev/null +++ b/book/_build/html/_sources/long_run_growth.ipynb @@ -0,0 +1,961 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "a14d94fa", + "metadata": {}, + "source": [ + "# Long-Run Growth\n", + "\n", + "## Overview\n", + "\n", + "In this lecture we use Python, {doc}`pandas`, and {doc}`Matplotlib` to download, organize, and visualize historical data on economic growth.\n", + "\n", + "In addition to learning how to deploy these tools more generally, we'll use them to describe facts about economic growth experiences across many countries over several centuries.\n", + "\n", + "Such \"growth facts\" are interesting for a variety of reasons. \n", + "\n", + "Explaining growth facts is a principal purpose of both \"development economics\" and \"economic history\".\n", + "\n", + "And growth facts are important inputs into historians' studies of geopolitical forces and dynamics.\n", + "\n", + "\n", + "Thus, Adam Tooze's account of the geopolitical precedents and antecedents of World War I begins by describing how the Gross Domestic Products (GDP) of European Great Powers had evolved during the 70 years preceding 1914 (see chapter 1 of {cite}`Tooze_2014`).\n", + "\n", + "Using the very same data that Tooze used to construct his figure (with a slightly longer timeline), here is our version of his chapter 1 figure.\n", + "\n", + "\n", + "```{figure} _static/lecture_specific/long_run_growth/tooze_ch1_graph.png\n", + ":width: 100%\n", + "```\n", + "\n", + "(This is just a copy of our figure {numref}`gdp1`. We describe how we constructed it later in this lecture.)\n", + "\n", + "Chapter 1 of {cite}`Tooze_2014` used his graph to show how US GDP started the 19th century way behind the GDP of the British Empire.\n", + "\n", + "By the end of the nineteenth century, US GDP had caught up with GDP of the British Empire, and how during the first half of the 20th century,\n", + "US GDP surpassed that of the British Empire.\n", + "\n", + "For Adam Tooze, that fact was a key geopolitical underpinning for the \"American century\".\n", + "\n", + "Looking at this graph and how it set the geopolitical stage for \"the American (20th) century\" naturally \n", + "tempts one to want a counterpart to his graph for 2014 or later.\n", + "\n", + "(An impatient reader seeking a hint at the answer might now want to jump ahead and look at figure {numref}`gdp2`.)\n", + "\n", + "As we'll see, reasoning by analogy, this graph perhaps set the stage for an \"XXX (21st) century\", where you are free to fill in your guess for country XXX.\n", + "\n", + "As we gather data to construct those two graphs, we'll also study growth experiences for a number of countries for time horizons extending as far back as possible.\n", + "\n", + "These graphs will portray how the \"Industrial Revolution\" began in Britain in the late 18th century, then migrated to one country after another. \n", + "\n", + "In a nutshell, this lecture records growth trajectories of various countries over long time periods. \n", + "\n", + "While some countries have experienced long-term rapid growth across that has lasted a hundred years, others have not. \n", + "\n", + "Since populations differ across countries and vary within a country over time, it will\n", + "be interesting to describe both total GDP and GDP per capita as it evolves within a country.\n", + "\n", + "First let's import the packages needed to explore what the data says about long-run growth" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cfd608b0", + "metadata": {}, + "outputs": [], + "source": [ + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import matplotlib.cm as cm\n", + "import numpy as np\n", + "from collections import namedtuple" + ] + }, + { + "cell_type": "markdown", + "id": "83c2e7e5", + "metadata": {}, + "source": [ + "## Setting up\n", + "\n", + "A project initiated by [Angus Maddison](https://en.wikipedia.org/wiki/Angus_Maddison) has collected many historical time series related to economic growth,\n", + "some dating back to the first century.\n", + "\n", + "The data can be downloaded from the [Maddison Historical Statistics](https://www.rug.nl/ggdc/historicaldevelopment/maddison/) by clicking on the \"Latest Maddison Project Release\". \n", + "\n", + "We are going to read the data from a QuantEcon GitHub repository.\n", + "\n", + "Our objective in this section is to produce a convenient `DataFrame` instance that contains per capita GDP for different countries.\n", + "\n", + "Here we read the Maddison data into a pandas `DataFrame`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a017c5e0", + "metadata": {}, + "outputs": [], + "source": [ + "data_url = \"https://github.com/QuantEcon/lecture-python-intro/raw/main/lectures/datasets/mpd2020.xlsx\"\n", + "data = pd.read_excel(data_url, \n", + " sheet_name='Full data')\n", + "data.head()" + ] + }, + { + "cell_type": "markdown", + "id": "c3139ca3", + "metadata": {}, + "source": [ + "We can see that this dataset contains GDP per capita (`gdppc`) and population (pop) for many countries and years.\n", + "\n", + "Let's look at how many and which countries are available in this dataset" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "968389a3", + "metadata": {}, + "outputs": [], + "source": [ + "countries = data.country.unique()\n", + "len(countries)" + ] + }, + { + "cell_type": "markdown", + "id": "612f85b1", + "metadata": {}, + "source": [ + "We can now explore some of the 169 countries that are available. \n", + "\n", + "Let's loop over each country to understand which years are available for each country" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1fb73567", + "metadata": {}, + "outputs": [], + "source": [ + "country_years = []\n", + "for country in countries:\n", + " cy_data = data[data.country == country]['year']\n", + " ymin, ymax = cy_data.min(), cy_data.max()\n", + " country_years.append((country, ymin, ymax))\n", + "country_years = pd.DataFrame(country_years,\n", + " columns=['country', 'min_year', 'max_year']).set_index('country')\n", + "country_years.head()" + ] + }, + { + "cell_type": "markdown", + "id": "34104840", + "metadata": {}, + "source": [ + "Let's now reshape the original data into some convenient variables to enable quicker access to countries' time series data.\n", + "\n", + "We can build a useful mapping between country codes and country names in this dataset" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b2904ae9", + "metadata": {}, + "outputs": [], + "source": [ + "code_to_name = data[\n", + " ['countrycode', 'country']].drop_duplicates().reset_index(drop=True).set_index(['countrycode'])" + ] + }, + { + "cell_type": "markdown", + "id": "e8c69e8a", + "metadata": {}, + "source": [ + "Now we can focus on GDP per capita (`gdppc`) and generate a wide data format" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9771d59d", + "metadata": {}, + "outputs": [], + "source": [ + "gdp_pc = data.set_index(['countrycode', 'year'])['gdppc']\n", + "gdp_pc = gdp_pc.unstack('countrycode')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8cc35cfe", + "metadata": {}, + "outputs": [], + "source": [ + "gdp_pc.tail()" + ] + }, + { + "cell_type": "markdown", + "id": "1798343f", + "metadata": {}, + "source": [ + "We create a variable `color_mapping` to store a map between country codes and colors for consistency" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fc3e2662", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "country_names = data['countrycode']\n", + "\n", + "# Generate a colormap with the number of colors matching the number of countries\n", + "colors = cm.tab20(np.linspace(0, 0.95, len(country_names)))\n", + "\n", + "# Create a dictionary to map each country to its corresponding color\n", + "color_mapping = {country: color for \n", + " country, color in zip(country_names, colors)}" + ] + }, + { + "cell_type": "markdown", + "id": "1ab960fe", + "metadata": {}, + "source": [ + "## GDP per capita\n", + "\n", + "In this section we examine GDP per capita over the long run for several different countries.\n", + "\n", + "### United Kingdom\n", + "\n", + "First we examine UK GDP growth" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "89d9527f", + "metadata": { + "mystnb": { + "figure": { + "caption": "GDP per Capita (GBR)", + "name": "gdppc_gbr1", + "width": "500px" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots(dpi=300)\n", + "country = 'GBR'\n", + "gdp_pc[country].plot(\n", + " ax=ax,\n", + " ylabel='international dollars',\n", + " xlabel='year',\n", + " color=color_mapping[country]\n", + " );" + ] + }, + { + "cell_type": "markdown", + "id": "fd5dbe85", + "metadata": {}, + "source": [ + ":::{note}\n", + "[International dollars](https://en.wikipedia.org/wiki/international_dollar) are a hypothetical unit of currency that has the same purchasing power parity that the U.S. Dollar has in the United States at a given point in time. They are also known as Geary–Khamis dollars (GK Dollars).\n", + ":::\n", + "\n", + "We can see that the data is non-continuous for longer periods in the early 250 years of this millennium, so we could choose to interpolate to get a continuous line plot.\n", + "\n", + "Here we use dashed lines to indicate interpolated trends" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c333bb14", + "metadata": { + "mystnb": { + "figure": { + "caption": "GDP per Capita (GBR)", + "name": "gdppc_gbr2" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots(dpi=300)\n", + "country = 'GBR'\n", + "ax.plot(gdp_pc[country].interpolate(),\n", + " linestyle='--',\n", + " lw=2,\n", + " color=color_mapping[country])\n", + "\n", + "ax.plot(gdp_pc[country],\n", + " lw=2,\n", + " color=color_mapping[country])\n", + "ax.set_ylabel('international dollars')\n", + "ax.set_xlabel('year')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "84124377", + "metadata": {}, + "source": [ + "### Comparing the US, UK, and China\n", + "\n", + "In this section we will compare GDP growth for the US, UK and China.\n", + "\n", + "As a first step we create a function to generate plots for a list of countries" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9ee4482a", + "metadata": {}, + "outputs": [], + "source": [ + "def draw_interp_plots(series, # pandas series\n", + " country, # list of country codes\n", + " ylabel, # label for y-axis\n", + " xlabel, # label for x-axis\n", + " color_mapping, # code-color mapping\n", + " code_to_name, # code-name mapping\n", + " lw, # line width\n", + " logscale, # log scale for y-axis\n", + " ax # matplolib axis\n", + " ):\n", + "\n", + " for c in country:\n", + " # Get the interpolated data\n", + " df_interpolated = series[c].interpolate(limit_area='inside')\n", + " interpolated_data = df_interpolated[series[c].isnull()]\n", + "\n", + " # Plot the interpolated data with dashed lines\n", + " ax.plot(interpolated_data,\n", + " linestyle='--',\n", + " lw=lw,\n", + " alpha=0.7,\n", + " color=color_mapping[c])\n", + "\n", + " # Plot the non-interpolated data with solid lines\n", + " ax.plot(series[c],\n", + " lw=lw,\n", + " color=color_mapping[c],\n", + " alpha=0.8,\n", + " label=code_to_name.loc[c]['country'])\n", + " \n", + " if logscale:\n", + " ax.set_yscale('log')\n", + " \n", + " # Draw the legend outside the plot\n", + " ax.legend(loc='upper left', frameon=False)\n", + " ax.set_ylabel(ylabel)\n", + " ax.set_xlabel(xlabel)" + ] + }, + { + "cell_type": "markdown", + "id": "499e599f", + "metadata": {}, + "source": [ + "As you can see from this chart, economic growth started in earnest in the 18th century and continued for the next two hundred years. \n", + "\n", + "How does this compare with other countries' growth trajectories? \n", + "\n", + "Let's look at the United States (USA), United Kingdom (GBR), and China (CHN)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "791e9c4a", + "metadata": { + "mystnb": { + "figure": { + "caption": "GDP per Capita, 1500- (China, UK, USA)", + "name": "gdppc_comparison" + } + }, + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "# Define the namedtuple for the events\n", + "Event = namedtuple('Event', ['year_range', 'y_text', 'text', 'color', 'ymax'])\n", + "\n", + "fig, ax = plt.subplots(dpi=300, figsize=(10, 6))\n", + "\n", + "country = ['CHN', 'GBR', 'USA']\n", + "draw_interp_plots(gdp_pc[country].loc[1500:], \n", + " country,\n", + " 'international dollars','year',\n", + " color_mapping, code_to_name, 2, False, ax)\n", + "\n", + "# Define the parameters for the events and the text\n", + "ylim = ax.get_ylim()[1]\n", + "b_params = {'color':'grey', 'alpha': 0.2}\n", + "t_params = {'fontsize': 9, \n", + " 'va':'center', 'ha':'center'}\n", + "\n", + "# Create a list of events to annotate\n", + "events = [\n", + " Event((1650, 1652), ylim + ylim*0.04, \n", + " 'the Navigation Act\\n(1651)',\n", + " color_mapping['GBR'], 1),\n", + " Event((1655, 1684), ylim + ylim*0.13, \n", + " 'Closed-door Policy\\n(1655-1684)', \n", + " color_mapping['CHN'], 1.1),\n", + " Event((1848, 1850), ylim + ylim*0.22,\n", + " 'the Repeal of Navigation Act\\n(1849)', \n", + " color_mapping['GBR'], 1.18),\n", + " Event((1765, 1791), ylim + ylim*0.04, \n", + " 'American Revolution\\n(1765-1791)', \n", + " color_mapping['USA'], 1),\n", + " Event((1760, 1840), ylim + ylim*0.13, \n", + " 'Industrial Revolution\\n(1760-1840)', \n", + " 'grey', 1.1),\n", + " Event((1929, 1939), ylim + ylim*0.04, \n", + " 'the Great Depression\\n(1929–1939)', \n", + " 'grey', 1),\n", + " Event((1978, 1979), ylim + ylim*0.13, \n", + " 'Reform and Opening-up\\n(1978-1979)', \n", + " color_mapping['CHN'], 1.1)\n", + "]\n", + "\n", + "def draw_events(events, ax):\n", + " # Iterate over events and add annotations and vertical lines\n", + " for event in events:\n", + " event_mid = sum(event.year_range)/2\n", + " ax.text(event_mid, \n", + " event.y_text, event.text, \n", + " color=event.color, **t_params)\n", + " ax.axvspan(*event.year_range, color=event.color, alpha=0.2)\n", + " ax.axvline(event_mid, ymin=1, ymax=event.ymax, color=event.color,\n", + " clip_on=False, alpha=0.15)\n", + "\n", + "# Draw events\n", + "draw_events(events, ax)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "2cdb8ada", + "metadata": {}, + "source": [ + "The preceding graph of per capita GDP strikingly reveals how the spread of the Industrial Revolution has over time gradually lifted the living standards of substantial\n", + "groups of people \n", + "\n", + "- most of the growth happened in the past 150 years after the Industrial Revolution.\n", + "- per capita GDP in the US and UK rose and diverged from that of China from 1820 to 1940.\n", + "- the gap has closed rapidly after 1950 and especially after the late 1970s.\n", + "- these outcomes reflect complicated combinations of technological and economic-policy factors that students of economic growth try to understand and quantify.\n", + "\n", + "### Focusing on China\n", + "\n", + "It is fascinating to see China's GDP per capita levels from 1500 through to the 1970s.\n", + "\n", + "Notice the long period of declining GDP per capital levels from the 1700s until the early 20th century.\n", + "\n", + "Thus, the graph indicates \n", + "\n", + "- a long economic downturn and stagnation after the Closed-door Policy by the Qing government.\n", + "- China's very different experience than the UK's after the onset of the industrial revolution in the UK.\n", + "- how the Self-Strengthening Movement seemed mostly to help China to grow.\n", + "- how stunning have been the growth achievements of modern Chinese economic policies by the PRC that culminated with its late 1970s reform and liberalization." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0bcd9639", + "metadata": { + "mystnb": { + "figure": { + "caption": "GDP per Capita, 1500-2000 (China)", + "name": "gdppc_china" + } + }, + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots(dpi=300, figsize=(10, 6))\n", + "\n", + "country = ['CHN']\n", + "draw_interp_plots(gdp_pc[country].loc[1600:2000], \n", + " country,\n", + " 'international dollars','year',\n", + " color_mapping, code_to_name, 2, True, ax)\n", + "\n", + "ylim = ax.get_ylim()[1]\n", + "\n", + "events = [\n", + "Event((1655, 1684), ylim + ylim*0.06, \n", + " 'Closed-door Policy\\n(1655-1684)', \n", + " 'tab:orange', 1),\n", + "Event((1760, 1840), ylim + ylim*0.06, \n", + " 'Industrial Revolution\\n(1760-1840)', \n", + " 'grey', 1),\n", + "Event((1839, 1842), ylim + ylim*0.2, \n", + " 'First Opium War\\n(1839–1842)', \n", + " 'tab:red', 1.07),\n", + "Event((1861, 1895), ylim + ylim*0.4, \n", + " 'Self-Strengthening Movement\\n(1861–1895)', \n", + " 'tab:blue', 1.14),\n", + "Event((1939, 1945), ylim + ylim*0.06, \n", + " 'WW 2\\n(1939-1945)', \n", + " 'tab:red', 1),\n", + "Event((1948, 1950), ylim + ylim*0.23, \n", + " 'Founding of PRC\\n(1949)', \n", + " color_mapping['CHN'], 1.08),\n", + "Event((1958, 1962), ylim + ylim*0.5, \n", + " 'Great Leap Forward\\n(1958-1962)', \n", + " 'tab:orange', 1.18),\n", + "Event((1978, 1979), ylim + ylim*0.7, \n", + " 'Reform and Opening-up\\n(1978-1979)', \n", + " 'tab:blue', 1.24)\n", + "]\n", + "\n", + "# Draw events\n", + "draw_events(events, ax)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "4f7f0dfe", + "metadata": {}, + "source": [ + "### Focusing on the US and UK\n", + "\n", + "Now we look at the United States (USA) and United Kingdom (GBR) in more detail.\n", + "\n", + "In the following graph, please watch for \n", + "- impact of trade policy (Navigation Act).\n", + "- productivity changes brought by the Industrial Revolution.\n", + "- how the US gradually approaches and then surpasses the UK, setting the stage for the ''American Century''.\n", + "- the often unanticipated consequences of wars.\n", + "- interruptions and scars left by [business cycle](business_cycle) recessions and depressions." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "519891a4", + "metadata": { + "mystnb": { + "figure": { + "caption": "GDP per Capita, 1500-2000 (UK and US)", + "name": "gdppc_ukus" + } + }, + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots(dpi=300, figsize=(10, 6))\n", + "\n", + "country = ['GBR', 'USA']\n", + "draw_interp_plots(gdp_pc[country].loc[1500:2000],\n", + " country,\n", + " 'international dollars','year',\n", + " color_mapping, code_to_name, 2, True, ax)\n", + "\n", + "ylim = ax.get_ylim()[1]\n", + "\n", + "# Create a list of data points\n", + "events = [\n", + " Event((1651, 1651), ylim + ylim*0.15, \n", + " 'Navigation Act (UK)\\n(1651)', \n", + " 'tab:orange', 1),\n", + " Event((1765, 1791), ylim + ylim*0.15, \n", + " 'American Revolution\\n(1765-1791)',\n", + " color_mapping['USA'], 1),\n", + " Event((1760, 1840), ylim + ylim*0.6, \n", + " 'Industrial Revolution\\n(1760-1840)', \n", + " 'grey', 1.08),\n", + " Event((1848, 1850), ylim + ylim*1.1, \n", + " 'Repeal of Navigation Act (UK)\\n(1849)', \n", + " 'tab:blue', 1.14),\n", + " Event((1861, 1865), ylim + ylim*1.8, \n", + " 'American Civil War\\n(1861-1865)', \n", + " color_mapping['USA'], 1.21),\n", + " Event((1914, 1918), ylim + ylim*0.15, \n", + " 'WW 1\\n(1914-1918)', \n", + " 'tab:red', 1),\n", + " Event((1929, 1939), ylim + ylim*0.6, \n", + " 'the Great Depression\\n(1929–1939)', \n", + " 'grey', 1.08),\n", + " Event((1939, 1945), ylim + ylim*1.1, \n", + " 'WW 2\\n(1939-1945)', \n", + " 'tab:red', 1.14)\n", + "]\n", + "\n", + "# Draw events\n", + "draw_events(events, ax)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "a06886e3", + "metadata": {}, + "source": [ + "## GDP growth\n", + "\n", + "Now we'll construct some graphs of interest to geopolitical historians like Adam Tooze.\n", + "\n", + "We'll focus on total Gross Domestic Product (GDP) (as a proxy for ''national geopolitical-military power'') rather than focusing on GDP per capita (as a proxy for living standards)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d4f26f74", + "metadata": {}, + "outputs": [], + "source": [ + "data = pd.read_excel(data_url, sheet_name='Full data')\n", + "data.set_index(['countrycode', 'year'], inplace=True)\n", + "data['gdp'] = data['gdppc'] * data['pop']\n", + "gdp = data['gdp'].unstack('countrycode')" + ] + }, + { + "cell_type": "markdown", + "id": "09902176", + "metadata": {}, + "source": [ + "### Early industrialization (1820 to 1940)\n", + "\n", + "We first visualize the trend of China, the Former Soviet Union, Japan, the UK and the US.\n", + "\n", + "The most notable trend is the rise of the US, surpassing the UK in the 1860s and China in the 1880s.\n", + "\n", + "The growth continued until the large dip in the 1930s when the Great Depression hit.\n", + "\n", + "Meanwhile, Russia experienced significant setbacks during World War I and recovered significantly after the February Revolution." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fcb586bf", + "metadata": { + "mystnb": { + "figure": { + "caption": "GDP in the early industrialization era", + "name": "gdp1" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots(dpi=300)\n", + "country = ['CHN', 'SUN', 'JPN', 'GBR', 'USA']\n", + "start_year, end_year = (1820, 1945)\n", + "draw_interp_plots(gdp[country].loc[start_year:end_year], \n", + " country,\n", + " 'international dollars', 'year',\n", + " color_mapping, code_to_name, 2, False, ax)" + ] + }, + { + "cell_type": "markdown", + "id": "e8866305", + "metadata": {}, + "source": [ + "#### Constructing a plot similar to Tooze's\n", + "\n", + "In this section we describe how we have constructed a version of the striking figure from chapter 1 of {cite}`Tooze_2014` that we discussed at the start of this lecture.\n", + "\n", + "Let's first define a collection of countries that consist of the British Empire (BEM) so we can replicate that series in Tooze's chart." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "30ee43c4", + "metadata": {}, + "outputs": [], + "source": [ + "BEM = ['GBR', 'IND', 'AUS', 'NZL', 'CAN', 'ZAF']\n", + "# Interpolate incomplete time-series\n", + "gdp['BEM'] = gdp[BEM].loc[start_year-1:end_year].interpolate(method='index').sum(axis=1)" + ] + }, + { + "cell_type": "markdown", + "id": "ac0893bd", + "metadata": {}, + "source": [ + "Now let's assemble our series and get ready to plot them." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "18df59eb", + "metadata": {}, + "outputs": [], + "source": [ + "# Define colour mapping and name for BEM\n", + "color_mapping['BEM'] = color_mapping['GBR'] # Set the color to be the same as Great Britain\n", + "# Add British Empire to code_to_name\n", + "bem = pd.DataFrame([\"British Empire\"], index=[\"BEM\"], columns=['country'])\n", + "bem.index.name = 'countrycode'\n", + "code_to_name = pd.concat([code_to_name, bem])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "71f0425a", + "metadata": {}, + "outputs": [], + "source": [ + "fig, ax = plt.subplots(dpi=300)\n", + "country = ['DEU', 'USA', 'SUN', 'BEM', 'FRA', 'JPN']\n", + "start_year, end_year = (1821, 1945)\n", + "draw_interp_plots(gdp[country].loc[start_year:end_year], \n", + " country,\n", + " 'international dollars', 'year',\n", + " color_mapping, code_to_name, 2, False, ax)\n", + "\n", + "plt.savefig(\"./_static/lecture_specific/long_run_growth/tooze_ch1_graph.png\", dpi=300,\n", + " bbox_inches='tight')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "e70b1fa4", + "metadata": {}, + "source": [ + "At the start of this lecture, we noted how US GDP came from \"nowhere\" at the start of the 19th century to rival and then overtake the GDP of the British Empire\n", + "by the end of the 19th century, setting the geopolitical stage for the \"American (twentieth) century\".\n", + "\n", + "Let's move forward in time and start roughly where Tooze's graph stopped after World War II.\n", + "\n", + "In the spirit of Tooze's chapter 1 analysis, doing this will provide some information about geopolitical realities today.\n", + "\n", + "### The modern era (1950 to 2020)\n", + "\n", + "The following graph displays how quickly China has grown, especially since the late 1970s." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3a01eb23", + "metadata": { + "mystnb": { + "figure": { + "caption": "GDP in the modern era", + "name": "gdp2" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots(dpi=300)\n", + "country = ['CHN', 'SUN', 'JPN', 'GBR', 'USA']\n", + "start_year, end_year = (1950, 2020)\n", + "draw_interp_plots(gdp[country].loc[start_year:end_year], \n", + " country,\n", + " 'international dollars', 'year',\n", + " color_mapping, code_to_name, 2, False, ax)" + ] + }, + { + "cell_type": "markdown", + "id": "6ba93e42", + "metadata": {}, + "source": [ + "It is tempting to compare this graph with figure {numref}`gdp1` that showed the US overtaking the UK near the start of the \"American Century\", a version of the graph featured in chapter 1 of {cite}`Tooze_2014`.\n", + "\n", + "## Regional analysis\n", + "\n", + "We often want to study the historical experiences of countries outside the club of \"World Powers\".\n", + "\n", + "The [Maddison Historical Statistics](https://www.rug.nl/ggdc/historicaldevelopment/maddison/) dataset also includes regional aggregations" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "46112902", + "metadata": {}, + "outputs": [], + "source": [ + "data = pd.read_excel(data_url, \n", + " sheet_name='Regional data', \n", + " header=(0,1,2),\n", + " index_col=0)\n", + "data.columns = data.columns.droplevel(level=2)" + ] + }, + { + "cell_type": "markdown", + "id": "06b9e57b", + "metadata": {}, + "source": [ + "We can save the raw data in a more convenient format to build a single table of regional GDP per capita" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cc1df9f5", + "metadata": {}, + "outputs": [], + "source": [ + "regionalgdp_pc = data['gdppc_2011'].copy()\n", + "regionalgdp_pc.index = pd.to_datetime(regionalgdp_pc.index, format='%Y')" + ] + }, + { + "cell_type": "markdown", + "id": "8627e091", + "metadata": {}, + "source": [ + "Let's interpolate based on time to fill in any gaps in the dataset for the purpose of plotting" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f72dcfc4", + "metadata": {}, + "outputs": [], + "source": [ + "regionalgdp_pc.interpolate(method='time', inplace=True)" + ] + }, + { + "cell_type": "markdown", + "id": "ad628174", + "metadata": {}, + "source": [ + "Looking more closely, let's compare the time series for `Western Offshoots` and `Sub-Saharan Africa` with a number of different regions around the world.\n", + "\n", + "Again we see the divergence of the West from the rest of the world after the Industrial Revolution and the convergence of the world after the 1950s" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a53e3413", + "metadata": { + "mystnb": { + "figure": { + "caption": "Regional GDP per capita", + "name": "region_gdppc" + } + } + }, + "outputs": [], + "source": [ + "fig, ax = plt.subplots(dpi=300)\n", + "regionalgdp_pc.plot(ax=ax, xlabel='year',\n", + " lw=2,\n", + " ylabel='international dollars')\n", + "ax.set_yscale('log')\n", + "plt.legend(loc='lower center',\n", + " ncol=3, bbox_to_anchor=[0.5, -0.5])\n", + "plt.show()" + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.16.1" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 67, + 73, + 88, + 93, + 99, + 102, + 108, + 117, + 123, + 126, + 130, + 135, + 137, + 141, + 152, + 162, + 178, + 188, + 208, + 216, + 254, + 262, + 326, + 349, + 397, + 410, + 459, + 467, + 472, + 484, + 498, + 506, + 510, + 514, + 523, + 535, + 548, + 562, + 572, + 578, + 582, + 585, + 589, + 591, + 597 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/long_run_growth.md b/book/_build/html/_sources/long_run_growth.md new file mode 100644 index 0000000..d9a5ef5 --- /dev/null +++ b/book/_build/html/_sources/long_run_growth.md @@ -0,0 +1,612 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.16.1 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Long-Run Growth + +## Overview + +In this lecture we use Python, {doc}`pandas`, and {doc}`Matplotlib` to download, organize, and visualize historical data on economic growth. + +In addition to learning how to deploy these tools more generally, we'll use them to describe facts about economic growth experiences across many countries over several centuries. + +Such "growth facts" are interesting for a variety of reasons. + +Explaining growth facts is a principal purpose of both "development economics" and "economic history". + +And growth facts are important inputs into historians' studies of geopolitical forces and dynamics. + + +Thus, Adam Tooze's account of the geopolitical precedents and antecedents of World War I begins by describing how the Gross Domestic Products (GDP) of European Great Powers had evolved during the 70 years preceding 1914 (see chapter 1 of {cite}`Tooze_2014`). + +Using the very same data that Tooze used to construct his figure (with a slightly longer timeline), here is our version of his chapter 1 figure. + + +```{figure} _static/lecture_specific/long_run_growth/tooze_ch1_graph.png +:width: 100% +``` + +(This is just a copy of our figure {numref}`gdp1`. We describe how we constructed it later in this lecture.) + +Chapter 1 of {cite}`Tooze_2014` used his graph to show how US GDP started the 19th century way behind the GDP of the British Empire. + +By the end of the nineteenth century, US GDP had caught up with GDP of the British Empire, and how during the first half of the 20th century, +US GDP surpassed that of the British Empire. + +For Adam Tooze, that fact was a key geopolitical underpinning for the "American century". + +Looking at this graph and how it set the geopolitical stage for "the American (20th) century" naturally +tempts one to want a counterpart to his graph for 2014 or later. + +(An impatient reader seeking a hint at the answer might now want to jump ahead and look at figure {numref}`gdp2`.) + +As we'll see, reasoning by analogy, this graph perhaps set the stage for an "XXX (21st) century", where you are free to fill in your guess for country XXX. + +As we gather data to construct those two graphs, we'll also study growth experiences for a number of countries for time horizons extending as far back as possible. + +These graphs will portray how the "Industrial Revolution" began in Britain in the late 18th century, then migrated to one country after another. + +In a nutshell, this lecture records growth trajectories of various countries over long time periods. + +While some countries have experienced long-term rapid growth across that has lasted a hundred years, others have not. + +Since populations differ across countries and vary within a country over time, it will +be interesting to describe both total GDP and GDP per capita as it evolves within a country. + +First let's import the packages needed to explore what the data says about long-run growth + +```{code-cell} ipython3 +import pandas as pd +import matplotlib.pyplot as plt +import matplotlib.cm as cm +import numpy as np +from collections import namedtuple +``` + +## Setting up + +A project initiated by [Angus Maddison](https://en.wikipedia.org/wiki/Angus_Maddison) has collected many historical time series related to economic growth, +some dating back to the first century. + +The data can be downloaded from the [Maddison Historical Statistics](https://www.rug.nl/ggdc/historicaldevelopment/maddison/) by clicking on the "Latest Maddison Project Release". + +We are going to read the data from a QuantEcon GitHub repository. + +Our objective in this section is to produce a convenient `DataFrame` instance that contains per capita GDP for different countries. + +Here we read the Maddison data into a pandas `DataFrame`: + +```{code-cell} ipython3 +data_url = "https://github.com/QuantEcon/lecture-python-intro/raw/main/lectures/datasets/mpd2020.xlsx" +data = pd.read_excel(data_url, + sheet_name='Full data') +data.head() +``` + +We can see that this dataset contains GDP per capita (`gdppc`) and population (pop) for many countries and years. + +Let's look at how many and which countries are available in this dataset + +```{code-cell} ipython3 +countries = data.country.unique() +len(countries) +``` + +We can now explore some of the 169 countries that are available. + +Let's loop over each country to understand which years are available for each country + +```{code-cell} ipython3 +country_years = [] +for country in countries: + cy_data = data[data.country == country]['year'] + ymin, ymax = cy_data.min(), cy_data.max() + country_years.append((country, ymin, ymax)) +country_years = pd.DataFrame(country_years, + columns=['country', 'min_year', 'max_year']).set_index('country') +country_years.head() +``` + +Let's now reshape the original data into some convenient variables to enable quicker access to countries' time series data. + +We can build a useful mapping between country codes and country names in this dataset + +```{code-cell} ipython3 +code_to_name = data[ + ['countrycode', 'country']].drop_duplicates().reset_index(drop=True).set_index(['countrycode']) +``` + +Now we can focus on GDP per capita (`gdppc`) and generate a wide data format + +```{code-cell} ipython3 +gdp_pc = data.set_index(['countrycode', 'year'])['gdppc'] +gdp_pc = gdp_pc.unstack('countrycode') +``` + +```{code-cell} ipython3 +gdp_pc.tail() +``` + +We create a variable `color_mapping` to store a map between country codes and colors for consistency + +```{code-cell} ipython3 +:tags: [hide-input] + +country_names = data['countrycode'] + +# Generate a colormap with the number of colors matching the number of countries +colors = cm.tab20(np.linspace(0, 0.95, len(country_names))) + +# Create a dictionary to map each country to its corresponding color +color_mapping = {country: color for + country, color in zip(country_names, colors)} +``` + +## GDP per capita + +In this section we examine GDP per capita over the long run for several different countries. + +### United Kingdom + +First we examine UK GDP growth + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: GDP per Capita (GBR) + name: gdppc_gbr1 + width: 500px +--- +fig, ax = plt.subplots(dpi=300) +country = 'GBR' +gdp_pc[country].plot( + ax=ax, + ylabel='international dollars', + xlabel='year', + color=color_mapping[country] + ); +``` + +:::{note} +[International dollars](https://en.wikipedia.org/wiki/international_dollar) are a hypothetical unit of currency that has the same purchasing power parity that the U.S. Dollar has in the United States at a given point in time. They are also known as Geary–Khamis dollars (GK Dollars). +::: + +We can see that the data is non-continuous for longer periods in the early 250 years of this millennium, so we could choose to interpolate to get a continuous line plot. + +Here we use dashed lines to indicate interpolated trends + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: GDP per Capita (GBR) + name: gdppc_gbr2 +--- +fig, ax = plt.subplots(dpi=300) +country = 'GBR' +ax.plot(gdp_pc[country].interpolate(), + linestyle='--', + lw=2, + color=color_mapping[country]) + +ax.plot(gdp_pc[country], + lw=2, + color=color_mapping[country]) +ax.set_ylabel('international dollars') +ax.set_xlabel('year') +plt.show() +``` + +### Comparing the US, UK, and China + +In this section we will compare GDP growth for the US, UK and China. + +As a first step we create a function to generate plots for a list of countries + +```{code-cell} ipython3 +def draw_interp_plots(series, # pandas series + country, # list of country codes + ylabel, # label for y-axis + xlabel, # label for x-axis + color_mapping, # code-color mapping + code_to_name, # code-name mapping + lw, # line width + logscale, # log scale for y-axis + ax # matplolib axis + ): + + for c in country: + # Get the interpolated data + df_interpolated = series[c].interpolate(limit_area='inside') + interpolated_data = df_interpolated[series[c].isnull()] + + # Plot the interpolated data with dashed lines + ax.plot(interpolated_data, + linestyle='--', + lw=lw, + alpha=0.7, + color=color_mapping[c]) + + # Plot the non-interpolated data with solid lines + ax.plot(series[c], + lw=lw, + color=color_mapping[c], + alpha=0.8, + label=code_to_name.loc[c]['country']) + + if logscale: + ax.set_yscale('log') + + # Draw the legend outside the plot + ax.legend(loc='upper left', frameon=False) + ax.set_ylabel(ylabel) + ax.set_xlabel(xlabel) +``` + +As you can see from this chart, economic growth started in earnest in the 18th century and continued for the next two hundred years. + +How does this compare with other countries' growth trajectories? + +Let's look at the United States (USA), United Kingdom (GBR), and China (CHN) + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: GDP per Capita, 1500- (China, UK, USA) + name: gdppc_comparison +tags: [hide-input] +--- +# Define the namedtuple for the events +Event = namedtuple('Event', ['year_range', 'y_text', 'text', 'color', 'ymax']) + +fig, ax = plt.subplots(dpi=300, figsize=(10, 6)) + +country = ['CHN', 'GBR', 'USA'] +draw_interp_plots(gdp_pc[country].loc[1500:], + country, + 'international dollars','year', + color_mapping, code_to_name, 2, False, ax) + +# Define the parameters for the events and the text +ylim = ax.get_ylim()[1] +b_params = {'color':'grey', 'alpha': 0.2} +t_params = {'fontsize': 9, + 'va':'center', 'ha':'center'} + +# Create a list of events to annotate +events = [ + Event((1650, 1652), ylim + ylim*0.04, + 'the Navigation Act\n(1651)', + color_mapping['GBR'], 1), + Event((1655, 1684), ylim + ylim*0.13, + 'Closed-door Policy\n(1655-1684)', + color_mapping['CHN'], 1.1), + Event((1848, 1850), ylim + ylim*0.22, + 'the Repeal of Navigation Act\n(1849)', + color_mapping['GBR'], 1.18), + Event((1765, 1791), ylim + ylim*0.04, + 'American Revolution\n(1765-1791)', + color_mapping['USA'], 1), + Event((1760, 1840), ylim + ylim*0.13, + 'Industrial Revolution\n(1760-1840)', + 'grey', 1.1), + Event((1929, 1939), ylim + ylim*0.04, + 'the Great Depression\n(1929–1939)', + 'grey', 1), + Event((1978, 1979), ylim + ylim*0.13, + 'Reform and Opening-up\n(1978-1979)', + color_mapping['CHN'], 1.1) +] + +def draw_events(events, ax): + # Iterate over events and add annotations and vertical lines + for event in events: + event_mid = sum(event.year_range)/2 + ax.text(event_mid, + event.y_text, event.text, + color=event.color, **t_params) + ax.axvspan(*event.year_range, color=event.color, alpha=0.2) + ax.axvline(event_mid, ymin=1, ymax=event.ymax, color=event.color, + clip_on=False, alpha=0.15) + +# Draw events +draw_events(events, ax) +plt.show() +``` + +The preceding graph of per capita GDP strikingly reveals how the spread of the Industrial Revolution has over time gradually lifted the living standards of substantial +groups of people + +- most of the growth happened in the past 150 years after the Industrial Revolution. +- per capita GDP in the US and UK rose and diverged from that of China from 1820 to 1940. +- the gap has closed rapidly after 1950 and especially after the late 1970s. +- these outcomes reflect complicated combinations of technological and economic-policy factors that students of economic growth try to understand and quantify. + +### Focusing on China + +It is fascinating to see China's GDP per capita levels from 1500 through to the 1970s. + +Notice the long period of declining GDP per capital levels from the 1700s until the early 20th century. + +Thus, the graph indicates + +- a long economic downturn and stagnation after the Closed-door Policy by the Qing government. +- China's very different experience than the UK's after the onset of the industrial revolution in the UK. +- how the Self-Strengthening Movement seemed mostly to help China to grow. +- how stunning have been the growth achievements of modern Chinese economic policies by the PRC that culminated with its late 1970s reform and liberalization. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: GDP per Capita, 1500-2000 (China) + name: gdppc_china +tags: [hide-input] +--- +fig, ax = plt.subplots(dpi=300, figsize=(10, 6)) + +country = ['CHN'] +draw_interp_plots(gdp_pc[country].loc[1600:2000], + country, + 'international dollars','year', + color_mapping, code_to_name, 2, True, ax) + +ylim = ax.get_ylim()[1] + +events = [ +Event((1655, 1684), ylim + ylim*0.06, + 'Closed-door Policy\n(1655-1684)', + 'tab:orange', 1), +Event((1760, 1840), ylim + ylim*0.06, + 'Industrial Revolution\n(1760-1840)', + 'grey', 1), +Event((1839, 1842), ylim + ylim*0.2, + 'First Opium War\n(1839–1842)', + 'tab:red', 1.07), +Event((1861, 1895), ylim + ylim*0.4, + 'Self-Strengthening Movement\n(1861–1895)', + 'tab:blue', 1.14), +Event((1939, 1945), ylim + ylim*0.06, + 'WW 2\n(1939-1945)', + 'tab:red', 1), +Event((1948, 1950), ylim + ylim*0.23, + 'Founding of PRC\n(1949)', + color_mapping['CHN'], 1.08), +Event((1958, 1962), ylim + ylim*0.5, + 'Great Leap Forward\n(1958-1962)', + 'tab:orange', 1.18), +Event((1978, 1979), ylim + ylim*0.7, + 'Reform and Opening-up\n(1978-1979)', + 'tab:blue', 1.24) +] + +# Draw events +draw_events(events, ax) +plt.show() +``` + +### Focusing on the US and UK + +Now we look at the United States (USA) and United Kingdom (GBR) in more detail. + +In the following graph, please watch for +- impact of trade policy (Navigation Act). +- productivity changes brought by the Industrial Revolution. +- how the US gradually approaches and then surpasses the UK, setting the stage for the ''American Century''. +- the often unanticipated consequences of wars. +- interruptions and scars left by [business cycle](business_cycle) recessions and depressions. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: GDP per Capita, 1500-2000 (UK and US) + name: gdppc_ukus +tags: [hide-input] +--- +fig, ax = plt.subplots(dpi=300, figsize=(10, 6)) + +country = ['GBR', 'USA'] +draw_interp_plots(gdp_pc[country].loc[1500:2000], + country, + 'international dollars','year', + color_mapping, code_to_name, 2, True, ax) + +ylim = ax.get_ylim()[1] + +# Create a list of data points +events = [ + Event((1651, 1651), ylim + ylim*0.15, + 'Navigation Act (UK)\n(1651)', + 'tab:orange', 1), + Event((1765, 1791), ylim + ylim*0.15, + 'American Revolution\n(1765-1791)', + color_mapping['USA'], 1), + Event((1760, 1840), ylim + ylim*0.6, + 'Industrial Revolution\n(1760-1840)', + 'grey', 1.08), + Event((1848, 1850), ylim + ylim*1.1, + 'Repeal of Navigation Act (UK)\n(1849)', + 'tab:blue', 1.14), + Event((1861, 1865), ylim + ylim*1.8, + 'American Civil War\n(1861-1865)', + color_mapping['USA'], 1.21), + Event((1914, 1918), ylim + ylim*0.15, + 'WW 1\n(1914-1918)', + 'tab:red', 1), + Event((1929, 1939), ylim + ylim*0.6, + 'the Great Depression\n(1929–1939)', + 'grey', 1.08), + Event((1939, 1945), ylim + ylim*1.1, + 'WW 2\n(1939-1945)', + 'tab:red', 1.14) +] + +# Draw events +draw_events(events, ax) +plt.show() +``` + +## GDP growth + +Now we'll construct some graphs of interest to geopolitical historians like Adam Tooze. + +We'll focus on total Gross Domestic Product (GDP) (as a proxy for ''national geopolitical-military power'') rather than focusing on GDP per capita (as a proxy for living standards). + +```{code-cell} ipython3 +data = pd.read_excel(data_url, sheet_name='Full data') +data.set_index(['countrycode', 'year'], inplace=True) +data['gdp'] = data['gdppc'] * data['pop'] +gdp = data['gdp'].unstack('countrycode') +``` + +### Early industrialization (1820 to 1940) + +We first visualize the trend of China, the Former Soviet Union, Japan, the UK and the US. + +The most notable trend is the rise of the US, surpassing the UK in the 1860s and China in the 1880s. + +The growth continued until the large dip in the 1930s when the Great Depression hit. + +Meanwhile, Russia experienced significant setbacks during World War I and recovered significantly after the February Revolution. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: GDP in the early industrialization era + name: gdp1 +--- +fig, ax = plt.subplots(dpi=300) +country = ['CHN', 'SUN', 'JPN', 'GBR', 'USA'] +start_year, end_year = (1820, 1945) +draw_interp_plots(gdp[country].loc[start_year:end_year], + country, + 'international dollars', 'year', + color_mapping, code_to_name, 2, False, ax) +``` + +#### Constructing a plot similar to Tooze's + +In this section we describe how we have constructed a version of the striking figure from chapter 1 of {cite}`Tooze_2014` that we discussed at the start of this lecture. + +Let's first define a collection of countries that consist of the British Empire (BEM) so we can replicate that series in Tooze's chart. + +```{code-cell} ipython3 +BEM = ['GBR', 'IND', 'AUS', 'NZL', 'CAN', 'ZAF'] +# Interpolate incomplete time-series +gdp['BEM'] = gdp[BEM].loc[start_year-1:end_year].interpolate(method='index').sum(axis=1) +``` + +Now let's assemble our series and get ready to plot them. + +```{code-cell} ipython3 +# Define colour mapping and name for BEM +color_mapping['BEM'] = color_mapping['GBR'] # Set the color to be the same as Great Britain +# Add British Empire to code_to_name +bem = pd.DataFrame(["British Empire"], index=["BEM"], columns=['country']) +bem.index.name = 'countrycode' +code_to_name = pd.concat([code_to_name, bem]) +``` + +```{code-cell} ipython3 +fig, ax = plt.subplots(dpi=300) +country = ['DEU', 'USA', 'SUN', 'BEM', 'FRA', 'JPN'] +start_year, end_year = (1821, 1945) +draw_interp_plots(gdp[country].loc[start_year:end_year], + country, + 'international dollars', 'year', + color_mapping, code_to_name, 2, False, ax) + +plt.savefig("./_static/lecture_specific/long_run_growth/tooze_ch1_graph.png", dpi=300, + bbox_inches='tight') +plt.show() +``` + +At the start of this lecture, we noted how US GDP came from "nowhere" at the start of the 19th century to rival and then overtake the GDP of the British Empire +by the end of the 19th century, setting the geopolitical stage for the "American (twentieth) century". + +Let's move forward in time and start roughly where Tooze's graph stopped after World War II. + +In the spirit of Tooze's chapter 1 analysis, doing this will provide some information about geopolitical realities today. + +### The modern era (1950 to 2020) + +The following graph displays how quickly China has grown, especially since the late 1970s. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: GDP in the modern era + name: gdp2 +--- +fig, ax = plt.subplots(dpi=300) +country = ['CHN', 'SUN', 'JPN', 'GBR', 'USA'] +start_year, end_year = (1950, 2020) +draw_interp_plots(gdp[country].loc[start_year:end_year], + country, + 'international dollars', 'year', + color_mapping, code_to_name, 2, False, ax) +``` + +It is tempting to compare this graph with figure {numref}`gdp1` that showed the US overtaking the UK near the start of the "American Century", a version of the graph featured in chapter 1 of {cite}`Tooze_2014`. + +## Regional analysis + +We often want to study the historical experiences of countries outside the club of "World Powers". + +The [Maddison Historical Statistics](https://www.rug.nl/ggdc/historicaldevelopment/maddison/) dataset also includes regional aggregations + +```{code-cell} ipython3 +data = pd.read_excel(data_url, + sheet_name='Regional data', + header=(0,1,2), + index_col=0) +data.columns = data.columns.droplevel(level=2) +``` + +We can save the raw data in a more convenient format to build a single table of regional GDP per capita + +```{code-cell} ipython3 +regionalgdp_pc = data['gdppc_2011'].copy() +regionalgdp_pc.index = pd.to_datetime(regionalgdp_pc.index, format='%Y') +``` + +Let's interpolate based on time to fill in any gaps in the dataset for the purpose of plotting + +```{code-cell} ipython3 +regionalgdp_pc.interpolate(method='time', inplace=True) +``` + +Looking more closely, let's compare the time series for `Western Offshoots` and `Sub-Saharan Africa` with a number of different regions around the world. + +Again we see the divergence of the West from the rest of the world after the Industrial Revolution and the convergence of the world after the 1950s + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Regional GDP per capita + name: region_gdppc +--- +fig, ax = plt.subplots(dpi=300) +regionalgdp_pc.plot(ax=ax, xlabel='year', + lw=2, + ylabel='international dollars') +ax.set_yscale('log') +plt.legend(loc='lower center', + ncol=3, bbox_to_anchor=[0.5, -0.5]) +plt.show() +``` diff --git a/content/lectures/lp_intro.ipynb b/book/_build/html/_sources/lp_intro.ipynb similarity index 80% rename from content/lectures/lp_intro.ipynb rename to book/_build/html/_sources/lp_intro.ipynb index 3e67a4a..1af72b0 100644 --- a/content/lectures/lp_intro.ipynb +++ b/book/_build/html/_sources/lp_intro.ipynb @@ -2,10 +2,11 @@ "cells": [ { "cell_type": "markdown", - "id": "842a22db", + "id": "546ab34c", "metadata": {}, "source": [ "(lp_intro)=\n", + "# Linear Programming\n", "\n", "In this lecture, we will need the following library. Install [ortools](https://developers.google.com/optimization) using `%pip`." ] @@ -13,7 +14,7 @@ { "cell_type": "code", "execution_count": null, - "id": "d8d2b729", + "id": "036b82fe", "metadata": { "tags": [ "hide-output" @@ -26,11 +27,9 @@ }, { "cell_type": "markdown", - "id": "96e2d6cc", + "id": "479b1538", "metadata": {}, "source": [ - "# Linear Programming\n", - "\n", "## Overview\n", "\n", "**Linear programming** problems either maximize or minimize\n", @@ -42,15 +41,18 @@ "\n", "* an associated **dual** problem.\n", "\n", - "If a primal problem involves **maximization**, the dual problem involves **minimization**.\n", + "If a primal problem involves *maximization*, the dual problem involves *minimization*.\n", "\n", - "If a primal problem involves **minimization**, the dual problem involves **maximization**.\n", + "If a primal problem involves *minimization**, the dual problem involves **maximization*.\n", "\n", "We provide a standard form of a linear program and methods to transform other forms of linear programming problems into a standard form.\n", "\n", "We tell how to solve a linear programming problem using [SciPy](https://scipy.org/) and [Google OR-Tools](https://developers.google.com/optimization).\n", "\n", - "We describe the important concept of complementary slackness and how it relates to the dual problem.\n", + "```{seealso}\n", + "In another lecture, we will employ the linear programming method to solve the \n", + "{doc}`optimal transport problem `.\n", + "```\n", "\n", "Let's start with some standard imports." ] @@ -58,7 +60,7 @@ { "cell_type": "code", "execution_count": null, - "id": "de80ca95", + "id": "31eac7f8", "metadata": {}, "outputs": [], "source": [ @@ -66,20 +68,19 @@ "from ortools.linear_solver import pywraplp\n", "from scipy.optimize import linprog\n", "import matplotlib.pyplot as plt\n", - "from matplotlib.patches import Polygon\n", - "%matplotlib inline" + "from matplotlib.patches import Polygon" ] }, { "cell_type": "markdown", - "id": "b69fe7eb", + "id": "fd43484f", "metadata": {}, "source": [ "Let's start with some examples of linear programming problem.\n", "\n", "\n", "\n", - "## Example 1: Production Problem\n", + "## Example 1: production problem\n", "\n", "This example was created by {cite}`bertsimas_tsitsiklis1997`\n", "\n", @@ -101,7 +102,7 @@ "\n", "A firm's problem is to construct a production plan that uses its 30 units of materials and 20 units of labor to maximize its revenue.\n", "\n", - "Let $x_i$ denote the quantity of Product $i$ that the firm produces.\n", + "Let $x_i$ denote the quantity of Product $i$ that the firm produces and $z$ denote the total revenue.\n", "\n", "This problem can be formulated as:\n", "\n", @@ -114,13 +115,15 @@ "\\end{aligned}\n", "$$\n", "\n", - "The following graph illustrates the firm's constraints and iso-revenue lines." + "The following graph illustrates the firm's constraints and iso-revenue lines.\n", + "\n", + "Iso-revenue lines show all the combinations of materials and labor that produce the same revenue." ] }, { "cell_type": "code", "execution_count": null, - "id": "be400b6f", + "id": "472d2cc1", "metadata": { "tags": [ "hide-input" @@ -129,60 +132,52 @@ "outputs": [], "source": [ "fig, ax = plt.subplots()\n", - "ax.grid()\n", - "\n", "# Draw constraint lines\n", - "ax.hlines(0, -1, 17.5)\n", - "ax.vlines(0, -1, 12)\n", - "ax.plot(np.linspace(-1, 17.5, 100), 6-0.4*np.linspace(-1, 17.5, 100), color=\"r\")\n", - "ax.plot(np.linspace(-1, 5.5, 100), 10-2*np.linspace(-1, 5.5, 100), color=\"r\")\n", - "ax.text(1.5, 8, \"$2x_1 + 5x_2 \\leq 30$\", size=12)\n", - "ax.text(10, 2.5, \"$4x_1 + 2x_2 \\leq 20$\", size=12)\n", - "ax.text(-2, 2, \"$x_2 \\geq 0$\", size=12)\n", - "ax.text(2.5, -0.7, \"$x_1 \\geq 0$\", size=12)\n", + "ax.set_xlim(0,15)\n", + "ax.set_ylim(0,10)\n", + "x1 = np.linspace(0, 15)\n", + "ax.plot(x1, 6-0.4*x1, label=\"$2x_1 + 5x_2=30$\")\n", + "ax.plot(x1, 10-2*x1, label=\"$4x_1 + 2x_2=20$\")\n", + "\n", "\n", "# Draw the feasible region\n", - "feasible_set = Polygon(np.array([[0, 0],\n", - " [0, 6],\n", - " [2.5, 5],\n", - " [5, 0]]),\n", - " color=\"cyan\")\n", + "feasible_set = Polygon(np.array([[0, 0],[0, 6],[2.5, 5],[5, 0]]), alpha=0.1)\n", "ax.add_patch(feasible_set)\n", "\n", "# Draw the objective function\n", - "ax.plot(np.linspace(-1, 5.5, 100), 3.875-0.75*np.linspace(-1, 5.5, 100), color=\"orange\")\n", - "ax.plot(np.linspace(-1, 5.5, 100), 5.375-0.75*np.linspace(-1, 5.5, 100), color=\"orange\")\n", - "ax.plot(np.linspace(-1, 5.5, 100), 6.875-0.75*np.linspace(-1, 5.5, 100), color=\"orange\")\n", - "ax.arrow(-1.6, 5, 0, 2, width = 0.05, head_width=0.2, head_length=0.5, color=\"orange\")\n", - "ax.text(5.7, 1, \"$z = 3x_1 + 4x_2$\", size=12)\n", + "ax.plot(x1, 3.875-0.75*x1, label=\"iso-revenue lines\",color='k',linewidth=0.75)\n", + "ax.plot(x1, 5.375-0.75*x1, color='k',linewidth=0.75)\n", + "ax.plot(x1, 6.875-0.75*x1, color='k',linewidth=0.75)\n", "\n", "# Draw the optimal solution\n", - "ax.plot(2.5, 5, \"*\", color=\"black\")\n", - "ax.text(2.7, 5.2, \"Optimal Solution\", size=12)\n", + "ax.plot(2.5, 5, \".\", label=\"optimal solution\")\n", + "ax.set_xlabel(\"$x_1$\")\n", + "ax.set_ylabel(\"$x_2$\")\n", + "ax.legend()\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "2801ca21", + "id": "0bf4b99a", "metadata": {}, "source": [ "The blue region is the feasible set within which all constraints are satisfied.\n", "\n", - "Parallel orange lines are iso-revenue lines.\n", + "Parallel black lines are iso-revenue lines.\n", "\n", - "The firm's objective is to find the parallel orange lines to the upper boundary of the feasible set.\n", + "The firm's objective is to find the parallel black lines to the upper boundary of the feasible set.\n", "\n", - "The intersection of the feasible set and the highest orange line delineates the optimal set.\n", + "The intersection of the feasible set and the highest black line delineates the optimal set.\n", "\n", "In this example, the optimal set is the point $(2.5, 5)$.\n", "\n", "\n", "\n", - "### Computation: Using OR-Tools\n", + "### Computation: using OR-Tools\n", "\n", - "Let's try to solve the same problem using the package *ortools.linear_solver*\n", + "Let's try to solve the same problem using the package `ortools.linear_solver`.\n", "\n", "\n", "\n", @@ -192,7 +187,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ee67ffc7", + "id": "66f875ad", "metadata": {}, "outputs": [], "source": [ @@ -202,16 +197,16 @@ }, { "cell_type": "markdown", - "id": "1c41abc7", + "id": "08110e78", "metadata": {}, "source": [ - "Let's us create two variables $x_1$ and $x_2$ such that they can only have nonnegative values." + "Let's create two variables $x_1$ and $x_2$ such that they can only have nonnegative values." ] }, { "cell_type": "code", "execution_count": null, - "id": "88067e6a", + "id": "4bd17792", "metadata": {}, "outputs": [], "source": [ @@ -222,7 +217,7 @@ }, { "cell_type": "markdown", - "id": "db5d1aae", + "id": "7db2997c", "metadata": {}, "source": [ "Add the constraints to the problem." @@ -231,7 +226,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3c95e820", + "id": "78f1ff94", "metadata": {}, "outputs": [], "source": [ @@ -244,7 +239,7 @@ }, { "cell_type": "markdown", - "id": "5d9b5afd", + "id": "41335ba4", "metadata": {}, "source": [ "Let's specify the objective function. We use `solver.Maximize` method in the case when we want to maximize the objective function and in the case of minimization we can use `solver.Minimize`." @@ -253,7 +248,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4a4ea495", + "id": "ad084c0e", "metadata": {}, "outputs": [], "source": [ @@ -263,16 +258,16 @@ }, { "cell_type": "markdown", - "id": "4f554b52", + "id": "09024445", "metadata": {}, "source": [ - "Once we solve the problem, we can check whether the solver was successful in solving the problem using it's status. If it's successful, then the status will be equal to `pywraplp.Solver.OPTIMAL`." + "Once we solve the problem, we can check whether the solver was successful in solving the problem using its status. If it's successful, then the status will be equal to `pywraplp.Solver.OPTIMAL`." ] }, { "cell_type": "code", "execution_count": null, - "id": "b24ff783", + "id": "690f6c9c", "metadata": {}, "outputs": [], "source": [ @@ -281,31 +276,29 @@ "\n", "if status == pywraplp.Solver.OPTIMAL:\n", " print('Objective value =', solver.Objective().Value())\n", - " x1_sol = round(x1.solution_value(), 2)\n", - " x2_sol = round(x2.solution_value(), 2)\n", - " print(f'(x1, x2): ({x1_sol}, {x2_sol})')\n", + " print(f'(x1, x2): ({x1.solution_value():.2}, {x2.solution_value():.2})')\n", "else:\n", " print('The problem does not have an optimal solution.')" ] }, { "cell_type": "markdown", - "id": "445481f8", + "id": "b1ac4e96", "metadata": {}, "source": [ - "## Example 2: Investment Problem\n", + "## Example 2: investment problem\n", "\n", "We now consider a problem posed and solved by {cite}`hu_guo2018`.\n", "\n", - "A mutual fund has $ \\$ 100,000$ to be invested over a three year horizon.\n", + "A mutual fund has $ \\$ 100,000$ to be invested over a three-year horizon.\n", "\n", "Three investment options are available:\n", "\n", - "1. **Annuity:** the fund can pay a same amount of new capital at the beginning of each of three years and receive a payoff of 130\\% of **total capital** invested at the end of the third year. Once the mutual fund decides to invest in this annuity, it has to keep investing in all subsequent years in the three year horizon.\n", + "1. Annuity: the fund can pay a same amount of new capital at the beginning of each of three years and receive a payoff of 130\\% of total capital invested at the end of the third year. Once the mutual fund decides to invest in this annuity, it has to keep investing in all subsequent years in the three year horizon.\n", "\n", - "2. **Bank account:** the fund can deposit any amount into a bank at the beginning of each year and receive its capital plus 6\\% interest at the end of that year. In addition, the mutual fund is permitted to borrow no more than $20,000 at the beginning of each year and is asked to pay back the amount borrowed plus 6\\% interest at the end of the year. The mutual fund can choose whether to deposit or borrow at the beginning of each year.\n", + "2. Bank account: the fund can deposit any amount into a bank at the beginning of each year and receive its capital plus 6\\% interest at the end of that year. In addition, the mutual fund is permitted to borrow no more than $20,000 at the beginning of each year and is asked to pay back the amount borrowed plus 6\\% interest at the end of the year. The mutual fund can choose whether to deposit or borrow at the beginning of each year.\n", "\n", - "3. **Corporate bond:** At the beginning of the second year, a corporate bond becomes available.\n", + "3. Corporate bond: At the beginning of the second year, a corporate bond becomes available.\n", "The fund can buy an amount\n", "that is no more than $ \\$ $50,000 of this bond at the beginning of the second year and at the end of the third year receive a payout of 130\\% of the amount invested in the bond.\n", "\n", @@ -375,9 +368,9 @@ "\n", "\n", "\n", - "### Computation: Using OR-Tools\n", + "### Computation: using OR-Tools\n", "\n", - "Let's try to solve the above problem using the package *ortools.linear_solver*.\n", + "Let's try to solve the above problem using the package `ortools.linear_solver`.\n", "\n", "The following cell instantiates a solver and creates two variables specifying the range of values that they can have." ] @@ -385,7 +378,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a3479f46", + "id": "62e90a60", "metadata": {}, "outputs": [], "source": [ @@ -395,16 +388,16 @@ }, { "cell_type": "markdown", - "id": "6ec2ffbc", + "id": "60fd5f33", "metadata": {}, "source": [ - "Let's us create five variables $x_1, x_2, x_3, x_4,$ and $x_5$ such that they can only have the values defined in the above constraints." + "Let's create five variables $x_1, x_2, x_3, x_4,$ and $x_5$ such that they can only have the values defined in the above constraints." ] }, { "cell_type": "code", "execution_count": null, - "id": "a728f1bd", + "id": "5bc991f7", "metadata": {}, "outputs": [], "source": [ @@ -418,7 +411,7 @@ }, { "cell_type": "markdown", - "id": "d45a1917", + "id": "29dca34a", "metadata": {}, "source": [ "Add the constraints to the problem." @@ -427,7 +420,7 @@ { "cell_type": "code", "execution_count": null, - "id": "67eb9c04", + "id": "1f35467b", "metadata": {}, "outputs": [], "source": [ @@ -443,7 +436,7 @@ }, { "cell_type": "markdown", - "id": "89b46202", + "id": "42f2beea", "metadata": {}, "source": [ "Let's specify the objective function." @@ -452,7 +445,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c18fdb93", + "id": "cca361b3", "metadata": {}, "outputs": [], "source": [ @@ -462,7 +455,7 @@ }, { "cell_type": "markdown", - "id": "23867d8d", + "id": "8c91d9f3", "metadata": {}, "source": [ "Let's solve the problem and check the status using `pywraplp.Solver.OPTIMAL`." @@ -471,7 +464,7 @@ { "cell_type": "code", "execution_count": null, - "id": "763417a7", + "id": "6d96a6c7", "metadata": {}, "outputs": [], "source": [ @@ -492,7 +485,7 @@ }, { "cell_type": "markdown", - "id": "4194ef87", + "id": "ead56dfa", "metadata": {}, "source": [ "OR-Tools tells us that the best investment strategy is:\n", @@ -503,11 +496,11 @@ "\n", "3. At the beginning of the third year, the bank balance should be $ \\$75,072.245 $.\n", "\n", - "4. At the end of the third year, the mutual fund will get payouts from the annuity and corporate bond and repay its loan from the bank. At the end it will own $ \\$141018.24 $, so that it's total net rate of return over the three periods is $ 41.02\\%$.\n", + "4. At the end of the third year, the mutual fund will get payouts from the annuity and corporate bond and repay its loan from the bank. At the end it will own $ \\$141,018.24 $, so that it's total net rate of return over the three periods is $ 41.02\\%$.\n", "\n", "\n", "\n", - "## Standard Form\n", + "## Standard form\n", "\n", "For purposes of\n", "\n", @@ -544,7 +537,7 @@ "x = \\begin{bmatrix} x_1 \\\\ x_2 \\\\ \\vdots \\\\ x_n \\\\ \\end{bmatrix}. \\quad\n", "$$\n", "\n", - "The standard form LP problem can be expressed concisely as:\n", + "The standard form linear programming problem can be expressed concisely as:\n", "\n", "$$\n", "\\begin{aligned}\n", @@ -558,21 +551,21 @@ "\n", "Similarly, $x \\geq 0$ means that $x_j$ is greater than equal to $0$ for every $j$.\n", "\n", - "### Useful Transformations\n", + "### Useful transformations\n", "\n", "It is useful to know how to transform a problem that initially is not stated in the standard form into one that is.\n", "\n", "By deploying the following steps, any linear programming problem can be transformed into an equivalent standard form linear programming problem.\n", "\n", - "1. **Objective Function:** If a problem is originally a constrained **maximization** problem, we can construct a new objective function that is the additive inverse of the original objective function. The transformed problem is then a **minimization** problem.\n", + "1. Objective function: If a problem is originally a constrained *maximization* problem, we can construct a new objective function that is the additive inverse of the original objective function. The transformed problem is then a *minimization* problem.\n", "\n", - "2. **Decision Variables:** Given a variable $x_j$ satisfying $x_j \\le 0$, we can introduce a new variable $x_j' = - x_j$ and substitute it into original problem. Given a free variable $x_i$ with no restriction on its sign, we can introduce two new variables $x_j^+$ and $x_j^-$ satisfying $x_j^+, x_j^- \\ge 0$ and replace $x_j$ by $x_j^+ - x_j^-$.\n", + "2. Decision variables: Given a variable $x_j$ satisfying $x_j \\le 0$, we can introduce a new variable $x_j' = - x_j$ and substitute it into original problem. Given a free variable $x_i$ with no restriction on its sign, we can introduce two new variables $x_j^+$ and $x_j^-$ satisfying $x_j^+, x_j^- \\ge 0$ and replace $x_j$ by $x_j^+ - x_j^-$.\n", "\n", - "3. **Inequality constraints:** Given an inequality constraint $\\sum_{j=1}^n a_{ij}x_j \\le 0$, we can introduce a new variable $s_i$, called a **slack variable** that satisfies $s_i \\ge 0$ and replace the original constraint by $\\sum_{j=1}^n a_{ij}x_j + s_i = 0$.\n", + "3. Inequality constraints: Given an inequality constraint $\\sum_{j=1}^n a_{ij}x_j \\le 0$, we can introduce a new variable $s_i$, called a **slack variable** that satisfies $s_i \\ge 0$ and replace the original constraint by $\\sum_{j=1}^n a_{ij}x_j + s_i = 0$.\n", "\n", "Let's apply the above steps to the two examples described above.\n", "\n", - "### Example 1: Production Problem\n", + "### Example 1: production problem\n", "\n", "The original problem is:\n", "\n", @@ -598,9 +591,9 @@ "\n", "\n", "\n", - "### Computation: Using SciPy\n", + "### Computation: using SciPy\n", "\n", - "The package *scipy.optimize* provides a function ***linprog*** to solve linear programming problems with a form below:\n", + "The package `scipy.optimize` provides a function `linprog` to solve linear programming problems with a form below:\n", "\n", "$$\n", "\\begin{aligned}\n", @@ -611,8 +604,10 @@ "\\end{aligned}\n", "$$\n", "\n", + "$A_{eq}, b_{eq}$ denote the equality constraint matrix and vector, and $A_{ub}, b_{ub}$ denote the inequality constraint matrix and vector.\n", + "\n", "```{note}\n", - "By default $l = 0$ and $u = \\text{None}$ unless explicitly specified with the argument 'bounds'.\n", + "By default $l = 0$ and $u = \\text{None}$ unless explicitly specified with the argument `bounds`.\n", "```\n", "\n", "Let's now try to solve the Problem 1 using SciPy." @@ -621,7 +616,7 @@ { "cell_type": "code", "execution_count": null, - "id": "eeab23ff", + "id": "f3f78251", "metadata": {}, "outputs": [], "source": [ @@ -636,7 +631,7 @@ }, { "cell_type": "markdown", - "id": "e73d554d", + "id": "b4fb42bb", "metadata": {}, "source": [ "Once we solve the problem, we can check whether the solver was successful in solving the problem using the boolean attribute `success`. If it's successful, then the `success` attribute is set to `True`." @@ -645,7 +640,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4250ccdd", + "id": "1b0a104b", "metadata": {}, "outputs": [], "source": [ @@ -663,12 +658,12 @@ }, { "cell_type": "markdown", - "id": "fe88f0d6", + "id": "9bca93ae", "metadata": {}, "source": [ "The optimal plan tells the factory to produce $2.5$ units of Product 1 and $5$ units of Product 2; that generates a maximizing value of revenue of $27.5$.\n", "\n", - "We are using the *linprog* function as a **black box**.\n", + "We are using the `linprog` function as a *black box*.\n", "\n", "Inside it, Python first transforms the problem into standard form.\n", "\n", @@ -679,12 +674,12 @@ "See the [official documentation](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linprog.html#scipy.optimize.linprog) for more details.\n", "\n", "```{note}\n", - "This problem is to maximize the objective, so that we need to put a minus sign in front of parameter vector c.\n", + "This problem is to maximize the objective, so that we need to put a minus sign in front of parameter vector $c$.\n", "```\n", "\n", "\n", "\n", - "### Example 2: Investment Problem\n", + "### Example 2: investment problem\n", "\n", "The original problem is:\n", "\n", @@ -725,7 +720,7 @@ { "cell_type": "code", "execution_count": null, - "id": "af04b463", + "id": "c0731e31", "metadata": {}, "outputs": [], "source": [ @@ -739,19 +734,19 @@ "A_ex2 = np.array([[1, 1, 0, 0, 0],\n", " [1, -rate, 1, 0, 1],\n", " [1, 0, -rate, 1, 0]])\n", - "b_ex2 = np.array([100000, 0, 0])\n", + "b_ex2 = np.array([100_000, 0, 0])\n", "\n", "# Bounds on decision variables\n", "bounds_ex2 = [( 0, None),\n", - " (-20000, None),\n", - " (-20000, None),\n", - " (-20000, None),\n", - " ( 0, 50000)]" + " (-20_000, None),\n", + " (-20_000, None),\n", + " (-20_000, None),\n", + " ( 0, 50_000)]" ] }, { "cell_type": "markdown", - "id": "4b3c69ce", + "id": "3813acc8", "metadata": {}, "source": [ "Let's solve the problem and check the status using `success` attribute." @@ -760,7 +755,7 @@ { "cell_type": "code", "execution_count": null, - "id": "acd6e77a", + "id": "9be8a2f5", "metadata": {}, "outputs": [], "source": [ @@ -783,7 +778,7 @@ }, { "cell_type": "markdown", - "id": "fb019646", + "id": "a8de20ad", "metadata": {}, "source": [ "SciPy tells us that the best investment strategy is:\n", @@ -794,7 +789,7 @@ "\n", "3. At the beginning of the third year, the mutual fund should borrow $ \\$20,000$ from the bank and invest in the annuity.\n", "\n", - "4. At the end of the third year, the mutual fund will get payouts from the annuity and corporate bond and repay its loan from the bank. At the end it will own $ \\$141018.24 $, so that it's total net rate of return over the three periods is $ 41.02\\% $.\n", + "4. At the end of the third year, the mutual fund will get payouts from the annuity and corporate bond and repay its loan from the bank. At the end it will own $ \\$141,018.24 $, so that it's total net rate of return over the three periods is $ 41.02\\% $.\n", "\n", "\n", "\n", @@ -836,7 +831,7 @@ { "cell_type": "code", "execution_count": null, - "id": "d2f3c93d", + "id": "1d98227c", "metadata": {}, "outputs": [], "source": [ @@ -851,7 +846,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5afdb8cd", + "id": "57cba998", "metadata": {}, "outputs": [], "source": [ @@ -868,7 +863,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1ba54cf6", + "id": "f3b10e06", "metadata": {}, "outputs": [], "source": [ @@ -879,7 +874,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1b0c4844", + "id": "2036168f", "metadata": {}, "outputs": [], "source": [ @@ -897,7 +892,7 @@ }, { "cell_type": "markdown", - "id": "f11ca476", + "id": "f98a055c", "metadata": {}, "source": [ "```{solution-end}\n", @@ -942,7 +937,7 @@ { "cell_type": "code", "execution_count": null, - "id": "727acd35", + "id": "259a98ce", "metadata": {}, "outputs": [], "source": [ @@ -952,16 +947,16 @@ }, { "cell_type": "markdown", - "id": "7b1a0458", + "id": "2977a563", "metadata": {}, "source": [ - "Let's us create two variables $x_1$ and $x_2$ such that they can only have nonnegative values." + "Let's create two variables $x_1$ and $x_2$ such that they can only have nonnegative values." ] }, { "cell_type": "code", "execution_count": null, - "id": "700e19a2", + "id": "5d6821a9", "metadata": {}, "outputs": [], "source": [ @@ -973,7 +968,7 @@ { "cell_type": "code", "execution_count": null, - "id": "49c829c0", + "id": "3f02230d", "metadata": {}, "outputs": [], "source": [ @@ -987,7 +982,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a5732b0d", + "id": "7024553b", "metadata": {}, "outputs": [], "source": [ @@ -998,7 +993,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ed00dbd0", + "id": "29398b36", "metadata": {}, "outputs": [], "source": [ @@ -1016,7 +1011,7 @@ }, { "cell_type": "markdown", - "id": "59ea99b9", + "id": "8bd48493", "metadata": {}, "source": [ "```{solution-end}\n", @@ -1025,12 +1020,67 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 10, + 17, + 22, + 50, + 56, + 101, + 130, + 152, + 155, + 159, + 163, + 167, + 173, + 177, + 180, + 184, + 193, + 283, + 286, + 290, + 297, + 301, + 310, + 314, + 317, + 321, + 335, + 461, + 469, + 473, + 484, + 541, + 560, + 565, + 581, + 630, + 639, + 650, + 655, + 666, + 706, + 709, + 712, + 718, + 726, + 731, + 742 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/lp_intro.md b/book/_build/html/_sources/lp_intro.md new file mode 100644 index 0000000..3b89c02 --- /dev/null +++ b/book/_build/html/_sources/lp_intro.md @@ -0,0 +1,745 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +(lp_intro)= +# Linear Programming + +In this lecture, we will need the following library. Install [ortools](https://developers.google.com/optimization) using `%pip`. + +```{code-cell} ipython3 +--- +tags: [hide-output] +--- +%pip install ortools +``` + +## Overview + +**Linear programming** problems either maximize or minimize +a linear objective function subject to a set of linear equality and/or inequality constraints. + +Linear programs come in pairs: + +* an original **primal** problem, and + +* an associated **dual** problem. + +If a primal problem involves *maximization*, the dual problem involves *minimization*. + +If a primal problem involves *minimization**, the dual problem involves **maximization*. + +We provide a standard form of a linear program and methods to transform other forms of linear programming problems into a standard form. + +We tell how to solve a linear programming problem using [SciPy](https://scipy.org/) and [Google OR-Tools](https://developers.google.com/optimization). + +```{seealso} +In another lecture, we will employ the linear programming method to solve the +{doc}`optimal transport problem `. +``` + +Let's start with some standard imports. + +```{code-cell} ipython3 +import numpy as np +from ortools.linear_solver import pywraplp +from scipy.optimize import linprog +import matplotlib.pyplot as plt +from matplotlib.patches import Polygon +``` + +Let's start with some examples of linear programming problem. + + + +## Example 1: production problem + +This example was created by {cite}`bertsimas_tsitsiklis1997` + +Suppose that a factory can produce two goods called Product $1$ and Product $2$. + +To produce each product requires both material and labor. + +Selling each product generates revenue. + +Required per unit material and labor inputs and revenues are shown in table below: + +| | Product 1 | Product 2 | +| :------: | :-------: | :-------: | +| Material | 2 | 5 | +| Labor | 4 | 2 | +| Revenue | 3 | 4 | + +30 units of material and 20 units of labor available. + +A firm's problem is to construct a production plan that uses its 30 units of materials and 20 units of labor to maximize its revenue. + +Let $x_i$ denote the quantity of Product $i$ that the firm produces and $z$ denote the total revenue. + +This problem can be formulated as: + +$$ +\begin{aligned} +\max_{x_1,x_2} \ & z = 3 x_1 + 4 x_2 \\ +\mbox{subject to } \ & 2 x_1 + 5 x_2 \le 30 \\ +& 4 x_1 + 2 x_2 \le 20 \\ +& x_1, x_2 \ge 0 \\ +\end{aligned} +$$ + +The following graph illustrates the firm's constraints and iso-revenue lines. + +Iso-revenue lines show all the combinations of materials and labor that produce the same revenue. + +```{code-cell} ipython3 +--- +tags: [hide-input] +--- +fig, ax = plt.subplots() +# Draw constraint lines +ax.set_xlim(0,15) +ax.set_ylim(0,10) +x1 = np.linspace(0, 15) +ax.plot(x1, 6-0.4*x1, label="$2x_1 + 5x_2=30$") +ax.plot(x1, 10-2*x1, label="$4x_1 + 2x_2=20$") + + +# Draw the feasible region +feasible_set = Polygon(np.array([[0, 0],[0, 6],[2.5, 5],[5, 0]]), alpha=0.1) +ax.add_patch(feasible_set) + +# Draw the objective function +ax.plot(x1, 3.875-0.75*x1, label="iso-revenue lines",color='k',linewidth=0.75) +ax.plot(x1, 5.375-0.75*x1, color='k',linewidth=0.75) +ax.plot(x1, 6.875-0.75*x1, color='k',linewidth=0.75) + +# Draw the optimal solution +ax.plot(2.5, 5, ".", label="optimal solution") +ax.set_xlabel("$x_1$") +ax.set_ylabel("$x_2$") +ax.legend() + +plt.show() +``` + +The blue region is the feasible set within which all constraints are satisfied. + +Parallel black lines are iso-revenue lines. + +The firm's objective is to find the parallel black lines to the upper boundary of the feasible set. + +The intersection of the feasible set and the highest black line delineates the optimal set. + +In this example, the optimal set is the point $(2.5, 5)$. + + + +### Computation: using OR-Tools + +Let's try to solve the same problem using the package `ortools.linear_solver`. + + + +The following cell instantiates a solver and creates two variables specifying the range of values that they can have. + +```{code-cell} ipython3 +# Instantiate a GLOP(Google Linear Optimization Package) solver +solver = pywraplp.Solver.CreateSolver('GLOP') +``` + +Let's create two variables $x_1$ and $x_2$ such that they can only have nonnegative values. + +```{code-cell} ipython3 +# Create the two variables and let them take on any non-negative value. +x1 = solver.NumVar(0, solver.infinity(), 'x1') +x2 = solver.NumVar(0, solver.infinity(), 'x2') +``` + +Add the constraints to the problem. + +```{code-cell} ipython3 +# Constraint 1: 2x_1 + 5x_2 <= 30.0 +solver.Add(2 * x1 + 5 * x2 <= 30.0) + +# Constraint 2: 4x_1 + 2x_2 <= 20.0 +solver.Add(4 * x1 + 2 * x2 <= 20.0) +``` + +Let's specify the objective function. We use `solver.Maximize` method in the case when we want to maximize the objective function and in the case of minimization we can use `solver.Minimize`. + +```{code-cell} ipython3 +# Objective function: 3x_1 + 4x_2 +solver.Maximize(3 * x1 + 4 * x2) +``` + +Once we solve the problem, we can check whether the solver was successful in solving the problem using its status. If it's successful, then the status will be equal to `pywraplp.Solver.OPTIMAL`. + +```{code-cell} ipython3 +# Solve the system. +status = solver.Solve() + +if status == pywraplp.Solver.OPTIMAL: + print('Objective value =', solver.Objective().Value()) + print(f'(x1, x2): ({x1.solution_value():.2}, {x2.solution_value():.2})') +else: + print('The problem does not have an optimal solution.') +``` + +## Example 2: investment problem + +We now consider a problem posed and solved by {cite}`hu_guo2018`. + +A mutual fund has $ \$ 100,000$ to be invested over a three-year horizon. + +Three investment options are available: + +1. Annuity: the fund can pay a same amount of new capital at the beginning of each of three years and receive a payoff of 130\% of total capital invested at the end of the third year. Once the mutual fund decides to invest in this annuity, it has to keep investing in all subsequent years in the three year horizon. + +2. Bank account: the fund can deposit any amount into a bank at the beginning of each year and receive its capital plus 6\% interest at the end of that year. In addition, the mutual fund is permitted to borrow no more than $20,000 at the beginning of each year and is asked to pay back the amount borrowed plus 6\% interest at the end of the year. The mutual fund can choose whether to deposit or borrow at the beginning of each year. + +3. Corporate bond: At the beginning of the second year, a corporate bond becomes available. +The fund can buy an amount +that is no more than $ \$ $50,000 of this bond at the beginning of the second year and at the end of the third year receive a payout of 130\% of the amount invested in the bond. + +The mutual fund's objective is to maximize total payout that it owns at the end of the third year. + +We can formulate this as a linear programming problem. + +Let $x_1$ be the amount of put in the annuity, $x_2, x_3, x_4$ be bank deposit balances at the beginning of the three years, and $x_5$ be the amount invested in the corporate bond. + +When $x_2, x_3, x_4$ are negative, it means that the mutual fund has borrowed from bank. + +The table below shows the mutual fund's decision variables together with the timing protocol described above: + +| | Year 1 | Year 2 | Year 3 | +| :------------: | :----: | :----: | :----: | +| Annuity | $x_1$ | $x_1$ | $x_1$ | +| Bank account | $x_2$ | $x_3$ | $x_4$ | +| Corporate bond | 0 | $x_5$ | 0 | + +The mutual fund's decision making proceeds according to the following timing protocol: + +1. At the beginning of the first year, the mutual fund decides how much to invest in the annuity and + how much to deposit in the bank. This decision is subject to the constraint: + + $$ + x_1 + x_2 = 100,000 + $$ + +2. At the beginning of the second year, the mutual fund has a bank balance of $1.06 x_2$. + It must keep $x_1$ in the annuity. It can choose to put $x_5$ into the corporate bond, + and put $x_3$ in the bank. These decisions are restricted by + + $$ + x_1 + x_5 = 1.06 x_2 - x_3 + $$ + +3. At the beginning of the third year, the mutual fund has a bank account balance equal + to $1.06 x_3$. It must again invest $x_1$ in the annuity, + leaving it with a bank account balance equal to $x_4$. This situation is summarized by the restriction: + + $$ + x_1 = 1.06 x_3 - x_4 + $$ + +The mutual fund's objective function, i.e., its wealth at the end of the third year is: + +$$ +1.30 \cdot 3x_1 + 1.06 x_4 + 1.30 x_5 +$$ + +Thus, the mutual fund confronts the linear program: + +$$ +\begin{aligned} +\max_{x} \ & 1.30 \cdot 3x_1 + 1.06 x_4 + 1.30 x_5 \\ +\mbox{subject to } \ & x_1 + x_2 = 100,000\\ + & x_1 - 1.06 x_2 + x_3 + x_5 = 0\\ + & x_1 - 1.06 x_3 + x_4 = 0\\ + & x_2 \ge -20,000\\ + & x_3 \ge -20,000\\ + & x_4 \ge -20,000\\ + & x_5 \le 50,000\\ + & x_j \ge 0, \quad j = 1,5\\ + & x_j \ \text{unrestricted}, \quad j = 2,3,4\\ +\end{aligned} +$$ + + + +### Computation: using OR-Tools + +Let's try to solve the above problem using the package `ortools.linear_solver`. + +The following cell instantiates a solver and creates two variables specifying the range of values that they can have. + +```{code-cell} ipython3 +# Instantiate a GLOP(Google Linear Optimization Package) solver +solver = pywraplp.Solver.CreateSolver('GLOP') +``` + +Let's create five variables $x_1, x_2, x_3, x_4,$ and $x_5$ such that they can only have the values defined in the above constraints. + +```{code-cell} ipython3 +# Create the variables using the ranges available from constraints +x1 = solver.NumVar(0, solver.infinity(), 'x1') +x2 = solver.NumVar(-20_000, solver.infinity(), 'x2') +x3 = solver.NumVar(-20_000, solver.infinity(), 'x3') +x4 = solver.NumVar(-20_000, solver.infinity(), 'x4') +x5 = solver.NumVar(0, 50_000, 'x5') +``` + +Add the constraints to the problem. + +```{code-cell} ipython3 +# Constraint 1: x_1 + x_2 = 100,000 +solver.Add(x1 + x2 == 100_000.0) + +# Constraint 2: x_1 - 1.06 * x_2 + x_3 + x_5 = 0 +solver.Add(x1 - 1.06 * x2 + x3 + x5 == 0.0) + +# Constraint 3: x_1 - 1.06 * x_3 + x_4 = 0 +solver.Add(x1 - 1.06 * x3 + x4 == 0.0) +``` + +Let's specify the objective function. + +```{code-cell} ipython3 +# Objective function: 1.30 * 3 * x_1 + 1.06 * x_4 + 1.30 * x_5 +solver.Maximize(1.30 * 3 * x1 + 1.06 * x4 + 1.30 * x5) +``` + +Let's solve the problem and check the status using `pywraplp.Solver.OPTIMAL`. + +```{code-cell} ipython3 +# Solve the system. +status = solver.Solve() + +if status == pywraplp.Solver.OPTIMAL: + print('Objective value =', solver.Objective().Value()) + x1_sol = round(x1.solution_value(), 3) + x2_sol = round(x2.solution_value(), 3) + x3_sol = round(x1.solution_value(), 3) + x4_sol = round(x2.solution_value(), 3) + x5_sol = round(x1.solution_value(), 3) + print(f'(x1, x2, x3, x4, x5): ({x1_sol}, {x2_sol}, {x3_sol}, {x4_sol}, {x5_sol})') +else: + print('The problem does not have an optimal solution.') +``` + +OR-Tools tells us that the best investment strategy is: + +1. At the beginning of the first year, the mutual fund should buy $ \$24,927.755$ of the annuity. Its bank account balance should be $ \$75,072.245$. + +2. At the beginning of the second year, the mutual fund should buy $ \$24,927.755$ of the corporate bond and keep invest in the annuity. Its bank balance should be $ \$24,927.755$. + +3. At the beginning of the third year, the bank balance should be $ \$75,072.245 $. + +4. At the end of the third year, the mutual fund will get payouts from the annuity and corporate bond and repay its loan from the bank. At the end it will own $ \$141,018.24 $, so that it's total net rate of return over the three periods is $ 41.02\%$. + + + +## Standard form + +For purposes of + +* unifying linear programs that are initially stated in superficially different forms, and + +* having a form that is convenient to put into black-box software packages, + +it is useful to devote some effort to describe a **standard form**. + +Our standard form is: + +$$ +\begin{aligned} +\min_{x} \ & c_1 x_1 + c_2 x_2 + \dots + c_n x_n \\ +\mbox{subject to } \ & a_{11} x_1 + a_{12} x_2 + \dots + a_{1n} x_n = b_1 \\ + & a_{21} x_1 + a_{22} x_2 + \dots + a_{2n} x_n = b_2 \\ + & \quad \vdots \\ + & a_{m1} x_1 + a_{m2} x_2 + \dots + a_{mn} x_n = b_m \\ + & x_1, x_2, \dots, x_n \ge 0 \\ +\end{aligned} +$$ + +Let + +$$ +A = \begin{bmatrix} +a_{11} & a_{12} & \dots & a_{1n} \\ +a_{21} & a_{22} & \dots & a_{2n} \\ + & & \vdots & \\ +a_{m1} & a_{m2} & \dots & a_{mn} \\ +\end{bmatrix}, \quad +b = \begin{bmatrix} b_1 \\ b_2 \\ \vdots \\ b_m \\ \end{bmatrix}, \quad +c = \begin{bmatrix} c_1 \\ c_2 \\ \vdots \\ c_n \\ \end{bmatrix}, \quad +x = \begin{bmatrix} x_1 \\ x_2 \\ \vdots \\ x_n \\ \end{bmatrix}. \quad +$$ + +The standard form linear programming problem can be expressed concisely as: + +$$ +\begin{aligned} +\min_{x} \ & c'x \\ +\mbox{subject to } \ & Ax = b\\ + & x \geq 0\\ +\end{aligned} +$$ (lpproblem) + +Here, $Ax = b$ means that the $i$-th entry of $Ax$ equals the $i$-th entry of $b$ for every $i$. + +Similarly, $x \geq 0$ means that $x_j$ is greater than equal to $0$ for every $j$. + +### Useful transformations + +It is useful to know how to transform a problem that initially is not stated in the standard form into one that is. + +By deploying the following steps, any linear programming problem can be transformed into an equivalent standard form linear programming problem. + +1. Objective function: If a problem is originally a constrained *maximization* problem, we can construct a new objective function that is the additive inverse of the original objective function. The transformed problem is then a *minimization* problem. + +2. Decision variables: Given a variable $x_j$ satisfying $x_j \le 0$, we can introduce a new variable $x_j' = - x_j$ and substitute it into original problem. Given a free variable $x_i$ with no restriction on its sign, we can introduce two new variables $x_j^+$ and $x_j^-$ satisfying $x_j^+, x_j^- \ge 0$ and replace $x_j$ by $x_j^+ - x_j^-$. + +3. Inequality constraints: Given an inequality constraint $\sum_{j=1}^n a_{ij}x_j \le 0$, we can introduce a new variable $s_i$, called a **slack variable** that satisfies $s_i \ge 0$ and replace the original constraint by $\sum_{j=1}^n a_{ij}x_j + s_i = 0$. + +Let's apply the above steps to the two examples described above. + +### Example 1: production problem + +The original problem is: + +$$ +\begin{aligned} +\max_{x_1,x_2} \ & 3 x_1 + 4 x_2 \\ +\mbox{subject to } \ & 2 x_1 + 5 x_2 \le 30 \\ +& 4 x_1 + 2 x_2 \le 20 \\ +& x_1, x_2 \ge 0 \\ +\end{aligned} +$$ + +This problem is equivalent to the following problem with a standard form: + +$$ +\begin{aligned} +\min_{x_1,x_2} \ & -(3 x_1 + 4 x_2) \\ +\mbox{subject to } \ & 2 x_1 + 5 x_2 + s_1 = 30 \\ +& 4 x_1 + 2 x_2 + s_2 = 20 \\ +& x_1, x_2, s_1, s_2 \ge 0 \\ +\end{aligned} +$$ + + + +### Computation: using SciPy + +The package `scipy.optimize` provides a function `linprog` to solve linear programming problems with a form below: + +$$ +\begin{aligned} +\min_{x} \ & c' x \\ +\mbox{subject to } \ & A_{ub}x \le b_{ub} \\ + & A_{eq}x = b_{eq} \\ + & l \le x \le u \\ +\end{aligned} +$$ + +$A_{eq}, b_{eq}$ denote the equality constraint matrix and vector, and $A_{ub}, b_{ub}$ denote the inequality constraint matrix and vector. + +```{note} +By default $l = 0$ and $u = \text{None}$ unless explicitly specified with the argument `bounds`. +``` + +Let's now try to solve the Problem 1 using SciPy. + +```{code-cell} ipython3 +# Construct parameters +c_ex1 = np.array([3, 4]) + +# Inequality constraints +A_ex1 = np.array([[2, 5], + [4, 2]]) +b_ex1 = np.array([30,20]) +``` + +Once we solve the problem, we can check whether the solver was successful in solving the problem using the boolean attribute `success`. If it's successful, then the `success` attribute is set to `True`. + +```{code-cell} ipython3 +# Solve the problem +# we put a negative sign on the objective as linprog does minimization +res_ex1 = linprog(-c_ex1, A_ub=A_ex1, b_ub=b_ex1) + +if res_ex1.success: + # We use negative sign to get the optimal value (maximized value) + print('Optimal Value:', -res_ex1.fun) + print(f'(x1, x2): {res_ex1.x[0], res_ex1.x[1]}') +else: + print('The problem does not have an optimal solution.') +``` + +The optimal plan tells the factory to produce $2.5$ units of Product 1 and $5$ units of Product 2; that generates a maximizing value of revenue of $27.5$. + +We are using the `linprog` function as a *black box*. + +Inside it, Python first transforms the problem into standard form. + +To do that, for each inequality constraint it generates one slack variable. + +Here the vector of slack variables is a two-dimensional NumPy array that equals $b_{ub} - A_{ub}x$. + +See the [official documentation](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linprog.html#scipy.optimize.linprog) for more details. + +```{note} +This problem is to maximize the objective, so that we need to put a minus sign in front of parameter vector $c$. +``` + + + +### Example 2: investment problem + +The original problem is: + +$$ +\begin{aligned} +\max_{x} \ & 1.30 \cdot 3x_1 + 1.06 x_4 + 1.30 x_5 \\ +\mbox{subject to } \ & x_1 + x_2 = 100,000\\ + & x_1 - 1.06 x_2 + x_3 + x_5 = 0\\ + & x_1 - 1.06 x_3 + x_4 = 0\\ + & x_2 \ge -20,000\\ + & x_3 \ge -20,000\\ + & x_4 \ge -20,000\\ + & x_5 \le 50,000\\ + & x_j \ge 0, \quad j = 1,5\\ + & x_j \ \text{unrestricted}, \quad j = 2,3,4\\ +\end{aligned} +$$ + +This problem is equivalent to the following problem with a standard form: + +$$ +\begin{aligned} +\min_{x} \ & -(1.30 \cdot 3x_1 + 1.06 x_4^+ - 1.06 x_4^- + 1.30 x_5) \\ +\mbox{subject to } \ & x_1 + x_2^+ - x_2^- = 100,000\\ + & x_1 - 1.06 (x_2^+ - x_2^-) + x_3^+ - x_3^- + x_5 = 0\\ + & x_1 - 1.06 (x_3^+ - x_3^-) + x_4^+ - x_4^- = 0\\ + & x_2^- - x_2^+ + s_1 = 20,000\\ + & x_3^- - x_3^+ + s_2 = 20,000\\ + & x_4^- - x_4^+ + s_3 = 20,000\\ + & x_5 + s_4 = 50,000\\ + & x_j \ge 0, \quad j = 1,5\\ + & x_j^+, x_j^- \ge 0, \quad j = 2,3,4\\ + & s_j \ge 0, \quad j = 1,2,3,4\\ +\end{aligned} +$$ + +```{code-cell} ipython3 +# Construct parameters +rate = 1.06 + +# Objective function parameters +c_ex2 = np.array([1.30*3, 0, 0, 1.06, 1.30]) + +# Inequality constraints +A_ex2 = np.array([[1, 1, 0, 0, 0], + [1, -rate, 1, 0, 1], + [1, 0, -rate, 1, 0]]) +b_ex2 = np.array([100_000, 0, 0]) + +# Bounds on decision variables +bounds_ex2 = [( 0, None), + (-20_000, None), + (-20_000, None), + (-20_000, None), + ( 0, 50_000)] +``` + +Let's solve the problem and check the status using `success` attribute. + + +```{code-cell} ipython3 +# Solve the problem +res_ex2 = linprog(-c_ex2, A_eq=A_ex2, b_eq=b_ex2, + bounds=bounds_ex2) + +if res_ex2.success: + # We use negative sign to get the optimal value (maximized value) + print('Optimal Value:', -res_ex2.fun) + x1_sol = round(res_ex2.x[0], 3) + x2_sol = round(res_ex2.x[1], 3) + x3_sol = round(res_ex2.x[2], 3) + x4_sol = round(res_ex2.x[3], 3) + x5_sol = round(res_ex2.x[4], 3) + print(f'(x1, x2, x3, x4, x5): {x1_sol, x2_sol, x3_sol, x4_sol, x5_sol}') +else: + print('The problem does not have an optimal solution.') +``` + +SciPy tells us that the best investment strategy is: + +1. At the beginning of the first year, the mutual fund should buy $ \$24,927.75$ of the annuity. Its bank account balance should be $ \$75,072.25$. + +2. At the beginning of the second year, the mutual fund should buy $ \$50,000 $ of the corporate bond and keep invest in the annuity. Its bank account balance should be $ \$ 4,648.83$. + +3. At the beginning of the third year, the mutual fund should borrow $ \$20,000$ from the bank and invest in the annuity. + +4. At the end of the third year, the mutual fund will get payouts from the annuity and corporate bond and repay its loan from the bank. At the end it will own $ \$141,018.24 $, so that it's total net rate of return over the three periods is $ 41.02\% $. + + + +```{note} +You might notice the difference in the values of optimal solution using OR-Tools and SciPy but the optimal value is the same. It is because there can be many optimal solutions for the same problem. +``` + + + +## Exercises + +```{exercise-start} +:label: lp_intro_ex1 +``` + +Implement a new extended solution for the Problem 1 where in the factory owner decides that number of units of Product 1 should not be less than the number of units of Product 2. + +```{exercise-end} +``` + + +```{solution-start} lp_intro_ex1 +:class: dropdown +``` + +So we can reformulate the problem as: + +$$ +\begin{aligned} +\max_{x_1,x_2} \ & z = 3 x_1 + 4 x_2 \\ +\mbox{subject to } \ & 2 x_1 + 5 x_2 \le 30 \\ +& 4 x_1 + 2 x_2 \le 20 \\ +& x_1 \ge x_2 \\ +& x_1, x_2 \ge 0 \\ +\end{aligned} +$$ + + +```{code-cell} ipython3 +# Instantiate a GLOP(Google Linear Optimization Package) solver +solver = pywraplp.Solver.CreateSolver('GLOP') + +# Create the two variables and let them take on any non-negative value. +x1 = solver.NumVar(0, solver.infinity(), 'x1') +x2 = solver.NumVar(0, solver.infinity(), 'x2') +``` + +```{code-cell} ipython3 +# Constraint 1: 2x_1 + 5x_2 <= 30.0 +solver.Add(2 * x1 + 5 * x2 <= 30.0) + +# Constraint 2: 4x_1 + 2x_2 <= 20.0 +solver.Add(4 * x1 + 2 * x2 <= 20.0) + +# Constraint 3: x_1 >= x_2 +solver.Add(x1 >= x2) +``` + +```{code-cell} ipython3 +# Objective function: 3x_1 + 4x_2 +solver.Maximize(3 * x1 + 4 * x2) +``` + +```{code-cell} ipython3 +# Solve the system. +status = solver.Solve() + +if status == pywraplp.Solver.OPTIMAL: + print('Objective value =', solver.Objective().Value()) + x1_sol = round(x1.solution_value(), 2) + x2_sol = round(x2.solution_value(), 2) + print(f'(x1, x2): ({x1_sol}, {x2_sol})') +else: + print('The problem does not have an optimal solution.') +``` + +```{solution-end} +``` + +```{exercise-start} +:label: lp_intro_ex2 +``` + +A carpenter manufactures $2$ products - $A$ and $B$. + + +Product $A$ generates a profit of $23$ and product $B$ generates a profit of $10$. + +It takes $2$ hours for the carpenter to produce $A$ and $0.8$ hours to produce $B$. + +Moreover, he can't spend more than $25$ hours per week and the total number of units of $A$ and $B$ should not be greater than $20$. + +Find the number of units of $A$ and product $B$ that he should manufacture in order to maximise his profit. + +```{exercise-end} +``` + + +```{solution-start} lp_intro_ex2 +:class: dropdown +``` + +Let us assume the carpenter produces $x$ units of $A$ and $y$ units of $B$. + +So we can formulate the problem as: + +$$ +\begin{aligned} +\max_{x,y} \ & z = 23 x + 10 y \\ +\mbox{subject to } \ & x + y \le 20 \\ +& 2 x + 0.8 y \le 25 \\ +\end{aligned} +$$ + +```{code-cell} ipython3 +# Instantiate a GLOP(Google Linear Optimization Package) solver +solver = pywraplp.Solver.CreateSolver('GLOP') +``` +Let's create two variables $x_1$ and $x_2$ such that they can only have nonnegative values. + +```{code-cell} ipython3 +# Create the two variables and let them take on any non-negative value. +x = solver.NumVar(0, solver.infinity(), 'x') +y = solver.NumVar(0, solver.infinity(), 'y') +``` + +```{code-cell} ipython3 +# Constraint 1: x + y <= 20.0 +solver.Add(x + y <= 20.0) + +# Constraint 2: 2x + 0.8y <= 25.0 +solver.Add(2 * x + 0.8 * y <= 25.0) +``` + +```{code-cell} ipython3 +# Objective function: 23x + 10y +solver.Maximize(23 * x + 10 * y) +``` + +```{code-cell} ipython3 +# Solve the system. +status = solver.Solve() + +if status == pywraplp.Solver.OPTIMAL: + print('Maximum Profit =', solver.Objective().Value()) + x_sol = round(x.solution_value(), 3) + y_sol = round(y.solution_value(), 3) + print(f'(x, y): ({x_sol}, {y_sol})') +else: + print('The problem does not have an optimal solution.') +``` + +```{solution-end} +``` diff --git a/content/lectures/markov_chains_I.ipynb b/book/_build/html/_sources/markov_chains_I.ipynb similarity index 70% rename from content/lectures/markov_chains_I.ipynb rename to book/_build/html/_sources/markov_chains_I.ipynb index 5fc8fcb..f51d103 100644 --- a/content/lectures/markov_chains_I.ipynb +++ b/book/_build/html/_sources/markov_chains_I.ipynb @@ -2,28 +2,22 @@ "cells": [ { "cell_type": "markdown", - "id": "5d6a50ec", - "metadata": { - "user_expressions": [] - }, + "id": "65bc233a", + "metadata": {}, "source": [ - "# Markov Chains: Basic Concepts and Stationarity\n", + "# Markov Chains: Basic Concepts \n", "\n", "\n", "```{index} single: Markov Chains: Basic Concepts and Stationarity\n", "```\n", "\n", - "```{contents} Contents\n", - ":depth: 2\n", - "```\n", - "\n", "In addition to what's in Anaconda, this lecture will need the following libraries:" ] }, { "cell_type": "code", "execution_count": null, - "id": "61d4fe07", + "id": "c48fced7", "metadata": { "tags": [ "hide-output" @@ -31,46 +25,34 @@ }, "outputs": [], "source": [ - "%pip install quantecon\n", - "%pip install graphviz" + "%pip install quantecon" ] }, { "cell_type": "markdown", - "id": "881cc8fe", + "id": "0be83526", "metadata": {}, - "source": [ - "```{admonition} graphviz\n", - ":class: warning\n", - "If you are running this lecture locally it requires [graphviz](https://www.graphviz.org)\n", - "to be installed on your computer. Installation instructions for graphviz can be found\n", - "[here](https://www.graphviz.org/download/) \n", - "```" - ] - }, - { - "cell_type": "markdown", - "id": "94b1a5f5", - "metadata": { - "user_expressions": [] - }, "source": [ "## Overview\n", "\n", - "Markov chains are a standard way to model time series with some dependence\n", - "between observations.\n", + "Markov chains provide a way to model situations in which the past casts shadows on the future.\n", + "\n", + "By this we mean that observing measurements about a present situation can help us forecast future situations.\n", + "\n", + "This can be possible when there are statistical dependencies among measurements of something taken at different points of time.\n", "\n", "For example,\n", "\n", - "* inflation next year depends on inflation this year\n", - "* unemployment next month depends on unemployment this month\n", + "* inflation next year might co-vary with inflation this year\n", + "* unemployment next month might co-vary with unemployment this month\n", + "\n", "\n", - "Markov chains are one of the workhorse models of economics and finance.\n", + "Markov chains are a workhorse for economics and finance.\n", "\n", "The theory of Markov chains is beautiful and provides many insights into\n", "probability and dynamics.\n", "\n", - "In this introductory lecture, we will\n", + "In this lecture, we will\n", "\n", "* review some of the key ideas from the theory of Markov chains and\n", "* show how Markov chains appear in some economic applications.\n", @@ -81,30 +63,31 @@ { "cell_type": "code", "execution_count": null, - "id": "63171ce3", + "id": "57847c09", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import quantecon as qe\n", "import numpy as np\n", - "from graphviz import Digraph\n", "import networkx as nx\n", "from matplotlib import cm\n", "import matplotlib as mpl\n", - "from itertools import cycle" + "from mpl_toolkits.mplot3d import Axes3D\n", + "from matplotlib.animation import FuncAnimation\n", + "from IPython.display import HTML\n", + "from matplotlib.patches import Polygon\n", + "from mpl_toolkits.mplot3d.art3d import Poly3DCollection" ] }, { "cell_type": "markdown", - "id": "9ce28539", - "metadata": { - "user_expressions": [] - }, + "id": "8b6f521b", + "metadata": {}, "source": [ "## Definitions and examples\n", "\n", - "In this section we provide the basic definitions and some elementary examples.\n", + "In this section we provide some definitions and elementary examples.\n", "\n", "(finite_dp_stoch_mat)=\n", "### Stochastic matrices\n", @@ -124,68 +107,34 @@ "\n", "If $P$ is a stochastic matrix, then so is the $k$-th power $P^k$ for all $k \\in \\mathbb N$.\n", "\n", - "Checking this is {ref}`one of the exercises ` below.\n", + "You are asked to check this in {ref}`an exercise ` below.\n", "\n", "\n", "### Markov chains\n", "\n", "Now we can introduce Markov chains.\n", "\n", - "First we will give some examples and then we will define them more carefully.\n", - "\n", - "At that time, the connection between stochastic matrices and Markov chains\n", - "will become clear.\n", + "Before defining a Markov chain rigorously, we'll give some examples.\n", "\n", "\n", "(mc_eg2)=\n", "#### Example 1\n", "\n", - "From US unemployment data, Hamilton {cite}`Hamilton2005` estimated the following dynamics." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "68c2e7d7", - "metadata": { - "tags": [ - "hide-input" - ] - }, - "outputs": [], - "source": [ - "dot = Digraph(comment='Graph')\n", - "dot.attr(rankdir='LR')\n", - "dot.node(\"ng\")\n", - "dot.node(\"mr\")\n", - "dot.node(\"sr\")\n", - "\n", - "dot.edge(\"ng\", \"ng\", label=\"0.971\")\n", - "dot.edge(\"ng\", \"mr\", label=\"0.029\")\n", - "dot.edge(\"mr\", \"ng\", label=\"0.145\")\n", - "\n", - "dot.edge(\"mr\", \"mr\", label=\"0.778\")\n", - "dot.edge(\"mr\", \"sr\", label=\"0.077\")\n", - "dot.edge(\"sr\", \"mr\", label=\"0.508\")\n", - "\n", - "dot.edge(\"sr\", \"sr\", label=\"0.492\")\n", - "dot" - ] - }, - { - "cell_type": "markdown", - "id": "f60f946d", - "metadata": { - "user_expressions": [] - }, - "source": [ + "From US unemployment data, Hamilton {cite}`Hamilton2005` estimated the following dynamics.\n", + "\n", + "```{image} /_static/lecture_specific/markov_chains_I/Hamilton.png\n", + ":name: mc_hamilton\n", + ":align: center\n", + "\n", + "```\n", + "\n", "Here there are three **states**\n", "\n", "* \"ng\" represents normal growth\n", "* \"mr\" represents mild recession\n", "* \"sr\" represents severe recession\n", "\n", - "The arrows represent **transition probabilities** over one month.\n", + "The arrows represent transition probabilities over one month.\n", "\n", "For example, the arrow from mild recession to normal growth has 0.145 next to it.\n", "\n", @@ -195,7 +144,7 @@ "97% probability of transitioning from normal growth to normal growth (staying\n", "in the same state).\n", "\n", - "Note that these are *conditional* probabilities --- the probability of\n", + "Note that these are conditional probabilities --- the probability of\n", "transitioning from one state to another (or staying at the same one) conditional on the\n", "current state.\n", "\n", @@ -220,11 +169,11 @@ "\n", "$$\n", "P =\n", - "\\begin{bmatrix} \n", + "\\begin{bmatrix}\n", "0.971 & 0.029 & 0 \\\\\n", "0.145 & 0.778 & 0.077 \\\\\n", "0 & 0.508 & 0.492\n", - "\\end{bmatrix} \n", + "\\end{bmatrix}\n", "$$\n", "\n", "Notice that $P$ is a stochastic matrix.\n", @@ -260,11 +209,11 @@ "```{math}\n", ":label: p_unempemp\n", "\n", - "P = \n", - "\\begin{bmatrix} \n", + "P =\n", + "\\begin{bmatrix}\n", " 1 - \\alpha & \\alpha \\\\\n", " \\beta & 1 - \\beta\n", - "\\end{bmatrix} \n", + "\\end{bmatrix}\n", "```\n", "\n", "For example,\n", @@ -295,33 +244,33 @@ "(mc_eg3)=\n", "#### Example 3\n", "\n", - "Imam and Temple {cite}`imampolitical` categorize political institutions into three types: democracy (D), autocracy (A), and an intermediate state called anocracy (N). \n", - "\n", - "Each institution can have two potential development regimes: collapse (C) and growth (G). This results in six possible states: DG, DC, NG, NC, AG, and AC. \n", + "Imam and Temple {cite}`imampolitical` categorize political institutions into\n", + "three types: democracy $\\text{(D)}$, autocracy $\\text{(A)}$, and an intermediate\n", + "state called anocracy $\\text{(N)}$.\n", "\n", - "The lower probability of transitioning from NC to itself indicates that collapses in anocracies quickly evolve into changes in the political institution. \n", + "Each institution can have two potential development regimes: collapse $\\text{(C)}$ and growth $\\text{(G)}$. This results in six possible states: $\\text{DG, DC, NG, NC, AG}$ and $\\text{AC}$.\n", "\n", - "Democracies tend to have longer-lasting growth regimes compared to autocracies as indicated by the lower probability of transitioning from growth to growth in autocracies.\n", + "Imam and Temple {cite}`imampolitical` estimate the following transition\n", + "probabilities:\n", "\n", - "We can also find a higher probability from collapse to growth in democratic regimes\n", "\n", "$$\n", "P :=\n", - "\\begin{bmatrix} \n", + "\\begin{bmatrix}\n", "0.86 & 0.11 & 0.03 & 0.00 & 0.00 & 0.00 \\\\\n", "0.52 & 0.33 & 0.13 & 0.02 & 0.00 & 0.00 \\\\\n", "0.12 & 0.03 & 0.70 & 0.11 & 0.03 & 0.01 \\\\\n", "0.13 & 0.02 & 0.35 & 0.36 & 0.10 & 0.04 \\\\\n", "0.00 & 0.00 & 0.09 & 0.11 & 0.55 & 0.25 \\\\\n", "0.00 & 0.00 & 0.09 & 0.15 & 0.26 & 0.50\n", - "\\end{bmatrix} \n", + "\\end{bmatrix}\n", "$$" ] }, { "cell_type": "code", "execution_count": null, - "id": "70d805e9", + "id": "b11cdea6", "metadata": {}, "outputs": [], "source": [ @@ -334,30 +283,40 @@ " [0.00, 0.00, 0.09, 0.15, 0.26, 0.50]]" ] }, + { + "cell_type": "markdown", + "id": "c32e1b31", + "metadata": {}, + "source": [ + "Here is a visualization, with darker colors indicating higher probability." + ] + }, { "cell_type": "code", "execution_count": null, - "id": "0920f497", - "metadata": {}, + "id": "e5d33f75", + "metadata": { + "tags": [ + "hide-input" + ] + }, "outputs": [], "source": [ "G = nx.MultiDiGraph()\n", - "edge_ls = []\n", - "label_dict = {}\n", "\n", "for start_idx, node_start in enumerate(nodes):\n", " for end_idx, node_end in enumerate(nodes):\n", " value = P[start_idx][end_idx]\n", " if value != 0:\n", - " G.add_edge(node_start,node_end, weight=value, len=100)\n", - " \n", + " G.add_edge(node_start,node_end, weight=value)\n", + "\n", "pos = nx.spring_layout(G, seed=10)\n", "fig, ax = plt.subplots()\n", "nx.draw_networkx_nodes(G, pos, node_size=600, edgecolors='black', node_color='white')\n", "nx.draw_networkx_labels(G, pos)\n", "\n", "arc_rad = 0.2\n", - "curved_edges = [edge for edge in G.edges()]\n", + "\n", "edges = nx.draw_networkx_edges(G, pos, ax=ax, connectionstyle=f'arc3, rad = {arc_rad}', edge_cmap=cm.Blues, width=2,\n", " edge_color=[G[nodes[0]][nodes[1]][0]['weight'] for nodes in G.edges])\n", "\n", @@ -371,13 +330,22 @@ }, { "cell_type": "markdown", - "id": "4aef09e5", + "id": "107b97fb", "metadata": {}, "source": [ + "Looking at the data, we see that democracies tend to have longer-lasting growth\n", + "regimes compared to autocracies (as indicated by the lower probability of\n", + "transitioning from growth to growth in autocracies).\n", + "\n", + "We can also find a higher probability from collapse to growth in democratic regimes.\n", + "\n", + "\n", "### Defining Markov chains\n", "\n", - "So far we've given examples of Markov chains but now let's define them more\n", - "carefully.\n", + "\n", + "So far we've given examples of Markov chains but we haven't defined them. \n", + "\n", + "Let's do that now. \n", "\n", "To begin, let $S$ be a finite set $\\{x_1, \\ldots, x_n\\}$ with $n$ elements.\n", "\n", @@ -385,7 +353,7 @@ "\n", "A **distribution** $\\psi$ on $S$ is a probability mass function of length $n$, where $\\psi(i)$ is the amount of probability allocated to state $x_i$.\n", "\n", - "A **Markov chain** $\\{X_t\\}$ on $S$ is a sequence of random variables taking values in $S$ \n", + "A **Markov chain** $\\{X_t\\}$ on $S$ is a sequence of random variables taking values in $S$\n", "that have the **Markov property**.\n", "\n", "This means that, for any date $t$ and any state $y \\in S$,\n", @@ -397,9 +365,9 @@ "= \\mathbb P \\{ X_{t+1} = y \\,|\\, X_t, X_{t-1}, \\ldots \\}\n", "```\n", "\n", - "In other words, knowing the current state is enough to know probabilities for the future states.\n", + "This means that once we know the current state $X_t$, adding knowledge of earlier states $X_{t-1}, X_{t-2}$ provides no additional information about probabilities of *future* states. \n", "\n", - "In particular, the dynamics of a Markov chain are fully determined by the set of values\n", + "Thus, the dynamics of a Markov chain are fully determined by the set of **conditional probabilities**\n", "\n", "```{math}\n", ":label: mpp\n", @@ -436,7 +404,7 @@ "```{index} single: Markov Chains; Simulation\n", "```\n", "\n", - "One natural way to answer questions about Markov chains is to simulate them.\n", + "A good way to study Markov chains is to simulate them.\n", "\n", "Let's start by doing this ourselves and then look at libraries that can help\n", "us.\n", @@ -448,10 +416,10 @@ "\n", "### Writing our own simulation code\n", "\n", - "To simulate a Markov chain, we need \n", + "To simulate a Markov chain, we need\n", "\n", - "1. a stochastic matrix $P$ and \n", - "1. a probability mass function $\\psi_0$ of length $n$ from which to draw a initial realization of $X_0$.\n", + "1. a stochastic matrix $P$ and\n", + "1. a probability mass function $\\psi_0$ of length $n$ from which to draw an initial realization of $X_0$.\n", "\n", "The Markov chain is then constructed as follows:\n", "\n", @@ -463,7 +431,7 @@ "To implement this simulation procedure, we need a method for generating draws\n", "from a discrete distribution.\n", "\n", - "For this task, we'll use `random.draw` from [QuantEcon](http://quantecon.org/quantecon-py).\n", + "For this task, we'll use `random.draw` from [QuantEcon.py](http://quantecon.org/quantecon-py).\n", "\n", "To use `random.draw`, we first need to convert the probability mass function\n", "to a cumulative distribution" @@ -472,7 +440,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5a3bef1e", + "id": "1ecb3267", "metadata": {}, "outputs": [], "source": [ @@ -483,10 +451,8 @@ }, { "cell_type": "markdown", - "id": "c0135298", - "metadata": { - "user_expressions": [] - }, + "id": "98ca3936", + "metadata": {}, "source": [ "We'll write our code as a function that accepts the following three arguments\n", "\n", @@ -498,7 +464,7 @@ { "cell_type": "code", "execution_count": null, - "id": "dff5b7bb", + "id": "5d996fe1", "metadata": {}, "outputs": [], "source": [ @@ -509,7 +475,6 @@ " X = np.empty(ts_length, dtype=int)\n", "\n", " # Convert each row of P into a cdf\n", - " n = len(P)\n", " P_dist = np.cumsum(P, axis=1) # Convert rows into cdfs\n", "\n", " # draw initial state, defaulting to 0\n", @@ -528,10 +493,8 @@ }, { "cell_type": "markdown", - "id": "5cdbabc5", - "metadata": { - "user_expressions": [] - }, + "id": "360b3912", + "metadata": {}, "source": [ "Let's see how it works using the small matrix" ] @@ -539,7 +502,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b112e918", + "id": "791ed31c", "metadata": {}, "outputs": [], "source": [ @@ -549,10 +512,8 @@ }, { "cell_type": "markdown", - "id": "aa575cac", - "metadata": { - "user_expressions": [] - }, + "id": "254c99dd", + "metadata": {}, "source": [ "Here's a short time series." ] @@ -560,19 +521,17 @@ { "cell_type": "code", "execution_count": null, - "id": "58d35abc", + "id": "42bf8952", "metadata": {}, "outputs": [], "source": [ - "mc_sample_path(P, ψ_0=[1.0, 0.0], ts_length=10)" + "mc_sample_path(P, ψ_0=(1.0, 0.0), ts_length=10)" ] }, { "cell_type": "markdown", - "id": "0e74a241", - "metadata": { - "user_expressions": [] - }, + "id": "3c4c533b", + "metadata": {}, "source": [ "It can be shown that for a long series drawn from `P`, the fraction of the\n", "sample that takes value 0 will be about 0.25.\n", @@ -588,20 +547,18 @@ { "cell_type": "code", "execution_count": null, - "id": "0b4c31a1", + "id": "ef15f3cd", "metadata": {}, "outputs": [], "source": [ - "X = mc_sample_path(P, ψ_0=[0.1, 0.9], ts_length=1_000_000)\n", + "X = mc_sample_path(P, ψ_0=(0.1, 0.9), ts_length=1_000_000)\n", "np.mean(X == 0)" ] }, { "cell_type": "markdown", - "id": "49eab3c8", - "metadata": { - "user_expressions": [] - }, + "id": "e4e1ac40", + "metadata": {}, "source": [ "You can try changing the initial distribution to confirm that the output is\n", "always close to 0.25 (for the `P` matrix above).\n", @@ -617,7 +574,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1911badb", + "id": "e5048c9c", "metadata": {}, "outputs": [], "source": [ @@ -628,10 +585,8 @@ }, { "cell_type": "markdown", - "id": "739383cc", - "metadata": { - "user_expressions": [] - }, + "id": "8d612db1", + "metadata": {}, "source": [ "The `simulate` routine is faster (because it is [JIT compiled](https://python-programming.quantecon.org/numba.html#numba-link))." ] @@ -639,7 +594,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4e1e5942", + "id": "bee5809f", "metadata": {}, "outputs": [], "source": [ @@ -649,7 +604,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5b2bdc65", + "id": "c2354379", "metadata": {}, "outputs": [], "source": [ @@ -658,10 +613,8 @@ }, { "cell_type": "markdown", - "id": "ff3650bf", - "metadata": { - "user_expressions": [] - }, + "id": "c4996271", + "metadata": {}, "source": [ "#### Adding state values and initial conditions\n", "\n", @@ -675,28 +628,28 @@ { "cell_type": "code", "execution_count": null, - "id": "eaabcc00", + "id": "adca7b1f", "metadata": {}, "outputs": [], "source": [ "mc = qe.MarkovChain(P, state_values=('unemployed', 'employed'))\n", - "mc.simulate(ts_length=4, init='employed')" + "mc.simulate(ts_length=4, init='employed') # Start at employed initial state" ] }, { "cell_type": "code", "execution_count": null, - "id": "b923aea0", + "id": "4da4b075", "metadata": {}, "outputs": [], "source": [ - "mc.simulate(ts_length=4, init='unemployed')" + "mc.simulate(ts_length=4, init='unemployed') # Start at unemployed initial state" ] }, { "cell_type": "code", "execution_count": null, - "id": "0e340cb3", + "id": "25bfffe3", "metadata": {}, "outputs": [], "source": [ @@ -705,10 +658,8 @@ }, { "cell_type": "markdown", - "id": "3a8ba3bc", - "metadata": { - "user_expressions": [] - }, + "id": "1390283f", + "metadata": {}, "source": [ "If we want to see indices rather than state values as outputs as we can use" ] @@ -716,7 +667,7 @@ { "cell_type": "code", "execution_count": null, - "id": "554e8829", + "id": "5e1b3353", "metadata": {}, "outputs": [], "source": [ @@ -725,10 +676,8 @@ }, { "cell_type": "markdown", - "id": "6015e53b", - "metadata": { - "user_expressions": [] - }, + "id": "1de9e573", + "metadata": {}, "source": [ "(mc_md)=\n", "## Distributions over time\n", @@ -769,7 +718,7 @@ "\n", "There are $n$ such equations, one for each $y \\in S$.\n", "\n", - "If we think of $\\psi_{t+1}$ and $\\psi_t$ as *row vectors*, these $n$ equations are summarized by the matrix expression\n", + "If we think of $\\psi_{t+1}$ and $\\psi_t$ as row vectors, these $n$ equations are summarized by the matrix expression\n", "\n", "```{math}\n", ":label: fin_mc_fr\n", @@ -777,7 +726,7 @@ "\\psi_{t+1} = \\psi_t P\n", "```\n", "\n", - "Thus, to move a distribution forward one unit of time, we postmultiply by $P$.\n", + "Thus, we postmultiply by $P$ to move a distribution forward one unit of time.\n", "\n", "By postmultiplying $m$ times, we move a distribution forward $m$ steps into the future.\n", "\n", @@ -795,7 +744,7 @@ "X_0 \\sim \\psi_0 \\quad \\implies \\quad X_m \\sim \\psi_0 P^m\n", "```\n", "\n", - "The general rule is that post-multiplying a distribution by $P^m$ shifts it forward $m$ units of time.\n", + "The general rule is that postmultiplying a distribution by $P^m$ shifts it forward $m$ units of time.\n", "\n", "Hence the following is also valid.\n", "\n", @@ -803,16 +752,10 @@ ":label: mdfmc2\n", "\n", "X_t \\sim \\psi_t \\quad \\implies \\quad X_{t+m} \\sim \\psi_t P^m\n", - "```" - ] - }, - { - "cell_type": "markdown", - "id": "87891667", - "metadata": { - "user_expressions": [] - }, - "source": [ + "```\n", + "\n", + "\n", + "\n", "(finite_mc_mstp)=\n", "### Multiple step transition probabilities\n", "\n", @@ -847,27 +790,21 @@ "\n", "We guess that the probability that the economy is in state $x$ is $\\psi_t(x)$ at time t.\n", "\n", - "The probability of being in recession (either mild or severe) in 6 months time is given by \n", + "The probability of being in recession (either mild or severe) in 6 months time is given by\n", "\n", "$$\n", "(\\psi_t P^6)(1) + (\\psi_t P^6)(2)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "85b9c422", - "metadata": { - "user_expressions": [] - }, - "source": [ + "$$\n", + "\n", + "\n", + "\n", "(mc_eg1-1)=\n", - "### Example 2: Cross-sectional distributions\n", + "### Example 2: cross-sectional distributions\n", "\n", - "The distributions we have been studying can be viewed either \n", + "The distributions we have been studying can be viewed either\n", "\n", - "1. as probabilities or \n", - "1. as cross-sectional frequencies that a Law of Large Numbers leads us to anticipate for large samples.\n", + "1. as probabilities or\n", + "1. as cross-sectional frequencies that the law of large numbers leads us to anticipate for large samples.\n", "\n", "To illustrate, recall our model of employment/unemployment dynamics for a given worker {ref}`discussed above `.\n", "\n", @@ -878,9 +815,9 @@ "\n", "Let $\\psi_t$ be the current *cross-sectional* distribution over $\\{ 0, 1 \\}$.\n", "\n", - "The cross-sectional distribution records fractions of workers employed and unemployed at a given moment t.\n", + "The cross-sectional distribution records fractions of workers employed and unemployed at a given moment $t$.\n", "\n", - "* For example, $\\psi_t(0)$ is the unemployment rate.\n", + "* For example, $\\psi_t(0)$ is the unemployment rate at time $t$.\n", "\n", "What will the cross-sectional distribution be in 10 periods hence?\n", "\n", @@ -888,11 +825,11 @@ "{eq}`p_unempemp`.\n", "\n", "This is because each worker's state evolves according to $P$, so\n", - "$\\psi_t P^{10}$ is a marginal distribution for a single randomly selected\n", + "$\\psi_t P^{10}$ is a [marginal distribution](https://en.wikipedia.org/wiki/Marginal_distribution) for a single randomly selected\n", "worker.\n", "\n", - "But when the sample is large, outcomes and probabilities are roughly equal (by an application of the Law\n", - "of Large Numbers).\n", + "But when the sample is large, outcomes and probabilities are roughly equal (by an application of the law\n", + "of large numbers).\n", "\n", "So for a very large (tending to infinite) population,\n", "$\\psi_t P^{10}$ also represents fractions of workers in\n", @@ -913,7 +850,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9b7aa412", + "id": "15bbbd78", "metadata": {}, "outputs": [], "source": [ @@ -925,31 +862,23 @@ }, { "cell_type": "markdown", - "id": "87a674e7", - "metadata": { - "user_expressions": [] - }, - "source": [ - "Notice that `ψ @ P` is the same as `ψ`" - ] - }, - { - "cell_type": "markdown", - "id": "06789d56", - "metadata": { - "user_expressions": [] - }, + "id": "85058363", + "metadata": {}, "source": [ + "Notice that `ψ @ P` is the same as `ψ`.\n", + "\n", + "\n", + "\n", "Such distributions are called **stationary** or **invariant**.\n", "\n", "(mc_stat_dd)=\n", "Formally, a distribution $\\psi^*$ on $S$ is called **stationary** for $P$ if $\\psi^* P = \\psi^* $.\n", "\n", - "Notice that, post-multiplying by $P$, we have $\\psi^* P^2 = \\psi^* P = \\psi^*$.\n", + "Notice that, postmultiplying by $P$, we have $\\psi^* P^2 = \\psi^* P = \\psi^*$.\n", "\n", - "Continuing in the same way leads to $\\psi^* = \\psi^* P^t$ for all $t$.\n", + "Continuing in the same way leads to $\\psi^* = \\psi^* P^t$ for all $t \\ge 0$.\n", "\n", - "This tells us an important fact: If the distribution of $\\psi_0$ is a stationary distribution, then $\\psi_t$ will have this same distribution for all $t$.\n", + "This tells us an important fact: If the distribution of $\\psi_0$ is a stationary distribution, then $\\psi_t$ will have this same distribution for all $t \\ge 0$.\n", "\n", "The following theorem is proved in Chapter 4 of {cite}`sargent2023economic` and numerous other sources.\n", "\n", @@ -977,16 +906,10 @@ "distribution.\n", "```\n", "\n", - "We will come back to this when we introduce irreducibility in the next lecture" - ] - }, - { - "cell_type": "markdown", - "id": "0662b717", - "metadata": { - "user_expressions": [] - }, - "source": [ + "We will come back to this when we introduce irreducibility in the {doc}`next lecture ` on Markov chains.\n", + "\n", + "\n", + "\n", "### Example\n", "\n", "Recall our model of the employment/unemployment dynamics of a particular worker {ref}`discussed above `.\n", @@ -1006,6 +929,11 @@ "\n", "Not surprisingly it tends to zero as $\\beta \\to 0$, and to one as $\\alpha \\to 0$.\n", "\n", + "\n", + "\n", + "\n", + "\n", + "\n", "### Calculating stationary distributions\n", "\n", "A stable algorithm for computing stationary distributions is implemented in [QuantEcon.py](http://quantecon.org/quantecon-py).\n", @@ -1016,7 +944,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3d43b273", + "id": "523d63eb", "metadata": {}, "outputs": [], "source": [ @@ -1029,7 +957,7 @@ }, { "cell_type": "markdown", - "id": "31bbf646", + "id": "133d78f0", "metadata": {}, "source": [ "### Asymptotic stationarity\n", @@ -1042,26 +970,27 @@ "\n", "(strict_stationary)=\n", "```{prf:theorem}\n", - "Theorem: If there exists an integer $m$ such that all entries of $P^m$ are\n", - "strictly positive, with unique stationary distribution $\\psi^*$, and\n", + ":label: mc_gs_thm\n", + "\n", + "If there exists an integer $m$ such that all entries of $P^m$ are\n", + "strictly positive, then\n", "\n", "$$\n", - " \\psi_0 P^t \\to \\psi\n", - " \\quad \\text{as } t \\to \\infty\n", + " \\psi_0 P^t \\to \\psi^*\n", + " \\quad \\text{ as } t \\to \\infty\n", "$$\n", + "\n", + "where $\\psi^*$ is the unique stationary distribution.\n", "```\n", "\n", + "This situation is often referred to as **asymptotic stationarity** or **global stability**.\n", + "\n", + "A proof of the theorem can be found in Chapter 4 of {cite}`sargent2023economic`, as well as many other sources.\n", + "\n", + "\n", + "\n", + "\n", "\n", - "See, for example, {cite}`sargent2023economic` Chapter 4." - ] - }, - { - "cell_type": "markdown", - "id": "ee419c4a", - "metadata": { - "user_expressions": [] - }, - "source": [ "(hamilton)=\n", "#### Example: Hamilton's chain\n", "\n", @@ -1071,7 +1000,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e6645913", + "id": "0f73c9ab", "metadata": {}, "outputs": [], "source": [ @@ -1083,12 +1012,10 @@ }, { "cell_type": "markdown", - "id": "06380d0a", - "metadata": { - "user_expressions": [] - }, + "id": "fa1c6e15", + "metadata": {}, "source": [ - "Let's pick an initial distribution $\\psi_0$ and trace out the sequence of distributions $\\psi_0 P^t$ for $t = 0, 1, 2, \\ldots$\n", + "Let's pick an initial distribution $\\psi_1, \\psi_2, \\psi_3$ and trace out the sequence of distributions $\\psi_i P^t$ for $t = 0, 1, 2, \\ldots$, for $i=1, 2, 3$.\n", "\n", "First, we write a function to iterate the sequence of distributions for `ts_length` period" ] @@ -1096,23 +1023,22 @@ { "cell_type": "code", "execution_count": null, - "id": "89ad46a2", + "id": "fa360cc3", "metadata": {}, "outputs": [], "source": [ "def iterate_ψ(ψ_0, P, ts_length):\n", " n = len(P)\n", " ψ_t = np.empty((ts_length, n))\n", - " ψ = ψ_0\n", - " for t in range(ts_length):\n", - " ψ_t[t] = ψ\n", - " ψ = ψ @ P\n", - " return np.array(ψ_t)" + " ψ_t[0 ]= ψ_0\n", + " for t in range(1, ts_length):\n", + " ψ_t[t] = ψ_t[t-1] @ P\n", + " return ψ_t" ] }, { "cell_type": "markdown", - "id": "b0e4be1f", + "id": "c76470e0", "metadata": {}, "source": [ "Now we plot the sequence" @@ -1121,195 +1047,184 @@ { "cell_type": "code", "execution_count": null, - "id": "8e337a2c", - "metadata": {}, + "id": "b4715060", + "metadata": { + "tags": [ + "hide-input" + ] + }, "outputs": [], "source": [ - "ψ_0 = (0.0, 0.2, 0.8) # Initial condition\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111, projection='3d')\n", + "ψ_1 = (0.0, 0.0, 1.0)\n", + "ψ_2 = (1.0, 0.0, 0.0)\n", + "ψ_3 = (0.0, 1.0, 0.0) # Three initial conditions\n", + "colors = ['blue','red', 'green'] # Different colors for each initial point\n", "\n", - "ax.set(xlim=(0, 1), ylim=(0, 1), zlim=(0, 1),\n", - " xticks=(0.25, 0.5, 0.75),\n", - " yticks=(0.25, 0.5, 0.75),\n", - " zticks=(0.25, 0.5, 0.75))\n", + "# Define the vertices of the unit simplex\n", + "v = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]])\n", "\n", - "ψ_t = iterate_ψ(ψ_0, P, 20)\n", + "# Define the faces of the unit simplex\n", + "faces = [\n", + " [v[0], v[1], v[2]],\n", + " [v[0], v[1], v[3]],\n", + " [v[0], v[2], v[3]],\n", + " [v[1], v[2], v[3]]\n", + "]\n", "\n", - "ax.scatter(ψ_t[:,0], ψ_t[:,1], ψ_t[:,2], c='r', s=60)\n", - "ax.view_init(30, 210)\n", - "\n", - "mc = qe.MarkovChain(P)\n", - "ψ_star = mc.stationary_distributions[0]\n", - "ax.scatter(ψ_star[0], ψ_star[1], ψ_star[2], c='k', s=60)\n", + "fig = plt.figure()\n", + "ax = fig.add_subplot(projection='3d')\n", + "\n", + "def update(n): \n", + " ax.clear()\n", + " ax.set_xlim([0, 1])\n", + " ax.set_ylim([0, 1])\n", + " ax.set_zlim([0, 1])\n", + " ax.view_init(45, 45)\n", + " \n", + " simplex = Poly3DCollection(faces, alpha=0.03)\n", + " ax.add_collection3d(simplex)\n", + " \n", + " for idx, ψ_0 in enumerate([ψ_1, ψ_2, ψ_3]):\n", + " ψ_t = iterate_ψ(ψ_0, P, n+1)\n", + " \n", + " for i, point in enumerate(ψ_t):\n", + " ax.scatter(point[0], point[1], point[2], color=colors[idx], s=60, alpha=(i+1)/len(ψ_t))\n", + " \n", + " mc = qe.MarkovChain(P)\n", + " ψ_star = mc.stationary_distributions[0]\n", + " ax.scatter(ψ_star[0], ψ_star[1], ψ_star[2], c='yellow', s=60)\n", + " \n", + " return fig,\n", "\n", - "plt.show()" + "anim = FuncAnimation(fig, update, frames=range(20), blit=False, repeat=False)\n", + "plt.close()\n", + "HTML(anim.to_jshtml())" ] }, { "cell_type": "markdown", - "id": "c20e4549", - "metadata": { - "tags": [], - "user_expressions": [] - }, + "id": "3e628702", + "metadata": {}, "source": [ "Here\n", "\n", "* $P$ is the stochastic matrix for recession and growth {ref}`considered above `.\n", - "* The highest red dot is an arbitrarily chosen initial marginal probability distribution $\\psi_0$, represented as a vector in $\\mathbb R^3$.\n", - "* The other red dots are the marginal distributions $\\psi_0 P^t$ for $t = 1, 2, \\ldots$.\n", - "* The black dot is $\\psi^*$.\n", + "* The red, blue and green dots are initial marginal probability distributions $\\psi_1, \\psi_2, \\psi_3$, each of which is represented as a vector in $\\mathbb R^3$.\n", + "* The transparent dots are the marginal distributions $\\psi_i P^t$ for $t = 1, 2, \\ldots$, for $i=1,2,3.$.\n", + "* The yellow dot is $\\psi^*$.\n", "\n", "You might like to try experimenting with different initial conditions.\n", "\n", "\n", - "#### An alternative illustration\n", "\n", - "We can show this in a slightly different way by focusing on the probability that $\\psi_t$ puts on each state.\n", "\n", - "First, we write a function to draw initial distributions $\\psi_0$ of size `num_distributions`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e5029804", - "metadata": {}, - "outputs": [], - "source": [ - "def generate_initial_values(num_distributions):\n", - " n = len(P)\n", - " ψ_0s = np.empty((num_distributions, n))\n", - " \n", - " for i in range(num_distributions):\n", - " draws = np.random.randint(1, 10_000_000, size=n)\n", + "#### Example: failure of convergence\n", "\n", - " # Scale them so that they add up into 1\n", - " ψ_0s[i,:] = np.array(draws/sum(draws))\n", - " \n", - " return ψ_0s" - ] - }, - { - "cell_type": "markdown", - "id": "3038d624", - "metadata": {}, - "source": [ - "We then write a function to plot the dynamics of $(\\psi_0 P^t)(i)$ as $t$ gets large, for each state $i$ with different initial distributions" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d8af1786", - "metadata": {}, - "outputs": [], - "source": [ - "def plot_distribution(P, ts_length, num_distributions):\n", "\n", - " # Get parameters of transition matrix\n", - " n = len(P)\n", - " mc = qe.MarkovChain(P)\n", - " ψ_star = mc.stationary_distributions[0]\n", + "Consider the periodic chain with stochastic matrix\n", + "\n", + "$$\n", + "P = \n", + "\\begin{bmatrix}\n", + " 0 & 1 \\\\\n", + " 1 & 0 \\\\\n", + "\\end{bmatrix}\n", + "$$\n", "\n", - " ## Draw the plot\n", - " fig, axes = plt.subplots(nrows=1, ncols=n, figsize=[11, 5])\n", - " plt.subplots_adjust(wspace=0.35)\n", + "This matrix does not satisfy the conditions of \n", + "{ref}`strict_stationary` because, as you can readily check, \n", "\n", - " ψ_0s = generate_initial_values(num_distributions)\n", + "* $P^m = P$ when $m$ is odd and \n", + "* $P^m = I$, the identity matrix, when $m$ is even.\n", "\n", - " # Get the path for each starting value\n", - " for ψ_0 in ψ_0s:\n", - " ψ_t = iterate_ψ(ψ_0, P, ts_length)\n", - " \n", - " # Obtain and plot distributions at each state\n", - " for i in range(n):\n", - " axes[i].plot(range(0, ts_length), ψ_t[:,i], alpha=0.3)\n", + "Hence there is no $m$ such that all elements of $P^m$ are strictly positive.\n", "\n", - " # Add labels\n", - " for i in range(n):\n", - " axes[i].axhline(ψ_star[i], linestyle='dashed', lw=2, color = 'black', \n", - " label = fr'$\\psi^*({i})$')\n", - " axes[i].set_xlabel('t')\n", - " axes[i].set_ylabel(fr'$\\psi_t({i})$')\n", - " axes[i].legend()\n", + "Moreover, we can see that global stability does not hold.\n", "\n", - " plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "98e5aabc", - "metadata": {}, - "source": [ - "The following figure shows" + "For instance, if we start at $\\psi_0 = (1,0)$, then $\\psi_m = \\psi_0 P^m$ is $(1, 0)$ when $m$ is even and $(0,1)$ when $m$ is odd.\n", + "\n", + "We can see similar phenomena in higher dimensions.\n", + "\n", + "The next figure illustrates this for a periodic Markov chain with three states." ] }, { "cell_type": "code", "execution_count": null, - "id": "e20fb14b", - "metadata": {}, + "id": "1f296518", + "metadata": { + "tags": [ + "hide-input" + ] + }, "outputs": [], "source": [ - "# Define the number of iterations \n", - "# and initial distributions\n", - "ts_length = 50\n", - "num_distributions = 25\n", + "ψ_1 = (0.0, 0.0, 1.0)\n", + "ψ_2 = (0.5, 0.5, 0.0)\n", + "ψ_3 = (0.25, 0.25, 0.5)\n", + "ψ_4 = (1/3, 1/3, 1/3)\n", "\n", - "P = np.array([[0.971, 0.029, 0.000],\n", - " [0.145, 0.778, 0.077],\n", - " [0.000, 0.508, 0.492]])\n", + "P = np.array([[0.0, 1.0, 0.0],\n", + " [0.0, 0.0, 1.0],\n", + " [1.0, 0.0, 0.0]])\n", "\n", - "plot_distribution(P, ts_length, num_distributions)" + "fig = plt.figure()\n", + "ax = fig.add_subplot(projection='3d')\n", + "colors = ['red','yellow', 'green', 'blue'] # Different colors for each initial point\n", + "\n", + "# Define the vertices of the unit simplex\n", + "v = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]])\n", + "\n", + "# Define the faces of the unit simplex\n", + "faces = [\n", + " [v[0], v[1], v[2]],\n", + " [v[0], v[1], v[3]],\n", + " [v[0], v[2], v[3]],\n", + " [v[1], v[2], v[3]]\n", + "]\n", + "\n", + "def update(n):\n", + " ax.clear()\n", + " ax.set_xlim([0, 1])\n", + " ax.set_ylim([0, 1])\n", + " ax.set_zlim([0, 1])\n", + " ax.view_init(45, 45)\n", + " \n", + " # Plot the 3D unit simplex as planes\n", + " simplex = Poly3DCollection(faces,alpha=0.05)\n", + " ax.add_collection3d(simplex)\n", + " \n", + " for idx, ψ_0 in enumerate([ψ_1, ψ_2, ψ_3, ψ_4]):\n", + " ψ_t = iterate_ψ(ψ_0, P, n+1)\n", + " \n", + " point = ψ_t[-1]\n", + " ax.scatter(point[0], point[1], point[2], color=colors[idx], s=60)\n", + " points = np.array(ψ_t)\n", + " ax.plot(points[:, 0], points[:, 1], points[:, 2], color=colors[idx],linewidth=0.75)\n", + " \n", + " return fig,\n", + "\n", + "anim = FuncAnimation(fig, update, frames=range(20), blit=False, repeat=False)\n", + "plt.close()\n", + "HTML(anim.to_jshtml())" ] }, { "cell_type": "markdown", - "id": "4d44091a", + "id": "75351c19", "metadata": {}, "source": [ - "The convergence to $\\psi^*$ holds for different initial distributions." - ] - }, - { - "cell_type": "markdown", - "id": "ca1ca1a6", - "metadata": { - "user_expressions": [] - }, - "source": [ - "#### Example: Failure of convergence\n", + "This animation demonstrates the behavior of an irreducible and periodic stochastic matrix.\n", "\n", + "The red, yellow, and green dots represent different initial probability distributions.\n", "\n", - "In the case of our periodic chain, we find the distribution is oscillating" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0270c743", - "metadata": {}, - "outputs": [], - "source": [ - "P = np.array([[0, 1],\n", - " [1, 0]])\n", + "The blue dot represents the unique stationary distribution.\n", + "\n", + "Unlike Hamilton’s Markov chain, these initial distributions do not converge to the unique stationary distribution.\n", + "\n", + "Instead, they cycle periodically around the probability simplex, illustrating that asymptotic stability fails.\n", "\n", - "ts_length = 20\n", - "num_distributions = 30\n", "\n", - "plot_distribution(P, ts_length, num_distributions)" - ] - }, - { - "cell_type": "markdown", - "id": "e84635ae", - "metadata": { - "user_expressions": [] - }, - "source": [ "(finite_mc_expec)=\n", "## Computing expectations\n", "\n", @@ -1339,8 +1254,8 @@ " algebra, we'll think of as the column vector\n", "\n", "$$\n", - "h = \n", - "\\begin{bmatrix} \n", + "h =\n", + "\\begin{bmatrix}\n", " h(x_1) \\\\\n", " \\vdots \\\\\n", " h(x_n)\n", @@ -1387,15 +1302,15 @@ "In view of the preceding discussion, this is\n", "\n", "$$\n", - "\\mathbb{E} \n", + "\\mathbb{E}\n", " \\left[\n", - " \\sum_{j=0}^\\infty \\beta^j h(X_{t+j}) \\mid X_t \n", + " \\sum_{j=0}^\\infty \\beta^j h(X_{t+j}) \\mid X_t\n", " = x\n", " \\right]\n", " = x + \\beta (Ph)(x) + \\beta^2 (P^2 h)(x) + \\cdots\n", "$$\n", "\n", - "By the {ref}`Neumann series lemma `, this sum can be calculated using \n", + "By the {ref}`Neumann series lemma `, this sum can be calculated using\n", "\n", "$$\n", " I + \\beta P + \\beta^2 P^2 + \\cdots = (I - \\beta P)^{-1}\n", @@ -1411,11 +1326,11 @@ "\n", "$$\n", "P :=\n", - "\\begin{bmatrix} \n", + "\\begin{bmatrix}\n", " 0.68 & 0.12 & 0.20 \\\\\n", " 0.50 & 0.24 & 0.26 \\\\\n", " 0.36 & 0.18 & 0.46\n", - "\\end{bmatrix} \n", + "\\end{bmatrix}\n", "$$\n", "\n", "where rows, from top to down, correspond to growth, stagnation, and collapse.\n", @@ -1433,47 +1348,15 @@ ":class: dropdown\n", "```\n", "\n", - "Solution 1:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3e84a69e", - "metadata": { - "tags": [ - "hide-output" - ] - }, - "outputs": [], - "source": [ - "dot = Digraph(comment='Graph')\n", - "dot.attr(rankdir='LR')\n", - "dot.node(\"Growth\")\n", - "dot.node(\"Stagnation\")\n", - "dot.node(\"Collapse\")\n", - "\n", - "dot.edge(\"Growth\", \"Growth\", label=\"0.68\")\n", - "dot.edge(\"Growth\", \"Stagnation\", label=\"0.12\")\n", - "dot.edge(\"Growth\", \"Collapse\", label=\"0.20\")\n", + "Solution 1:\n", "\n", - "dot.edge(\"Stagnation\", \"Stagnation\", label=\"0.24\")\n", - "dot.edge(\"Stagnation\", \"Growth\", label=\"0.50\")\n", - "dot.edge(\"Stagnation\", \"Collapse\", label=\"0.26\")\n", + "```{image} /_static/lecture_specific/markov_chains_I/Temple.png\n", + ":name: mc_temple\n", + ":align: center\n", "\n", - "dot.edge(\"Collapse\", \"Collapse\", label=\"0.46\")\n", - "dot.edge(\"Collapse\", \"Stagnation\", label=\"0.18\")\n", - "dot.edge(\"Collapse\", \"Growth\", label=\"0.36\")\n", + "```\n", "\n", - "dot" - ] - }, - { - "cell_type": "markdown", - "id": "e10d3e9a", - "metadata": {}, - "source": [ - "Since the matrix is everywhere positive, there is a unique stationary distribution.\n", + "Since the matrix is everywhere positive, there is a unique stationary distribution $\\psi^*$ such that $\\psi_t\\to \\psi^*$ as $t\\to \\infty$.\n", "\n", "Solution 2:\n", "\n", @@ -1483,7 +1366,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c5b26947", + "id": "30958498", "metadata": {}, "outputs": [], "source": [ @@ -1496,7 +1379,7 @@ }, { "cell_type": "markdown", - "id": "420c1241", + "id": "df200bab", "metadata": {}, "source": [ "Note that rows of the transition matrix converge to the stationary distribution." @@ -1505,7 +1388,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6dd65169", + "id": "782516ff", "metadata": {}, "outputs": [], "source": [ @@ -1516,7 +1399,7 @@ { "cell_type": "code", "execution_count": null, - "id": "2f1b01d8", + "id": "1d5e4bc5", "metadata": {}, "outputs": [], "source": [ @@ -1527,88 +1410,9 @@ }, { "cell_type": "markdown", - "id": "64c63323", - "metadata": {}, - "source": [ - "Solution 3:\n", - "\n", - "We find the distribution $\\psi$ converges to the stationary distribution more quickly compared to the {ref}`hamilton's chain `." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "dc554fa0", - "metadata": {}, - "outputs": [], - "source": [ - "ts_length = 10\n", - "num_distributions = 25\n", - "plot_distribution(P, ts_length, num_distributions)" - ] - }, - { - "cell_type": "markdown", - "id": "25bdca90", - "metadata": {}, - "source": [ - "In fact, the rate of convergence is governed by {ref}`eigenvalues` {cite}`sargent2023economic`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2468c56a", - "metadata": {}, - "outputs": [], - "source": [ - "P_eigenvals = np.linalg.eigvals(P)\n", - "P_eigenvals" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fea0d320", + "id": "d922e9c1", "metadata": {}, - "outputs": [], "source": [ - "P_hamilton = np.array([[0.971, 0.029, 0.000],\n", - " [0.145, 0.778, 0.077],\n", - " [0.000, 0.508, 0.492]])\n", - "\n", - "hamilton_eigenvals = np.linalg.eigvals(P_hamilton)\n", - "hamilton_eigenvals" - ] - }, - { - "cell_type": "markdown", - "id": "a4387067", - "metadata": {}, - "source": [ - "More specifically, it is governed by the spectral gap, the difference between the largest and the second largest eigenvalue." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9d3670f3", - "metadata": {}, - "outputs": [], - "source": [ - "sp_gap_P = P_eigenvals[0] - np.diff(P_eigenvals)[0]\n", - "sp_gap_hamilton = hamilton_eigenvals[0] - np.diff(hamilton_eigenvals)[0]\n", - "\n", - "sp_gap_P > sp_gap_hamilton" - ] - }, - { - "cell_type": "markdown", - "id": "0f487393", - "metadata": {}, - "source": [ - "We will come back to this when we discuss {ref}`spectral theory`.\n", - "\n", "```{solution-end}\n", "```\n", "\n", @@ -1646,7 +1450,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6423da11", + "id": "d970e677", "metadata": {}, "outputs": [], "source": [ @@ -1662,7 +1466,7 @@ }, { "cell_type": "markdown", - "id": "785bf8e8", + "id": "ac9c7363", "metadata": {}, "source": [ "So it satisfies the requirement.\n", @@ -1675,7 +1479,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f6ee8813", + "id": "98288398", "metadata": {}, "outputs": [], "source": [ @@ -1707,7 +1511,7 @@ }, { "cell_type": "markdown", - "id": "b2449b2a", + "id": "2269e534", "metadata": {}, "source": [ "```{solution-end}\n", @@ -1748,12 +1552,73 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.4" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 12, + 22, + 26, + 54, + 66, + 249, + 257, + 261, + 288, + 393, + 397, + 405, + 427, + 431, + 434, + 438, + 440, + 452, + 455, + 467, + 471, + 475, + 479, + 481, + 491, + 496, + 500, + 502, + 506, + 508, + 677, + 682, + 759, + 765, + 808, + 813, + 819, + 827, + 831, + 878, + 921, + 972, + 1121, + 1127, + 1131, + 1136, + 1140, + 1176, + 1185, + 1193, + 1218 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/markov_chains_I.md b/book/_build/html/_sources/markov_chains_I.md new file mode 100644 index 0000000..5bd603e --- /dev/null +++ b/book/_build/html/_sources/markov_chains_I.md @@ -0,0 +1,1253 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.4 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Markov Chains: Basic Concepts + + +```{index} single: Markov Chains: Basic Concepts and Stationarity +``` + +In addition to what's in Anaconda, this lecture will need the following libraries: + +```{code-cell} ipython3 +:tags: [hide-output] + +%pip install quantecon +``` + +## Overview + +Markov chains provide a way to model situations in which the past casts shadows on the future. + +By this we mean that observing measurements about a present situation can help us forecast future situations. + +This can be possible when there are statistical dependencies among measurements of something taken at different points of time. + +For example, + +* inflation next year might co-vary with inflation this year +* unemployment next month might co-vary with unemployment this month + + +Markov chains are a workhorse for economics and finance. + +The theory of Markov chains is beautiful and provides many insights into +probability and dynamics. + +In this lecture, we will + +* review some of the key ideas from the theory of Markov chains and +* show how Markov chains appear in some economic applications. + +Let's start with some standard imports: + +```{code-cell} ipython3 +import matplotlib.pyplot as plt +import quantecon as qe +import numpy as np +import networkx as nx +from matplotlib import cm +import matplotlib as mpl +from mpl_toolkits.mplot3d import Axes3D +from matplotlib.animation import FuncAnimation +from IPython.display import HTML +from matplotlib.patches import Polygon +from mpl_toolkits.mplot3d.art3d import Poly3DCollection +``` + +## Definitions and examples + +In this section we provide some definitions and elementary examples. + +(finite_dp_stoch_mat)= +### Stochastic matrices + +Recall that a **probability mass function** over $n$ possible outcomes is a +nonnegative $n$-vector $p$ that sums to one. + +For example, $p = (0.2, 0.2, 0.6)$ is a probability mass function over $3$ outcomes. + +A **stochastic matrix** (or **Markov matrix**) is an $n \times n$ square matrix $P$ +such that each row of $P$ is a probability mass function over $n$ outcomes. + +In other words, + +1. each element of $P$ is nonnegative, and +1. each row of $P$ sums to one + +If $P$ is a stochastic matrix, then so is the $k$-th power $P^k$ for all $k \in \mathbb N$. + +You are asked to check this in {ref}`an exercise ` below. + + +### Markov chains + +Now we can introduce Markov chains. + +Before defining a Markov chain rigorously, we'll give some examples. + + +(mc_eg2)= +#### Example 1 + +From US unemployment data, Hamilton {cite}`Hamilton2005` estimated the following dynamics. + +```{image} /_static/lecture_specific/markov_chains_I/Hamilton.png +:name: mc_hamilton +:align: center + +``` + +Here there are three **states** + +* "ng" represents normal growth +* "mr" represents mild recession +* "sr" represents severe recession + +The arrows represent transition probabilities over one month. + +For example, the arrow from mild recession to normal growth has 0.145 next to it. + +This tells us that, according to past data, there is a 14.5% probability of transitioning from mild recession to normal growth in one month. + +The arrow from normal growth back to normal growth tells us that there is a +97% probability of transitioning from normal growth to normal growth (staying +in the same state). + +Note that these are conditional probabilities --- the probability of +transitioning from one state to another (or staying at the same one) conditional on the +current state. + +To make the problem easier to work with numerically, let's convert states to +numbers. + +In particular, we agree that + +* state 0 represents normal growth +* state 1 represents mild recession +* state 2 represents severe recession + +Let $X_t$ record the value of the state at time $t$. + +Now we can write the statement "there is a 14.5% probability of transitioning from mild recession to normal growth in one month" as + +$$ + \mathbb P\{X_{t+1} = 0 \,|\, X_t = 1\} = 0.145 +$$ + +We can collect all of these conditional probabilities into a matrix, as follows + +$$ +P = +\begin{bmatrix} +0.971 & 0.029 & 0 \\ +0.145 & 0.778 & 0.077 \\ +0 & 0.508 & 0.492 +\end{bmatrix} +$$ + +Notice that $P$ is a stochastic matrix. + +Now we have the following relationship + +$$ + P(i,j) + = \mathbb P\{X_{t+1} = j \,|\, X_t = i\} +$$ + +This holds for any $i,j$ between 0 and 2. + +In particular, $P(i,j)$ is the + probability of transitioning from state $i$ to state $j$ in one month. + + + + +(mc_eg1)= +#### Example 2 + +Consider a worker who, at any given time $t$, is either unemployed (state 0) +or employed (state 1). + +Suppose that, over a one-month period, + +1. the unemployed worker finds a job with probability $\alpha \in (0, 1)$. +1. the employed worker loses her job and becomes unemployed with probability $\beta \in (0, 1)$. + +Given the above information, we can write out the transition probabilities in matrix form as + +```{math} +:label: p_unempemp + +P = +\begin{bmatrix} + 1 - \alpha & \alpha \\ + \beta & 1 - \beta +\end{bmatrix} +``` + +For example, + +$$ +\begin{aligned} + P(0,1) + & = + \text{ probability of transitioning from state $0$ to state $1$ in one month} + \\ + & = + \text{ probability finding a job next month} + \\ + & = \alpha +\end{aligned} +$$ + +Suppose we can estimate the values $\alpha$ and $\beta$. + +Then we can address a range of questions, such as + +* What is the average duration of unemployment? +* Over the long-run, what fraction of the time does a worker find herself unemployed? +* Conditional on employment, what is the probability of becoming unemployed at least once over the next 12 months? + +We'll cover some of these applications below. + +(mc_eg3)= +#### Example 3 + +Imam and Temple {cite}`imampolitical` categorize political institutions into +three types: democracy $\text{(D)}$, autocracy $\text{(A)}$, and an intermediate +state called anocracy $\text{(N)}$. + +Each institution can have two potential development regimes: collapse $\text{(C)}$ and growth $\text{(G)}$. This results in six possible states: $\text{DG, DC, NG, NC, AG}$ and $\text{AC}$. + +Imam and Temple {cite}`imampolitical` estimate the following transition +probabilities: + + +$$ +P := +\begin{bmatrix} +0.86 & 0.11 & 0.03 & 0.00 & 0.00 & 0.00 \\ +0.52 & 0.33 & 0.13 & 0.02 & 0.00 & 0.00 \\ +0.12 & 0.03 & 0.70 & 0.11 & 0.03 & 0.01 \\ +0.13 & 0.02 & 0.35 & 0.36 & 0.10 & 0.04 \\ +0.00 & 0.00 & 0.09 & 0.11 & 0.55 & 0.25 \\ +0.00 & 0.00 & 0.09 & 0.15 & 0.26 & 0.50 +\end{bmatrix} +$$ + +```{code-cell} ipython3 +nodes = ['DG', 'DC', 'NG', 'NC', 'AG', 'AC'] +P = [[0.86, 0.11, 0.03, 0.00, 0.00, 0.00], + [0.52, 0.33, 0.13, 0.02, 0.00, 0.00], + [0.12, 0.03, 0.70, 0.11, 0.03, 0.01], + [0.13, 0.02, 0.35, 0.36, 0.10, 0.04], + [0.00, 0.00, 0.09, 0.11, 0.55, 0.25], + [0.00, 0.00, 0.09, 0.15, 0.26, 0.50]] +``` + +Here is a visualization, with darker colors indicating higher probability. + +```{code-cell} ipython3 +:tags: [hide-input] + +G = nx.MultiDiGraph() + +for start_idx, node_start in enumerate(nodes): + for end_idx, node_end in enumerate(nodes): + value = P[start_idx][end_idx] + if value != 0: + G.add_edge(node_start,node_end, weight=value) + +pos = nx.spring_layout(G, seed=10) +fig, ax = plt.subplots() +nx.draw_networkx_nodes(G, pos, node_size=600, edgecolors='black', node_color='white') +nx.draw_networkx_labels(G, pos) + +arc_rad = 0.2 + +edges = nx.draw_networkx_edges(G, pos, ax=ax, connectionstyle=f'arc3, rad = {arc_rad}', edge_cmap=cm.Blues, width=2, + edge_color=[G[nodes[0]][nodes[1]][0]['weight'] for nodes in G.edges]) + +pc = mpl.collections.PatchCollection(edges, cmap=cm.Blues) + +ax = plt.gca() +ax.set_axis_off() +plt.colorbar(pc, ax=ax) +plt.show() +``` + +Looking at the data, we see that democracies tend to have longer-lasting growth +regimes compared to autocracies (as indicated by the lower probability of +transitioning from growth to growth in autocracies). + +We can also find a higher probability from collapse to growth in democratic regimes. + + +### Defining Markov chains + + +So far we've given examples of Markov chains but we haven't defined them. + +Let's do that now. + +To begin, let $S$ be a finite set $\{x_1, \ldots, x_n\}$ with $n$ elements. + +The set $S$ is called the **state space** and $x_1, \ldots, x_n$ are the **state values**. + +A **distribution** $\psi$ on $S$ is a probability mass function of length $n$, where $\psi(i)$ is the amount of probability allocated to state $x_i$. + +A **Markov chain** $\{X_t\}$ on $S$ is a sequence of random variables taking values in $S$ +that have the **Markov property**. + +This means that, for any date $t$ and any state $y \in S$, + +```{math} +:label: fin_markov_mp + +\mathbb P \{ X_{t+1} = y \,|\, X_t \} += \mathbb P \{ X_{t+1} = y \,|\, X_t, X_{t-1}, \ldots \} +``` + +This means that once we know the current state $X_t$, adding knowledge of earlier states $X_{t-1}, X_{t-2}$ provides no additional information about probabilities of *future* states. + +Thus, the dynamics of a Markov chain are fully determined by the set of **conditional probabilities** + +```{math} +:label: mpp + +P(x, y) := \mathbb P \{ X_{t+1} = y \,|\, X_t = x \} +\qquad (x, y \in S) +``` + +By construction, + +* $P(x, y)$ is the probability of going from $x$ to $y$ in one unit of time (one step) +* $P(x, \cdot)$ is the conditional distribution of $X_{t+1}$ given $X_t = x$ + +We can view $P$ as a stochastic matrix where + +$$ + P_{ij} = P(x_i, x_j) + \qquad 1 \leq i, j \leq n +$$ + +Going the other way, if we take a stochastic matrix $P$, we can generate a Markov +chain $\{X_t\}$ as follows: + +* draw $X_0$ from a distribution $\psi_0$ on $S$ +* for each $t = 0, 1, \ldots$, draw $X_{t+1}$ from $P(X_t,\cdot)$ + +By construction, the resulting process satisfies {eq}`mpp`. + + + + +## Simulation + +```{index} single: Markov Chains; Simulation +``` + +A good way to study Markov chains is to simulate them. + +Let's start by doing this ourselves and then look at libraries that can help +us. + +In these exercises, we'll take the state space to be $S = 0,\ldots, n-1$. + +(We start at $0$ because Python arrays are indexed from $0$.) + + +### Writing our own simulation code + +To simulate a Markov chain, we need + +1. a stochastic matrix $P$ and +1. a probability mass function $\psi_0$ of length $n$ from which to draw an initial realization of $X_0$. + +The Markov chain is then constructed as follows: + +1. At time $t=0$, draw a realization of $X_0$ from the distribution $\psi_0$. +1. At each subsequent time $t$, draw a realization of the new state $X_{t+1}$ from $P(X_t, \cdot)$. + +(That is, draw from row $X_t$ of $P$.) + +To implement this simulation procedure, we need a method for generating draws +from a discrete distribution. + +For this task, we'll use `random.draw` from [QuantEcon.py](http://quantecon.org/quantecon-py). + +To use `random.draw`, we first need to convert the probability mass function +to a cumulative distribution + +```{code-cell} ipython3 +ψ_0 = (0.3, 0.7) # probabilities over {0, 1} +cdf = np.cumsum(ψ_0) # convert into cumulative distribution +qe.random.draw(cdf, 5) # generate 5 independent draws from ψ +``` + +We'll write our code as a function that accepts the following three arguments + +* A stochastic matrix `P`. +* An initial distribution `ψ_0`. +* A positive integer `ts_length` representing the length of the time series the function should return. + +```{code-cell} ipython3 +def mc_sample_path(P, ψ_0=None, ts_length=1_000): + + # set up + P = np.asarray(P) + X = np.empty(ts_length, dtype=int) + + # Convert each row of P into a cdf + P_dist = np.cumsum(P, axis=1) # Convert rows into cdfs + + # draw initial state, defaulting to 0 + if ψ_0 is not None: + X_0 = qe.random.draw(np.cumsum(ψ_0)) + else: + X_0 = 0 + + # simulate + X[0] = X_0 + for t in range(ts_length - 1): + X[t+1] = qe.random.draw(P_dist[X[t], :]) + + return X +``` + +Let's see how it works using the small matrix + +```{code-cell} ipython3 +P = [[0.4, 0.6], + [0.2, 0.8]] +``` + +Here's a short time series. + +```{code-cell} ipython3 +mc_sample_path(P, ψ_0=(1.0, 0.0), ts_length=10) +``` + +It can be shown that for a long series drawn from `P`, the fraction of the +sample that takes value 0 will be about 0.25. + +(We will explain why {ref}`later `.) + +Moreover, this is true regardless of the initial distribution from which +$X_0$ is drawn. + +The following code illustrates this + +```{code-cell} ipython3 +X = mc_sample_path(P, ψ_0=(0.1, 0.9), ts_length=1_000_000) +np.mean(X == 0) +``` + +You can try changing the initial distribution to confirm that the output is +always close to 0.25 (for the `P` matrix above). + + +### Using QuantEcon's routines + +[QuantEcon.py](http://quantecon.org/quantecon-py) has routines for handling Markov chains, including simulation. + +Here's an illustration using the same $P$ as the preceding example + +```{code-cell} ipython3 +mc = qe.MarkovChain(P) +X = mc.simulate(ts_length=1_000_000) +np.mean(X == 0) +``` + +The `simulate` routine is faster (because it is [JIT compiled](https://python-programming.quantecon.org/numba.html#numba-link)). + +```{code-cell} ipython3 +%time mc_sample_path(P, ts_length=1_000_000) # Our homemade code version +``` + +```{code-cell} ipython3 +%time mc.simulate(ts_length=1_000_000) # qe code version +``` + +#### Adding state values and initial conditions + +If we wish to, we can provide a specification of state values to `MarkovChain`. + +These state values can be integers, floats, or even strings. + +The following code illustrates + +```{code-cell} ipython3 +mc = qe.MarkovChain(P, state_values=('unemployed', 'employed')) +mc.simulate(ts_length=4, init='employed') # Start at employed initial state +``` + +```{code-cell} ipython3 +mc.simulate(ts_length=4, init='unemployed') # Start at unemployed initial state +``` + +```{code-cell} ipython3 +mc.simulate(ts_length=4) # Start at randomly chosen initial state +``` + +If we want to see indices rather than state values as outputs as we can use + +```{code-cell} ipython3 +mc.simulate_indices(ts_length=4) +``` + +(mc_md)= +## Distributions over time + +We learned that + +1. $\{X_t\}$ is a Markov chain with stochastic matrix $P$ +1. the distribution of $X_t$ is known to be $\psi_t$ + +What then is the distribution of $X_{t+1}$, or, more generally, of $X_{t+m}$? + +To answer this, we let $\psi_t$ be the distribution of $X_t$ for $t = 0, 1, 2, \ldots$. + +Our first aim is to find $\psi_{t + 1}$ given $\psi_t$ and $P$. + +To begin, pick any $y \in S$. + +To get the probability of being at $y$ tomorrow (at $t+1$), we account for +all ways this can happen and sum their probabilities. + +This leads to + +$$ +\mathbb P \{X_{t+1} = y \} + = \sum_{x \in S} \mathbb P \{ X_{t+1} = y \, | \, X_t = x \} + \cdot \mathbb P \{ X_t = x \} +$$ + + + +(We are using the [law of total probability](https://en.wikipedia.org/wiki/Law_of_total_probability).) + +Rewriting this statement in terms of marginal and conditional probabilities gives + +$$ + \psi_{t+1}(y) = \sum_{x \in S} P(x,y) \psi_t(x) +$$ + +There are $n$ such equations, one for each $y \in S$. + +If we think of $\psi_{t+1}$ and $\psi_t$ as row vectors, these $n$ equations are summarized by the matrix expression + +```{math} +:label: fin_mc_fr + +\psi_{t+1} = \psi_t P +``` + +Thus, we postmultiply by $P$ to move a distribution forward one unit of time. + +By postmultiplying $m$ times, we move a distribution forward $m$ steps into the future. + +Hence, iterating on {eq}`fin_mc_fr`, the expression $\psi_{t+m} = \psi_t P^m$ is also valid --- here $P^m$ is the $m$-th power of $P$. + +As a special case, we see that if $\psi_0$ is the initial distribution from +which $X_0$ is drawn, then $\psi_0 P^m$ is the distribution of +$X_m$. + +This is very important, so let's repeat it + +```{math} +:label: mdfmc + +X_0 \sim \psi_0 \quad \implies \quad X_m \sim \psi_0 P^m +``` + +The general rule is that postmultiplying a distribution by $P^m$ shifts it forward $m$ units of time. + +Hence the following is also valid. + +```{math} +:label: mdfmc2 + +X_t \sim \psi_t \quad \implies \quad X_{t+m} \sim \psi_t P^m +``` + + + +(finite_mc_mstp)= +### Multiple step transition probabilities + +We know that the probability of transitioning from $x$ to $y$ in +one step is $P(x,y)$. + +It turns out that the probability of transitioning from $x$ to $y$ in +$m$ steps is $P^m(x,y)$, the $(x,y)$-th element of the +$m$-th power of $P$. + +To see why, consider again {eq}`mdfmc2`, but now with a $\psi_t$ that puts all probability on state $x$. + +Then $\psi_t$ is a vector with $1$ in position $x$ and zero elsewhere. + +Inserting this into {eq}`mdfmc2`, we see that, conditional on $X_t = x$, the distribution of $X_{t+m}$ is the $x$-th row of $P^m$. + +In particular + +$$ +\mathbb P \{X_{t+m} = y \,|\, X_t = x \} = P^m(x, y) = (x, y) \text{-th element of } P^m +$$ + + +### Example: probability of recession + +```{index} single: Markov Chains; Future Probabilities +``` + +Recall the stochastic matrix $P$ for recession and growth {ref}`considered above `. + +Suppose that the current state is unknown --- perhaps statistics are available only at the *end* of the current month. + +We guess that the probability that the economy is in state $x$ is $\psi_t(x)$ at time t. + +The probability of being in recession (either mild or severe) in 6 months time is given by + +$$ +(\psi_t P^6)(1) + (\psi_t P^6)(2) +$$ + + + +(mc_eg1-1)= +### Example 2: cross-sectional distributions + +The distributions we have been studying can be viewed either + +1. as probabilities or +1. as cross-sectional frequencies that the law of large numbers leads us to anticipate for large samples. + +To illustrate, recall our model of employment/unemployment dynamics for a given worker {ref}`discussed above `. + +Consider a large population of workers, each of whose lifetime experience is +described by the specified dynamics, with each worker's outcomes being +realizations of processes that are statistically independent of all other +workers' processes. + +Let $\psi_t$ be the current *cross-sectional* distribution over $\{ 0, 1 \}$. + +The cross-sectional distribution records fractions of workers employed and unemployed at a given moment $t$. + +* For example, $\psi_t(0)$ is the unemployment rate at time $t$. + +What will the cross-sectional distribution be in 10 periods hence? + +The answer is $\psi_t P^{10}$, where $P$ is the stochastic matrix in +{eq}`p_unempemp`. + +This is because each worker's state evolves according to $P$, so +$\psi_t P^{10}$ is a [marginal distribution](https://en.wikipedia.org/wiki/Marginal_distribution) for a single randomly selected +worker. + +But when the sample is large, outcomes and probabilities are roughly equal (by an application of the law +of large numbers). + +So for a very large (tending to infinite) population, +$\psi_t P^{10}$ also represents fractions of workers in +each state. + +This is exactly the cross-sectional distribution. + +(stationary)= +## Stationary distributions + + +As seen in {eq}`fin_mc_fr`, we can shift a distribution forward one +unit of time via postmultiplication by $P$. + +Some distributions are invariant under this updating process --- for example, + +```{code-cell} ipython3 +P = np.array([[0.4, 0.6], + [0.2, 0.8]]) +ψ = (0.25, 0.75) +ψ @ P +``` + +Notice that `ψ @ P` is the same as `ψ`. + + + +Such distributions are called **stationary** or **invariant**. + +(mc_stat_dd)= +Formally, a distribution $\psi^*$ on $S$ is called **stationary** for $P$ if $\psi^* P = \psi^* $. + +Notice that, postmultiplying by $P$, we have $\psi^* P^2 = \psi^* P = \psi^*$. + +Continuing in the same way leads to $\psi^* = \psi^* P^t$ for all $t \ge 0$. + +This tells us an important fact: If the distribution of $\psi_0$ is a stationary distribution, then $\psi_t$ will have this same distribution for all $t \ge 0$. + +The following theorem is proved in Chapter 4 of {cite}`sargent2023economic` and numerous other sources. + +```{prf:theorem} +:label: unique_stat + +Every stochastic matrix $P$ has at least one stationary distribution. +``` + +Note that there can be many stationary distributions corresponding to a given +stochastic matrix $P$. + +* For example, if $P$ is the identity matrix, then all distributions on $S$ are stationary. + +To get uniqueness, we need the Markov chain to "mix around," so that the state +doesn't get stuck in some part of the state space. + +This gives some intuition for the following theorem. + + +```{prf:theorem} +:label: mc_po_conv_thm + +If $P$ is everywhere positive, then $P$ has exactly one stationary +distribution. +``` + +We will come back to this when we introduce irreducibility in the {doc}`next lecture ` on Markov chains. + + + +### Example + +Recall our model of the employment/unemployment dynamics of a particular worker {ref}`discussed above `. + +If $\alpha \in (0,1)$ and $\beta \in (0,1)$, then the transition matrix is everywhere positive. + +Let $\psi^* = (p, 1-p)$ be the stationary distribution, so that $p$ +corresponds to unemployment (state 0). + +Using $\psi^* = \psi^* P$ and a bit of algebra yields + +$$ + p = \frac{\beta}{\alpha + \beta} +$$ + +This is, in some sense, a steady state probability of unemployment. + +Not surprisingly it tends to zero as $\beta \to 0$, and to one as $\alpha \to 0$. + + + + + + +### Calculating stationary distributions + +A stable algorithm for computing stationary distributions is implemented in [QuantEcon.py](http://quantecon.org/quantecon-py). + +Here's an example + +```{code-cell} ipython3 +P = [[0.4, 0.6], + [0.2, 0.8]] + +mc = qe.MarkovChain(P) +mc.stationary_distributions # Show all stationary distributions +``` + + + + + + +### Asymptotic stationarity + +Consider an everywhere positive stochastic matrix with unique stationary distribution $\psi^*$. + +Sometimes the distribution $\psi_t = \psi_0 P^t$ of $X_t$ converges to $\psi^*$ regardless of $\psi_0$. + +For example, we have the following result + +(strict_stationary)= +```{prf:theorem} +:label: mc_gs_thm + +If there exists an integer $m$ such that all entries of $P^m$ are +strictly positive, then + +$$ + \psi_0 P^t \to \psi^* + \quad \text{ as } t \to \infty +$$ + +where $\psi^*$ is the unique stationary distribution. +``` + +This situation is often referred to as **asymptotic stationarity** or **global stability**. + +A proof of the theorem can be found in Chapter 4 of {cite}`sargent2023economic`, as well as many other sources. + + + + + +(hamilton)= +#### Example: Hamilton's chain + +Hamilton's chain satisfies the conditions of the theorem because $P^2$ is everywhere positive: + +```{code-cell} ipython3 +P = np.array([[0.971, 0.029, 0.000], + [0.145, 0.778, 0.077], + [0.000, 0.508, 0.492]]) +P @ P +``` + +Let's pick an initial distribution $\psi_1, \psi_2, \psi_3$ and trace out the sequence of distributions $\psi_i P^t$ for $t = 0, 1, 2, \ldots$, for $i=1, 2, 3$. + +First, we write a function to iterate the sequence of distributions for `ts_length` period + +```{code-cell} ipython3 +def iterate_ψ(ψ_0, P, ts_length): + n = len(P) + ψ_t = np.empty((ts_length, n)) + ψ_t[0 ]= ψ_0 + for t in range(1, ts_length): + ψ_t[t] = ψ_t[t-1] @ P + return ψ_t +``` + +Now we plot the sequence + +```{code-cell} ipython3 +:tags: [hide-input] + +ψ_1 = (0.0, 0.0, 1.0) +ψ_2 = (1.0, 0.0, 0.0) +ψ_3 = (0.0, 1.0, 0.0) # Three initial conditions +colors = ['blue','red', 'green'] # Different colors for each initial point + +# Define the vertices of the unit simplex +v = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]]) + +# Define the faces of the unit simplex +faces = [ + [v[0], v[1], v[2]], + [v[0], v[1], v[3]], + [v[0], v[2], v[3]], + [v[1], v[2], v[3]] +] + +fig = plt.figure() +ax = fig.add_subplot(projection='3d') + +def update(n): + ax.clear() + ax.set_xlim([0, 1]) + ax.set_ylim([0, 1]) + ax.set_zlim([0, 1]) + ax.view_init(45, 45) + + simplex = Poly3DCollection(faces, alpha=0.03) + ax.add_collection3d(simplex) + + for idx, ψ_0 in enumerate([ψ_1, ψ_2, ψ_3]): + ψ_t = iterate_ψ(ψ_0, P, n+1) + + for i, point in enumerate(ψ_t): + ax.scatter(point[0], point[1], point[2], color=colors[idx], s=60, alpha=(i+1)/len(ψ_t)) + + mc = qe.MarkovChain(P) + ψ_star = mc.stationary_distributions[0] + ax.scatter(ψ_star[0], ψ_star[1], ψ_star[2], c='yellow', s=60) + + return fig, + +anim = FuncAnimation(fig, update, frames=range(20), blit=False, repeat=False) +plt.close() +HTML(anim.to_jshtml()) +``` + +Here + +* $P$ is the stochastic matrix for recession and growth {ref}`considered above `. +* The red, blue and green dots are initial marginal probability distributions $\psi_1, \psi_2, \psi_3$, each of which is represented as a vector in $\mathbb R^3$. +* The transparent dots are the marginal distributions $\psi_i P^t$ for $t = 1, 2, \ldots$, for $i=1,2,3.$. +* The yellow dot is $\psi^*$. + +You might like to try experimenting with different initial conditions. + + + + +#### Example: failure of convergence + + +Consider the periodic chain with stochastic matrix + +$$ +P = +\begin{bmatrix} + 0 & 1 \\ + 1 & 0 \\ +\end{bmatrix} +$$ + +This matrix does not satisfy the conditions of +{ref}`strict_stationary` because, as you can readily check, + +* $P^m = P$ when $m$ is odd and +* $P^m = I$, the identity matrix, when $m$ is even. + +Hence there is no $m$ such that all elements of $P^m$ are strictly positive. + +Moreover, we can see that global stability does not hold. + +For instance, if we start at $\psi_0 = (1,0)$, then $\psi_m = \psi_0 P^m$ is $(1, 0)$ when $m$ is even and $(0,1)$ when $m$ is odd. + +We can see similar phenomena in higher dimensions. + +The next figure illustrates this for a periodic Markov chain with three states. + +```{code-cell} ipython3 +:tags: [hide-input] + +ψ_1 = (0.0, 0.0, 1.0) +ψ_2 = (0.5, 0.5, 0.0) +ψ_3 = (0.25, 0.25, 0.5) +ψ_4 = (1/3, 1/3, 1/3) + +P = np.array([[0.0, 1.0, 0.0], + [0.0, 0.0, 1.0], + [1.0, 0.0, 0.0]]) + +fig = plt.figure() +ax = fig.add_subplot(projection='3d') +colors = ['red','yellow', 'green', 'blue'] # Different colors for each initial point + +# Define the vertices of the unit simplex +v = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]]) + +# Define the faces of the unit simplex +faces = [ + [v[0], v[1], v[2]], + [v[0], v[1], v[3]], + [v[0], v[2], v[3]], + [v[1], v[2], v[3]] +] + +def update(n): + ax.clear() + ax.set_xlim([0, 1]) + ax.set_ylim([0, 1]) + ax.set_zlim([0, 1]) + ax.view_init(45, 45) + + # Plot the 3D unit simplex as planes + simplex = Poly3DCollection(faces,alpha=0.05) + ax.add_collection3d(simplex) + + for idx, ψ_0 in enumerate([ψ_1, ψ_2, ψ_3, ψ_4]): + ψ_t = iterate_ψ(ψ_0, P, n+1) + + point = ψ_t[-1] + ax.scatter(point[0], point[1], point[2], color=colors[idx], s=60) + points = np.array(ψ_t) + ax.plot(points[:, 0], points[:, 1], points[:, 2], color=colors[idx],linewidth=0.75) + + return fig, + +anim = FuncAnimation(fig, update, frames=range(20), blit=False, repeat=False) +plt.close() +HTML(anim.to_jshtml()) +``` +This animation demonstrates the behavior of an irreducible and periodic stochastic matrix. + +The red, yellow, and green dots represent different initial probability distributions. + +The blue dot represents the unique stationary distribution. + +Unlike Hamilton’s Markov chain, these initial distributions do not converge to the unique stationary distribution. + +Instead, they cycle periodically around the probability simplex, illustrating that asymptotic stability fails. + + +(finite_mc_expec)= +## Computing expectations + +```{index} single: Markov Chains; Forecasting Future Values +``` + +We sometimes want to compute mathematical expectations of functions of $X_t$ of the form + +```{math} +:label: mc_une + +\mathbb E [ h(X_t) ] +``` + +and conditional expectations such as + +```{math} +:label: mc_cce + +\mathbb E [ h(X_{t + k}) \mid X_t = x] +``` + +where + +* $\{X_t\}$ is a Markov chain generated by $n \times n$ stochastic matrix $P$. +* $h$ is a given function, which, in terms of matrix + algebra, we'll think of as the column vector + +$$ +h = +\begin{bmatrix} + h(x_1) \\ + \vdots \\ + h(x_n) +\end{bmatrix}. +$$ + +Computing the unconditional expectation {eq}`mc_une` is easy. + + +We just sum over the marginal distribution of $X_t$ to get + +$$ +\mathbb E [ h(X_t) ] += \sum_{x \in S} (\psi P^t)(x) h(x) +$$ + +Here $\psi$ is the distribution of $X_0$. + +Since $\psi$ and hence $\psi P^t$ are row vectors, we can also +write this as + +$$ +\mathbb E [ h(X_t) ] += \psi P^t h +$$ + +For the conditional expectation {eq}`mc_cce`, we need to sum over +the conditional distribution of $X_{t + k}$ given $X_t = x$. + +We already know that this is $P^k(x, \cdot)$, so + +```{math} +:label: mc_cce2 + +\mathbb E [ h(X_{t + k}) \mid X_t = x] += (P^k h)(x) +``` + +### Expectations of geometric sums + +Sometimes we want to compute the mathematical expectation of a geometric sum, such as +$\sum_t \beta^t h(X_t)$. + +In view of the preceding discussion, this is + +$$ +\mathbb{E} + \left[ + \sum_{j=0}^\infty \beta^j h(X_{t+j}) \mid X_t + = x + \right] + = x + \beta (Ph)(x) + \beta^2 (P^2 h)(x) + \cdots +$$ + +By the {ref}`Neumann series lemma `, this sum can be calculated using + +$$ + I + \beta P + \beta^2 P^2 + \cdots = (I - \beta P)^{-1} +$$ + +The vector $P^k h$ stores the conditional expectation $\mathbb E [ h(X_{t + k}) \mid X_t = x]$ over all $x$. + + +```{exercise} +:label: mc1_ex_1 + +Imam and Temple {cite}`imampolitical` used a three-state transition matrix to describe the transition of three states of a regime: growth, stagnation, and collapse + +$$ +P := +\begin{bmatrix} + 0.68 & 0.12 & 0.20 \\ + 0.50 & 0.24 & 0.26 \\ + 0.36 & 0.18 & 0.46 +\end{bmatrix} +$$ + +where rows, from top to down, correspond to growth, stagnation, and collapse. + +In this exercise, + +1. visualize the transition matrix and show this process is asymptotically stationary +1. calculate the stationary distribution using simulations +1. visualize the dynamics of $(\psi_0 P^t)(i)$ where $t \in 0, ..., 25$ and compare the convergent path with the previous transition matrix + +Compare your solution to the paper. +``` + +```{solution-start} mc1_ex_1 +:class: dropdown +``` + +Solution 1: + +```{image} /_static/lecture_specific/markov_chains_I/Temple.png +:name: mc_temple +:align: center + +``` + +Since the matrix is everywhere positive, there is a unique stationary distribution $\psi^*$ such that $\psi_t\to \psi^*$ as $t\to \infty$. + +Solution 2: + +One simple way to calculate the stationary distribution is to take the power of the transition matrix as we have shown before + +```{code-cell} ipython3 +P = np.array([[0.68, 0.12, 0.20], + [0.50, 0.24, 0.26], + [0.36, 0.18, 0.46]]) +P_power = np.linalg.matrix_power(P, 20) +P_power +``` + +Note that rows of the transition matrix converge to the stationary distribution. + +```{code-cell} ipython3 +ψ_star_p = P_power[0] +ψ_star_p +``` + +```{code-cell} ipython3 +mc = qe.MarkovChain(P) +ψ_star = mc.stationary_distributions[0] +ψ_star +``` + + +```{solution-end} +``` + +````{exercise} +:label: mc1_ex_2 + +We discussed the six-state transition matrix estimated by Imam & Temple {cite}`imampolitical` [before](mc_eg3). + +```python +nodes = ['DG', 'DC', 'NG', 'NC', 'AG', 'AC'] +P = [[0.86, 0.11, 0.03, 0.00, 0.00, 0.00], + [0.52, 0.33, 0.13, 0.02, 0.00, 0.00], + [0.12, 0.03, 0.70, 0.11, 0.03, 0.01], + [0.13, 0.02, 0.35, 0.36, 0.10, 0.04], + [0.00, 0.00, 0.09, 0.11, 0.55, 0.25], + [0.00, 0.00, 0.09, 0.15, 0.26, 0.50]] +``` + +In this exercise, + +1. show this process is asymptotically stationary without simulation +2. simulate and visualize the dynamics starting with a uniform distribution across states (each state will have a probability of 1/6) +3. change the initial distribution to P(DG) = 1, while all other states have a probability of 0 +```` + +```{solution-start} mc1_ex_2 +:class: dropdown +``` + +Solution 1: + +Although $P$ is not every positive, $P^m$ when $m=3$ is everywhere positive. + +```{code-cell} ipython3 +P = np.array([[0.86, 0.11, 0.03, 0.00, 0.00, 0.00], + [0.52, 0.33, 0.13, 0.02, 0.00, 0.00], + [0.12, 0.03, 0.70, 0.11, 0.03, 0.01], + [0.13, 0.02, 0.35, 0.36, 0.10, 0.04], + [0.00, 0.00, 0.09, 0.11, 0.55, 0.25], + [0.00, 0.00, 0.09, 0.15, 0.26, 0.50]]) + +np.linalg.matrix_power(P,3) +``` + +So it satisfies the requirement. + +Solution 2: + +We find the distribution $\psi$ converges to the stationary distribution quickly regardless of the initial distributions + +```{code-cell} ipython3 +ts_length = 30 +num_distributions = 20 +nodes = ['DG', 'DC', 'NG', 'NC', 'AG', 'AC'] + +# Get parameters of transition matrix +n = len(P) +mc = qe.MarkovChain(P) +ψ_star = mc.stationary_distributions[0] +ψ_0 = np.array([[1/6 for i in range(6)], + [0 if i != 0 else 1 for i in range(6)]]) +## Draw the plot +fig, axes = plt.subplots(ncols=2) +plt.subplots_adjust(wspace=0.35) +for idx in range(2): + ψ_t = iterate_ψ(ψ_0[idx], P, ts_length) + for i in range(n): + axes[idx].plot(ψ_t[:, i] - ψ_star[i], alpha=0.5, label=fr'$\psi_t({i+1})$') + axes[idx].set_ylim([-0.3, 0.3]) + axes[idx].set_xlabel('t') + axes[idx].set_ylabel(fr'$\psi_t$') + axes[idx].legend() + axes[idx].axhline(0, linestyle='dashed', lw=1, color = 'black') + +plt.show() +``` + +```{solution-end} +``` + +```{exercise} +:label: mc1_ex_3 +Prove the following: If $P$ is a stochastic matrix, then so is the $k$-th +power $P^k$ for all $k \in \mathbb N$. +``` + + +```{solution-start} mc1_ex_3 +:class: dropdown +``` + +Suppose that $P$ is stochastic and, moreover, that $P^k$ is +stochastic for some integer $k$. + +We will prove that $P^{k+1} = P P^k$ is also stochastic. + +(We are doing proof by induction --- we assume the claim is true at $k$ and +now prove it is true at $k+1$.) + +To see this, observe that, since $P^k$ is stochastic and the product of +nonnegative matrices is nonnegative, $P^{k+1} = P P^k$ is nonnegative. + +Also, if $\mathbf 1$ is a column vector of ones, then, since $P^k$ is stochastic we +have $P^k \mathbf 1 = \mathbf 1$ (rows sum to one). + +Therefore $P^{k+1} \mathbf 1 = P P^k \mathbf 1 = P \mathbf 1 = \mathbf 1$ + +The proof is done. + +```{solution-end} +``` diff --git a/content/lectures/markov_chains_II.ipynb b/book/_build/html/_sources/markov_chains_II.ipynb similarity index 56% rename from content/lectures/markov_chains_II.ipynb rename to book/_build/html/_sources/markov_chains_II.ipynb index 10af1c9..99198aa 100644 --- a/content/lectures/markov_chains_II.ipynb +++ b/book/_build/html/_sources/markov_chains_II.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "f8c9c2bf", + "id": "9fd4b257", "metadata": {}, "source": [ "# Markov Chains: Irreducibility and Ergodicity\n", @@ -10,18 +10,13 @@ "```{index} single: Markov Chains: Irreducibility and Ergodicity\n", "```\n", "\n", - "```{contents} Contents\n", - ":depth: 2\n", - "```\n", - "\n", - "\n", "In addition to what's in Anaconda, this lecture will need the following libraries:" ] }, { "cell_type": "code", "execution_count": null, - "id": "2af21a09", + "id": "f3733fea", "metadata": { "tags": [ "hide-output" @@ -29,43 +24,31 @@ }, "outputs": [], "source": [ - "%pip install quantecon\n", - "%pip install graphviz" + "%pip install quantecon" ] }, { "cell_type": "markdown", - "id": "7f122565", + "id": "00af1853", "metadata": {}, - "source": [ - "```{admonition} graphviz\n", - ":class: warning\n", - "If you are running this lecture locally it requires [graphviz](https://www.graphviz.org)\n", - "to be installed on your computer. Installation instructions for graphviz can be found\n", - "[here](https://www.graphviz.org/download/) \n", - "```" - ] - }, - { - "cell_type": "markdown", - "id": "a65d321d", - "metadata": { - "user_expressions": [] - }, "source": [ "## Overview\n", "\n", - "This lecture continues our journey in Markov chains.\n", + "This lecture continues on from our {doc}`earlier lecture on Markov chains\n", + "`.\n", + "\n", "\n", - "Specifically, we will introduce irreducibility and ergodicity, and how they connect to stationarity.\n", + "Specifically, we will introduce the concepts of irreducibility and ergodicity, and see how they connect to stationarity.\n", "\n", - "Irreducibility is a concept that describes the ability of a Markov chain to move between any two states in the system.\n", + "Irreducibility describes the ability of a Markov chain to move between any two states in the system.\n", "\n", "Ergodicity is a sample path property that describes the behavior of the system over long periods of time. \n", "\n", - "The concepts of irreducibility and ergodicity are closely related to the idea of stationarity. \n", + "As we will see, \n", "\n", - "An irreducible Markov chain guarantees the existence of a unique stationary distribution, while an ergodic Markov chain ensures that the system eventually reaches its stationary distribution, regardless of its initial state. \n", + "* an irreducible Markov chain guarantees the existence of a unique stationary distribution, while \n", + "* an ergodic Markov chain generates time series that satisfy a version of the\n", + " law of large numbers. \n", "\n", "Together, these concepts provide a foundation for understanding the long-term behavior of Markov chains.\n", "\n", @@ -75,40 +58,29 @@ { "cell_type": "code", "execution_count": null, - "id": "1cc8e4a9", + "id": "47297271", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", - "plt.rcParams[\"figure.figsize\"] = (11, 5) # set default figure size\n", "import quantecon as qe\n", - "import numpy as np\n", - "from graphviz import Digraph\n", - "import networkx as nx\n", - "from matplotlib import cm\n", - "import matplotlib as mpl" + "import numpy as np" ] }, { "cell_type": "markdown", - "id": "017f1122", + "id": "f76c7886", "metadata": {}, "source": [ + "(mc_irreducible)=\n", "## Irreducibility\n", "\n", "\n", - "Irreducibility is a central concept of Markov chain theory.\n", + "To explain irreducibility, let's take $P$ to be a fixed stochastic matrix.\n", "\n", - "To explain it, let's take $P$ to be a fixed stochastic matrix.\n", + "State $x$ is called **accessible** (or **reachable**) from state $y$ if $P^t(x,y)>0$ for some integer $t\\ge 0$. \n", "\n", - "Two states $x$ and $y$ are said to **communicate** with each other if\n", - "there exist positive integers $j$ and $k$ such that\n", - "\n", - "$$\n", - "P^j(x, y) > 0\n", - "\\quad \\text{and} \\quad\n", - "P^k(y, x) > 0\n", - "$$\n", + "Two states, $x$ and $y$, are said to **communicate** if $x$ and $y$ are accessible from each other.\n", "\n", "In view of our discussion {ref}`above `, this means precisely\n", "that\n", @@ -119,44 +91,16 @@ "The stochastic matrix $P$ is called **irreducible** if all states communicate;\n", "that is, if $x$ and $y$ communicate for all $(x, y)$ in $S \\times S$.\n", "\n", + "````{prf:example}\n", + ":label: mc2_ex_ir\n", "For example, consider the following transition probabilities for wealth of a\n", - "fictitious set of households" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fafc08c9", - "metadata": { - "tags": [ - "hide-input" - ] - }, - "outputs": [], - "source": [ - "dot = Digraph(comment='Graph')\n", - "dot.attr(rankdir='LR')\n", - "dot.node(\"poor\")\n", - "dot.node(\"middle class\")\n", - "dot.node(\"rich\")\n", - "\n", - "dot.edge(\"poor\", \"poor\", label=\"0.9\")\n", - "dot.edge(\"poor\", \"middle class\", label=\"0.1\")\n", - "dot.edge(\"middle class\", \"poor\", label=\"0.4\")\n", - "dot.edge(\"middle class\", \"middle class\", label=\"0.4\")\n", - "dot.edge(\"middle class\", \"rich\", label=\"0.2\")\n", - "dot.edge(\"rich\", \"poor\", label=\"0.1\")\n", - "dot.edge(\"rich\", \"middle class\", label=\"0.1\")\n", - "dot.edge(\"rich\", \"rich\", label=\"0.8\")\n", - "\n", - "dot" - ] - }, - { - "cell_type": "markdown", - "id": "a1cabeb4", - "metadata": {}, - "source": [ + "fictitious set of households\n", + "\n", + "```{image} /_static/lecture_specific/markov_chains_II/Irre_1.png\n", + ":name: mc_irre1\n", + ":align: center\n", + "```\n", + "\n", "We can translate this into a stochastic matrix, putting zeros where\n", "there's no edge between nodes\n", "\n", @@ -171,6 +115,7 @@ "\n", "It's clear from the graph that this stochastic matrix is irreducible: we can eventually\n", "reach any state from any other state.\n", + "````\n", "\n", "We can also test this using [QuantEcon.py](http://quantecon.org/quantecon-py)'s MarkovChain class" ] @@ -178,7 +123,7 @@ { "cell_type": "code", "execution_count": null, - "id": "05cee317", + "id": "a52be55f", "metadata": {}, "outputs": [], "source": [ @@ -192,46 +137,22 @@ }, { "cell_type": "markdown", - "id": "bdd8c0af", - "metadata": {}, - "source": [ - "Here's a more pessimistic scenario in which poor people remain poor forever" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "52a2b599", - "metadata": { - "tags": [ - "hide-input" - ] - }, - "outputs": [], - "source": [ - "dot = Digraph(comment='Graph')\n", - "dot.attr(rankdir='LR')\n", - "dot.node(\"poor\")\n", - "dot.node(\"middle class\")\n", - "dot.node(\"rich\")\n", - "\n", - "dot.edge(\"poor\", \"poor\", label=\"1.0\")\n", - "dot.edge(\"middle class\", \"poor\", label=\"0.1\")\n", - "dot.edge(\"middle class\", \"middle class\", label=\"0.8\")\n", - "dot.edge(\"middle class\", \"rich\", label=\"0.1\")\n", - "dot.edge(\"rich\", \"middle class\", label=\"0.2\")\n", - "dot.edge(\"rich\", \"rich\", label=\"0.8\")\n", - "\n", - "dot" - ] - }, - { - "cell_type": "markdown", - "id": "a1a13c0f", + "id": "f2971bb3", "metadata": {}, "source": [ + "````{prf:example}\n", + ":label: mc2_ex_pf\n", + "\n", + "Here's a more pessimistic scenario in which poor people remain poor forever\n", + "\n", + "```{image} /_static/lecture_specific/markov_chains_II/Irre_2.png\n", + ":name: mc_irre2\n", + ":align: center\n", + "```\n", + "\n", "This stochastic matrix is not irreducible since, for example, rich is not\n", "accessible from poor.\n", + "````\n", "\n", "Let's confirm this" ] @@ -239,7 +160,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e46202b4", + "id": "1fff5d05", "metadata": {}, "outputs": [], "source": [ @@ -253,10 +174,8 @@ }, { "cell_type": "markdown", - "id": "04255600", - "metadata": { - "user_expressions": [] - }, + "id": "fb8fada1", + "metadata": {}, "source": [ "It might be clear to you already that irreducibility is going to be important\n", "in terms of long-run outcomes.\n", @@ -267,11 +186,11 @@ "\n", "### Irreducibility and stationarity\n", "\n", - "We discussed the uniqueness of the stationary in the {ref}`previous lecture ` requires the transition matrix to be everywhere positive.\n", + "We discussed uniqueness of stationary distributions in our earlier lecture {doc}`markov_chains_I`.\n", "\n", - "In fact irreducibility is enough for the uniqueness of the stationary distribution to hold if the distribution exists.\n", + "There we {prf:ref}`stated ` that uniqueness holds when the transition matrix is everywhere positive.\n", "\n", - "We can revise the {ref}`theorem` into the following fundamental theorem:\n", + "In fact irreducibility is sufficient:\n", "\n", "```{prf:theorem}\n", ":label: mc_conv_thm\n", @@ -287,6 +206,7 @@ "(ergodicity)=\n", "## Ergodicity\n", "\n", + "\n", "Under irreducibility, yet another important result obtains:\n", "\n", "````{prf:theorem}\n", @@ -298,7 +218,7 @@ "```{math}\n", ":label: llnfmc0\n", "\n", - "\\frac{1}{m} \\sum_{t = 1}^m \\mathbf{1}\\{X_t = x\\} \\to \\psi^*(x)\n", + "\\frac{1}{m} \\sum_{t = 1}^m \\mathbb{1}\\{X_t = x\\} \\to \\psi^*(x)\n", " \\quad \\text{as } m \\to \\infty\n", "```\n", "\n", @@ -306,9 +226,9 @@ "\n", "Here\n", "\n", - "* $\\{X_t\\}$ is a Markov chain with stochastic matrix $P$ and initial\n", - " distribution $\\psi_0$\n", - "* $\\mathbf{1}\\{X_t = x\\} = 1$ if $X_t = x$ and zero otherwise\n", + "* $\\{X_t\\}$ is a Markov chain with stochastic matrix $P$ and initial distribution $\\psi_0$\n", + "\n", + "* $\\mathbb{1} \\{X_t = x\\} = 1$ if $X_t = x$ and zero otherwise.\n", "\n", "The result in [theorem 4.3](llnfmc0) is sometimes called **ergodicity**.\n", "\n", @@ -327,9 +247,9 @@ "\n", "\n", "(mc_eg1-2)=\n", - "### Example 1\n", + "### Example: ergodicity and unemployment\n", "\n", - "Recall our cross-sectional interpretation of the employment/unemployment model {ref}`discussed above `.\n", + "Recall our cross-sectional interpretation of the employment/unemployment model {ref}`discussed before `.\n", "\n", "Assume that $\\alpha \\in (0,1)$ and $\\beta \\in (0,1)$, so that irreducibility holds.\n", "\n", @@ -349,121 +269,74 @@ "\n", "\n", "(ergo)=\n", - "### Example 2\n", + "### Example: Hamilton dynamics\n", "\n", - "Another example is Hamilton {cite}`Hamilton2005` dynamics {ref}`discussed before `.\n", + "Another example is the Hamilton dynamics we {ref}`discussed before `.\n", "\n", - "The diagram of the Markov chain shows that it is **irreducible**.\n", - "\n", - "Therefore, we can see the sample path averages for each state (the fraction of time spent in each state) converges to the stationary distribution regardless of the starting state" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f9d7b3ce", - "metadata": {}, - "outputs": [], - "source": [ - "P = np.array([[0.971, 0.029, 0.000],\n", - " [0.145, 0.778, 0.077],\n", - " [0.000, 0.508, 0.492]])\n", - "ts_length = 10_000\n", - "mc = qe.MarkovChain(P)\n", - "n = len(P)\n", - "fig, axes = plt.subplots(nrows=1, ncols=n)\n", - "ψ_star = mc.stationary_distributions[0]\n", - "plt.subplots_adjust(wspace=0.35)\n", - "\n", - "for i in range(n):\n", - " axes[i].grid()\n", - " axes[i].axhline(ψ_star[i], linestyle='dashed', lw=2, color = 'black', \n", - " label = fr'$\\psi^*({i})$')\n", - " axes[i].set_xlabel('t')\n", - " axes[i].set_ylabel(f'fraction of time spent at {i}')\n", - "\n", - " # Compute the fraction of time spent, starting from different x_0s\n", - " for x0, col in ((0, 'blue'), (1, 'green'), (2, 'red')):\n", - " # Generate time series that starts at different x0\n", - " X = mc.simulate(ts_length, init=x0)\n", - " X_bar = (X == i).cumsum() / (1 + np.arange(ts_length, dtype=float))\n", - " axes[i].plot(X_bar, color=col, label=f'$x_0 = \\, {x0} $')\n", - " axes[i].legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "8e3d8cd6", - "metadata": {}, - "source": [ - "### Example 3\n", - "\n", - "Let's look at one more example with six states {ref}`discussed before `.\n", + "Let $\\{X_t\\}$ be a sample path generated by these dynamics.\n", "\n", + "Let's denote the fraction of time spent in state $x$ over the period $t=1,\n", + "\\ldots, n$ by $\\hat p_n(x)$, so that \n", "\n", "$$\n", - "P :=\n", - "\\begin{bmatrix} \n", - "0.86 & 0.11 & 0.03 & 0.00 & 0.00 & 0.00 \\\\\n", - "0.52 & 0.33 & 0.13 & 0.02 & 0.00 & 0.00 \\\\\n", - "0.12 & 0.03 & 0.70 & 0.11 & 0.03 & 0.01 \\\\\n", - "0.13 & 0.02 & 0.35 & 0.36 & 0.10 & 0.04 \\\\\n", - "0.00 & 0.00 & 0.09 & 0.11 & 0.55 & 0.25 \\\\\n", - "0.00 & 0.00 & 0.09 & 0.15 & 0.26 & 0.50\n", - "\\end{bmatrix} \n", + " \\hat p_n(x) := \\frac{1}{n} \\sum_{t = 1}^n \\mathbb{1}\\{X_t = x\\}\n", + " \\qquad (x \\in \\{0, 1, 2\\})\n", "$$\n", "\n", "\n", - "The graph for the chain shows states are densely connected indicating that it is **irreducible**.\n", + "The {ref}`graph ` of the Markov chain shows it is irreducible, so\n", + "ergodicity holds.\n", "\n", - "Similar to previous examples, the sample path averages for each state converge to the stationary distribution" + "Hence we expect that $\\hat p_n(x) \\approx \\psi^*(x)$ when $n$ is large.\n", + "\n", + "The next figure shows convergence of $\\hat p_n(x)$ to $\\psi^*(x)$ when $x=1$ and\n", + "$X_0$ is either $0, 1$ or $2$." ] }, { "cell_type": "code", "execution_count": null, - "id": "31299f8c", + "id": "87ea9318", "metadata": {}, "outputs": [], "source": [ - "P = [[0.86, 0.11, 0.03, 0.00, 0.00, 0.00],\n", - " [0.52, 0.33, 0.13, 0.02, 0.00, 0.00],\n", - " [0.12, 0.03, 0.70, 0.11, 0.03, 0.01],\n", - " [0.13, 0.02, 0.35, 0.36, 0.10, 0.04],\n", - " [0.00, 0.00, 0.09, 0.11, 0.55, 0.25],\n", - " [0.00, 0.00, 0.09, 0.15, 0.26, 0.50]]\n", - "\n", + "P = np.array([[0.971, 0.029, 0.000],\n", + " [0.145, 0.778, 0.077],\n", + " [0.000, 0.508, 0.492]])\n", "ts_length = 10_000\n", "mc = qe.MarkovChain(P)\n", "ψ_star = mc.stationary_distributions[0]\n", - "fig, ax = plt.subplots(figsize=(9, 6))\n", - "X = mc.simulate(ts_length)\n", - "# Center the plot at 0\n", - "ax.set_ylim(-0.25, 0.25)\n", - "ax.axhline(0, linestyle='dashed', lw=2, color = 'black', alpha=0.4)\n", - "\n", - "\n", - "for x0 in range(6):\n", - " # Calculate the fraction of time for each state\n", - " X_bar = (X == x0).cumsum() / (1 + np.arange(ts_length, dtype=float))\n", - " ax.plot(X_bar - ψ_star[x0], label=f'$X = {x0+1} $')\n", - " ax.set_xlabel('t')\n", - " ax.set_ylabel(r'fraction of time spent in a state $- \\psi^* (x)$')\n", + "x = 1 # We study convergence to psi^*(x) \n", "\n", + "fig, ax = plt.subplots()\n", + "ax.axhline(ψ_star[x], linestyle='dashed', color='black', \n", + " label = fr'$\\psi^*({x})$')\n", + "# Compute the fraction of time spent in state 0, starting from different x_0s\n", + "for x0 in range(len(P)):\n", + " X = mc.simulate(ts_length, init=x0)\n", + " p_hat = (X == x).cumsum() / np.arange(1, ts_length+1)\n", + " ax.plot(p_hat, label=fr'$\\hat p_n({x})$ when $X_0 = \\, {x0}$')\n", + "ax.set_xlabel('t')\n", + "ax.set_ylabel(fr'$\\hat p_n({x})$')\n", "ax.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "7bc9274c", + "id": "82b93009", "metadata": {}, "source": [ - "### Example 4\n", + "You might like to try changing $x=1$ to either $x=0$ or $x=2$.\n", + "\n", + "In any of these cases, ergodicity will hold.\n", + "\n", + "### Example: a periodic chain\n", "\n", - "Let's look at another example with two states: 0 and 1.\n", + "````{prf:example}\n", + ":label: mc2_ex_pc\n", "\n", + "Let's look at the following example with states 0 and 1:\n", "\n", "$$\n", "P :=\n", @@ -474,139 +347,153 @@ "$$\n", "\n", "\n", - "The diagram of the Markov chain shows that it is **irreducible**" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3e67180f", - "metadata": { - "tags": [ - "hide-input" - ] - }, - "outputs": [], - "source": [ - "dot = Digraph(comment='Graph')\n", - "dot.attr(rankdir='LR')\n", - "dot.node(\"0\")\n", - "dot.node(\"1\")\n", + "The transition graph shows that this model is irreducible.\n", "\n", - "dot.edge(\"0\", \"1\", label=\"1.0\", color='red')\n", - "dot.edge(\"1\", \"0\", label=\"1.0\", color='red')\n", + "```{image} /_static/lecture_specific/markov_chains_II/example4.png\n", + ":name: mc_example4\n", + ":align: center\n", + "```\n", "\n", - "dot" - ] - }, - { - "cell_type": "markdown", - "id": "1a93eaea", - "metadata": { - "user_expressions": [] - }, - "source": [ - "Unlike other Markov chains we have seen before, it has a periodic cycle --- the state cycles between the two states in a regular way.\n", + "Notice that there is a periodic cycle --- the state cycles between the two states in a regular way.\n", + "````\n", + "\n", + "Not surprisingly, this property \n", + "is called [periodicity](https://stats.libretexts.org/Bookshelves/Probability_Theory/Probability_Mathematical_Statistics_and_Stochastic_Processes_(Siegrist)/16%3A_Markov_Processes/16.05%3A_Periodicity_of_Discrete-Time_Chains).\n", "\n", - "This is called [periodicity](https://www.randomservices.org/random/markov/Periodicity.html).\n", + "Nonetheless, the model is irreducible, so ergodicity holds.\n", "\n", - "It is still irreducible, however, so ergodicity holds." + "The following figure illustrates" ] }, { "cell_type": "code", "execution_count": null, - "id": "65584de6", + "id": "9d263649", "metadata": {}, "outputs": [], "source": [ "P = np.array([[0, 1],\n", " [1, 0]])\n", - "ts_length = 10_000\n", + "ts_length = 100\n", "mc = qe.MarkovChain(P)\n", "n = len(P)\n", "fig, axes = plt.subplots(nrows=1, ncols=n)\n", "ψ_star = mc.stationary_distributions[0]\n", "\n", "for i in range(n):\n", - " axes[i].grid()\n", - " axes[i].set_ylim(0.45, 0.55)\n", - " axes[i].axhline(ψ_star[i], linestyle='dashed', lw=2, color = 'black', \n", + " axes[i].axhline(ψ_star[i], linestyle='dashed', lw=2, color='black', \n", " label = fr'$\\psi^*({i})$')\n", " axes[i].set_xlabel('t')\n", - " axes[i].set_ylabel(f'fraction of time spent at {i}')\n", + " axes[i].set_ylabel(fr'$\\hat p_n({i})$')\n", "\n", " # Compute the fraction of time spent, for each x\n", " for x0 in range(n):\n", " # Generate time series starting at different x_0\n", " X = mc.simulate(ts_length, init=x0)\n", - " X_bar = (X == i).cumsum() / (1 + np.arange(ts_length, dtype=float))\n", - " axes[i].plot(X_bar, label=f'$x_0 = \\, {x0} $')\n", + " p_hat = (X == i).cumsum() / np.arange(1, ts_length+1)\n", + " axes[i].plot(p_hat, label=f'$x_0 = \\, {x0} $')\n", "\n", " axes[i].legend()\n", + "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "9afad405", + "id": "2212d87d", "metadata": {}, "source": [ - "This example helps to emphasize the fact that asymptotic stationarity is about the distribution, while ergodicity is about the sample path.\n", + "This example helps to emphasize that asymptotic stationarity is about the distribution, while ergodicity is about the sample path.\n", "\n", "The proportion of time spent in a state can converge to the stationary distribution with periodic chains.\n", "\n", - "However, the distribution at each state does not." - ] - }, - { - "cell_type": "markdown", - "id": "fee64ca2", - "metadata": { - "user_expressions": [] - }, - "source": [ - "### Expectations of geometric sums\n", + "However, the distribution at each state does not.\n", "\n", - "Sometimes we want to compute the mathematical expectation of a geometric sum, such as\n", - "$\\sum_t \\beta^t h(X_t)$.\n", + "### Example: political institutions\n", "\n", - "In view of the preceding discussion, this is\n", + "Let's go back to the political institutions model with six states discussed {ref}`in a previous lecture ` and study ergodicity.\n", "\n", - "$$\n", - "\\mathbb{E} \n", - " \\left[\n", - " \\sum_{j=0}^\\infty \\beta^j h(X_{t+j}) \\mid X_t \n", - " = x\n", - " \\right]\n", - " = x + \\beta (Ph)(x) + \\beta^2 (P^2 h)(x) + \\cdots\n", - "$$\n", "\n", - "By the {ref}`Neumann series lemma `, this sum can be calculated using \n", + "Here's the transition matrix.\n", "\n", "$$\n", - " I + \\beta P + \\beta^2 P^2 + \\cdots = (I - \\beta P)^{-1}\n", + " P :=\n", + " \\begin{bmatrix} \n", + " 0.86 & 0.11 & 0.03 & 0.00 & 0.00 & 0.00 \\\\\n", + " 0.52 & 0.33 & 0.13 & 0.02 & 0.00 & 0.00 \\\\\n", + " 0.12 & 0.03 & 0.70 & 0.11 & 0.03 & 0.01 \\\\\n", + " 0.13 & 0.02 & 0.35 & 0.36 & 0.10 & 0.04 \\\\\n", + " 0.00 & 0.00 & 0.09 & 0.11 & 0.55 & 0.25 \\\\\n", + " 0.00 & 0.00 & 0.09 & 0.15 & 0.26 & 0.50\n", + " \\end{bmatrix} \n", "$$\n", "\n", "\n", + "The {ref}`graph ` for the chain shows all states are reachable,\n", + "indicating that this chain is irreducible.\n", + "\n", + "In the next figure, we visualize the difference $\\hat p_n(x) - \\psi^* (x)$ for each state $x$.\n", + "\n", + "Unlike the previous figure, $X_0$ is held fixed." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e9d431f2", + "metadata": {}, + "outputs": [], + "source": [ + "P = [[0.86, 0.11, 0.03, 0.00, 0.00, 0.00],\n", + " [0.52, 0.33, 0.13, 0.02, 0.00, 0.00],\n", + " [0.12, 0.03, 0.70, 0.11, 0.03, 0.01],\n", + " [0.13, 0.02, 0.35, 0.36, 0.10, 0.04],\n", + " [0.00, 0.00, 0.09, 0.11, 0.55, 0.25],\n", + " [0.00, 0.00, 0.09, 0.15, 0.26, 0.50]]\n", + "\n", + "ts_length = 2500\n", + "mc = qe.MarkovChain(P)\n", + "ψ_star = mc.stationary_distributions[0]\n", + "fig, ax = plt.subplots()\n", + "X = mc.simulate(ts_length, random_state=1)\n", + "# Center the plot at 0\n", + "ax.axhline(linestyle='dashed', lw=2, color='black')\n", + "\n", + "\n", + "for x0 in range(len(P)):\n", + " # Calculate the fraction of time for each state\n", + " p_hat = (X == x0).cumsum() / np.arange(1, ts_length+1)\n", + " ax.plot(p_hat - ψ_star[x0], label=f'$x = {x0+1} $')\n", + " ax.set_xlabel('t')\n", + " ax.set_ylabel(r'$\\hat p_n(x) - \\psi^* (x)$')\n", + "\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "54285084", + "metadata": {}, + "source": [ "## Exercises\n", "\n", "````{exercise}\n", ":label: mc_ex1\n", "\n", - "Benhabib el al. {cite}`benhabib_wealth_2019` estimated that the transition matrix for social mobility as the following\n", + "Benhabib et al. {cite}`benhabib_wealth_2019` estimated that the transition matrix for social mobility as the following\n", "\n", "$$\n", "P:=\n", - "\\begin{bmatrix} \n", - "0.222 & 0.222 & 0.215 & 0.187 & 0.081 & 0.038 & 0.029 & 0.006 \\\\\n", - "0.221 & 0.22 & 0.215 & 0.188 & 0.082 & 0.039 & 0.029 & 0.006 \\\\\n", - "0.207 & 0.209 & 0.21 & 0.194 & 0.09 & 0.046 & 0.036 & 0.008 \\\\ \n", - "0.198 & 0.201 & 0.207 & 0.198 & 0.095 & 0.052 & 0.04 & 0.009 \\\\ \n", - "0.175 & 0.178 & 0.197 & 0.207 & 0.11 & 0.067 & 0.054 & 0.012 \\\\ \n", - "0.182 & 0.184 & 0.2 & 0.205 & 0.106 & 0.062 & 0.05 & 0.011 \\\\ \n", - "0.123 & 0.125 & 0.166 & 0.216 & 0.141 & 0.114 & 0.094 & 0.021 \\\\ \n", - "0.084 & 0.084 & 0.142 & 0.228 & 0.17 & 0.143 & 0.121 & 0.028\n", + " \\begin{bmatrix} \n", + " 0.222 & 0.222 & 0.215 & 0.187 & 0.081 & 0.038 & 0.029 & 0.006 \\\\\n", + " 0.221 & 0.22 & 0.215 & 0.188 & 0.082 & 0.039 & 0.029 & 0.006 \\\\\n", + " 0.207 & 0.209 & 0.21 & 0.194 & 0.09 & 0.046 & 0.036 & 0.008 \\\\ \n", + " 0.198 & 0.201 & 0.207 & 0.198 & 0.095 & 0.052 & 0.04 & 0.009 \\\\ \n", + " 0.175 & 0.178 & 0.197 & 0.207 & 0.11 & 0.067 & 0.054 & 0.012 \\\\ \n", + " 0.182 & 0.184 & 0.2 & 0.205 & 0.106 & 0.062 & 0.05 & 0.011 \\\\ \n", + " 0.123 & 0.125 & 0.166 & 0.216 & 0.141 & 0.114 & 0.094 & 0.021 \\\\ \n", + " 0.084 & 0.084 & 0.142 & 0.228 & 0.17 & 0.143 & 0.121 & 0.028\n", "\\end{bmatrix} \n", "$$\n", "\n", @@ -634,26 +521,24 @@ "codes_B = ('1','2','3','4','5','6','7','8')\n", "```\n", "\n", - "In this exercise,\n", - "\n", - "1. show this process is asymptotically stationary and calculate the stationary distribution using simulations.\n", + "1. Show this process is asymptotically stationary and calculate an approximation to the stationary distribution.\n", "\n", - "1. use simulations to demonstrate ergodicity of this process.\n", + "1. Use simulations to illustrate ergodicity.\n", "\n", "````\n", "\n", "```{solution-start} mc_ex1\n", ":class: dropdown\n", "```\n", - "Solution 1:\n", + "Part 1:\n", "\n", - "Use the technique we learnt before, we can take the power of the transition matrix" + "One option is to take the power of the transition matrix." ] }, { "cell_type": "code", "execution_count": null, - "id": "54c8d528", + "id": "e017a5ed", "metadata": {}, "outputs": [], "source": [ @@ -674,16 +559,17 @@ }, { "cell_type": "markdown", - "id": "ee6c0e75", + "id": "a7c41cbc", "metadata": {}, "source": [ - "We find again that rows of the transition matrix converge to the stationary distribution" + "For this model, rows of $P^n$ converge to the stationary distribution as $n \\to\n", + "\\infty$:" ] }, { "cell_type": "code", "execution_count": null, - "id": "43c66237", + "id": "f2483c35", "metadata": {}, "outputs": [], "source": [ @@ -694,32 +580,31 @@ }, { "cell_type": "markdown", - "id": "2339cad4", + "id": "60b11531", "metadata": {}, "source": [ - "Solution 2:" + "Part 2:" ] }, { "cell_type": "code", "execution_count": null, - "id": "f45a6f47", + "id": "f047e864", "metadata": {}, "outputs": [], "source": [ "ts_length = 1000\n", "mc = qe.MarkovChain(P)\n", - "fig, ax = plt.subplots(figsize=(9, 6))\n", - "X = mc.simulate(ts_length)\n", - "ax.set_ylim(-0.25, 0.25)\n", - "ax.axhline(0, linestyle='dashed', lw=2, color = 'black', alpha=0.4)\n", + "fig, ax = plt.subplots()\n", + "X = mc.simulate(ts_length, random_state=1)\n", + "ax.axhline(linestyle='dashed', lw=2, color='black')\n", "\n", - "for x0 in range(8):\n", + "for x0 in range(len(P)):\n", " # Calculate the fraction of time for each worker\n", - " X_bar = (X == x0).cumsum() / (1 + np.arange(ts_length, dtype=float))\n", - " ax.plot(X_bar - ψ_star[x0], label=f'$X = {x0+1} $')\n", + " p_hat = (X == x0).cumsum() / np.arange(1, ts_length+1)\n", + " ax.plot(p_hat - ψ_star[x0], label=f'$x = {x0+1} $')\n", " ax.set_xlabel('t')\n", - " ax.set_ylabel(r'fraction of time spent in a state $- \\psi^* (x)$')\n", + " ax.set_ylabel(r'$\\hat p_n(x) - \\psi^* (x)$')\n", "\n", "ax.legend()\n", "plt.show()" @@ -727,10 +612,11 @@ }, { "cell_type": "markdown", - "id": "a5ac768f", + "id": "0c544b6d", "metadata": {}, "source": [ - "Note that the fraction of time spent at each state quickly converges to the probability assigned to that state by the stationary distribution.\n", + "Note that the fraction of time spent at each state converges to the probability\n", + "assigned to that state by the stationary distribution.\n", "\n", "```{solution-end}\n", "```\n", @@ -760,7 +646,7 @@ "employment, then $\\bar X_m \\to p$ as $m \\to \\infty$, where\n", "\n", "$$\n", - "\\bar X_m := \\frac{1}{m} \\sum_{t = 1}^m \\mathbf{1}\\{X_t = 0\\}\n", + "\\bar X_m := \\frac{1}{m} \\sum_{t = 1}^m \\mathbb{1}\\{X_t = 0\\}\n", "$$\n", "\n", "This exercise asks you to illustrate convergence by computing\n", @@ -789,41 +675,38 @@ { "cell_type": "code", "execution_count": null, - "id": "3f9ddd4d", + "id": "e769b903", "metadata": {}, "outputs": [], "source": [ "α = β = 0.1\n", - "ts_length = 10000\n", + "ts_length = 3000\n", "p = β / (α + β)\n", "\n", "P = ((1 - α, α), # Careful: P and p are distinct\n", " ( β, 1 - β))\n", "mc = qe.MarkovChain(P)\n", "\n", - "fig, ax = plt.subplots(figsize=(9, 6))\n", - "ax.set_ylim(-0.25, 0.25)\n", - "ax.grid()\n", - "ax.hlines(0, 0, ts_length, lw=2, alpha=0.6) # Horizonal line at zero\n", + "fig, ax = plt.subplots()\n", + "ax.axhline(linestyle='dashed', lw=2, color='black')\n", "\n", - "for x0, col in ((0, 'blue'), (1, 'green')):\n", + "for x0 in range(len(P)):\n", " # Generate time series for worker that starts at x0\n", " X = mc.simulate(ts_length, init=x0)\n", " # Compute fraction of time spent unemployed, for each n\n", - " X_bar = (X == 0).cumsum() / (1 + np.arange(ts_length, dtype=float))\n", + " X_bar = (X == 0).cumsum() / np.arange(1, ts_length+1)\n", " # Plot\n", - " ax.fill_between(range(ts_length), np.zeros(ts_length), X_bar - p, color=col, alpha=0.1)\n", - " ax.plot(X_bar - p, color=col, label=f'$X_0 = \\, {x0} $')\n", - " # Overlay in black--make lines clearer\n", - " ax.plot(X_bar - p, 'k-', alpha=0.6)\n", - "\n", - "ax.legend(loc='upper right')\n", + " ax.plot(X_bar - p, label=f'$x_0 = \\, {x0} $')\n", + " ax.set_xlabel('t')\n", + " ax.set_ylabel(r'$\\bar X_m - \\psi^* (x)$')\n", + " \n", + "ax.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "68d4ccd3", + "id": "82143e6d", "metadata": {}, "source": [ "```{solution-end}\n", @@ -834,11 +717,12 @@ "\n", "In `quantecon` library, irreducibility is tested by checking whether the chain forms a [strongly connected component](https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.components.is_strongly_connected.html).\n", "\n", - "However, another way to verify irreducibility is by checking whether $A$ satisfies the following statement:\n", + "Another way to test irreducibility is via the following statement:\n", "\n", - "Assume A is an $n \\times n$ $A$ is irreducible if and only if $\\sum_{k=0}^{n-1}A^k$ is a positive matrix.\n", + "The $n \\times n$ matrix $A$ is irreducible if and only if $\\sum_{k=0}^{n-1}A^k$\n", + "is a strictly positive matrix.\n", "\n", - "(see more: {cite}`zhao_power_2012` and [here](https://math.stackexchange.com/questions/3336616/how-to-prove-this-matrix-is-a-irreducible-matrix))\n", + "(see, e.g., {cite}`zhao_power_2012` and [this StackExchange post](https://math.stackexchange.com/questions/3336616/how-to-prove-this-matrix-is-a-irreducible-matrix))\n", "\n", "Based on this claim, write a function to test irreducibility.\n", "\n", @@ -852,7 +736,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a6ccdf65", + "id": "c765a48d", "metadata": {}, "outputs": [], "source": [ @@ -864,10 +748,18 @@ " return np.all(result > 0)" ] }, + { + "cell_type": "markdown", + "id": "e1eea47b", + "metadata": {}, + "source": [ + "Let's try it." + ] + }, { "cell_type": "code", "execution_count": null, - "id": "e1091f95", + "id": "2e508bde", "metadata": {}, "outputs": [], "source": [ @@ -887,7 +779,7 @@ }, { "cell_type": "markdown", - "id": "9d5a7a4f", + "id": "8be27b84", "metadata": {}, "source": [ "```{solution-end}\n", @@ -896,12 +788,49 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.16.1" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 12, + 21, + 25, + 49, + 53, + 102, + 109, + 127, + 134, + 251, + 272, + 311, + 336, + 371, + 397, + 457, + 471, + 476, + 480, + 484, + 500, + 558, + 582, + 607, + 614, + 618, + 631 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/markov_chains_II.md b/book/_build/html/_sources/markov_chains_II.md new file mode 100644 index 0000000..c8ceb04 --- /dev/null +++ b/book/_build/html/_sources/markov_chains_II.md @@ -0,0 +1,634 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.16.1 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Markov Chains: Irreducibility and Ergodicity + +```{index} single: Markov Chains: Irreducibility and Ergodicity +``` + +In addition to what's in Anaconda, this lecture will need the following libraries: + +```{code-cell} ipython3 +:tags: [hide-output] + +%pip install quantecon +``` + +## Overview + +This lecture continues on from our {doc}`earlier lecture on Markov chains +`. + + +Specifically, we will introduce the concepts of irreducibility and ergodicity, and see how they connect to stationarity. + +Irreducibility describes the ability of a Markov chain to move between any two states in the system. + +Ergodicity is a sample path property that describes the behavior of the system over long periods of time. + +As we will see, + +* an irreducible Markov chain guarantees the existence of a unique stationary distribution, while +* an ergodic Markov chain generates time series that satisfy a version of the + law of large numbers. + +Together, these concepts provide a foundation for understanding the long-term behavior of Markov chains. + +Let's start with some standard imports: + +```{code-cell} ipython3 +import matplotlib.pyplot as plt +import quantecon as qe +import numpy as np +``` + +(mc_irreducible)= +## Irreducibility + + +To explain irreducibility, let's take $P$ to be a fixed stochastic matrix. + +State $x$ is called **accessible** (or **reachable**) from state $y$ if $P^t(x,y)>0$ for some integer $t\ge 0$. + +Two states, $x$ and $y$, are said to **communicate** if $x$ and $y$ are accessible from each other. + +In view of our discussion {ref}`above `, this means precisely +that + +* state $x$ can eventually be reached from state $y$, and +* state $y$ can eventually be reached from state $x$ + +The stochastic matrix $P$ is called **irreducible** if all states communicate; +that is, if $x$ and $y$ communicate for all $(x, y)$ in $S \times S$. + +````{prf:example} +:label: mc2_ex_ir +For example, consider the following transition probabilities for wealth of a +fictitious set of households + +```{image} /_static/lecture_specific/markov_chains_II/Irre_1.png +:name: mc_irre1 +:align: center +``` + +We can translate this into a stochastic matrix, putting zeros where +there's no edge between nodes + +$$ +P := +\begin{bmatrix} + 0.9 & 0.1 & 0 \\ + 0.4 & 0.4 & 0.2 \\ + 0.1 & 0.1 & 0.8 +\end{bmatrix} +$$ + +It's clear from the graph that this stochastic matrix is irreducible: we can eventually +reach any state from any other state. +```` + +We can also test this using [QuantEcon.py](http://quantecon.org/quantecon-py)'s MarkovChain class + +```{code-cell} ipython3 +P = [[0.9, 0.1, 0.0], + [0.4, 0.4, 0.2], + [0.1, 0.1, 0.8]] + +mc = qe.MarkovChain(P, ('poor', 'middle', 'rich')) +mc.is_irreducible +``` + +````{prf:example} +:label: mc2_ex_pf + +Here's a more pessimistic scenario in which poor people remain poor forever + +```{image} /_static/lecture_specific/markov_chains_II/Irre_2.png +:name: mc_irre2 +:align: center +``` + +This stochastic matrix is not irreducible since, for example, rich is not +accessible from poor. +```` + +Let's confirm this + +```{code-cell} ipython3 +P = [[1.0, 0.0, 0.0], + [0.1, 0.8, 0.1], + [0.0, 0.2, 0.8]] + +mc = qe.MarkovChain(P, ('poor', 'middle', 'rich')) +mc.is_irreducible +``` + +It might be clear to you already that irreducibility is going to be important +in terms of long-run outcomes. + +For example, poverty is a life sentence in the second graph but not the first. + +We'll come back to this a bit later. + +### Irreducibility and stationarity + +We discussed uniqueness of stationary distributions in our earlier lecture {doc}`markov_chains_I`. + +There we {prf:ref}`stated ` that uniqueness holds when the transition matrix is everywhere positive. + +In fact irreducibility is sufficient: + +```{prf:theorem} +:label: mc_conv_thm + +If $P$ is irreducible, then $P$ has exactly one stationary +distribution. +``` + +For proof, see Chapter 4 of {cite}`sargent2023economic` or +Theorem 5.2 of {cite}`haggstrom2002finite`. + + +(ergodicity)= +## Ergodicity + + +Under irreducibility, yet another important result obtains: + +````{prf:theorem} +:label: stationary + +If $P$ is irreducible and $\psi^*$ is the unique stationary +distribution, then, for all $x \in S$, + +```{math} +:label: llnfmc0 + +\frac{1}{m} \sum_{t = 1}^m \mathbb{1}\{X_t = x\} \to \psi^*(x) + \quad \text{as } m \to \infty +``` + +```` + +Here + +* $\{X_t\}$ is a Markov chain with stochastic matrix $P$ and initial distribution $\psi_0$ + +* $\mathbb{1} \{X_t = x\} = 1$ if $X_t = x$ and zero otherwise. + +The result in [theorem 4.3](llnfmc0) is sometimes called **ergodicity**. + +The theorem tells us that the fraction of time the chain spends at state $x$ +converges to $\psi^*(x)$ as time goes to infinity. + +(new_interp_sd)= +This gives us another way to interpret the stationary distribution (provided irreducibility holds). + +Importantly, the result is valid for any choice of $\psi_0$. + +The theorem is related to {doc}`the law of large numbers `. + +It tells us that, in some settings, the law of large numbers sometimes holds even when the +sequence of random variables is [not IID](iid_violation). + + +(mc_eg1-2)= +### Example: ergodicity and unemployment + +Recall our cross-sectional interpretation of the employment/unemployment model {ref}`discussed before `. + +Assume that $\alpha \in (0,1)$ and $\beta \in (0,1)$, so that irreducibility holds. + +We saw that the stationary distribution is $(p, 1-p)$, where + +$$ +p = \frac{\beta}{\alpha + \beta} +$$ + +In the cross-sectional interpretation, this is the fraction of people unemployed. + +In view of our latest (ergodicity) result, it is also the fraction of time that a single worker can expect to spend unemployed. + +Thus, in the long run, cross-sectional averages for a population and time-series averages for a given person coincide. + +This is one aspect of the concept of ergodicity. + + +(ergo)= +### Example: Hamilton dynamics + +Another example is the Hamilton dynamics we {ref}`discussed before `. + +Let $\{X_t\}$ be a sample path generated by these dynamics. + +Let's denote the fraction of time spent in state $x$ over the period $t=1, +\ldots, n$ by $\hat p_n(x)$, so that + +$$ + \hat p_n(x) := \frac{1}{n} \sum_{t = 1}^n \mathbb{1}\{X_t = x\} + \qquad (x \in \{0, 1, 2\}) +$$ + + +The {ref}`graph ` of the Markov chain shows it is irreducible, so +ergodicity holds. + +Hence we expect that $\hat p_n(x) \approx \psi^*(x)$ when $n$ is large. + +The next figure shows convergence of $\hat p_n(x)$ to $\psi^*(x)$ when $x=1$ and +$X_0$ is either $0, 1$ or $2$. + +```{code-cell} ipython3 +P = np.array([[0.971, 0.029, 0.000], + [0.145, 0.778, 0.077], + [0.000, 0.508, 0.492]]) +ts_length = 10_000 +mc = qe.MarkovChain(P) +ψ_star = mc.stationary_distributions[0] +x = 1 # We study convergence to psi^*(x) + +fig, ax = plt.subplots() +ax.axhline(ψ_star[x], linestyle='dashed', color='black', + label = fr'$\psi^*({x})$') +# Compute the fraction of time spent in state 0, starting from different x_0s +for x0 in range(len(P)): + X = mc.simulate(ts_length, init=x0) + p_hat = (X == x).cumsum() / np.arange(1, ts_length+1) + ax.plot(p_hat, label=fr'$\hat p_n({x})$ when $X_0 = \, {x0}$') +ax.set_xlabel('t') +ax.set_ylabel(fr'$\hat p_n({x})$') +ax.legend() +plt.show() +``` + +You might like to try changing $x=1$ to either $x=0$ or $x=2$. + +In any of these cases, ergodicity will hold. + +### Example: a periodic chain + +````{prf:example} +:label: mc2_ex_pc + +Let's look at the following example with states 0 and 1: + +$$ +P := +\begin{bmatrix} + 0 & 1\\ + 1 & 0\\ +\end{bmatrix} +$$ + + +The transition graph shows that this model is irreducible. + +```{image} /_static/lecture_specific/markov_chains_II/example4.png +:name: mc_example4 +:align: center +``` + +Notice that there is a periodic cycle --- the state cycles between the two states in a regular way. +```` + +Not surprisingly, this property +is called [periodicity](https://stats.libretexts.org/Bookshelves/Probability_Theory/Probability_Mathematical_Statistics_and_Stochastic_Processes_(Siegrist)/16%3A_Markov_Processes/16.05%3A_Periodicity_of_Discrete-Time_Chains). + +Nonetheless, the model is irreducible, so ergodicity holds. + +The following figure illustrates + +```{code-cell} ipython3 +P = np.array([[0, 1], + [1, 0]]) +ts_length = 100 +mc = qe.MarkovChain(P) +n = len(P) +fig, axes = plt.subplots(nrows=1, ncols=n) +ψ_star = mc.stationary_distributions[0] + +for i in range(n): + axes[i].axhline(ψ_star[i], linestyle='dashed', lw=2, color='black', + label = fr'$\psi^*({i})$') + axes[i].set_xlabel('t') + axes[i].set_ylabel(fr'$\hat p_n({i})$') + + # Compute the fraction of time spent, for each x + for x0 in range(n): + # Generate time series starting at different x_0 + X = mc.simulate(ts_length, init=x0) + p_hat = (X == i).cumsum() / np.arange(1, ts_length+1) + axes[i].plot(p_hat, label=f'$x_0 = \, {x0} $') + + axes[i].legend() +plt.tight_layout() +plt.show() +``` + +This example helps to emphasize that asymptotic stationarity is about the distribution, while ergodicity is about the sample path. + +The proportion of time spent in a state can converge to the stationary distribution with periodic chains. + +However, the distribution at each state does not. + +### Example: political institutions + +Let's go back to the political institutions model with six states discussed {ref}`in a previous lecture ` and study ergodicity. + + +Here's the transition matrix. + +$$ + P := + \begin{bmatrix} + 0.86 & 0.11 & 0.03 & 0.00 & 0.00 & 0.00 \\ + 0.52 & 0.33 & 0.13 & 0.02 & 0.00 & 0.00 \\ + 0.12 & 0.03 & 0.70 & 0.11 & 0.03 & 0.01 \\ + 0.13 & 0.02 & 0.35 & 0.36 & 0.10 & 0.04 \\ + 0.00 & 0.00 & 0.09 & 0.11 & 0.55 & 0.25 \\ + 0.00 & 0.00 & 0.09 & 0.15 & 0.26 & 0.50 + \end{bmatrix} +$$ + + +The {ref}`graph ` for the chain shows all states are reachable, +indicating that this chain is irreducible. + +In the next figure, we visualize the difference $\hat p_n(x) - \psi^* (x)$ for each state $x$. + +Unlike the previous figure, $X_0$ is held fixed. + +```{code-cell} ipython3 +P = [[0.86, 0.11, 0.03, 0.00, 0.00, 0.00], + [0.52, 0.33, 0.13, 0.02, 0.00, 0.00], + [0.12, 0.03, 0.70, 0.11, 0.03, 0.01], + [0.13, 0.02, 0.35, 0.36, 0.10, 0.04], + [0.00, 0.00, 0.09, 0.11, 0.55, 0.25], + [0.00, 0.00, 0.09, 0.15, 0.26, 0.50]] + +ts_length = 2500 +mc = qe.MarkovChain(P) +ψ_star = mc.stationary_distributions[0] +fig, ax = plt.subplots() +X = mc.simulate(ts_length, random_state=1) +# Center the plot at 0 +ax.axhline(linestyle='dashed', lw=2, color='black') + + +for x0 in range(len(P)): + # Calculate the fraction of time for each state + p_hat = (X == x0).cumsum() / np.arange(1, ts_length+1) + ax.plot(p_hat - ψ_star[x0], label=f'$x = {x0+1} $') + ax.set_xlabel('t') + ax.set_ylabel(r'$\hat p_n(x) - \psi^* (x)$') + +ax.legend() +plt.show() +``` + +## Exercises + +````{exercise} +:label: mc_ex1 + +Benhabib et al. {cite}`benhabib_wealth_2019` estimated that the transition matrix for social mobility as the following + +$$ +P:= + \begin{bmatrix} + 0.222 & 0.222 & 0.215 & 0.187 & 0.081 & 0.038 & 0.029 & 0.006 \\ + 0.221 & 0.22 & 0.215 & 0.188 & 0.082 & 0.039 & 0.029 & 0.006 \\ + 0.207 & 0.209 & 0.21 & 0.194 & 0.09 & 0.046 & 0.036 & 0.008 \\ + 0.198 & 0.201 & 0.207 & 0.198 & 0.095 & 0.052 & 0.04 & 0.009 \\ + 0.175 & 0.178 & 0.197 & 0.207 & 0.11 & 0.067 & 0.054 & 0.012 \\ + 0.182 & 0.184 & 0.2 & 0.205 & 0.106 & 0.062 & 0.05 & 0.011 \\ + 0.123 & 0.125 & 0.166 & 0.216 & 0.141 & 0.114 & 0.094 & 0.021 \\ + 0.084 & 0.084 & 0.142 & 0.228 & 0.17 & 0.143 & 0.121 & 0.028 +\end{bmatrix} +$$ + +where each state 1 to 8 corresponds to a percentile of wealth shares + +$$ +0-20 \%, 20-40 \%, 40-60 \%, 60-80 \%, 80-90 \%, 90-95 \%, 95-99 \%, 99-100 \% +$$ + +The matrix is recorded as `P` below + +```python +P = [ + [0.222, 0.222, 0.215, 0.187, 0.081, 0.038, 0.029, 0.006], + [0.221, 0.22, 0.215, 0.188, 0.082, 0.039, 0.029, 0.006], + [0.207, 0.209, 0.21, 0.194, 0.09, 0.046, 0.036, 0.008], + [0.198, 0.201, 0.207, 0.198, 0.095, 0.052, 0.04, 0.009], + [0.175, 0.178, 0.197, 0.207, 0.11, 0.067, 0.054, 0.012], + [0.182, 0.184, 0.2, 0.205, 0.106, 0.062, 0.05, 0.011], + [0.123, 0.125, 0.166, 0.216, 0.141, 0.114, 0.094, 0.021], + [0.084, 0.084, 0.142, 0.228, 0.17, 0.143, 0.121, 0.028] + ] + +P = np.array(P) +codes_B = ('1','2','3','4','5','6','7','8') +``` + +1. Show this process is asymptotically stationary and calculate an approximation to the stationary distribution. + +1. Use simulations to illustrate ergodicity. + +```` + +```{solution-start} mc_ex1 +:class: dropdown +``` +Part 1: + +One option is to take the power of the transition matrix. + +```{code-cell} ipython3 +P = [[0.222, 0.222, 0.215, 0.187, 0.081, 0.038, 0.029, 0.006], + [0.221, 0.22, 0.215, 0.188, 0.082, 0.039, 0.029, 0.006], + [0.207, 0.209, 0.21, 0.194, 0.09, 0.046, 0.036, 0.008], + [0.198, 0.201, 0.207, 0.198, 0.095, 0.052, 0.04, 0.009], + [0.175, 0.178, 0.197, 0.207, 0.11, 0.067, 0.054, 0.012], + [0.182, 0.184, 0.2, 0.205, 0.106, 0.062, 0.05, 0.011], + [0.123, 0.125, 0.166, 0.216, 0.141, 0.114, 0.094, 0.021], + [0.084, 0.084, 0.142, 0.228, 0.17, 0.143, 0.121, 0.028]] + +P = np.array(P) +codes_B = ('1','2','3','4','5','6','7','8') + +np.linalg.matrix_power(P, 10) +``` + +For this model, rows of $P^n$ converge to the stationary distribution as $n \to +\infty$: + +```{code-cell} ipython3 +mc = qe.MarkovChain(P) +ψ_star = mc.stationary_distributions[0] +ψ_star +``` + +Part 2: + +```{code-cell} ipython3 +ts_length = 1000 +mc = qe.MarkovChain(P) +fig, ax = plt.subplots() +X = mc.simulate(ts_length, random_state=1) +ax.axhline(linestyle='dashed', lw=2, color='black') + +for x0 in range(len(P)): + # Calculate the fraction of time for each worker + p_hat = (X == x0).cumsum() / np.arange(1, ts_length+1) + ax.plot(p_hat - ψ_star[x0], label=f'$x = {x0+1} $') + ax.set_xlabel('t') + ax.set_ylabel(r'$\hat p_n(x) - \psi^* (x)$') + +ax.legend() +plt.show() +``` + +Note that the fraction of time spent at each state converges to the probability +assigned to that state by the stationary distribution. + +```{solution-end} +``` + + +```{exercise} +:label: mc_ex2 + +According to the discussion {ref}`above `, if a worker's employment dynamics obey the stochastic matrix + +$$ +P := +\begin{bmatrix} +1 - \alpha & \alpha \\ +\beta & 1 - \beta +\end{bmatrix} +$$ + +with $\alpha \in (0,1)$ and $\beta \in (0,1)$, then, in the long run, the fraction +of time spent unemployed will be + +$$ +p := \frac{\beta}{\alpha + \beta} +$$ + +In other words, if $\{X_t\}$ represents the Markov chain for +employment, then $\bar X_m \to p$ as $m \to \infty$, where + +$$ +\bar X_m := \frac{1}{m} \sum_{t = 1}^m \mathbb{1}\{X_t = 0\} +$$ + +This exercise asks you to illustrate convergence by computing +$\bar X_m$ for large $m$ and checking that +it is close to $p$. + +You will see that this statement is true regardless of the choice of initial +condition or the values of $\alpha, \beta$, provided both lie in +$(0, 1)$. + +The result should be similar to the plot we plotted [here](ergo) +``` + +```{solution-start} mc_ex2 +:class: dropdown +``` + +We will address this exercise graphically. + +The plots show the time series of $\bar X_m - p$ for two initial +conditions. + +As $m$ gets large, both series converge to zero. + +```{code-cell} ipython3 +α = β = 0.1 +ts_length = 3000 +p = β / (α + β) + +P = ((1 - α, α), # Careful: P and p are distinct + ( β, 1 - β)) +mc = qe.MarkovChain(P) + +fig, ax = plt.subplots() +ax.axhline(linestyle='dashed', lw=2, color='black') + +for x0 in range(len(P)): + # Generate time series for worker that starts at x0 + X = mc.simulate(ts_length, init=x0) + # Compute fraction of time spent unemployed, for each n + X_bar = (X == 0).cumsum() / np.arange(1, ts_length+1) + # Plot + ax.plot(X_bar - p, label=f'$x_0 = \, {x0} $') + ax.set_xlabel('t') + ax.set_ylabel(r'$\bar X_m - \psi^* (x)$') + +ax.legend() +plt.show() +``` + +```{solution-end} +``` + +```{exercise} +:label: mc_ex3 + +In `quantecon` library, irreducibility is tested by checking whether the chain forms a [strongly connected component](https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.components.is_strongly_connected.html). + +Another way to test irreducibility is via the following statement: + +The $n \times n$ matrix $A$ is irreducible if and only if $\sum_{k=0}^{n-1}A^k$ +is a strictly positive matrix. + +(see, e.g., {cite}`zhao_power_2012` and [this StackExchange post](https://math.stackexchange.com/questions/3336616/how-to-prove-this-matrix-is-a-irreducible-matrix)) + +Based on this claim, write a function to test irreducibility. + +``` + +```{solution-start} mc_ex3 +:class: dropdown +``` + +```{code-cell} ipython3 +def is_irreducible(P): + n = len(P) + result = np.zeros((n, n)) + for i in range(n): + result += np.linalg.matrix_power(P, i) + return np.all(result > 0) +``` + +Let's try it. + +```{code-cell} ipython3 +P1 = np.array([[0, 1], + [1, 0]]) +P2 = np.array([[1.0, 0.0, 0.0], + [0.1, 0.8, 0.1], + [0.0, 0.2, 0.8]]) +P3 = np.array([[0.971, 0.029, 0.000], + [0.145, 0.778, 0.077], + [0.000, 0.508, 0.492]]) + +for P in (P1, P2, P3): + result = lambda P: 'irreducible' if is_irreducible(P) else 'reducible' + print(f'{P}: {result(P)}') +``` + +```{solution-end} +``` diff --git a/book/_build/html/_sources/mle.ipynb b/book/_build/html/_sources/mle.ipynb new file mode 100644 index 0000000..0833564 --- /dev/null +++ b/book/_build/html/_sources/mle.ipynb @@ -0,0 +1,845 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "36353d21", + "metadata": {}, + "source": [ + "# Maximum Likelihood Estimation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "61f73822", + "metadata": {}, + "outputs": [], + "source": [ + "from scipy.stats import lognorm, pareto, expon\n", + "import numpy as np\n", + "from scipy.integrate import quad\n", + "import matplotlib.pyplot as plt\n", + "import pandas as pd\n", + "from math import exp" + ] + }, + { + "cell_type": "markdown", + "id": "689dc197", + "metadata": {}, + "source": [ + "## Introduction\n", + "\n", + "Consider a situation where a policymaker is trying to estimate how much revenue\n", + "a proposed wealth tax will raise.\n", + "\n", + "The proposed tax is \n", + "\n", + "$$\n", + " h(w) = \n", + " \\begin{cases}\n", + " a w & \\text{if } w \\leq \\bar w \\\\\n", + " a \\bar{w} + b (w-\\bar{w}) & \\text{if } w > \\bar w \n", + " \\end{cases}\n", + "$$ \n", + "\n", + "where $w$ is wealth.\n", + "\n", + "```{prf:example}\n", + ":label: mle_ex_wt\n", + "\n", + "For example, if $a = 0.05$, $b = 0.1$, and $\\bar w = 2.5$, this means \n", + "\n", + "* a 5% tax on wealth up to 2.5 and \n", + "* a 10% tax on wealth in excess of 2.5.\n", + "\n", + "The unit is 100,000, so $w= 2.5$ means 250,000 dollars.\n", + "```\n", + "Let's go ahead and define $h$:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f4d5cd5e", + "metadata": {}, + "outputs": [], + "source": [ + "def h(w, a=0.05, b=0.1, w_bar=2.5):\n", + " if w <= w_bar:\n", + " return a * w\n", + " else:\n", + " return a * w_bar + b * (w - w_bar)" + ] + }, + { + "cell_type": "markdown", + "id": "9987b41b", + "metadata": {}, + "source": [ + "For a population of size $N$, where individual $i$ has wealth $w_i$, total revenue raised by \n", + "the tax will be \n", + "\n", + "$$\n", + " T = \\sum_{i=1}^{N} h(w_i)\n", + "$$\n", + "\n", + "We wish to calculate this quantity.\n", + "\n", + "The problem we face is that, in most countries, wealth is not observed for all individuals.\n", + "\n", + "Collecting and maintaining accurate wealth data for all individuals or households in a country\n", + "is just too hard.\n", + "\n", + "So let's suppose instead that we obtain a sample $w_1, w_2, \\cdots, w_n$ telling us the wealth of $n$ randomly selected individuals.\n", + "\n", + "For our exercise we are going to use a sample of $n = 10,000$ observations from wealth data in the US in 2016." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d2b8bf4d", + "metadata": {}, + "outputs": [], + "source": [ + "n = 10_000" + ] + }, + { + "cell_type": "markdown", + "id": "04e9fe5f", + "metadata": {}, + "source": [ + "The data is derived from the\n", + "[Survey of Consumer Finances](https://en.wikipedia.org/wiki/Survey_of_Consumer_Finances) (SCF).\n", + "\n", + "\n", + "The following code imports this data and reads it into an array called `sample`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "87585a3a", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "url = 'https://media.githubusercontent.com/media/QuantEcon/high_dim_data/update_scf_noweights/SCF_plus/SCF_plus_mini_no_weights.csv'\n", + "df = pd.read_csv(url)\n", + "df = df.dropna()\n", + "df = df[df['year'] == 2016]\n", + "df = df.loc[df['n_wealth'] > 1 ] #restrcting data to net worth > 1\n", + "rv = df['n_wealth'].sample(n=n, random_state=1234)\n", + "rv = rv.to_numpy() / 100_000\n", + "sample = rv" + ] + }, + { + "cell_type": "markdown", + "id": "73d2ccc1", + "metadata": {}, + "source": [ + "Let's histogram this sample." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c0bfffe5", + "metadata": {}, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "ax.set_xlim(-1, 20)\n", + "density, edges = np.histogram(sample, bins=5000, density=True)\n", + "prob = density * np.diff(edges)\n", + "plt.stairs(prob, edges, fill=True, alpha=0.8, label=r\"unit: $\\$100,000$\")\n", + "plt.ylabel(\"prob\")\n", + "plt.xlabel(\"net wealth\")\n", + "plt.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "10e5f054", + "metadata": {}, + "source": [ + "The histogram shows that many people have very low wealth and a few people have\n", + "very high wealth.\n", + "\n", + "\n", + "We will take the full population size to be" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "05a2069e", + "metadata": {}, + "outputs": [], + "source": [ + "N = 100_000_000" + ] + }, + { + "cell_type": "markdown", + "id": "b7175caf", + "metadata": {}, + "source": [ + "How can we estimate total revenue from the full population using only the sample data?\n", + "\n", + "Our plan is to assume that wealth of each individual is a draw from a distribution with density $f$.\n", + "\n", + "If we obtain an estimate of $f$ we can then approximate $T$ as follows:\n", + "\n", + "$$\n", + " T = \\sum_{i=1}^{N} h(w_i) \n", + " = N \\frac{1}{N} \\sum_{i=1}^{N} h(w_i) \n", + " \\approx N \\int_{0}^{\\infty} h(w)f(w) dw\n", + "$$ (eq:est_rev)\n", + "\n", + "(The sample mean should be close to the mean by the law of large numbers.)\n", + "\n", + "The problem now is: how do we estimate $f$?\n", + "\n", + "\n", + "## Maximum likelihood estimation\n", + "\n", + "[Maximum likelihood estimation](https://en.wikipedia.org/wiki/Maximum_likelihood_estimation) \n", + "is a method of estimating an unknown distribution.\n", + "\n", + "Maximum likelihood estimation has two steps:\n", + "\n", + "1. Guess what the underlying distribution is (e.g., normal with mean $\\mu$ and\n", + " standard deviation $\\sigma$).\n", + "2. Estimate the parameter values (e.g., estimate $\\mu$ and $\\sigma$ for the\n", + " normal distribution)\n", + "\n", + "One possible assumption for the wealth is that each\n", + "$w_i$ is [log-normally distributed](https://en.wikipedia.org/wiki/Log-normal_distribution),\n", + "with parameters $\\mu \\in (-\\infty,\\infty)$ and $\\sigma \\in (0,\\infty)$.\n", + "\n", + "(This means that $\\ln w_i$ is normally distributed with mean $\\mu$ and standard deviation $\\sigma$.)\n", + "\n", + "You can see that this assumption is not completely unreasonable because, if we\n", + "histogram log wealth instead of wealth, the picture starts to look something\n", + "like a bell-shaped curve." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d4f3cfd8", + "metadata": {}, + "outputs": [], + "source": [ + "ln_sample = np.log(sample)\n", + "fig, ax = plt.subplots()\n", + "ax.hist(ln_sample, density=True, bins=200, histtype='stepfilled', alpha=0.8)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "6d9d0cee", + "metadata": {}, + "source": [ + "Now our job is to obtain the maximum likelihood estimates of $\\mu$ and $\\sigma$, which\n", + "we denote by $\\hat{\\mu}$ and $\\hat{\\sigma}$.\n", + "\n", + "These estimates can be found by maximizing the likelihood function given the\n", + "data.\n", + "\n", + "The pdf of a lognormally distributed random variable $X$ is given by:\n", + "\n", + "$$\n", + " f(x, \\mu, \\sigma) \n", + " = \\frac{1}{x}\\frac{1}{\\sigma \\sqrt{2\\pi}} \n", + " \\exp\\left(\\frac{-1}{2}\\left(\\frac{\\ln x-\\mu}{\\sigma}\\right)\\right)^2\n", + "$$\n", + "\n", + "For our sample $w_1, w_2, \\cdots, w_n$, the [likelihood function](https://en.wikipedia.org/wiki/Likelihood_function) is given by\n", + "\n", + "$$\n", + " L(\\mu, \\sigma | w_i) = \\prod_{i=1}^{n} f(w_i, \\mu, \\sigma)\n", + "$$\n", + "\n", + "The likelihood function can be viewed as both\n", + "\n", + "* the joint distribution of the sample (which is assumed to be IID) and\n", + "* the \"likelihood\" of parameters $(\\mu, \\sigma)$ given the data.\n", + "\n", + "Taking logs on both sides gives us the log likelihood function, which is\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + " \\ell(\\mu, \\sigma | w_i) \n", + " & = \\ln \\left[ \\prod_{i=1}^{n} f(w_i, \\mu, \\sigma) \\right] \\\\\n", + " & = -\\sum_{i=1}^{n} \\ln w_i \n", + " - \\frac{n}{2} \\ln(2\\pi) - \\frac{n}{2} \\ln \\sigma^2 - \\frac{1}{2\\sigma^2}\n", + " \\sum_{i=1}^n (\\ln w_i - \\mu)^2\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "To find where this function is maximised we find its partial derivatives wrt $\\mu$ and $\\sigma ^2$ and equate them to $0$.\n", + "\n", + "Let's first find the maximum likelihood estimate (MLE) of $\\mu$\n", + "\n", + "$$\n", + "\\frac{\\delta \\ell}{\\delta \\mu} \n", + " = - \\frac{1}{2\\sigma^2} \\times 2 \\sum_{i=1}^n (\\ln w_i - \\mu) = 0 \\\\\n", + "\\implies \\sum_{i=1}^n \\ln w_i - n \\mu = 0 \\\\\n", + "\\implies \\hat{\\mu} = \\frac{\\sum_{i=1}^n \\ln w_i}{n}\n", + "$$\n", + "\n", + "Now let's find the MLE of $\\sigma$\n", + "\n", + "$$\n", + "\\frac{\\delta \\ell}{\\delta \\sigma^2} \n", + " = - \\frac{n}{2\\sigma^2} + \\frac{1}{2\\sigma^4} \n", + " \\sum_{i=1}^n (\\ln w_i - \\mu)^2 = 0 \\\\\n", + " \\implies \\frac{n}{2\\sigma^2} = \n", + " \\frac{1}{2\\sigma^4} \\sum_{i=1}^n (\\ln w_i - \\mu)^2 \\\\\n", + " \\implies \\hat{\\sigma} = \n", + " \\left( \\frac{\\sum_{i=1}^{n}(\\ln w_i - \\hat{\\mu})^2}{n} \\right)^{1/2}\n", + "$$\n", + "\n", + "Now that we have derived the expressions for $\\hat{\\mu}$ and $\\hat{\\sigma}$,\n", + "let's compute them for our wealth sample." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9856e591", + "metadata": {}, + "outputs": [], + "source": [ + "μ_hat = np.mean(ln_sample)\n", + "μ_hat" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3ef2d83a", + "metadata": {}, + "outputs": [], + "source": [ + "num = (ln_sample - μ_hat)**2\n", + "σ_hat = (np.mean(num))**(1/2)\n", + "σ_hat" + ] + }, + { + "cell_type": "markdown", + "id": "1cec149f", + "metadata": {}, + "source": [ + "Let's plot the lognormal pdf using the estimated parameters against our sample data." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "da0ba6f3", + "metadata": {}, + "outputs": [], + "source": [ + "dist_lognorm = lognorm(σ_hat, scale = exp(μ_hat))\n", + "x = np.linspace(0,50,10000)\n", + "\n", + "fig, ax = plt.subplots()\n", + "ax.set_xlim(-1,20)\n", + "\n", + "ax.hist(sample, density=True, bins=5_000, histtype='stepfilled', alpha=0.5)\n", + "ax.plot(x, dist_lognorm.pdf(x), 'k-', lw=0.5, label='lognormal pdf')\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "f4e050d4", + "metadata": {}, + "source": [ + "Our estimated lognormal distribution appears to be a reasonable fit for the overall data.\n", + "\n", + "We now use {eq}`eq:est_rev` to calculate total revenue.\n", + "\n", + "We will compute the integral using numerical integration via SciPy's\n", + "[quad](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html)\n", + "function" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fdac3e00", + "metadata": {}, + "outputs": [], + "source": [ + "def total_revenue(dist):\n", + " integral, _ = quad(lambda x: h(x) * dist.pdf(x), 0, 100_000)\n", + " T = N * integral\n", + " return T" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2c5359e0", + "metadata": {}, + "outputs": [], + "source": [ + "tr_lognorm = total_revenue(dist_lognorm)\n", + "tr_lognorm" + ] + }, + { + "cell_type": "markdown", + "id": "fbd47158", + "metadata": {}, + "source": [ + "(Our unit was 100,000 dollars, so this means that actual revenue is 100,000\n", + "times as large.)\n", + "\n", + "\n", + "## Pareto distribution\n", + "\n", + "We mentioned above that using maximum likelihood estimation requires us to make\n", + "a prior assumption of the underlying distribution.\n", + "\n", + "Previously we assumed that the distribution is lognormal.\n", + "\n", + "Suppose instead we assume that $w_i$ are drawn from the \n", + "[Pareto Distribution](https://en.wikipedia.org/wiki/Pareto_distribution)\n", + "with parameters $b$ and $x_m$.\n", + "\n", + "In this case, the maximum likelihood estimates are known to be\n", + "\n", + "$$\n", + " \\hat{b} = \\frac{n}{\\sum_{i=1}^{n} \\ln (w_i/\\hat{x_m})}\n", + " \\quad \\text{and} \\quad\n", + " \\hat{x}_m = \\min_{i} w_i\n", + "$$\n", + "\n", + "Let's calculate them." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "452fb75a", + "metadata": {}, + "outputs": [], + "source": [ + "xm_hat = min(sample)\n", + "xm_hat" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8a66ffd3", + "metadata": {}, + "outputs": [], + "source": [ + "den = np.log(sample/xm_hat)\n", + "b_hat = 1/np.mean(den)\n", + "b_hat" + ] + }, + { + "cell_type": "markdown", + "id": "967d64c5", + "metadata": {}, + "source": [ + "Now let's recompute total revenue." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2ef18457", + "metadata": {}, + "outputs": [], + "source": [ + "dist_pareto = pareto(b = b_hat, scale = xm_hat)\n", + "tr_pareto = total_revenue(dist_pareto) \n", + "tr_pareto" + ] + }, + { + "cell_type": "markdown", + "id": "269c1233", + "metadata": {}, + "source": [ + "The number is very different!" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2f8fbfe3", + "metadata": {}, + "outputs": [], + "source": [ + "tr_pareto / tr_lognorm" + ] + }, + { + "cell_type": "markdown", + "id": "800c6b28", + "metadata": {}, + "source": [ + "We see that choosing the right distribution is extremely important.\n", + "\n", + "\n", + "\n", + "Let's compare the fitted Pareto distribution to the histogram:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "814e3689", + "metadata": {}, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "ax.set_xlim(-1, 20)\n", + "ax.set_ylim(0,1.75)\n", + "\n", + "ax.hist(sample, density=True, bins=5_000, histtype='stepfilled', alpha=0.5)\n", + "ax.plot(x, dist_pareto.pdf(x), 'k-', lw=0.5, label='Pareto pdf')\n", + "ax.legend()\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "74308f32", + "metadata": {}, + "source": [ + "We observe that in this case the fit for the Pareto distribution is not very\n", + "good, so we can probably reject it.\n", + "\n", + "## What is the best distribution?\n", + "\n", + "There is no \"best\" distribution --- every choice we make is an assumption.\n", + "\n", + "All we can do is try to pick a distribution that fits the data well.\n", + "\n", + "The plots above suggested that the lognormal distribution is optimal.\n", + "\n", + "However when we inspect the upper tail (the richest people), the Pareto distribution may be a better fit.\n", + "\n", + "To see this, let's now set a minimum threshold of net worth in our dataset.\n", + "\n", + "We set an arbitrary threshold of $500,000 and read the data into `sample_tail`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ee99a028", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "df_tail = df.loc[df['n_wealth'] > 500_000 ]\n", + "df_tail.head()\n", + "rv_tail = df_tail['n_wealth'].sample(n=10_000, random_state=4321)\n", + "rv_tail = rv_tail.to_numpy()\n", + "sample_tail = rv_tail/500_000" + ] + }, + { + "cell_type": "markdown", + "id": "1ad46bcd", + "metadata": {}, + "source": [ + "Let's plot this data." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "03202e55", + "metadata": {}, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "ax.set_xlim(0,50)\n", + "ax.hist(sample_tail, density=True, bins=500, histtype='stepfilled', alpha=0.8)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "5ae9ded1", + "metadata": {}, + "source": [ + "Now let's try fitting some distributions to this data.\n", + "\n", + "\n", + "### Lognormal distribution for the right hand tail\n", + "\n", + "Let's start with the lognormal distribution\n", + "\n", + "We estimate the parameters again and plot the density against our data." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bce38d5f", + "metadata": {}, + "outputs": [], + "source": [ + "ln_sample_tail = np.log(sample_tail)\n", + "μ_hat_tail = np.mean(ln_sample_tail)\n", + "num_tail = (ln_sample_tail - μ_hat_tail)**2\n", + "σ_hat_tail = (np.mean(num_tail))**(1/2)\n", + "dist_lognorm_tail = lognorm(σ_hat_tail, scale = exp(μ_hat_tail))\n", + "\n", + "fig, ax = plt.subplots()\n", + "ax.set_xlim(0,50)\n", + "ax.hist(sample_tail, density=True, bins=500, histtype='stepfilled', alpha=0.5)\n", + "ax.plot(x, dist_lognorm_tail.pdf(x), 'k-', lw=0.5, label='lognormal pdf')\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "85a7ef42", + "metadata": {}, + "source": [ + "While the lognormal distribution was a good fit for the entire dataset,\n", + "it is not a good fit for the right hand tail.\n", + "\n", + "\n", + "### Pareto distribution for the right hand tail\n", + "\n", + "Let's now assume the truncated dataset has a Pareto distribution.\n", + "\n", + "We estimate the parameters again and plot the density against our data." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f38ba0ef", + "metadata": {}, + "outputs": [], + "source": [ + "xm_hat_tail = min(sample_tail)\n", + "den_tail = np.log(sample_tail/xm_hat_tail)\n", + "b_hat_tail = 1/np.mean(den_tail)\n", + "dist_pareto_tail = pareto(b = b_hat_tail, scale = xm_hat_tail)\n", + "\n", + "fig, ax = plt.subplots()\n", + "ax.set_xlim(0, 50)\n", + "ax.set_ylim(0,0.65)\n", + "ax.hist(sample_tail, density=True, bins= 500, histtype='stepfilled', alpha=0.5)\n", + "ax.plot(x, dist_pareto_tail.pdf(x), 'k-', lw=0.5, label='pareto pdf')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "6ecfe931", + "metadata": {}, + "source": [ + "The Pareto distribution is a better fit for the right hand tail of our dataset.\n", + "\n", + "### So what is the best distribution?\n", + "\n", + "As we said above, there is no \"best\" distribution --- each choice is an\n", + "assumption.\n", + "\n", + "We just have to test what we think are reasonable distributions.\n", + "\n", + "One test is to plot the data against the fitted distribution, as we did.\n", + "\n", + "There are other more rigorous tests, such as the [Kolmogorov-Smirnov test](https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test).\n", + "\n", + "We omit such advanced topics (but encourage readers to study them once\n", + "they have completed these lectures).\n", + "\n", + "## Exercises\n", + "\n", + "```{exercise-start}\n", + ":label: mle_ex1\n", + "```\n", + "Suppose we assume wealth is [exponentially](https://en.wikipedia.org/wiki/Exponential_distribution)\n", + "distributed with parameter $\\lambda > 0$.\n", + "\n", + "The maximum likelihood estimate of $\\lambda$ is given by\n", + "\n", + "$$\n", + "\\hat{\\lambda} = \\frac{n}{\\sum_{i=1}^n w_i}\n", + "$$\n", + "\n", + "1. Compute $\\hat{\\lambda}$ for our initial sample.\n", + "2. Use $\\hat{\\lambda}$ to find the total revenue \n", + "\n", + "```{exercise-end}\n", + "```\n", + "\n", + "```{solution-start} mle_ex1\n", + ":class: dropdown\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e3c17b81", + "metadata": {}, + "outputs": [], + "source": [ + "λ_hat = 1/np.mean(sample)\n", + "λ_hat" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fbb60096", + "metadata": {}, + "outputs": [], + "source": [ + "dist_exp = expon(scale = 1/λ_hat)\n", + "tr_expo = total_revenue(dist_exp) \n", + "tr_expo" + ] + }, + { + "cell_type": "markdown", + "id": "4bbeeb2b", + "metadata": {}, + "source": [ + "```{solution-end}\n", + "```\n", + "\n", + "```{exercise-start}\n", + ":label: mle_ex2\n", + "```\n", + "\n", + "Plot the exponential distribution against the sample and check if it is a good fit or not.\n", + "\n", + "```{exercise-end}\n", + "```\n", + "\n", + "```{solution-start} mle_ex2\n", + ":class: dropdown\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "224c0da8", + "metadata": {}, + "outputs": [], + "source": [ + "fig, ax = plt.subplots()\n", + "ax.set_xlim(-1, 20)\n", + "\n", + "ax.hist(sample, density=True, bins=5000, histtype='stepfilled', alpha=0.5)\n", + "ax.plot(x, dist_exp.pdf(x), 'k-', lw=0.5, label='exponential pdf')\n", + "ax.legend()\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "2f28d1a4", + "metadata": {}, + "source": [ + "Clearly, this distribution is not a good fit for our data.\n", + "\n", + "```{solution-end}\n", + "```" + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.15.2" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 16, + 23, + 54, + 60, + 80, + 82, + 90, + 101, + 105, + 115, + 123, + 125, + 166, + 171, + 236, + 241, + 245, + 249, + 260, + 270, + 277, + 280, + 307, + 312, + 316, + 320, + 324, + 328, + 330, + 338, + 348, + 367, + 375, + 379, + 384, + 395, + 408, + 420, + 432, + 474, + 479, + 483, + 501, + 510 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/mle.md b/book/_build/html/_sources/mle.md new file mode 100644 index 0000000..8a15d6a --- /dev/null +++ b/book/_build/html/_sources/mle.md @@ -0,0 +1,515 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.15.2 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Maximum Likelihood Estimation + +```{code-cell} ipython3 +from scipy.stats import lognorm, pareto, expon +import numpy as np +from scipy.integrate import quad +import matplotlib.pyplot as plt +import pandas as pd +from math import exp +``` + +## Introduction + +Consider a situation where a policymaker is trying to estimate how much revenue +a proposed wealth tax will raise. + +The proposed tax is + +$$ + h(w) = + \begin{cases} + a w & \text{if } w \leq \bar w \\ + a \bar{w} + b (w-\bar{w}) & \text{if } w > \bar w + \end{cases} +$$ + +where $w$ is wealth. + +```{prf:example} +:label: mle_ex_wt + +For example, if $a = 0.05$, $b = 0.1$, and $\bar w = 2.5$, this means + +* a 5% tax on wealth up to 2.5 and +* a 10% tax on wealth in excess of 2.5. + +The unit is 100,000, so $w= 2.5$ means 250,000 dollars. +``` +Let's go ahead and define $h$: + +```{code-cell} ipython3 +def h(w, a=0.05, b=0.1, w_bar=2.5): + if w <= w_bar: + return a * w + else: + return a * w_bar + b * (w - w_bar) +``` + +For a population of size $N$, where individual $i$ has wealth $w_i$, total revenue raised by +the tax will be + +$$ + T = \sum_{i=1}^{N} h(w_i) +$$ + +We wish to calculate this quantity. + +The problem we face is that, in most countries, wealth is not observed for all individuals. + +Collecting and maintaining accurate wealth data for all individuals or households in a country +is just too hard. + +So let's suppose instead that we obtain a sample $w_1, w_2, \cdots, w_n$ telling us the wealth of $n$ randomly selected individuals. + +For our exercise we are going to use a sample of $n = 10,000$ observations from wealth data in the US in 2016. + +```{code-cell} ipython3 +n = 10_000 +``` + +The data is derived from the +[Survey of Consumer Finances](https://en.wikipedia.org/wiki/Survey_of_Consumer_Finances) (SCF). + + +The following code imports this data and reads it into an array called `sample`. + +```{code-cell} ipython3 +:tags: [hide-input] + +url = 'https://media.githubusercontent.com/media/QuantEcon/high_dim_data/update_scf_noweights/SCF_plus/SCF_plus_mini_no_weights.csv' +df = pd.read_csv(url) +df = df.dropna() +df = df[df['year'] == 2016] +df = df.loc[df['n_wealth'] > 1 ] #restrcting data to net worth > 1 +rv = df['n_wealth'].sample(n=n, random_state=1234) +rv = rv.to_numpy() / 100_000 +sample = rv +``` + +Let's histogram this sample. + +```{code-cell} ipython3 +fig, ax = plt.subplots() +ax.set_xlim(-1, 20) +density, edges = np.histogram(sample, bins=5000, density=True) +prob = density * np.diff(edges) +plt.stairs(prob, edges, fill=True, alpha=0.8, label=r"unit: $\$100,000$") +plt.ylabel("prob") +plt.xlabel("net wealth") +plt.legend() +plt.show() +``` + +The histogram shows that many people have very low wealth and a few people have +very high wealth. + + +We will take the full population size to be + +```{code-cell} ipython3 +N = 100_000_000 +``` + +How can we estimate total revenue from the full population using only the sample data? + +Our plan is to assume that wealth of each individual is a draw from a distribution with density $f$. + +If we obtain an estimate of $f$ we can then approximate $T$ as follows: + +$$ + T = \sum_{i=1}^{N} h(w_i) + = N \frac{1}{N} \sum_{i=1}^{N} h(w_i) + \approx N \int_{0}^{\infty} h(w)f(w) dw +$$ (eq:est_rev) + +(The sample mean should be close to the mean by the law of large numbers.) + +The problem now is: how do we estimate $f$? + + +## Maximum likelihood estimation + +[Maximum likelihood estimation](https://en.wikipedia.org/wiki/Maximum_likelihood_estimation) +is a method of estimating an unknown distribution. + +Maximum likelihood estimation has two steps: + +1. Guess what the underlying distribution is (e.g., normal with mean $\mu$ and + standard deviation $\sigma$). +2. Estimate the parameter values (e.g., estimate $\mu$ and $\sigma$ for the + normal distribution) + +One possible assumption for the wealth is that each +$w_i$ is [log-normally distributed](https://en.wikipedia.org/wiki/Log-normal_distribution), +with parameters $\mu \in (-\infty,\infty)$ and $\sigma \in (0,\infty)$. + +(This means that $\ln w_i$ is normally distributed with mean $\mu$ and standard deviation $\sigma$.) + +You can see that this assumption is not completely unreasonable because, if we +histogram log wealth instead of wealth, the picture starts to look something +like a bell-shaped curve. + +```{code-cell} ipython3 +ln_sample = np.log(sample) +fig, ax = plt.subplots() +ax.hist(ln_sample, density=True, bins=200, histtype='stepfilled', alpha=0.8) +plt.show() +``` + +Now our job is to obtain the maximum likelihood estimates of $\mu$ and $\sigma$, which +we denote by $\hat{\mu}$ and $\hat{\sigma}$. + +These estimates can be found by maximizing the likelihood function given the +data. + +The pdf of a lognormally distributed random variable $X$ is given by: + +$$ + f(x, \mu, \sigma) + = \frac{1}{x}\frac{1}{\sigma \sqrt{2\pi}} + \exp\left(\frac{-1}{2}\left(\frac{\ln x-\mu}{\sigma}\right)\right)^2 +$$ + +For our sample $w_1, w_2, \cdots, w_n$, the [likelihood function](https://en.wikipedia.org/wiki/Likelihood_function) is given by + +$$ + L(\mu, \sigma | w_i) = \prod_{i=1}^{n} f(w_i, \mu, \sigma) +$$ + +The likelihood function can be viewed as both + +* the joint distribution of the sample (which is assumed to be IID) and +* the "likelihood" of parameters $(\mu, \sigma)$ given the data. + +Taking logs on both sides gives us the log likelihood function, which is + +$$ +\begin{aligned} + \ell(\mu, \sigma | w_i) + & = \ln \left[ \prod_{i=1}^{n} f(w_i, \mu, \sigma) \right] \\ + & = -\sum_{i=1}^{n} \ln w_i + - \frac{n}{2} \ln(2\pi) - \frac{n}{2} \ln \sigma^2 - \frac{1}{2\sigma^2} + \sum_{i=1}^n (\ln w_i - \mu)^2 +\end{aligned} +$$ + +To find where this function is maximised we find its partial derivatives wrt $\mu$ and $\sigma ^2$ and equate them to $0$. + +Let's first find the maximum likelihood estimate (MLE) of $\mu$ + +$$ +\frac{\delta \ell}{\delta \mu} + = - \frac{1}{2\sigma^2} \times 2 \sum_{i=1}^n (\ln w_i - \mu) = 0 \\ +\implies \sum_{i=1}^n \ln w_i - n \mu = 0 \\ +\implies \hat{\mu} = \frac{\sum_{i=1}^n \ln w_i}{n} +$$ + +Now let's find the MLE of $\sigma$ + +$$ +\frac{\delta \ell}{\delta \sigma^2} + = - \frac{n}{2\sigma^2} + \frac{1}{2\sigma^4} + \sum_{i=1}^n (\ln w_i - \mu)^2 = 0 \\ + \implies \frac{n}{2\sigma^2} = + \frac{1}{2\sigma^4} \sum_{i=1}^n (\ln w_i - \mu)^2 \\ + \implies \hat{\sigma} = + \left( \frac{\sum_{i=1}^{n}(\ln w_i - \hat{\mu})^2}{n} \right)^{1/2} +$$ + +Now that we have derived the expressions for $\hat{\mu}$ and $\hat{\sigma}$, +let's compute them for our wealth sample. + +```{code-cell} ipython3 +μ_hat = np.mean(ln_sample) +μ_hat +``` + +```{code-cell} ipython3 +num = (ln_sample - μ_hat)**2 +σ_hat = (np.mean(num))**(1/2) +σ_hat +``` + +Let's plot the lognormal pdf using the estimated parameters against our sample data. + +```{code-cell} ipython3 +dist_lognorm = lognorm(σ_hat, scale = exp(μ_hat)) +x = np.linspace(0,50,10000) + +fig, ax = plt.subplots() +ax.set_xlim(-1,20) + +ax.hist(sample, density=True, bins=5_000, histtype='stepfilled', alpha=0.5) +ax.plot(x, dist_lognorm.pdf(x), 'k-', lw=0.5, label='lognormal pdf') +ax.legend() +plt.show() +``` + +Our estimated lognormal distribution appears to be a reasonable fit for the overall data. + +We now use {eq}`eq:est_rev` to calculate total revenue. + +We will compute the integral using numerical integration via SciPy's +[quad](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html) +function + +```{code-cell} ipython3 +def total_revenue(dist): + integral, _ = quad(lambda x: h(x) * dist.pdf(x), 0, 100_000) + T = N * integral + return T +``` + +```{code-cell} ipython3 +tr_lognorm = total_revenue(dist_lognorm) +tr_lognorm +``` + +(Our unit was 100,000 dollars, so this means that actual revenue is 100,000 +times as large.) + + +## Pareto distribution + +We mentioned above that using maximum likelihood estimation requires us to make +a prior assumption of the underlying distribution. + +Previously we assumed that the distribution is lognormal. + +Suppose instead we assume that $w_i$ are drawn from the +[Pareto Distribution](https://en.wikipedia.org/wiki/Pareto_distribution) +with parameters $b$ and $x_m$. + +In this case, the maximum likelihood estimates are known to be + +$$ + \hat{b} = \frac{n}{\sum_{i=1}^{n} \ln (w_i/\hat{x_m})} + \quad \text{and} \quad + \hat{x}_m = \min_{i} w_i +$$ + +Let's calculate them. + +```{code-cell} ipython3 +xm_hat = min(sample) +xm_hat +``` + +```{code-cell} ipython3 +den = np.log(sample/xm_hat) +b_hat = 1/np.mean(den) +b_hat +``` + +Now let's recompute total revenue. + +```{code-cell} ipython3 +dist_pareto = pareto(b = b_hat, scale = xm_hat) +tr_pareto = total_revenue(dist_pareto) +tr_pareto +``` + +The number is very different! + +```{code-cell} ipython3 +tr_pareto / tr_lognorm +``` + +We see that choosing the right distribution is extremely important. + + + +Let's compare the fitted Pareto distribution to the histogram: + +```{code-cell} ipython3 +fig, ax = plt.subplots() +ax.set_xlim(-1, 20) +ax.set_ylim(0,1.75) + +ax.hist(sample, density=True, bins=5_000, histtype='stepfilled', alpha=0.5) +ax.plot(x, dist_pareto.pdf(x), 'k-', lw=0.5, label='Pareto pdf') +ax.legend() + +plt.show() +``` + +We observe that in this case the fit for the Pareto distribution is not very +good, so we can probably reject it. + +## What is the best distribution? + +There is no "best" distribution --- every choice we make is an assumption. + +All we can do is try to pick a distribution that fits the data well. + +The plots above suggested that the lognormal distribution is optimal. + +However when we inspect the upper tail (the richest people), the Pareto distribution may be a better fit. + +To see this, let's now set a minimum threshold of net worth in our dataset. + +We set an arbitrary threshold of $500,000 and read the data into `sample_tail`. + +```{code-cell} ipython3 +:tags: [hide-input] + +df_tail = df.loc[df['n_wealth'] > 500_000 ] +df_tail.head() +rv_tail = df_tail['n_wealth'].sample(n=10_000, random_state=4321) +rv_tail = rv_tail.to_numpy() +sample_tail = rv_tail/500_000 +``` + +Let's plot this data. + +```{code-cell} ipython3 +fig, ax = plt.subplots() +ax.set_xlim(0,50) +ax.hist(sample_tail, density=True, bins=500, histtype='stepfilled', alpha=0.8) +plt.show() +``` + +Now let's try fitting some distributions to this data. + + +### Lognormal distribution for the right hand tail + +Let's start with the lognormal distribution + +We estimate the parameters again and plot the density against our data. + +```{code-cell} ipython3 +ln_sample_tail = np.log(sample_tail) +μ_hat_tail = np.mean(ln_sample_tail) +num_tail = (ln_sample_tail - μ_hat_tail)**2 +σ_hat_tail = (np.mean(num_tail))**(1/2) +dist_lognorm_tail = lognorm(σ_hat_tail, scale = exp(μ_hat_tail)) + +fig, ax = plt.subplots() +ax.set_xlim(0,50) +ax.hist(sample_tail, density=True, bins=500, histtype='stepfilled', alpha=0.5) +ax.plot(x, dist_lognorm_tail.pdf(x), 'k-', lw=0.5, label='lognormal pdf') +ax.legend() +plt.show() +``` + +While the lognormal distribution was a good fit for the entire dataset, +it is not a good fit for the right hand tail. + + +### Pareto distribution for the right hand tail + +Let's now assume the truncated dataset has a Pareto distribution. + +We estimate the parameters again and plot the density against our data. + +```{code-cell} ipython3 +xm_hat_tail = min(sample_tail) +den_tail = np.log(sample_tail/xm_hat_tail) +b_hat_tail = 1/np.mean(den_tail) +dist_pareto_tail = pareto(b = b_hat_tail, scale = xm_hat_tail) + +fig, ax = plt.subplots() +ax.set_xlim(0, 50) +ax.set_ylim(0,0.65) +ax.hist(sample_tail, density=True, bins= 500, histtype='stepfilled', alpha=0.5) +ax.plot(x, dist_pareto_tail.pdf(x), 'k-', lw=0.5, label='pareto pdf') +plt.show() +``` + +The Pareto distribution is a better fit for the right hand tail of our dataset. + +### So what is the best distribution? + +As we said above, there is no "best" distribution --- each choice is an +assumption. + +We just have to test what we think are reasonable distributions. + +One test is to plot the data against the fitted distribution, as we did. + +There are other more rigorous tests, such as the [Kolmogorov-Smirnov test](https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test). + +We omit such advanced topics (but encourage readers to study them once +they have completed these lectures). + +## Exercises + +```{exercise-start} +:label: mle_ex1 +``` +Suppose we assume wealth is [exponentially](https://en.wikipedia.org/wiki/Exponential_distribution) +distributed with parameter $\lambda > 0$. + +The maximum likelihood estimate of $\lambda$ is given by + +$$ +\hat{\lambda} = \frac{n}{\sum_{i=1}^n w_i} +$$ + +1. Compute $\hat{\lambda}$ for our initial sample. +2. Use $\hat{\lambda}$ to find the total revenue + +```{exercise-end} +``` + +```{solution-start} mle_ex1 +:class: dropdown +``` + +```{code-cell} ipython3 +λ_hat = 1/np.mean(sample) +λ_hat +``` + +```{code-cell} ipython3 +dist_exp = expon(scale = 1/λ_hat) +tr_expo = total_revenue(dist_exp) +tr_expo +``` + +```{solution-end} +``` + +```{exercise-start} +:label: mle_ex2 +``` + +Plot the exponential distribution against the sample and check if it is a good fit or not. + +```{exercise-end} +``` + +```{solution-start} mle_ex2 +:class: dropdown +``` + +```{code-cell} ipython3 +fig, ax = plt.subplots() +ax.set_xlim(-1, 20) + +ax.hist(sample, density=True, bins=5000, histtype='stepfilled', alpha=0.5) +ax.plot(x, dist_exp.pdf(x), 'k-', lw=0.5, label='exponential pdf') +ax.legend() + +plt.show() +``` + +Clearly, this distribution is not a good fit for our data. + +```{solution-end} +``` diff --git a/book/_build/html/_sources/money_inflation.ipynb b/book/_build/html/_sources/money_inflation.ipynb new file mode 100644 index 0000000..0833366 --- /dev/null +++ b/book/_build/html/_sources/money_inflation.ipynb @@ -0,0 +1,1218 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "25f0a1aa", + "metadata": {}, + "source": [ + "# Money Financed Government Deficits and Price Levels\n", + "\n", + "## Overview\n", + "\n", + "This lecture extends and modifies the model in this lecture {doc}`cagan_ree` by modifying the\n", + "law of motion that governed the supply of money. \n", + "\n", + "The model in this lecture consists of two components\n", + "\n", + "* a demand function for money \n", + "* a law of motion for the supply of money\n", + " \n", + "The demand function describes the public's demand for \"real balances\", defined as the ratio of nominal money balances to the price level\n", + "\n", + "* it assumes that the demand for real balance today varies inversely with the rate of inflation that the public forecasts to prevail between today and tomorrow\n", + "* it assumes that the public's forecast of that rate of inflation is perfect \n", + "\n", + "The law of motion for the supply of money assumes that the government prints money to finance government expenditures\n", + "\n", + "Our model equates the demand for money to the supply at each time $t \\geq 0$.\n", + "\n", + "Equality between those demands and supply gives a *dynamic* model in which money supply\n", + "and price level *sequences* are simultaneously determined by a set of simultaneous linear equations.\n", + "\n", + "These equations take the form of what is often called vector linear **difference equations**. \n", + "\n", + "In this lecture, we'll roll up our sleeves and solve those equations in two different ways.\n", + "\n", + "\n", + "(One of the methods for solving vector linear difference equations will take advantage of a decomposition of a matrix that is studied in this lecture {doc}`eigen_I`.)\n", + "\n", + "In this lecture we will encounter these concepts from macroeconomics:\n", + "\n", + "* an **inflation tax** that a government gathers by printing paper or electronic money\n", + "* a dynamic **Laffer curve** in the inflation tax rate that has two stationary equilibria\n", + "* perverse dynamics under rational expectations in which the system converges to the higher stationary inflation tax rate\n", + "* a peculiar comparative stationary-state outcome connected with that stationary inflation rate: it asserts that inflation can be *reduced* by running *higher* government deficits, i.e., by raising more resources by printing money. \n", + "\n", + "The same qualitative outcomes prevail in this lecture {doc}`money_inflation_nonlinear` that studies a nonlinear version of the model in this lecture. \n", + "\n", + "These outcomes set the stage for the analysis to be presented in this lecture {doc}`laffer_adaptive` that studies a nonlinear version of the present model; it assumes a version of \"adaptive expectations\" instead of rational expectations.\n", + "\n", + "That lecture will show that \n", + "\n", + "* replacing rational expectations with adaptive expectations leaves the two stationary inflation rates unchanged, but that $\\ldots$ \n", + "* it reverses the perverse dynamics by making the *lower* stationary inflation rate the one to which the system typically converges\n", + "* a more plausible comparative dynamic outcome emerges in which now inflation can be *reduced* by running *lower* government deficits\n", + "\n", + "This outcome will be used to justify a selection of a stationary inflation rate that underlies the analysis of unpleasant monetarist arithmetic to be studied in this lecture {doc}`unpleasant`.\n", + "\n", + "We'll use these tools from linear algebra:\n", + "\n", + "* matrix multiplication\n", + "* matrix inversion\n", + "* eigenvalues and eigenvectors of a matrix\n", + "\n", + "\n", + "## Demand for and supply of money\n", + "\n", + "We say demand*s* and suppl*ies* (plurals) because there is one of each for each $t \\geq 0$.\n", + "\n", + "Let \n", + "\n", + "* $m_{t+1}$ be the supply of currency at the end of time $t \\geq 0$\n", + "* $m_{t}$ be the supply of currency brought into time $t$ from time $t-1$\n", + "* $g$ be the government deficit that is financed by printing currency at $t \\geq 1$\n", + "* $m_{t+1}^d$ be the demand at time $t$ for currency to bring into time $t+1$\n", + "* $p_t$ be the price level at time $t$\n", + "* $b_t = \\frac{m_{t+1}}{p_t}$ is real balances at the end of time $t$ \n", + "* $R_t = \\frac{p_t}{p_{t+1}} $ be the gross rate of return on currency held from time $t$ to time $t+1$\n", + " \n", + "It is often helpful to state units in which quantities are measured:\n", + "\n", + "* $m_t$ and $m_t^d$ are measured in dollars\n", + "* $g$ is measured in time $t$ goods \n", + "* $p_t$ is measured in dollars per time $t$ goods\n", + "* $R_t$ is measured in time $t+1$ goods per unit of time $t$ goods\n", + "* $b_t$ is measured in time $t$ goods\n", + " \n", + " \n", + "Our job now is to specify demand and supply functions for money. \n", + "\n", + "We assume that the demand for currency satisfies the Cagan-like demand function\n", + "\n", + "$$\n", + "\\frac{m_{t+1}^d}{p_t}=\\gamma_1 - \\gamma_2 \\frac{p_{t+1}}{p_t}, \\quad t \\geq 0\n", + "$$ (eq:demandmoney)\n", + "where $\\gamma_1, \\gamma_2$ are positive parameters.\n", + " \n", + "Now we turn to the supply of money.\n", + "\n", + "We assume that $m_0 >0$ is an \"initial condition\" determined outside the model. \n", + "\n", + "We set $m_0$ at some arbitrary positive value, say \\$100.\n", + " \n", + "For $ t \\geq 1$, we assume that the supply of money is determined by the government's budget constraint\n", + "\n", + "$$\n", + "m_{t+1} - m_{t} = p_t g , \\quad t \\geq 0\n", + "$$ (eq:budgcontraint)\n", + "\n", + "According to this equation, each period, the government prints money to pay for quantity $g$ of goods. \n", + "\n", + "In an **equilibrium**, the demand for currency equals the supply:\n", + "\n", + "$$\n", + "m_{t+1}^d = m_{t+1}, \\quad t \\geq 0\n", + "$$ (eq:syeqdemand)\n", + "\n", + "Let's take a moment to think about what equation {eq}`eq:syeqdemand` tells us.\n", + "\n", + "The demand for money at any time $t$ depends on the price level at time $t$ and the price level at time $t+1$.\n", + "\n", + "The supply of money at time $t+1$ depends on the money supply at time $t$ and the price level at time $t$.\n", + "\n", + "So the infinite sequence of equations {eq}`eq:syeqdemand` for $ t \\geq 0$ imply that the *sequences* $\\{p_t\\}_{t=0}^\\infty$ and $\\{m_t\\}_{t=0}^\\infty$ are tied together and ultimately simulataneously determined.\n", + "\n", + "\n", + "## Equilibrium price and money supply sequences\n", + "\n", + "\n", + "The preceding specifications imply that for $t \\geq 1$, **real balances** evolve according to\n", + "\n", + "\n", + "$$\n", + "\\frac{m_{t+1}}{p_t} - \\frac{m_{t}}{p_{t-1}} \\frac{p_{t-1}}{p_t} = g\n", + "$$\n", + "\n", + "or\n", + "\n", + "$$\n", + "b_t - b_{t-1} R_{t-1} = g\n", + "$$ (eq:bmotion)\n", + "\n", + "The demand for real balances is \n", + "\n", + "$$\n", + "b_t = \\gamma_1 - \\gamma_2 R_t^{-1} . \n", + "$$ (eq:bdemand)\n", + " \n", + "We'll restrict our attention to parameter values and associated gross real rates of return on real balances that assure that the demand for real balances is positive, which according to {eq}`eq:bdemand` means that\n", + "\n", + "$$\n", + "b_t = \\gamma_1 - \\gamma_2 R_t^{-1} > 0 \n", + "$$ \n", + "\n", + "which implies that \n", + "\n", + "$$\n", + "R_t \\geq \\left( \\frac{\\gamma_2}{\\gamma_1} \\right) \\equiv \\underline R\n", + "$$ (eq:Requation)\n", + "\n", + "Gross real rate of return $\\underline R$ is the smallest rate of return on currency \n", + "that is consistent with a nonnegative demand for real balances.\n", + "\n", + "We shall describe two distinct but closely related ways of computing a pair $\\{p_t, m_t\\}_{t=0}^\\infty$ of sequences for the price level and money supply.\n", + "\n", + "But first it is instructive to describe a special type of equilibrium known as a **steady state**.\n", + "\n", + "In a steady-state equilibrium, a subset of key variables remain constant or **invariant** over time, while remaining variables can be expressed as functions of those constant variables.\n", + "\n", + "Finding such state variables is something of an art. \n", + "\n", + "In many models, a good source of candidates for such invariant variables is a set of *ratios*. \n", + "\n", + "This is true in the present model.\n", + "\n", + "### Steady states\n", + "\n", + "In a steady-state equilibrium of the model we are studying, \n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "R_t & = \\bar R \\cr\n", + "b_t & = \\bar b\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "for $t \\geq 0$. \n", + "\n", + "Notice that both $R_t = \\frac{p_t}{p_{t+1}}$ and $b_t = \\frac{m_{t+1}}{p_t} $ are *ratios*.\n", + "\n", + "To compute a steady state, we seek gross rates of return on currency and real balances $\\bar R, \\bar b$ that satisfy steady-state versions of both the government budget constraint and the demand function for real balances:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "g & = \\bar b ( 1 - \\bar R) \\cr\n", + "\\bar b & = \\gamma_1- \\gamma_2 \\bar R^{-1}\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "Together these equations imply\n", + "\n", + "$$\n", + "(\\gamma_1 + \\gamma_2) - \\frac{\\gamma_2}{\\bar R} - \\gamma_1 \\bar R = g\n", + "$$ (eq:seignsteady)\n", + "\n", + "\n", + "The left side is the steady-state amount of **seigniorage** or government revenues that the government gathers by paying a gross rate of return $\\bar R \\le 1$ on currency. \n", + "\n", + "The right side is government expenditures.\n", + "\n", + "Define steady-state seigniorage as\n", + "\n", + "$$\n", + "S(\\bar R) = (\\gamma_1 + \\gamma_2) - \\frac{\\gamma_2}{\\bar R} - \\gamma_1 \\bar R\n", + "$$ (eq:SSsigng)\n", + "\n", + "Notice that $S(\\bar R) \\geq 0$ only when $\\bar R \\in [\\frac{\\gamma_2}{\\gamma_1}, 1] \n", + "\\equiv [\\underline R, \\overline R]$ and that $S(\\bar R) = 0$ if $\\bar R = \\underline R$\n", + "or if $\\bar R = \\overline R$.\n", + "\n", + "We shall study equilibrium sequences that satisfy\n", + "\n", + "$$\n", + "R_t \\in [\\underline R, \\overline R], \\quad t \\geq 0. \n", + "$$\n", + "\n", + "Maximizing steady-state seigniorage {eq}`eq:SSsigng` with respect to $\\bar R$, we find that the maximizing rate of return on currency is \n", + "\n", + "$$\n", + "\\bar R_{\\rm max} = \\sqrt{\\frac{\\gamma_2}{\\gamma_1}}\n", + "$$\n", + "\n", + "and that the associated maximum seigniorage revenue that the government can gather from printing money is\n", + "\n", + "$$\n", + "(\\gamma_1 + \\gamma_2) - \\frac{\\gamma_2}{\\bar R_{\\rm max}} - \\gamma_1 \\bar R_{\\rm max}\n", + "$$\n", + "\n", + "It is useful to rewrite equation {eq}`eq:seignsteady` as\n", + "\n", + "$$\n", + "-\\gamma_2 + (\\gamma_1 + \\gamma_2 - g) \\bar R - \\gamma_1 \\bar R^2 = 0\n", + "$$ (eq:steadyquadratic)\n", + "\n", + "A steady state gross rate of return $\\bar R$ solves quadratic equation {eq}`eq:steadyquadratic`.\n", + "\n", + "So two steady states typically exist. \n", + "\n", + "## Some code\n", + "\n", + "Let's start with some imports:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b52a3a02", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from matplotlib.ticker import MaxNLocator\n", + "plt.rcParams['figure.dpi'] = 300\n", + "from collections import namedtuple" + ] + }, + { + "cell_type": "markdown", + "id": "69da801a", + "metadata": {}, + "source": [ + "Let's set some parameter values and compute possible steady-state rates of return on currency $\\bar R$, the seigniorage maximizing rate of return on currency, and an object that we'll discuss later, namely, an initial price level $p_0$ associated with the maximum steady-state rate of return on currency.\n", + "\n", + "First, we create a `namedtuple` to store parameters so that we can reuse this `namedtuple` in our functions throughout this lecture" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "398a01ae", + "metadata": {}, + "outputs": [], + "source": [ + "# Create a namedtuple that contains parameters\n", + "MoneySupplyModel = namedtuple(\"MoneySupplyModel\", \n", + " [\"γ1\", \"γ2\", \"g\", \n", + " \"M0\", \"R_u\", \"R_l\"])\n", + "\n", + "def create_model(γ1=100, γ2=50, g=3.0, M0=100):\n", + " \n", + " # Calculate the steady states for R\n", + " R_steady = np.roots((-γ1, γ1 + γ2 - g, -γ2))\n", + " R_u, R_l = R_steady\n", + " print(\"[R_u, R_l] =\", R_steady)\n", + " \n", + " return MoneySupplyModel(γ1=γ1, γ2=γ2, g=g, M0=M0, R_u=R_u, R_l=R_l)" + ] + }, + { + "cell_type": "markdown", + "id": "8ac8ba33", + "metadata": {}, + "source": [ + "Now we compute the $\\bar R_{\\rm max}$ and corresponding revenue" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "67df20bd", + "metadata": {}, + "outputs": [], + "source": [ + "def seign(R, model):\n", + " γ1, γ2, g = model.γ1, model.γ2, model.g\n", + " return -γ2/R + (γ1 + γ2) - γ1 * R\n", + "\n", + "msm = create_model()\n", + "\n", + "# Calculate initial guess for p0\n", + "p0_guess = msm.M0 / (msm.γ1 - msm.g - msm.γ2 / msm.R_u)\n", + "print(f'p0 guess = {p0_guess:.4f}')\n", + "\n", + "# Calculate seigniorage maximizing rate of return\n", + "R_max = np.sqrt(msm.γ2/msm.γ1)\n", + "g_max = seign(R_max, msm)\n", + "print(f'R_max, g_max = {R_max:.4f}, {g_max:.4f}')" + ] + }, + { + "cell_type": "markdown", + "id": "4ded976f", + "metadata": {}, + "source": [ + "Now let's plot seigniorage as a function of alternative potential steady-state values of $R$.\n", + "\n", + "We'll see that there are two steady-state values of $R$ that attain seigniorage levels equal to $g$,\n", + "one that we'll denote $R_\\ell$, another that we'll denote $R_u$.\n", + "\n", + "They satisfy $R_\\ell < R_u$ and are affiliated with a higher inflation tax rate $(1-R_\\ell)$ and a lower\n", + "inflation tax rate $1 - R_u$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6604fd40", + "metadata": { + "mystnb": { + "figure": { + "caption": "Steady state revenue from inflation tax as function of steady state gross return on currency (solid blue curve) and real government expenditures (dotted red line) plotted against steady-state rate of return currency", + "name": "infl_tax", + "width": "500px" + } + } + }, + "outputs": [], + "source": [ + "# Generate values for R\n", + "R_values = np.linspace(msm.γ2/msm.γ1, 1, 250)\n", + "\n", + "# Calculate the function values\n", + "seign_values = seign(R_values, msm)\n", + "\n", + "# Visualize seign_values against R values\n", + "fig, ax = plt.subplots(figsize=(11, 5))\n", + "plt.plot(R_values, seign_values, label='inflation tax revenue')\n", + "plt.axhline(y=msm.g, color='red', linestyle='--', label='government deficit')\n", + "plt.xlabel('$R$')\n", + "plt.ylabel('seigniorage')\n", + "\n", + "plt.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "3cc67a1a", + "metadata": {}, + "source": [ + "Let's print the two steady-state rates of return $\\bar R$ and the associated seigniorage revenues that the government collects.\n", + "\n", + "(By construction, both steady-state rates of return should raise the same amounts real revenue.)\n", + "\n", + "We hope that the following code will confirm this." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bacc0b1e", + "metadata": {}, + "outputs": [], + "source": [ + "g1 = seign(msm.R_u, msm)\n", + "print(f'R_u, g_u = {msm.R_u:.4f}, {g1:.4f}')\n", + "\n", + "g2 = seign(msm.R_l, msm)\n", + "print(f'R_l, g_l = {msm.R_l:.4f}, {g2:.4f}')" + ] + }, + { + "cell_type": "markdown", + "id": "589be8c3", + "metadata": {}, + "source": [ + "Now let's compute the maximum steady-state amount of seigniorage that could be gathered by printing money and the state-state rate of return on money that attains it.\n", + "\n", + "## Two computation strategies\n", + "\n", + "We now proceed to compute equilibria, not necessarily steady states.\n", + "\n", + "We shall deploy two distinct computation strategies.\n", + "\n", + "### Method 1 \n", + "\n", + "* set $R_0 \\in [\\frac{\\gamma_2}{\\gamma_1}, R_u]$ and compute $b_0 = \\gamma_1 - \\gamma_2/R_0$.\n", + "\n", + "* compute sequences $\\{R_t, b_t\\}_{t=1}^\\infty$ of rates of return and real balances that are associated with an equilibrium by solving equation {eq}`eq:bmotion` and {eq}`eq:bdemand` sequentially for $t \\geq 1$: \n", + " \n", + "$$\n", + "\\begin{aligned}\n", + "b_t & = b_{t-1} R_{t-1} + g \\cr\n", + "R_t^{-1} & = \\frac{\\gamma_1}{\\gamma_2} - \\gamma_2^{-1} b_t \n", + "\\end{aligned}\n", + "$$ (eq:rtbt)\n", + "\n", + "* Construct the associated equilibrium $p_0$ from \n", + "\n", + "$$\n", + "p_0 = \\frac{m_0}{\\gamma_1 - g - \\gamma_2/R_0}\n", + "$$ (eq:p0fromR0)\n", + "\n", + "* compute $\\{p_t, m_t\\}_{t=1}^\\infty$ by solving the following equations sequentially\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "p_t & = R_t p_{t-1} \\cr\n", + "m_t & = b_{t-1} p_t \n", + "\\end{aligned}\n", + "$$ (eq:method1) \n", + " \n", + "```{prf:remark}\n", + ":label: method_1\n", + "Method 1 uses an indirect approach to computing an equilibrium by first computing an equilibrium $\\{R_t, b_t\\}_{t=0}^\\infty$ sequence and then using it to back out an equilibrium $\\{p_t, m_t\\}_{t=0}^\\infty$ sequence.\n", + "```\n", + "\n", + "```{prf:remark}\n", + ":label: initial_condition\n", + "Notice that method 1 starts by picking an **initial condition** $R_0$ from a set $[\\frac{\\gamma_2}{\\gamma_1}, R_u]$. Equilibrium $\\{p_t, m_t\\}_{t=0}^\\infty$ sequences are not unique. There is actually a continuum of equilibria indexed by a choice of $R_0$ from the set $[\\frac{\\gamma_2}{\\gamma_1}, R_u]$. \n", + "```\n", + "\n", + "```{prf:remark}\n", + ":label: unique_selection\n", + "Associated with each selection of $R_0$ there is a unique $p_0$ described by\n", + "equation {eq}`eq:p0fromR0`.\n", + "```\n", + " \n", + "### Method 2\n", + "\n", + "This method deploys a direct approach. \n", + "It defines a \"state vector\" \n", + "$y_t = \\begin{bmatrix} m_t \\cr p_t\\end{bmatrix} $\n", + "and formulates equilibrium conditions {eq}`eq:demandmoney`, {eq}`eq:budgcontraint`, and\n", + "{eq}`eq:syeqdemand`\n", + "in terms of a first-order vector difference equation\n", + "\n", + "$$\n", + "y_{t+1} = M y_t, \\quad t \\geq 0 ,\n", + "$$\n", + "\n", + "where we temporarily take $y_0 = \\begin{bmatrix} m_0 \\cr p_0 \\end{bmatrix}$ as an **initial condition**. \n", + "\n", + "The solution is \n", + "\n", + "$$\n", + "y_t = M^t y_0 .\n", + "$$\n", + "\n", + "Now let's think about the initial condition $y_0$. \n", + "\n", + "It is natural to take the initial stock of money $m_0 >0$ as an initial condition.\n", + "\n", + "But what about $p_0$? \n", + "\n", + "Isn't it something that we want to be *determined* by our model?\n", + "\n", + "Yes, but sometimes we want too much, because there is actually a continuum of initial $p_0$ levels that are compatible with the existence of an equilibrium. \n", + "\n", + "As we shall see soon, selecting an initial $p_0$ in method 2 is intimately tied to selecting an initial rate of return on currency $R_0$ in method 1. \n", + " \n", + "## Computation method 1 \n", + "\n", + "%We start from an arbitrary $R_0$ and $b_t = \\frac{m_{t+1}}{p_t}$, we have \n", + "\n", + "%$$\n", + "%b_0 = \\gamma_1 - \\gamma_0 R_0^{-1} \n", + "%$$\n", + "\n", + "Remember that there exist two steady-state equilibrium values $ R_\\ell < R_u$ of the rate of return on currency $R_t$.\n", + "\n", + "We proceed as follows.\n", + "\n", + "Start at $t=0$ \n", + "* select a $R_0 \\in [\\frac{\\gamma_2}{\\gamma_1}, R_u]$ \n", + "* compute $b_0 = \\gamma_1 - \\gamma_0 R_0^{-1} $ \n", + " \n", + "Then for $t \\geq 1$ construct $b_t, R_t$ by\n", + "iterating on equation {eq}`eq:rtbt`.\n", + "\n", + "When we implement this part of method 1, we shall discover the following striking \n", + "outcome:\n", + "\n", + "* starting from an $R_0$ in $[\\frac{\\gamma_2}{\\gamma_1}, R_u]$, we shall find that \n", + "$\\{R_t\\}$ always converges to a limiting \"steady state\" value $\\bar R$ that depends on the initial\n", + "condition $R_0$.\n", + "\n", + "* there are only two possible limit points $\\{ R_\\ell, R_u\\}$. \n", + "\n", + "* for almost every initial condition $R_0$, $\\lim_{t \\rightarrow +\\infty} R_t = R_\\ell$.\n", + "\n", + "* if and only if $R_0 = R_u$, $\\lim_{t \\rightarrow +\\infty} R_t = R_u$.\n", + " \n", + "The quantity $1 - R_t$ can be interpreted as an **inflation tax rate** that the government imposes on holders of its currency.\n", + "\n", + "We shall soon see that the existence of two steady-state rates of return on currency\n", + "that serve to finance the government deficit of $g$ indicates the presence of a **Laffer curve** in the inflation tax rate. \n", + "\n", + "```{note}\n", + "Arthur Laffer's curve plots a hump shaped curve of revenue raised from a tax against the tax rate. \n", + "Its hump shape indicates that there are typically two tax rates that yield the same amount of revenue. This is due to two countervailing courses, one being that raising a tax rate typically decreases the **base** of the tax as people take decisions to reduce their exposure to the tax.\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d6ed2ff3", + "metadata": {}, + "outputs": [], + "source": [ + "def simulate_system(R0, model, num_steps):\n", + " γ1, γ2, g = model.γ1, model.γ2, model.g\n", + "\n", + " # Initialize arrays to store results\n", + " b_values = np.empty(num_steps)\n", + " R_values = np.empty(num_steps)\n", + "\n", + " # Initial values\n", + " b_values[0] = γ1 - γ2/R0\n", + " R_values[0] = 1 / (γ1/γ2 - (1 / γ2) * b_values[0])\n", + "\n", + " # Iterate over time steps\n", + " for t in range(1, num_steps):\n", + " b_t = b_values[t - 1] * R_values[t - 1] + g\n", + " R_values[t] = 1 / (γ1/γ2 - (1/γ2) * b_t)\n", + " b_values[t] = b_t\n", + "\n", + " return b_values, R_values" + ] + }, + { + "cell_type": "markdown", + "id": "d9abdcc5", + "metadata": {}, + "source": [ + "Let's write some code to plot outcomes for several possible initial values $R_0$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "56ed07cf", + "metadata": { + "tags": [ + "hide-cell" + ] + }, + "outputs": [], + "source": [ + "line_params = {'lw': 1.5, \n", + " 'marker': 'o',\n", + " 'markersize': 3}\n", + "\n", + "def annotate_graph(ax, model, num_steps):\n", + " for y, label in [(model.R_u, '$R_u$'), (model.R_l, '$R_l$'), \n", + " (model.γ2 / model.γ1, r'$\\frac{\\gamma_2}{\\gamma_1}$')]:\n", + " ax.axhline(y=y, color='grey', linestyle='--', lw=1.5, alpha=0.6)\n", + " ax.text(num_steps * 1.02, y, label, verticalalignment='center', \n", + " color='grey', size=12)\n", + "\n", + "def draw_paths(R0_values, model, line_params, num_steps):\n", + "\n", + " fig, axes = plt.subplots(2, 1, figsize=(8, 8), sharex=True)\n", + " \n", + " # Pre-compute time steps\n", + " time_steps = np.arange(num_steps) \n", + " \n", + " # Iterate over R_0s and simulate the system \n", + " for R0 in R0_values:\n", + " b_values, R_values = simulate_system(R0, model, num_steps)\n", + " \n", + " # Plot R_t against time\n", + " axes[0].plot(time_steps, R_values, **line_params)\n", + " \n", + " # Plot b_t against time\n", + " axes[1].plot(time_steps, b_values, **line_params)\n", + " \n", + " # Add line and text annotations to the subgraph \n", + " annotate_graph(axes[0], model, num_steps)\n", + " \n", + " # Add Labels\n", + " axes[0].set_ylabel('$R_t$')\n", + " axes[1].set_xlabel('timestep')\n", + " axes[1].set_ylabel('$b_t$')\n", + " axes[1].xaxis.set_major_locator(MaxNLocator(integer=True))\n", + " \n", + " plt.tight_layout()\n", + " plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "562b5182", + "metadata": {}, + "source": [ + "Let's plot distinct outcomes associated with several $R_0 \\in [\\frac{\\gamma_2}{\\gamma_1}, R_u]$.\n", + "\n", + "Each line below shows a path associated with a different $R_0$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "90dd8b02", + "metadata": { + "mystnb": { + "figure": { + "caption": "Paths of $R_t$ (top panel) and $b_t$ (bottom panel) starting from different initial condition $R_0$", + "name": "R0_path", + "width": "500px" + } + } + }, + "outputs": [], + "source": [ + "# Create a grid of R_0s\n", + "R0s = np.linspace(msm.γ2/msm.γ1, msm.R_u, 9)\n", + "R0s = np.append(msm.R_l, R0s)\n", + "draw_paths(R0s, msm, line_params, num_steps=20)" + ] + }, + { + "cell_type": "markdown", + "id": "946d8e1f", + "metadata": {}, + "source": [ + "Notice how sequences that start from $R_0$ in the half-open interval $[R_\\ell, R_u)$ converge to the steady state associated with to $ R_\\ell$.\n", + "\n", + "## Computation method 2 \n", + "\n", + "Set $m_t = m_t^d $ for all $t \\geq -1$. \n", + "\n", + "Let \n", + "\n", + "$$\n", + "y_t = \\begin{bmatrix} m_{t} \\cr p_{t} \\end{bmatrix} .\n", + "$$\n", + "\n", + "Represent equilibrium conditions {eq}`eq:demandmoney`, {eq}`eq:budgcontraint`, and {eq}`eq:syeqdemand` as\n", + "\n", + "$$\n", + "\\begin{bmatrix} 1 & \\gamma_2 \\cr\n", + " 1 & 0 \\end{bmatrix} \\begin{bmatrix} m_{t+1} \\cr p_{t+1} \\end{bmatrix} =\n", + " \\begin{bmatrix} 0 & \\gamma_1 \\cr\n", + " 1 & g \\end{bmatrix} \\begin{bmatrix} m_{t} \\cr p_{t} \\end{bmatrix} \n", + "$$ (eq:sytem101)\n", + "\n", + "or\n", + "\n", + "$$ \n", + "H_1 y_t = H_2 y_{t-1} \n", + "$$\n", + "\n", + "where \n", + "\n", + "$$\n", + "\\begin{aligned} H_1 & = \\begin{bmatrix} 1 & \\gamma_2 \\cr\n", + " 1 & 0 \\end{bmatrix} \\cr\n", + " H_2 & = \\begin{bmatrix} 0 & \\gamma_1 \\cr\n", + " 1 & g \\end{bmatrix} \n", + "\\end{aligned}\n", + "$$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e07f4a88", + "metadata": {}, + "outputs": [], + "source": [ + "H1 = np.array([[1, msm.γ2], \n", + " [1, 0]])\n", + "H2 = np.array([[0, msm.γ1], \n", + " [1, msm.g]]) " + ] + }, + { + "cell_type": "markdown", + "id": "68ca7a68", + "metadata": {}, + "source": [ + "Define\n", + "\n", + "$$\n", + "H = H_1^{-1} H_2\n", + "$$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1250f4e4", + "metadata": {}, + "outputs": [], + "source": [ + "H = np.linalg.solve(H1, H2)\n", + "print('H = \\n', H)" + ] + }, + { + "cell_type": "markdown", + "id": "f6612e31", + "metadata": {}, + "source": [ + "and write the system {eq}`eq:sytem101` as\n", + "\n", + "$$\n", + "y_{t+1} = H y_t, \\quad t \\geq 0 \n", + "$$ (eq:Vaughn)\n", + "\n", + "so that $\\{y_t\\}_{t=0}$ can be computed from\n", + "\n", + "$$\n", + "y_t = H^t y_0, t \\geq 0\n", + "$$ (eq:ytiterate)\n", + "\n", + "where \n", + "\n", + "$$\n", + "y_0 = \\begin{bmatrix} m_{0} \\cr p_0 \\end{bmatrix} .\n", + "$$\n", + "\n", + "It is natural to take $m_0$ as an initial condition determined outside the model.\n", + "\n", + "The mathematics seems to tell us that $p_0$ must also be determined outside the model, even though\n", + "it is something that we actually wanted to be determined by the model.\n", + "\n", + "(As usual, we should listen when mathematics talks to us.)\n", + "\n", + "For now, let's just proceed mechanically on faith. \n", + "\n", + "Compute the eigenvector decomposition \n", + "\n", + "$$\n", + "H = Q \\Lambda Q^{-1} \n", + "$$ \n", + "\n", + "where $\\Lambda$ is a diagonal matrix of eigenvalues and the columns of $Q$ are eigenvectors corresponding to those eigenvalues.\n", + "\n", + "It turns out that \n", + "\n", + "$$\n", + "\\Lambda = \\begin{bmatrix} {R_\\ell}^{-1} & 0 \\cr \n", + " 0 & {R_u}^{-1} \\end{bmatrix}\n", + "$$\n", + "\n", + "where $R_\\ell$ and $R_u$ are the lower and higher steady-state rates of return on currency that we computed above." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7b8c19b6", + "metadata": {}, + "outputs": [], + "source": [ + "Λ, Q = np.linalg.eig(H)\n", + "print('Λ = \\n', Λ)\n", + "print('Q = \\n', Q)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4b48bfcd", + "metadata": {}, + "outputs": [], + "source": [ + "R_l = 1 / Λ[0]\n", + "R_u = 1 / Λ[1]\n", + "\n", + "print(f'R_l = {R_l:.4f}')\n", + "print(f'R_u = {R_u:.4f}')" + ] + }, + { + "cell_type": "markdown", + "id": "1545922a", + "metadata": {}, + "source": [ + "Partition $Q$ as\n", + "\n", + "$$ \n", + "Q =\\begin{bmatrix} Q_{11} & Q_{12} \\cr\n", + " Q_{21} & Q_{22} \\end{bmatrix}\n", + "$$\n", + "\n", + "Below we shall verify the following claims: \n", + "\n", + "\n", + "**Claims:** If we set \n", + "\n", + "$$\n", + "p_0 = \\overline p_0 \\equiv Q_{21} Q_{11}^{-1} m_{0} ,\n", + "$$ (eq:magicp0)\n", + "\n", + "it turns out that \n", + "\n", + "$$ \n", + "\\frac{p_{t+1}}{p_t} = {R_u}^{-1}, \\quad t \\geq 0\n", + "$$\n", + "\n", + "\n", + "However, if we set \n", + "\n", + "$$ \n", + "p_0 > \\bar p_0\n", + "$$\n", + "\n", + "then\n", + "\n", + "$$\n", + "\\lim_{t\\rightarrow + \\infty} \\frac{p_{t+1}}{p_t} = {R_\\ell}^{-1}.\n", + "$$\n", + "\n", + "Let's verify these claims step by step.\n", + "\n", + "\n", + "\n", + "Note that\n", + "\n", + "$$\n", + "H^t = Q \\Lambda^t Q^{-1}\n", + "$$\n", + "\n", + "so that\n", + "\n", + "$$\n", + "y_t = Q \\Lambda^t Q^{-1} y_0\n", + "$$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fa35576b", + "metadata": {}, + "outputs": [], + "source": [ + "def iterate_H(y_0, H, num_steps):\n", + " Λ, Q = np.linalg.eig(H)\n", + " Q_inv = np.linalg.inv(Q)\n", + " y = np.stack(\n", + " [Q @ np.diag(Λ**t) @ Q_inv @ y_0 for t in range(num_steps)], 1)\n", + " \n", + " return y" + ] + }, + { + "cell_type": "markdown", + "id": "1ba0670e", + "metadata": {}, + "source": [ + "For almost all initial vectors $y_0$, the gross rate of inflation $\\frac{p_{t+1}}{p_t}$ eventually converges to the larger eigenvalue ${R_\\ell}^{-1}$.\n", + "\n", + "The only way to avoid this outcome is for $p_0$ to take the specific value described by {eq}`eq:magicp0`.\n", + "\n", + "To understand this situation, we use the following\n", + "transformation\n", + "\n", + "$$\n", + "y^*_t = Q^{-1} y_t . \n", + "$$\n", + "\n", + "Dynamics of $y^*_t$ are evidently governed by \n", + "\n", + "$$\n", + "y^*_{t+1} = \\Lambda^t y^*_t .\n", + "$$ (eq:stardynamics)\n", + "\n", + "This equation represents the dynamics of our system in a way that lets us isolate the\n", + "force that causes gross inflation to converge to the inverse of the lower steady-state rate\n", + "of inflation $R_\\ell$ that we discovered earlier. \n", + "\n", + "Staring at equation {eq}`eq:stardynamics` indicates that unless\n", + "\n", + "```{math}\n", + ":label: equation_11\n", + "\n", + "y^*_0 = \\begin{bmatrix} y^*_{1,0} \\cr 0 \\end{bmatrix}\n", + "```\n", + "\n", + "the path of $y^*_t$, and therefore the paths of both $m_t$ and $p_t$ given by\n", + "$y_t = Q y^*_t$ will eventually grow at gross rates ${R_\\ell}^{-1}$ as \n", + "$t \\rightarrow +\\infty$. \n", + "\n", + "Equation {eq}`equation_11` also leads us to conclude that there is a unique setting\n", + "for the initial vector $y_0$ for which both components forever grow at the lower rate ${R_u}^{-1}$. \n", + "\n", + "\n", + "For this to occur, the required setting of $y_0$ must evidently have the property\n", + "that\n", + "\n", + "$$\n", + "Q^{-1} y_0 = y^*_0 = \\begin{bmatrix} y^*_{1,0} \\cr 0 \\end{bmatrix} .\n", + "$$\n", + "\n", + "But note that since\n", + "$y_0 = \\begin{bmatrix} m_0 \\cr p_0 \\end{bmatrix}$ and $m_0$\n", + "is given to us an initial condition, $p_0$ has to do all the adjusting to satisfy this equation.\n", + "\n", + "Sometimes this situation is described informally by saying that while $m_0$\n", + "is truly a **state** variable, $p_0$ is a **jump** variable that\n", + "must adjust at $t=0$ in order to satisfy the equation.\n", + "\n", + "Thus, in a nutshell the unique value of the vector $y_0$ for which\n", + "the paths of $y_t$ *don't* eventually grow at rate ${R_\\ell}^{-1}$ requires setting the second component\n", + "of $y^*_0$ equal to zero.\n", + "\n", + "The component $p_0$ of the initial vector\n", + "$y_0 = \\begin{bmatrix} m_0 \\cr p_0 \\end{bmatrix}$ must evidently\n", + "satisfy\n", + "\n", + "$$\n", + "Q^{\\{2\\}} y_0 =0\n", + "$$\n", + "\n", + "where $Q^{\\{2\\}}$ denotes the second row of $Q^{-1}$, a\n", + "restriction that is equivalent to\n", + "\n", + "```{math}\n", + ":label: equation_12\n", + "\n", + "Q^{21} m_0 + Q^{22} p_0 = 0\n", + "```\n", + "\n", + "where $Q^{ij}$ denotes the $(i,j)$ component of\n", + "$Q^{-1}$.\n", + "\n", + "Solving this equation for $p_0$, we find\n", + "\n", + "```{math}\n", + ":label: equation_13\n", + "\n", + "p_0 = - (Q^{22})^{-1} Q^{21} m_0.\n", + "```\n", + "\n", + "\n", + "### More convenient formula \n", + "\n", + "We can get the equivalent but perhaps more convenient formula {eq}`eq:magicp0` for $p_0$ that is cast\n", + "in terms of components of $Q$ instead of components of\n", + "$Q^{-1}$.\n", + "\n", + "To get this formula, first note that because $(Q^{21}\\ Q^{22})$ is\n", + "the second row of the inverse of $Q$ and because\n", + "$Q^{-1} Q = I$, it follows that\n", + "\n", + "$$\n", + "\\begin{bmatrix} Q^{21} & Q^{22} \\end{bmatrix} \\begin{bmatrix} Q_{11}\\cr Q_{21} \\end{bmatrix} = 0\n", + "$$\n", + "\n", + "which implies that\n", + "\n", + "$$\n", + "Q^{21} Q_{11} + Q^{22} Q_{21} = 0.\n", + "$$\n", + "\n", + "Therefore,\n", + "\n", + "$$\n", + "-(Q^{22})^{-1} Q^{21} = Q_{21} Q^{-1}_{11}.\n", + "$$\n", + "\n", + "So we can write\n", + "\n", + "```{math}\n", + "\n", + "p_0 = Q_{21} Q_{11}^{-1} m_0 .\n", + "```\n", + "\n", + "which is our formula {eq}`eq:magicp0`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "39259df1", + "metadata": {}, + "outputs": [], + "source": [ + "p0_bar = (Q[1, 0]/Q[0, 0]) * msm.M0\n", + "\n", + "print(f'p0_bar = {p0_bar:.4f}')" + ] + }, + { + "cell_type": "markdown", + "id": "003330ff", + "metadata": {}, + "source": [ + "It can be verified that this formula replicates itself over time in the sense that\n", + "\n", + "```{math}\n", + ":label: equation_15\n", + "\n", + "p_t = Q_{21} Q^{-1}_{11} m_t.\n", + "```\n", + "\n", + "Now let's visualize the dynamics of $m_t$, $p_t$, and $R_t$ starting from different $p_0$ values to verify our claims above.\n", + "\n", + "We create a function `draw_iterations` to generate the plot" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a5b58ed3", + "metadata": { + "tags": [ + "hide-cell" + ] + }, + "outputs": [], + "source": [ + "def draw_iterations(p0s, model, line_params, num_steps):\n", + "\n", + " fig, axes = plt.subplots(3, 1, figsize=(8, 10), sharex=True)\n", + " \n", + " # Pre-compute time steps\n", + " time_steps = np.arange(num_steps) \n", + " \n", + " # Plot the first two y-axes in log scale\n", + " for ax in axes[:2]:\n", + " ax.set_yscale('log')\n", + "\n", + " # Iterate over p_0s and calculate a series of y_t\n", + " for p0 in p0s:\n", + " y0 = np.array([msm.M0, p0])\n", + " y_series = iterate_H(y0, H, num_steps)\n", + " M, P = y_series[0, :], y_series[1, :]\n", + "\n", + " # Plot R_t against time\n", + " axes[0].plot(time_steps, M, **line_params)\n", + "\n", + " # Plot b_t against time\n", + " axes[1].plot(time_steps, P, **line_params)\n", + " \n", + " # Calculate R_t\n", + " R = np.insert(P[:-1] / P[1:], 0, np.NAN)\n", + " axes[2].plot(time_steps, R, **line_params)\n", + " \n", + " # Add line and text annotations to the subgraph \n", + " annotate_graph(axes[2], model, num_steps)\n", + " \n", + " # Draw labels\n", + " axes[0].set_ylabel('$m_t$')\n", + " axes[1].set_ylabel('$p_t$')\n", + " axes[2].set_ylabel('$R_t$')\n", + " axes[2].set_xlabel('timestep')\n", + " \n", + " # Enforce integar axis label\n", + " axes[2].xaxis.set_major_locator(MaxNLocator(integer=True))\n", + "\n", + " plt.tight_layout()\n", + " plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2a44a454", + "metadata": { + "mystnb": { + "figure": { + "caption": "Starting from different initial values of $p_0$, paths of $m_t$ (top panel, log scale for $m$), $p_t$ (middle panel, log scale for $m$), $R_t$ (bottom panel)", + "name": "p0_path", + "width": "500px" + } + } + }, + "outputs": [], + "source": [ + "p0s = [p0_bar, 2.34, 2.5, 3, 4, 7, 30, 100_000]\n", + "\n", + "draw_iterations(p0s, msm, line_params, num_steps=20)" + ] + }, + { + "cell_type": "markdown", + "id": "998e268a", + "metadata": {}, + "source": [ + "Please notice that for $m_t$ and $p_t$, we have used log scales for the coordinate (i.e., vertical) axes. \n", + "\n", + "Using log scales allows us to spot distinct constant limiting gross rates of growth ${R_u}^{-1}$ and\n", + "${R_\\ell}^{-1}$ by eye.\n", + "\n", + "\n", + "## Peculiar stationary outcomes\n", + "\n", + "As promised at the start of this lecture, we have encountered these concepts from macroeconomics:\n", + "\n", + "* an **inflation tax** that a government gathers by printing paper or electronic money\n", + "* a dynamic **Laffer curve** in the inflation tax rate that has two stationary equilibria\n", + "\n", + "Staring at the paths of rates of return on the price level in figure {numref}`R0_path` and price levels in {numref}`p0_path` show indicate that almost all paths converge to the *higher* inflation tax rate displayed in the stationary state Laffer curve displayed in figure {numref}`infl_tax`. \n", + "\n", + "Thus, we have indeed discovered what we earlier called \"perverse\" dynamics under rational expectations in which the system converges to the higher of two possible stationary inflation tax rates.\n", + "\n", + "Those dynamics are \"perverse\" not only in the sense that they imply that the monetary and fiscal authorities that have chosen to finance government expenditures eventually impose a higher inflation tax than required to finance government expenditures, but because of the following \"counterintuitive\" situation that we can deduce by staring at the stationary state Laffer curve displayed in figure {numref}`infl_tax`:\n", + "\n", + "* the figure indicates that inflation can be *reduced* by running *higher* government deficits, i.e., by raising more resources through printing money. \n", + "\n", + "\n", + "```{note}\n", + "The same qualitative outcomes prevail in this lecture {doc}`money_inflation_nonlinear` that studies a nonlinear version of the model in this lecture.\n", + "```\n", + "\n", + "\n", + "## Equilibrium selection \n", + "\n", + "We have discovered that as a model of price level paths or model is **incomplete** because there is a continuum of \"equilibrium\" paths for $\\{m_{t+1}, p_t\\}_{t=0}^\\infty$ that are consistent with the demand for real balances always equaling the supply.\n", + " \n", + "\n", + "Through application of our computational methods 1 and 2, we have learned that this continuum can be indexed by choice of one of two scalars:\n", + "\n", + "* for computational method 1, $R_0$ \n", + "* for computational method 2, $p_0$\n", + "\n", + "To apply our model, we have somehow to *complete* it by *selecting* an equilibrium path from among the continuum of possible paths. \n", + "\n", + "We discovered that \n", + "\n", + " * all but one of the equilibrium paths converge to limits in which the higher of two possible stationary inflation tax prevails\n", + " * there is a unique equilibrium path associated with \"plausible\" statements about how reductions in government deficits affect a stationary inflation rate\n", + "\n", + "On grounds of plausibility, we recommend following many macroeconomists in selecting the unique equilibrium that converges to the lower stationary inflation tax rate. \n", + "\n", + "As we shall see, we shall accept this recommendation in lecture {doc}`unpleasant`.\n", + "\n", + "In lecture, {doc}`laffer_adaptive`, we shall explore how {cite}`bruno1990seigniorage` and others justified this in other ways." + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.16.1" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 258, + 264, + 270, + 284, + 288, + 303, + 313, + 336, + 344, + 350, + 479, + 498, + 502, + 544, + 550, + 563, + 602, + 607, + 615, + 618, + 664, + 670, + 676, + 729, + 737, + 859, + 863, + 877, + 923, + 936 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/money_inflation.md b/book/_build/html/_sources/money_inflation.md new file mode 100644 index 0000000..d7e37ec --- /dev/null +++ b/book/_build/html/_sources/money_inflation.md @@ -0,0 +1,986 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.16.1 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Money Financed Government Deficits and Price Levels + +## Overview + +This lecture extends and modifies the model in this lecture {doc}`cagan_ree` by modifying the +law of motion that governed the supply of money. + +The model in this lecture consists of two components + +* a demand function for money +* a law of motion for the supply of money + +The demand function describes the public's demand for "real balances", defined as the ratio of nominal money balances to the price level + +* it assumes that the demand for real balance today varies inversely with the rate of inflation that the public forecasts to prevail between today and tomorrow +* it assumes that the public's forecast of that rate of inflation is perfect + +The law of motion for the supply of money assumes that the government prints money to finance government expenditures + +Our model equates the demand for money to the supply at each time $t \geq 0$. + +Equality between those demands and supply gives a *dynamic* model in which money supply +and price level *sequences* are simultaneously determined by a set of simultaneous linear equations. + +These equations take the form of what is often called vector linear **difference equations**. + +In this lecture, we'll roll up our sleeves and solve those equations in two different ways. + + +(One of the methods for solving vector linear difference equations will take advantage of a decomposition of a matrix that is studied in this lecture {doc}`eigen_I`.) + +In this lecture we will encounter these concepts from macroeconomics: + +* an **inflation tax** that a government gathers by printing paper or electronic money +* a dynamic **Laffer curve** in the inflation tax rate that has two stationary equilibria +* perverse dynamics under rational expectations in which the system converges to the higher stationary inflation tax rate +* a peculiar comparative stationary-state outcome connected with that stationary inflation rate: it asserts that inflation can be *reduced* by running *higher* government deficits, i.e., by raising more resources by printing money. + +The same qualitative outcomes prevail in this lecture {doc}`money_inflation_nonlinear` that studies a nonlinear version of the model in this lecture. + +These outcomes set the stage for the analysis to be presented in this lecture {doc}`laffer_adaptive` that studies a nonlinear version of the present model; it assumes a version of "adaptive expectations" instead of rational expectations. + +That lecture will show that + +* replacing rational expectations with adaptive expectations leaves the two stationary inflation rates unchanged, but that $\ldots$ +* it reverses the perverse dynamics by making the *lower* stationary inflation rate the one to which the system typically converges +* a more plausible comparative dynamic outcome emerges in which now inflation can be *reduced* by running *lower* government deficits + +This outcome will be used to justify a selection of a stationary inflation rate that underlies the analysis of unpleasant monetarist arithmetic to be studied in this lecture {doc}`unpleasant`. + +We'll use these tools from linear algebra: + +* matrix multiplication +* matrix inversion +* eigenvalues and eigenvectors of a matrix + + +## Demand for and supply of money + +We say demand*s* and suppl*ies* (plurals) because there is one of each for each $t \geq 0$. + +Let + +* $m_{t+1}$ be the supply of currency at the end of time $t \geq 0$ +* $m_{t}$ be the supply of currency brought into time $t$ from time $t-1$ +* $g$ be the government deficit that is financed by printing currency at $t \geq 1$ +* $m_{t+1}^d$ be the demand at time $t$ for currency to bring into time $t+1$ +* $p_t$ be the price level at time $t$ +* $b_t = \frac{m_{t+1}}{p_t}$ is real balances at the end of time $t$ +* $R_t = \frac{p_t}{p_{t+1}} $ be the gross rate of return on currency held from time $t$ to time $t+1$ + +It is often helpful to state units in which quantities are measured: + +* $m_t$ and $m_t^d$ are measured in dollars +* $g$ is measured in time $t$ goods +* $p_t$ is measured in dollars per time $t$ goods +* $R_t$ is measured in time $t+1$ goods per unit of time $t$ goods +* $b_t$ is measured in time $t$ goods + + +Our job now is to specify demand and supply functions for money. + +We assume that the demand for currency satisfies the Cagan-like demand function + +$$ +\frac{m_{t+1}^d}{p_t}=\gamma_1 - \gamma_2 \frac{p_{t+1}}{p_t}, \quad t \geq 0 +$$ (eq:demandmoney) +where $\gamma_1, \gamma_2$ are positive parameters. + +Now we turn to the supply of money. + +We assume that $m_0 >0$ is an "initial condition" determined outside the model. + +We set $m_0$ at some arbitrary positive value, say \$100. + +For $ t \geq 1$, we assume that the supply of money is determined by the government's budget constraint + +$$ +m_{t+1} - m_{t} = p_t g , \quad t \geq 0 +$$ (eq:budgcontraint) + +According to this equation, each period, the government prints money to pay for quantity $g$ of goods. + +In an **equilibrium**, the demand for currency equals the supply: + +$$ +m_{t+1}^d = m_{t+1}, \quad t \geq 0 +$$ (eq:syeqdemand) + +Let's take a moment to think about what equation {eq}`eq:syeqdemand` tells us. + +The demand for money at any time $t$ depends on the price level at time $t$ and the price level at time $t+1$. + +The supply of money at time $t+1$ depends on the money supply at time $t$ and the price level at time $t$. + +So the infinite sequence of equations {eq}`eq:syeqdemand` for $ t \geq 0$ imply that the *sequences* $\{p_t\}_{t=0}^\infty$ and $\{m_t\}_{t=0}^\infty$ are tied together and ultimately simulataneously determined. + + +## Equilibrium price and money supply sequences + + +The preceding specifications imply that for $t \geq 1$, **real balances** evolve according to + + +$$ +\frac{m_{t+1}}{p_t} - \frac{m_{t}}{p_{t-1}} \frac{p_{t-1}}{p_t} = g +$$ + +or + +$$ +b_t - b_{t-1} R_{t-1} = g +$$ (eq:bmotion) + +The demand for real balances is + +$$ +b_t = \gamma_1 - \gamma_2 R_t^{-1} . +$$ (eq:bdemand) + +We'll restrict our attention to parameter values and associated gross real rates of return on real balances that assure that the demand for real balances is positive, which according to {eq}`eq:bdemand` means that + +$$ +b_t = \gamma_1 - \gamma_2 R_t^{-1} > 0 +$$ + +which implies that + +$$ +R_t \geq \left( \frac{\gamma_2}{\gamma_1} \right) \equiv \underline R +$$ (eq:Requation) + +Gross real rate of return $\underline R$ is the smallest rate of return on currency +that is consistent with a nonnegative demand for real balances. + +We shall describe two distinct but closely related ways of computing a pair $\{p_t, m_t\}_{t=0}^\infty$ of sequences for the price level and money supply. + +But first it is instructive to describe a special type of equilibrium known as a **steady state**. + +In a steady-state equilibrium, a subset of key variables remain constant or **invariant** over time, while remaining variables can be expressed as functions of those constant variables. + +Finding such state variables is something of an art. + +In many models, a good source of candidates for such invariant variables is a set of *ratios*. + +This is true in the present model. + +### Steady states + +In a steady-state equilibrium of the model we are studying, + +$$ +\begin{aligned} +R_t & = \bar R \cr +b_t & = \bar b +\end{aligned} +$$ + +for $t \geq 0$. + +Notice that both $R_t = \frac{p_t}{p_{t+1}}$ and $b_t = \frac{m_{t+1}}{p_t} $ are *ratios*. + +To compute a steady state, we seek gross rates of return on currency and real balances $\bar R, \bar b$ that satisfy steady-state versions of both the government budget constraint and the demand function for real balances: + +$$ +\begin{aligned} +g & = \bar b ( 1 - \bar R) \cr +\bar b & = \gamma_1- \gamma_2 \bar R^{-1} +\end{aligned} +$$ + +Together these equations imply + +$$ +(\gamma_1 + \gamma_2) - \frac{\gamma_2}{\bar R} - \gamma_1 \bar R = g +$$ (eq:seignsteady) + + +The left side is the steady-state amount of **seigniorage** or government revenues that the government gathers by paying a gross rate of return $\bar R \le 1$ on currency. + +The right side is government expenditures. + +Define steady-state seigniorage as + +$$ +S(\bar R) = (\gamma_1 + \gamma_2) - \frac{\gamma_2}{\bar R} - \gamma_1 \bar R +$$ (eq:SSsigng) + +Notice that $S(\bar R) \geq 0$ only when $\bar R \in [\frac{\gamma_2}{\gamma_1}, 1] +\equiv [\underline R, \overline R]$ and that $S(\bar R) = 0$ if $\bar R = \underline R$ +or if $\bar R = \overline R$. + +We shall study equilibrium sequences that satisfy + +$$ +R_t \in [\underline R, \overline R], \quad t \geq 0. +$$ + +Maximizing steady-state seigniorage {eq}`eq:SSsigng` with respect to $\bar R$, we find that the maximizing rate of return on currency is + +$$ +\bar R_{\rm max} = \sqrt{\frac{\gamma_2}{\gamma_1}} +$$ + +and that the associated maximum seigniorage revenue that the government can gather from printing money is + +$$ +(\gamma_1 + \gamma_2) - \frac{\gamma_2}{\bar R_{\rm max}} - \gamma_1 \bar R_{\rm max} +$$ + +It is useful to rewrite equation {eq}`eq:seignsteady` as + +$$ +-\gamma_2 + (\gamma_1 + \gamma_2 - g) \bar R - \gamma_1 \bar R^2 = 0 +$$ (eq:steadyquadratic) + +A steady state gross rate of return $\bar R$ solves quadratic equation {eq}`eq:steadyquadratic`. + +So two steady states typically exist. + +## Some code + +Let's start with some imports: + +```{code-cell} ipython3 +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.ticker import MaxNLocator +plt.rcParams['figure.dpi'] = 300 +from collections import namedtuple +``` + +Let's set some parameter values and compute possible steady-state rates of return on currency $\bar R$, the seigniorage maximizing rate of return on currency, and an object that we'll discuss later, namely, an initial price level $p_0$ associated with the maximum steady-state rate of return on currency. + +First, we create a `namedtuple` to store parameters so that we can reuse this `namedtuple` in our functions throughout this lecture + +```{code-cell} ipython3 +# Create a namedtuple that contains parameters +MoneySupplyModel = namedtuple("MoneySupplyModel", + ["γ1", "γ2", "g", + "M0", "R_u", "R_l"]) + +def create_model(γ1=100, γ2=50, g=3.0, M0=100): + + # Calculate the steady states for R + R_steady = np.roots((-γ1, γ1 + γ2 - g, -γ2)) + R_u, R_l = R_steady + print("[R_u, R_l] =", R_steady) + + return MoneySupplyModel(γ1=γ1, γ2=γ2, g=g, M0=M0, R_u=R_u, R_l=R_l) +``` + +Now we compute the $\bar R_{\rm max}$ and corresponding revenue + +```{code-cell} ipython3 +def seign(R, model): + γ1, γ2, g = model.γ1, model.γ2, model.g + return -γ2/R + (γ1 + γ2) - γ1 * R + +msm = create_model() + +# Calculate initial guess for p0 +p0_guess = msm.M0 / (msm.γ1 - msm.g - msm.γ2 / msm.R_u) +print(f'p0 guess = {p0_guess:.4f}') + +# Calculate seigniorage maximizing rate of return +R_max = np.sqrt(msm.γ2/msm.γ1) +g_max = seign(R_max, msm) +print(f'R_max, g_max = {R_max:.4f}, {g_max:.4f}') +``` + +Now let's plot seigniorage as a function of alternative potential steady-state values of $R$. + +We'll see that there are two steady-state values of $R$ that attain seigniorage levels equal to $g$, +one that we'll denote $R_\ell$, another that we'll denote $R_u$. + +They satisfy $R_\ell < R_u$ and are affiliated with a higher inflation tax rate $(1-R_\ell)$ and a lower +inflation tax rate $1 - R_u$. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Steady state revenue from inflation tax as function of steady state gross return on currency (solid blue curve) and real government expenditures (dotted red line) plotted against steady-state rate of return currency + name: infl_tax + width: 500px +--- +# Generate values for R +R_values = np.linspace(msm.γ2/msm.γ1, 1, 250) + +# Calculate the function values +seign_values = seign(R_values, msm) + +# Visualize seign_values against R values +fig, ax = plt.subplots(figsize=(11, 5)) +plt.plot(R_values, seign_values, label='inflation tax revenue') +plt.axhline(y=msm.g, color='red', linestyle='--', label='government deficit') +plt.xlabel('$R$') +plt.ylabel('seigniorage') + +plt.legend() +plt.show() +``` + +Let's print the two steady-state rates of return $\bar R$ and the associated seigniorage revenues that the government collects. + +(By construction, both steady-state rates of return should raise the same amounts real revenue.) + +We hope that the following code will confirm this. + +```{code-cell} ipython3 +g1 = seign(msm.R_u, msm) +print(f'R_u, g_u = {msm.R_u:.4f}, {g1:.4f}') + +g2 = seign(msm.R_l, msm) +print(f'R_l, g_l = {msm.R_l:.4f}, {g2:.4f}') +``` + +Now let's compute the maximum steady-state amount of seigniorage that could be gathered by printing money and the state-state rate of return on money that attains it. + +## Two computation strategies + +We now proceed to compute equilibria, not necessarily steady states. + +We shall deploy two distinct computation strategies. + +### Method 1 + +* set $R_0 \in [\frac{\gamma_2}{\gamma_1}, R_u]$ and compute $b_0 = \gamma_1 - \gamma_2/R_0$. + +* compute sequences $\{R_t, b_t\}_{t=1}^\infty$ of rates of return and real balances that are associated with an equilibrium by solving equation {eq}`eq:bmotion` and {eq}`eq:bdemand` sequentially for $t \geq 1$: + +$$ +\begin{aligned} +b_t & = b_{t-1} R_{t-1} + g \cr +R_t^{-1} & = \frac{\gamma_1}{\gamma_2} - \gamma_2^{-1} b_t +\end{aligned} +$$ (eq:rtbt) + +* Construct the associated equilibrium $p_0$ from + +$$ +p_0 = \frac{m_0}{\gamma_1 - g - \gamma_2/R_0} +$$ (eq:p0fromR0) + +* compute $\{p_t, m_t\}_{t=1}^\infty$ by solving the following equations sequentially + +$$ +\begin{aligned} +p_t & = R_t p_{t-1} \cr +m_t & = b_{t-1} p_t +\end{aligned} +$$ (eq:method1) + +```{prf:remark} +:label: method_1 +Method 1 uses an indirect approach to computing an equilibrium by first computing an equilibrium $\{R_t, b_t\}_{t=0}^\infty$ sequence and then using it to back out an equilibrium $\{p_t, m_t\}_{t=0}^\infty$ sequence. +``` + +```{prf:remark} +:label: initial_condition +Notice that method 1 starts by picking an **initial condition** $R_0$ from a set $[\frac{\gamma_2}{\gamma_1}, R_u]$. Equilibrium $\{p_t, m_t\}_{t=0}^\infty$ sequences are not unique. There is actually a continuum of equilibria indexed by a choice of $R_0$ from the set $[\frac{\gamma_2}{\gamma_1}, R_u]$. +``` + +```{prf:remark} +:label: unique_selection +Associated with each selection of $R_0$ there is a unique $p_0$ described by +equation {eq}`eq:p0fromR0`. +``` + +### Method 2 + +This method deploys a direct approach. +It defines a "state vector" +$y_t = \begin{bmatrix} m_t \cr p_t\end{bmatrix} $ +and formulates equilibrium conditions {eq}`eq:demandmoney`, {eq}`eq:budgcontraint`, and +{eq}`eq:syeqdemand` +in terms of a first-order vector difference equation + +$$ +y_{t+1} = M y_t, \quad t \geq 0 , +$$ + +where we temporarily take $y_0 = \begin{bmatrix} m_0 \cr p_0 \end{bmatrix}$ as an **initial condition**. + +The solution is + +$$ +y_t = M^t y_0 . +$$ + +Now let's think about the initial condition $y_0$. + +It is natural to take the initial stock of money $m_0 >0$ as an initial condition. + +But what about $p_0$? + +Isn't it something that we want to be *determined* by our model? + +Yes, but sometimes we want too much, because there is actually a continuum of initial $p_0$ levels that are compatible with the existence of an equilibrium. + +As we shall see soon, selecting an initial $p_0$ in method 2 is intimately tied to selecting an initial rate of return on currency $R_0$ in method 1. + +## Computation method 1 + +%We start from an arbitrary $R_0$ and $b_t = \frac{m_{t+1}}{p_t}$, we have + +%$$ +%b_0 = \gamma_1 - \gamma_0 R_0^{-1} +%$$ + +Remember that there exist two steady-state equilibrium values $ R_\ell < R_u$ of the rate of return on currency $R_t$. + +We proceed as follows. + +Start at $t=0$ +* select a $R_0 \in [\frac{\gamma_2}{\gamma_1}, R_u]$ +* compute $b_0 = \gamma_1 - \gamma_0 R_0^{-1} $ + +Then for $t \geq 1$ construct $b_t, R_t$ by +iterating on equation {eq}`eq:rtbt`. + +When we implement this part of method 1, we shall discover the following striking +outcome: + +* starting from an $R_0$ in $[\frac{\gamma_2}{\gamma_1}, R_u]$, we shall find that +$\{R_t\}$ always converges to a limiting "steady state" value $\bar R$ that depends on the initial +condition $R_0$. + +* there are only two possible limit points $\{ R_\ell, R_u\}$. + +* for almost every initial condition $R_0$, $\lim_{t \rightarrow +\infty} R_t = R_\ell$. + +* if and only if $R_0 = R_u$, $\lim_{t \rightarrow +\infty} R_t = R_u$. + +The quantity $1 - R_t$ can be interpreted as an **inflation tax rate** that the government imposes on holders of its currency. + +We shall soon see that the existence of two steady-state rates of return on currency +that serve to finance the government deficit of $g$ indicates the presence of a **Laffer curve** in the inflation tax rate. + +```{note} +Arthur Laffer's curve plots a hump shaped curve of revenue raised from a tax against the tax rate. +Its hump shape indicates that there are typically two tax rates that yield the same amount of revenue. This is due to two countervailing courses, one being that raising a tax rate typically decreases the **base** of the tax as people take decisions to reduce their exposure to the tax. +``` + +```{code-cell} ipython3 +def simulate_system(R0, model, num_steps): + γ1, γ2, g = model.γ1, model.γ2, model.g + + # Initialize arrays to store results + b_values = np.empty(num_steps) + R_values = np.empty(num_steps) + + # Initial values + b_values[0] = γ1 - γ2/R0 + R_values[0] = 1 / (γ1/γ2 - (1 / γ2) * b_values[0]) + + # Iterate over time steps + for t in range(1, num_steps): + b_t = b_values[t - 1] * R_values[t - 1] + g + R_values[t] = 1 / (γ1/γ2 - (1/γ2) * b_t) + b_values[t] = b_t + + return b_values, R_values +``` + +Let's write some code to plot outcomes for several possible initial values $R_0$. + +```{code-cell} ipython3 +:tags: [hide-cell] + +line_params = {'lw': 1.5, + 'marker': 'o', + 'markersize': 3} + +def annotate_graph(ax, model, num_steps): + for y, label in [(model.R_u, '$R_u$'), (model.R_l, '$R_l$'), + (model.γ2 / model.γ1, r'$\frac{\gamma_2}{\gamma_1}$')]: + ax.axhline(y=y, color='grey', linestyle='--', lw=1.5, alpha=0.6) + ax.text(num_steps * 1.02, y, label, verticalalignment='center', + color='grey', size=12) + +def draw_paths(R0_values, model, line_params, num_steps): + + fig, axes = plt.subplots(2, 1, figsize=(8, 8), sharex=True) + + # Pre-compute time steps + time_steps = np.arange(num_steps) + + # Iterate over R_0s and simulate the system + for R0 in R0_values: + b_values, R_values = simulate_system(R0, model, num_steps) + + # Plot R_t against time + axes[0].plot(time_steps, R_values, **line_params) + + # Plot b_t against time + axes[1].plot(time_steps, b_values, **line_params) + + # Add line and text annotations to the subgraph + annotate_graph(axes[0], model, num_steps) + + # Add Labels + axes[0].set_ylabel('$R_t$') + axes[1].set_xlabel('timestep') + axes[1].set_ylabel('$b_t$') + axes[1].xaxis.set_major_locator(MaxNLocator(integer=True)) + + plt.tight_layout() + plt.show() +``` + +Let's plot distinct outcomes associated with several $R_0 \in [\frac{\gamma_2}{\gamma_1}, R_u]$. + +Each line below shows a path associated with a different $R_0$. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Paths of $R_t$ (top panel) and $b_t$ (bottom panel) starting from different + initial condition $R_0$ + name: R0_path + width: 500px +--- +# Create a grid of R_0s +R0s = np.linspace(msm.γ2/msm.γ1, msm.R_u, 9) +R0s = np.append(msm.R_l, R0s) +draw_paths(R0s, msm, line_params, num_steps=20) +``` + +Notice how sequences that start from $R_0$ in the half-open interval $[R_\ell, R_u)$ converge to the steady state associated with to $ R_\ell$. + +## Computation method 2 + +Set $m_t = m_t^d $ for all $t \geq -1$. + +Let + +$$ +y_t = \begin{bmatrix} m_{t} \cr p_{t} \end{bmatrix} . +$$ + +Represent equilibrium conditions {eq}`eq:demandmoney`, {eq}`eq:budgcontraint`, and {eq}`eq:syeqdemand` as + +$$ +\begin{bmatrix} 1 & \gamma_2 \cr + 1 & 0 \end{bmatrix} \begin{bmatrix} m_{t+1} \cr p_{t+1} \end{bmatrix} = + \begin{bmatrix} 0 & \gamma_1 \cr + 1 & g \end{bmatrix} \begin{bmatrix} m_{t} \cr p_{t} \end{bmatrix} +$$ (eq:sytem101) + +or + +$$ +H_1 y_t = H_2 y_{t-1} +$$ + +where + +$$ +\begin{aligned} H_1 & = \begin{bmatrix} 1 & \gamma_2 \cr + 1 & 0 \end{bmatrix} \cr + H_2 & = \begin{bmatrix} 0 & \gamma_1 \cr + 1 & g \end{bmatrix} +\end{aligned} +$$ + +```{code-cell} ipython3 +H1 = np.array([[1, msm.γ2], + [1, 0]]) +H2 = np.array([[0, msm.γ1], + [1, msm.g]]) +``` + +Define + +$$ +H = H_1^{-1} H_2 +$$ + +```{code-cell} ipython3 +H = np.linalg.solve(H1, H2) +print('H = \n', H) +``` + +and write the system {eq}`eq:sytem101` as + +$$ +y_{t+1} = H y_t, \quad t \geq 0 +$$ (eq:Vaughn) + +so that $\{y_t\}_{t=0}$ can be computed from + +$$ +y_t = H^t y_0, t \geq 0 +$$ (eq:ytiterate) + +where + +$$ +y_0 = \begin{bmatrix} m_{0} \cr p_0 \end{bmatrix} . +$$ + +It is natural to take $m_0$ as an initial condition determined outside the model. + +The mathematics seems to tell us that $p_0$ must also be determined outside the model, even though +it is something that we actually wanted to be determined by the model. + +(As usual, we should listen when mathematics talks to us.) + +For now, let's just proceed mechanically on faith. + +Compute the eigenvector decomposition + +$$ +H = Q \Lambda Q^{-1} +$$ + +where $\Lambda$ is a diagonal matrix of eigenvalues and the columns of $Q$ are eigenvectors corresponding to those eigenvalues. + +It turns out that + +$$ +\Lambda = \begin{bmatrix} {R_\ell}^{-1} & 0 \cr + 0 & {R_u}^{-1} \end{bmatrix} +$$ + +where $R_\ell$ and $R_u$ are the lower and higher steady-state rates of return on currency that we computed above. + +```{code-cell} ipython3 +Λ, Q = np.linalg.eig(H) +print('Λ = \n', Λ) +print('Q = \n', Q) +``` + +```{code-cell} ipython3 +R_l = 1 / Λ[0] +R_u = 1 / Λ[1] + +print(f'R_l = {R_l:.4f}') +print(f'R_u = {R_u:.4f}') +``` + +Partition $Q$ as + +$$ +Q =\begin{bmatrix} Q_{11} & Q_{12} \cr + Q_{21} & Q_{22} \end{bmatrix} +$$ + +Below we shall verify the following claims: + + +**Claims:** If we set + +$$ +p_0 = \overline p_0 \equiv Q_{21} Q_{11}^{-1} m_{0} , +$$ (eq:magicp0) + +it turns out that + +$$ +\frac{p_{t+1}}{p_t} = {R_u}^{-1}, \quad t \geq 0 +$$ + + +However, if we set + +$$ +p_0 > \bar p_0 +$$ + +then + +$$ +\lim_{t\rightarrow + \infty} \frac{p_{t+1}}{p_t} = {R_\ell}^{-1}. +$$ + +Let's verify these claims step by step. + + + +Note that + +$$ +H^t = Q \Lambda^t Q^{-1} +$$ + +so that + +$$ +y_t = Q \Lambda^t Q^{-1} y_0 +$$ + +```{code-cell} ipython3 +def iterate_H(y_0, H, num_steps): + Λ, Q = np.linalg.eig(H) + Q_inv = np.linalg.inv(Q) + y = np.stack( + [Q @ np.diag(Λ**t) @ Q_inv @ y_0 for t in range(num_steps)], 1) + + return y +``` + +For almost all initial vectors $y_0$, the gross rate of inflation $\frac{p_{t+1}}{p_t}$ eventually converges to the larger eigenvalue ${R_\ell}^{-1}$. + +The only way to avoid this outcome is for $p_0$ to take the specific value described by {eq}`eq:magicp0`. + +To understand this situation, we use the following +transformation + +$$ +y^*_t = Q^{-1} y_t . +$$ + +Dynamics of $y^*_t$ are evidently governed by + +$$ +y^*_{t+1} = \Lambda^t y^*_t . +$$ (eq:stardynamics) + +This equation represents the dynamics of our system in a way that lets us isolate the +force that causes gross inflation to converge to the inverse of the lower steady-state rate +of inflation $R_\ell$ that we discovered earlier. + +Staring at equation {eq}`eq:stardynamics` indicates that unless + +```{math} +:label: equation_11 + +y^*_0 = \begin{bmatrix} y^*_{1,0} \cr 0 \end{bmatrix} +``` + +the path of $y^*_t$, and therefore the paths of both $m_t$ and $p_t$ given by +$y_t = Q y^*_t$ will eventually grow at gross rates ${R_\ell}^{-1}$ as +$t \rightarrow +\infty$. + +Equation {eq}`equation_11` also leads us to conclude that there is a unique setting +for the initial vector $y_0$ for which both components forever grow at the lower rate ${R_u}^{-1}$. + + +For this to occur, the required setting of $y_0$ must evidently have the property +that + +$$ +Q^{-1} y_0 = y^*_0 = \begin{bmatrix} y^*_{1,0} \cr 0 \end{bmatrix} . +$$ + +But note that since +$y_0 = \begin{bmatrix} m_0 \cr p_0 \end{bmatrix}$ and $m_0$ +is given to us an initial condition, $p_0$ has to do all the adjusting to satisfy this equation. + +Sometimes this situation is described informally by saying that while $m_0$ +is truly a **state** variable, $p_0$ is a **jump** variable that +must adjust at $t=0$ in order to satisfy the equation. + +Thus, in a nutshell the unique value of the vector $y_0$ for which +the paths of $y_t$ *don't* eventually grow at rate ${R_\ell}^{-1}$ requires setting the second component +of $y^*_0$ equal to zero. + +The component $p_0$ of the initial vector +$y_0 = \begin{bmatrix} m_0 \cr p_0 \end{bmatrix}$ must evidently +satisfy + +$$ +Q^{\{2\}} y_0 =0 +$$ + +where $Q^{\{2\}}$ denotes the second row of $Q^{-1}$, a +restriction that is equivalent to + +```{math} +:label: equation_12 + +Q^{21} m_0 + Q^{22} p_0 = 0 +``` + +where $Q^{ij}$ denotes the $(i,j)$ component of +$Q^{-1}$. + +Solving this equation for $p_0$, we find + +```{math} +:label: equation_13 + +p_0 = - (Q^{22})^{-1} Q^{21} m_0. +``` + + +### More convenient formula + +We can get the equivalent but perhaps more convenient formula {eq}`eq:magicp0` for $p_0$ that is cast +in terms of components of $Q$ instead of components of +$Q^{-1}$. + +To get this formula, first note that because $(Q^{21}\ Q^{22})$ is +the second row of the inverse of $Q$ and because +$Q^{-1} Q = I$, it follows that + +$$ +\begin{bmatrix} Q^{21} & Q^{22} \end{bmatrix} \begin{bmatrix} Q_{11}\cr Q_{21} \end{bmatrix} = 0 +$$ + +which implies that + +$$ +Q^{21} Q_{11} + Q^{22} Q_{21} = 0. +$$ + +Therefore, + +$$ +-(Q^{22})^{-1} Q^{21} = Q_{21} Q^{-1}_{11}. +$$ + +So we can write + +```{math} + +p_0 = Q_{21} Q_{11}^{-1} m_0 . +``` + +which is our formula {eq}`eq:magicp0`. + +```{code-cell} ipython3 +p0_bar = (Q[1, 0]/Q[0, 0]) * msm.M0 + +print(f'p0_bar = {p0_bar:.4f}') +``` + +It can be verified that this formula replicates itself over time in the sense that + +```{math} +:label: equation_15 + +p_t = Q_{21} Q^{-1}_{11} m_t. +``` + +Now let's visualize the dynamics of $m_t$, $p_t$, and $R_t$ starting from different $p_0$ values to verify our claims above. + +We create a function `draw_iterations` to generate the plot + +```{code-cell} ipython3 +:tags: [hide-cell] + +def draw_iterations(p0s, model, line_params, num_steps): + + fig, axes = plt.subplots(3, 1, figsize=(8, 10), sharex=True) + + # Pre-compute time steps + time_steps = np.arange(num_steps) + + # Plot the first two y-axes in log scale + for ax in axes[:2]: + ax.set_yscale('log') + + # Iterate over p_0s and calculate a series of y_t + for p0 in p0s: + y0 = np.array([msm.M0, p0]) + y_series = iterate_H(y0, H, num_steps) + M, P = y_series[0, :], y_series[1, :] + + # Plot R_t against time + axes[0].plot(time_steps, M, **line_params) + + # Plot b_t against time + axes[1].plot(time_steps, P, **line_params) + + # Calculate R_t + R = np.insert(P[:-1] / P[1:], 0, np.NAN) + axes[2].plot(time_steps, R, **line_params) + + # Add line and text annotations to the subgraph + annotate_graph(axes[2], model, num_steps) + + # Draw labels + axes[0].set_ylabel('$m_t$') + axes[1].set_ylabel('$p_t$') + axes[2].set_ylabel('$R_t$') + axes[2].set_xlabel('timestep') + + # Enforce integar axis label + axes[2].xaxis.set_major_locator(MaxNLocator(integer=True)) + + plt.tight_layout() + plt.show() +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Starting from different initial values of $p_0$, paths of $m_t$ (top + panel, log scale for $m$), $p_t$ (middle panel, log scale for $m$), $R_t$ (bottom + panel) + name: p0_path + width: 500px +--- +p0s = [p0_bar, 2.34, 2.5, 3, 4, 7, 30, 100_000] + +draw_iterations(p0s, msm, line_params, num_steps=20) +``` + +Please notice that for $m_t$ and $p_t$, we have used log scales for the coordinate (i.e., vertical) axes. + +Using log scales allows us to spot distinct constant limiting gross rates of growth ${R_u}^{-1}$ and +${R_\ell}^{-1}$ by eye. + + +## Peculiar stationary outcomes + +As promised at the start of this lecture, we have encountered these concepts from macroeconomics: + +* an **inflation tax** that a government gathers by printing paper or electronic money +* a dynamic **Laffer curve** in the inflation tax rate that has two stationary equilibria + +Staring at the paths of rates of return on the price level in figure {numref}`R0_path` and price levels in {numref}`p0_path` show indicate that almost all paths converge to the *higher* inflation tax rate displayed in the stationary state Laffer curve displayed in figure {numref}`infl_tax`. + +Thus, we have indeed discovered what we earlier called "perverse" dynamics under rational expectations in which the system converges to the higher of two possible stationary inflation tax rates. + +Those dynamics are "perverse" not only in the sense that they imply that the monetary and fiscal authorities that have chosen to finance government expenditures eventually impose a higher inflation tax than required to finance government expenditures, but because of the following "counterintuitive" situation that we can deduce by staring at the stationary state Laffer curve displayed in figure {numref}`infl_tax`: + +* the figure indicates that inflation can be *reduced* by running *higher* government deficits, i.e., by raising more resources through printing money. + + +```{note} +The same qualitative outcomes prevail in this lecture {doc}`money_inflation_nonlinear` that studies a nonlinear version of the model in this lecture. +``` + + +## Equilibrium selection + +We have discovered that as a model of price level paths or model is **incomplete** because there is a continuum of "equilibrium" paths for $\{m_{t+1}, p_t\}_{t=0}^\infty$ that are consistent with the demand for real balances always equaling the supply. + + +Through application of our computational methods 1 and 2, we have learned that this continuum can be indexed by choice of one of two scalars: + +* for computational method 1, $R_0$ +* for computational method 2, $p_0$ + +To apply our model, we have somehow to *complete* it by *selecting* an equilibrium path from among the continuum of possible paths. + +We discovered that + + * all but one of the equilibrium paths converge to limits in which the higher of two possible stationary inflation tax prevails + * there is a unique equilibrium path associated with "plausible" statements about how reductions in government deficits affect a stationary inflation rate + +On grounds of plausibility, we recommend following many macroeconomists in selecting the unique equilibrium that converges to the lower stationary inflation tax rate. + +As we shall see, we shall accept this recommendation in lecture {doc}`unpleasant`. + +In lecture, {doc}`laffer_adaptive`, we shall explore how {cite}`bruno1990seigniorage` and others justified this in other ways. diff --git a/book/_build/html/_sources/money_inflation_nonlinear.ipynb b/book/_build/html/_sources/money_inflation_nonlinear.ipynb new file mode 100644 index 0000000..a5aa7ae --- /dev/null +++ b/book/_build/html/_sources/money_inflation_nonlinear.ipynb @@ -0,0 +1,567 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "ce75d2bd", + "metadata": {}, + "source": [ + "# Inflation Rate Laffer Curves \n", + "\n", + "## Overview\n", + "\n", + "We study stationary and dynamic *Laffer curves* in the inflation tax rate in a non-linear version of the model studied in {doc}`money_inflation`.\n", + "\n", + "We use the log-linear version of the demand function for money that {cite}`Cagan`\n", + "used in his classic paper in place of the linear demand function used in {doc}`money_inflation`. \n", + "\n", + "That change requires that we modify parts of our analysis.\n", + "\n", + "In particular, our dynamic system is no longer linear in state variables. \n", + "\n", + "Nevertheless, the economic logic underlying an analysis based on what we called ''method 2'' remains unchanged. \n", + "\n", + "We shall discover qualitatively similar outcomes to those that we studied in {doc}`money_inflation`.\n", + "\n", + "That lecture presented a linear version of the model in this lecture. \n", + "\n", + "As in that lecture, we discussed these topics:\n", + "\n", + "* an **inflation tax** that a government gathers by printing paper or electronic money\n", + "* a dynamic **Laffer curve** in the inflation tax rate that has two stationary equilibria\n", + "* perverse dynamics under rational expectations in which the system converges to the higher stationary inflation tax rate\n", + "* a peculiar comparative stationary-state analysis connected with that stationary inflation rate that asserts that inflation can be *reduced* by running *higher* government deficits \n", + "\n", + "These outcomes will set the stage for the analysis of {doc}`laffer_adaptive` that studies a version of the present model that uses a version of \"adaptive expectations\" instead of rational expectations.\n", + "\n", + "That lecture will show that \n", + "\n", + "* replacing rational expectations with adaptive expectations leaves the two stationary inflation rates unchanged, but that $\\ldots$ \n", + "* it reverses the perverse dynamics by making the *lower* stationary inflation rate the one to which the system typically converges\n", + "* a more plausible comparative dynamic outcome emerges in which now inflation can be *reduced* by running *lower* government deficits\n", + "\n", + "## The Model\n", + "\n", + "Let \n", + "\n", + "* $m_t$ be the log of the money supply at the beginning of time $t$\n", + "* $p_t$ be the log of the price level at time $t$\n", + " \n", + "The demand function for money is \n", + "\n", + "$$\n", + "m_{t+1} - p_t = -\\alpha (p_{t+1} - p_t) \n", + "$$ (eq:mdemand)\n", + "\n", + "where $\\alpha \\geq 0$. \n", + "\n", + "The law of motion of the money supply is\n", + "\n", + "$$ \n", + "\\exp(m_{t+1}) - \\exp(m_t) = g \\exp(p_t) \n", + "$$ (eq:msupply)\n", + "\n", + "where $g$ is the part of government expenditures financed by printing money.\n", + "\n", + "```{prf:remark}\n", + ":label: linear_log\n", + "Please notice that while equation {eq}`eq:mdemand` is linear in logs of the money supply and price level, equation {eq}`eq:msupply` is linear in levels. This will require adapting the equilibrium computation methods that we deployed in {doc}`money_inflation`.\n", + "```\n", + "\n", + "\n", + "\n", + "## Limiting Values of Inflation Rate\n", + "\n", + "We can compute the two prospective limiting values for $\\overline \\pi$ by studying the steady-state Laffer curve.\n", + "\n", + "Thus, in a *steady state* \n", + "\n", + "$$\n", + "m_{t+1} - m_t = p_{t+1} - p_t = x \\quad \\forall t ,\n", + "$$\n", + "\n", + "where $x > 0 $ is a common rate of growth of logarithms of the money supply and price level.\n", + "\n", + "A few lines of algebra yields the following equation that $x$ satisfies\n", + "\n", + "$$\n", + "\\exp(-\\alpha x) - \\exp(-(1 + \\alpha) x) = g \n", + "$$ (eq:steadypi)\n", + "\n", + "where we require that\n", + "\n", + "$$\n", + "g \\leq \\max_{x \\geq 0} \\{\\exp(-\\alpha x) - \\exp(-(1 + \\alpha) x) \\}, \n", + "$$ (eq:revmax)\n", + "\n", + "so that it is feasible to finance $g$ by printing money.\n", + "\n", + "The left side of {eq}`eq:steadypi` is steady state revenue raised by printing money.\n", + "\n", + "The right side of {eq}`eq:steadypi` is the quantity of time $t$ goods that the government raises by printing money. \n", + "\n", + "Soon we'll plot the left and right sides of equation {eq}`eq:steadypi`.\n", + "\n", + "But first we'll write code that computes a steady-state\n", + "$\\overline \\pi$.\n", + "\n", + "Let's start by importing some libraries" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "349ba9a5", + "metadata": {}, + "outputs": [], + "source": [ + "from collections import namedtuple\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from matplotlib.ticker import MaxNLocator\n", + "from scipy.optimize import fsolve " + ] + }, + { + "cell_type": "markdown", + "id": "04dd62c5", + "metadata": { + "user_expressions": [] + }, + "source": [ + "Let's create a `namedtuple` to store the parameters of the model" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d2b26898", + "metadata": {}, + "outputs": [], + "source": [ + "CaganLaffer = namedtuple('CaganLaffer', \n", + " [\"m0\", # log of the money supply at t=0\n", + " \"α\", # sensitivity of money demand\n", + " \"λ\",\n", + " \"g\" ])\n", + "\n", + "# Create a Cagan Laffer model\n", + "def create_model(α=0.5, m0=np.log(100), g=0.35):\n", + " return CaganLaffer(α=α, m0=m0, λ=α/(1+α), g=g)\n", + "\n", + "model = create_model()" + ] + }, + { + "cell_type": "markdown", + "id": "8f034cc6", + "metadata": { + "user_expressions": [] + }, + "source": [ + "Now we write code that computes steady-state $\\overline \\pi$s." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "111cba78", + "metadata": {}, + "outputs": [], + "source": [ + "# Define formula for π_bar\n", + "def solve_π(x, α, g):\n", + " return np.exp(-α * x) - np.exp(-(1 + α) * x) - g\n", + "\n", + "def solve_π_bar(model, x0):\n", + " π_bar = fsolve(solve_π, x0=x0, xtol=1e-10, args=(model.α, model.g))[0]\n", + " return π_bar\n", + "\n", + "# Solve for the two steady state of π\n", + "π_l = solve_π_bar(model, x0=0.6)\n", + "π_u = solve_π_bar(model, x0=3.0)\n", + "print(f'The two steady state of π are: {π_l, π_u}')" + ] + }, + { + "cell_type": "markdown", + "id": "94211d13", + "metadata": {}, + "source": [ + "We find two steady state $\\overline \\pi$ values.\n", + "\n", + "## Steady State Laffer curve\n", + "\n", + "The following figure plots the steady state Laffer curve together with the two stationary inflation rates." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2ce45a64", + "metadata": { + "mystnb": { + "figure": { + "caption": "Seigniorage as function of steady state inflation. The dashed brown lines indicate $\\pi_l$ and $\\pi_u$.", + "name": "laffer_curve_nonlinear", + "width": "500px" + } + } + }, + "outputs": [], + "source": [ + "def compute_seign(x, α):\n", + " return np.exp(-α * x) - np.exp(-(1 + α) * x) \n", + "\n", + "def plot_laffer(model, πs):\n", + " α, g = model.α, model.g\n", + " \n", + " # Generate π values\n", + " x_values = np.linspace(0, 5, 1000)\n", + "\n", + " # Compute corresponding seigniorage values for the function\n", + " y_values = compute_seign(x_values, α)\n", + "\n", + " # Plot the function\n", + " plt.plot(x_values, y_values, \n", + " label=f'Laffer curve')\n", + " for π, label in zip(πs, ['$\\pi_l$', '$\\pi_u$']):\n", + " plt.text(π, plt.gca().get_ylim()[0]*2, \n", + " label, horizontalalignment='center',\n", + " color='brown', size=10)\n", + " plt.axvline(π, color='brown', linestyle='--')\n", + " plt.axhline(g, color='red', linewidth=0.5, \n", + " linestyle='--', label='g')\n", + " plt.xlabel('$\\pi$')\n", + " plt.ylabel('seigniorage')\n", + " plt.legend()\n", + " plt.show()\n", + "\n", + "# Steady state Laffer curve\n", + "plot_laffer(model, (π_l, π_u))" + ] + }, + { + "cell_type": "markdown", + "id": "a6b92bfb", + "metadata": {}, + "source": [ + "## Initial Price Levels\n", + "\n", + "Now that we have our hands on the two possible steady states, we can compute two functions $\\underline p(m_0)$ and\n", + "$\\overline p(m_0)$, which as initial conditions for $p_t$ at time $t$, imply that $\\pi_t = \\overline \\pi $ for all $t \\geq 0$.\n", + "\n", + "The function $\\underline p(m_0)$ will be associated with $\\pi_l$ the lower steady-state inflation rate.\n", + "\n", + "The function $\\overline p(m_0)$ will be associated with $\\pi_u$ the lower steady-state inflation rate." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c204dbb7", + "metadata": {}, + "outputs": [], + "source": [ + "def solve_p0(p0, m0, α, g, π):\n", + " return np.log(np.exp(m0) + g * np.exp(p0)) + α * π - p0\n", + "\n", + "def solve_p0_bar(model, x0, π_bar):\n", + " p0_bar = fsolve(solve_p0, x0=x0, xtol=1e-20, args=(model.m0, \n", + " model.α, \n", + " model.g, \n", + " π_bar))[0]\n", + " return p0_bar\n", + "\n", + "# Compute two initial price levels associated with π_l and π_u\n", + "p0_l = solve_p0_bar(model, \n", + " x0=np.log(220), \n", + " π_bar=π_l)\n", + "p0_u = solve_p0_bar(model, \n", + " x0=np.log(220), \n", + " π_bar=π_u)\n", + "print(f'Associated initial p_0s are: {p0_l, p0_u}')" + ] + }, + { + "cell_type": "markdown", + "id": "daf77df8", + "metadata": {}, + "source": [ + "### Verification \n", + "\n", + "To start, let's write some code to verify that if the initial log price level $p_0$ takes one\n", + "of the two values we just calculated, the inflation rate $\\pi_t$ will be constant for all $t \\geq 0$.\n", + "\n", + "The following code verifies this." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e087ddb5", + "metadata": {}, + "outputs": [], + "source": [ + "# Implement pseudo-code above\n", + "def simulate_seq(p0, model, num_steps):\n", + " λ, g = model.λ, model.g\n", + " π_seq, μ_seq, m_seq, p_seq = [], [], [model.m0], [p0]\n", + "\n", + " for t in range(num_steps):\n", + " \n", + " m_seq.append(np.log(np.exp(m_seq[t]) + g * np.exp(p_seq[t])))\n", + " p_seq.append(1/λ * p_seq[t] + (1 - 1/λ) * m_seq[t+1])\n", + "\n", + " μ_seq.append(m_seq[t+1]-m_seq[t])\n", + " π_seq.append(p_seq[t+1]-p_seq[t])\n", + "\n", + " return π_seq, μ_seq, m_seq, p_seq" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "762a8a3b", + "metadata": {}, + "outputs": [], + "source": [ + "π_seq, μ_seq, m_seq, p_seq = simulate_seq(p0_l, model, 150)\n", + "\n", + "# Check π and μ at steady state\n", + "print('π_bar == μ_bar:', π_seq[-1] == μ_seq[-1])\n", + "\n", + "# Check steady state m_{t+1} - m_t and p_{t+1} - p_t \n", + "print('m_{t+1} - m_t:', m_seq[-1] - m_seq[-2])\n", + "print('p_{t+1} - p_t:', p_seq[-1] - p_seq[-2])\n", + "\n", + "# Check if exp(-αx) - exp(-(1 + α)x) = g\n", + "eq_g = lambda x: np.exp(-model.α * x) - np.exp(-(1 + model.α) * x)\n", + "\n", + "print('eq_g == g:', np.isclose(eq_g(m_seq[-1] - m_seq[-2]), model.g))" + ] + }, + { + "cell_type": "markdown", + "id": "70c0675d", + "metadata": {}, + "source": [ + "## Computing an Equilibrium Sequence \n", + "\n", + "We'll deploy a method similar to *Method 2* used in {doc}`money_inflation`. \n", + "\n", + "We'll take the time $t$ state vector to be the pair $(m_t, p_t)$.\n", + "\n", + "We'll treat $m_t$ as a ``natural state variable`` and $p_t$ as a ``jump`` variable.\n", + " \n", + "Let\n", + "\n", + "$$\n", + "\\lambda \\equiv \\frac{\\alpha}{1+ \\alpha}\n", + "$$\n", + "\n", + "Let's rewrite equation {eq}`eq:mdemand` as\n", + "\n", + "$$\n", + "p_t = (1-\\lambda) m_{t+1} + \\lambda p_{t+1} \n", + "$$ (eq:mdemand2)\n", + "\n", + "We'll summarize our algorithm with the following pseudo-code.\n", + "\n", + "**Pseudo-code**\n", + "\n", + "The heart of the pseudo-code iterates on the following mapping from state vector $(m_t, p_t)$ at time $t$\n", + "to state vector $(m_{t+1}, p_{t+1})$ at time $t+1$.\n", + "\n", + "\n", + "* starting from a given pair $(m_t, p_t)$ at time $t \\geq 0$\n", + "\n", + " * solve {eq}`eq:msupply` for $m_{t+1}$\n", + "\n", + " * solve {eq}`eq:mdemand2` for $p_{t+1} = \\lambda^{-1} p_t + (1 - \\lambda^{-1}) m_{t+1}$\n", + "\n", + " * compute the inflation rate $\\pi_t = p_{t+1} - p_t$ and growth of money supply $\\mu_t = m_{t+1} - m_t $\n", + "\n", + "Next, compute the two functions $\\underline p(m_0)$ and $\\overline p(m_0)$ described above\n", + "\n", + "Now initiate the algorithm as follows.\n", + "\n", + " * set $m_0 >0$\n", + " * set a value of $p_0 \\in [\\underline p(m_0), \\overline p(m_0)]$ and form the pair $(m_0, p_0)$ at time $t =0$\n", + " \n", + "Starting from $(m_0, p_0)$ iterate on $t$ to convergence of $\\pi_t \\rightarrow \\overline \\pi$ and $\\mu_t \\rightarrow \\overline \\mu$\n", + " \n", + "It will turn out that \n", + "\n", + "* if they exist, limiting values $\\overline \\pi$ and $\\overline \\mu$ will be equal\n", + "\n", + "* if limiting values exist, there are two possible limiting values, one high, one low\n", + "\n", + "* for almost all initial log price levels $p_0$, the limiting $\\overline \\pi = \\overline \\mu$ is \n", + "the higher value\n", + "\n", + "* for each of the two possible limiting values $\\overline \\pi$ ,there is a unique initial log price level $p_0$ that implies that $\\pi_t = \\mu_t = \\overline \\mu$ for all $t \\geq 0$\n", + "\n", + " * this unique initial log price level solves $\\log(\\exp(m_0) + g \\exp(p_0)) - p_0 = - \\alpha \\overline \\pi $\n", + " \n", + " * the preceding equation for $p_0$ comes from $m_1 - p_0 = - \\alpha \\overline \\pi$\n", + "\n", + "\n", + "## Slippery Side of Laffer Curve Dynamics\n", + "\n", + "We are now equipped to compute time series starting from different $p_0$ settings, like those in {doc}`money_inflation`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e7b05650", + "metadata": { + "tags": [ + "hide-cell" + ] + }, + "outputs": [], + "source": [ + "def draw_iterations(p0s, model, line_params, p0_bars, num_steps):\n", + "\n", + " fig, axes = plt.subplots(4, 1, figsize=(8, 10), sharex=True)\n", + " \n", + " # Pre-compute time steps\n", + " time_steps = np.arange(num_steps) \n", + " \n", + " # Plot the first two y-axes in log scale\n", + " for ax in axes[:2]:\n", + " ax.set_yscale('log')\n", + "\n", + " # Iterate over p_0s and calculate a series of y_t\n", + " for p0 in p0s:\n", + " π_seq, μ_seq, m_seq, p_seq = simulate_seq(p0, model, num_steps)\n", + "\n", + " # Plot m_t\n", + " axes[0].plot(time_steps, m_seq[1:], **line_params)\n", + "\n", + " # Plot p_t\n", + " axes[1].plot(time_steps, p_seq[1:], **line_params)\n", + " \n", + " # Plot π_t\n", + " axes[2].plot(time_steps, π_seq, **line_params)\n", + " \n", + " # Plot μ_t\n", + " axes[3].plot(time_steps, μ_seq, **line_params)\n", + " \n", + " # Draw labels\n", + " axes[0].set_ylabel('$m_t$')\n", + " axes[1].set_ylabel('$p_t$')\n", + " axes[2].set_ylabel('$\\pi_t$')\n", + " axes[3].set_ylabel('$\\mu_t$')\n", + " axes[3].set_xlabel('timestep')\n", + " \n", + " for p_0, label in [(p0_bars[0], '$p_0=p_l$'), (p0_bars[1], '$p_0=p_u$')]:\n", + " y = simulate_seq(p_0, model, 1)[0]\n", + " for ax in axes[2:]:\n", + " ax.axhline(y=y[0], color='grey', linestyle='--', lw=1.5, alpha=0.6)\n", + " ax.text(num_steps * 1.02, y[0], label, verticalalignment='center', \n", + " color='grey', size=10)\n", + " \n", + " # Enforce integar axis label\n", + " axes[3].xaxis.set_major_locator(MaxNLocator(integer=True))\n", + "\n", + " plt.tight_layout()\n", + " plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a70ade64", + "metadata": { + "mystnb": { + "figure": { + "caption": "Starting from different initial values of $p_0$, paths of $m_t$ (top panel, log scale for $m$), $p_t$ (second panel, log scale for $p$), $\\pi_t$ (third panel), and $\\mu_t$ (bottom panel)", + "name": "p0_path_nonlin", + "width": "500px" + } + } + }, + "outputs": [], + "source": [ + "# Generate a sequence from p0_l to p0_u\n", + "p0s = np.arange(p0_l, p0_u, 0.1) \n", + "\n", + "line_params = {'lw': 1.5, \n", + " 'marker': 'o',\n", + " 'markersize': 3}\n", + "\n", + "p0_bars = (p0_l, p0_u)\n", + " \n", + "draw_iterations(p0s, model, line_params, p0_bars, num_steps=20)" + ] + }, + { + "cell_type": "markdown", + "id": "cf5d3e69", + "metadata": {}, + "source": [ + "Staring at the paths of price levels in {numref}`p0_path_nonlin` reveals that almost all paths converge to the *higher* inflation tax rate displayed in the stationary state Laffer curve. displayed in figure {numref}`laffer_curve_nonlinear`. \n", + "\n", + "Thus, we have reconfirmed what we have called the \"perverse\" dynamics under rational expectations in which the system converges to the higher of two possible stationary inflation tax rates.\n", + "\n", + "Those dynamics are \"perverse\" not only in the sense that they imply that the monetary and fiscal authorities that have chosen to finance government expenditures eventually impose a higher inflation tax than required to finance government expenditures, but because of the following \"counterintuitive\" situation that we can deduce by staring at the stationary state Laffer curve displayed in figure {numref}`laffer_curve_nonlinear`:\n", + "\n", + "* the figure indicates that inflation can be *reduced* by running *higher* government deficits, i.e., by raising more resources through printing money. \n", + "\n", + "```{note}\n", + "The same qualitative outcomes prevail in {doc}`money_inflation` that studies a linear version of the model in this lecture.\n", + "```\n", + "\n", + "We discovered that \n", + "\n", + "* all but one of the equilibrium paths converge to limits in which the higher of two possible stationary inflation tax prevails\n", + "* there is a unique equilibrium path associated with \"plausible\" statements about how reductions in government deficits affect a stationary inflation rate\n", + "\n", + "As in {doc}`money_inflation`,\n", + "on grounds of plausibility, we again recommend selecting the unique equilibrium that converges to the lower stationary inflation tax rate. \n", + "\n", + "As we shall see, we accepting this recommendation is a key ingredient of outcomes of the \"unpleasant arithmetic\" that we describe in {doc}`unpleasant`.\n", + "\n", + "In {doc}`laffer_adaptive`, we shall explore how {cite}`bruno1990seigniorage` and others justified our equilibrium selection in other ways." + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.5" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 115, + 123, + 127, + 141, + 145, + 158, + 166, + 204, + 217, + 236, + 245, + 262, + 276, + 343, + 394, + 415 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/money_inflation_nonlinear.md b/book/_build/html/_sources/money_inflation_nonlinear.md new file mode 100644 index 0000000..0792237 --- /dev/null +++ b/book/_build/html/_sources/money_inflation_nonlinear.md @@ -0,0 +1,439 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.5 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Inflation Rate Laffer Curves + +## Overview + +We study stationary and dynamic *Laffer curves* in the inflation tax rate in a non-linear version of the model studied in {doc}`money_inflation`. + +We use the log-linear version of the demand function for money that {cite}`Cagan` +used in his classic paper in place of the linear demand function used in {doc}`money_inflation`. + +That change requires that we modify parts of our analysis. + +In particular, our dynamic system is no longer linear in state variables. + +Nevertheless, the economic logic underlying an analysis based on what we called ''method 2'' remains unchanged. + +We shall discover qualitatively similar outcomes to those that we studied in {doc}`money_inflation`. + +That lecture presented a linear version of the model in this lecture. + +As in that lecture, we discussed these topics: + +* an **inflation tax** that a government gathers by printing paper or electronic money +* a dynamic **Laffer curve** in the inflation tax rate that has two stationary equilibria +* perverse dynamics under rational expectations in which the system converges to the higher stationary inflation tax rate +* a peculiar comparative stationary-state analysis connected with that stationary inflation rate that asserts that inflation can be *reduced* by running *higher* government deficits + +These outcomes will set the stage for the analysis of {doc}`laffer_adaptive` that studies a version of the present model that uses a version of "adaptive expectations" instead of rational expectations. + +That lecture will show that + +* replacing rational expectations with adaptive expectations leaves the two stationary inflation rates unchanged, but that $\ldots$ +* it reverses the perverse dynamics by making the *lower* stationary inflation rate the one to which the system typically converges +* a more plausible comparative dynamic outcome emerges in which now inflation can be *reduced* by running *lower* government deficits + +## The Model + +Let + +* $m_t$ be the log of the money supply at the beginning of time $t$ +* $p_t$ be the log of the price level at time $t$ + +The demand function for money is + +$$ +m_{t+1} - p_t = -\alpha (p_{t+1} - p_t) +$$ (eq:mdemand) + +where $\alpha \geq 0$. + +The law of motion of the money supply is + +$$ +\exp(m_{t+1}) - \exp(m_t) = g \exp(p_t) +$$ (eq:msupply) + +where $g$ is the part of government expenditures financed by printing money. + +```{prf:remark} +:label: linear_log +Please notice that while equation {eq}`eq:mdemand` is linear in logs of the money supply and price level, equation {eq}`eq:msupply` is linear in levels. This will require adapting the equilibrium computation methods that we deployed in {doc}`money_inflation`. +``` + + + +## Limiting Values of Inflation Rate + +We can compute the two prospective limiting values for $\overline \pi$ by studying the steady-state Laffer curve. + +Thus, in a *steady state* + +$$ +m_{t+1} - m_t = p_{t+1} - p_t = x \quad \forall t , +$$ + +where $x > 0 $ is a common rate of growth of logarithms of the money supply and price level. + +A few lines of algebra yields the following equation that $x$ satisfies + +$$ +\exp(-\alpha x) - \exp(-(1 + \alpha) x) = g +$$ (eq:steadypi) + +where we require that + +$$ +g \leq \max_{x \geq 0} \{\exp(-\alpha x) - \exp(-(1 + \alpha) x) \}, +$$ (eq:revmax) + +so that it is feasible to finance $g$ by printing money. + +The left side of {eq}`eq:steadypi` is steady state revenue raised by printing money. + +The right side of {eq}`eq:steadypi` is the quantity of time $t$ goods that the government raises by printing money. + +Soon we'll plot the left and right sides of equation {eq}`eq:steadypi`. + +But first we'll write code that computes a steady-state +$\overline \pi$. + +Let's start by importing some libraries + +```{code-cell} ipython3 +from collections import namedtuple +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.ticker import MaxNLocator +from scipy.optimize import fsolve +``` + ++++ {"user_expressions": []} + +Let's create a `namedtuple` to store the parameters of the model + +```{code-cell} ipython3 +CaganLaffer = namedtuple('CaganLaffer', + ["m0", # log of the money supply at t=0 + "α", # sensitivity of money demand + "λ", + "g" ]) + +# Create a Cagan Laffer model +def create_model(α=0.5, m0=np.log(100), g=0.35): + return CaganLaffer(α=α, m0=m0, λ=α/(1+α), g=g) + +model = create_model() +``` + ++++ {"user_expressions": []} + +Now we write code that computes steady-state $\overline \pi$s. + +```{code-cell} ipython3 +# Define formula for π_bar +def solve_π(x, α, g): + return np.exp(-α * x) - np.exp(-(1 + α) * x) - g + +def solve_π_bar(model, x0): + π_bar = fsolve(solve_π, x0=x0, xtol=1e-10, args=(model.α, model.g))[0] + return π_bar + +# Solve for the two steady state of π +π_l = solve_π_bar(model, x0=0.6) +π_u = solve_π_bar(model, x0=3.0) +print(f'The two steady state of π are: {π_l, π_u}') +``` + +We find two steady state $\overline \pi$ values. + +## Steady State Laffer curve + +The following figure plots the steady state Laffer curve together with the two stationary inflation rates. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Seigniorage as function of steady state inflation. The dashed brown lines indicate $\pi_l$ and $\pi_u$. + name: laffer_curve_nonlinear + width: 500px +--- + +def compute_seign(x, α): + return np.exp(-α * x) - np.exp(-(1 + α) * x) + +def plot_laffer(model, πs): + α, g = model.α, model.g + + # Generate π values + x_values = np.linspace(0, 5, 1000) + + # Compute corresponding seigniorage values for the function + y_values = compute_seign(x_values, α) + + # Plot the function + plt.plot(x_values, y_values, + label=f'Laffer curve') + for π, label in zip(πs, ['$\pi_l$', '$\pi_u$']): + plt.text(π, plt.gca().get_ylim()[0]*2, + label, horizontalalignment='center', + color='brown', size=10) + plt.axvline(π, color='brown', linestyle='--') + plt.axhline(g, color='red', linewidth=0.5, + linestyle='--', label='g') + plt.xlabel('$\pi$') + plt.ylabel('seigniorage') + plt.legend() + plt.show() + +# Steady state Laffer curve +plot_laffer(model, (π_l, π_u)) +``` + +## Initial Price Levels + +Now that we have our hands on the two possible steady states, we can compute two functions $\underline p(m_0)$ and +$\overline p(m_0)$, which as initial conditions for $p_t$ at time $t$, imply that $\pi_t = \overline \pi $ for all $t \geq 0$. + +The function $\underline p(m_0)$ will be associated with $\pi_l$ the lower steady-state inflation rate. + +The function $\overline p(m_0)$ will be associated with $\pi_u$ the lower steady-state inflation rate. + + + +```{code-cell} ipython3 +def solve_p0(p0, m0, α, g, π): + return np.log(np.exp(m0) + g * np.exp(p0)) + α * π - p0 + +def solve_p0_bar(model, x0, π_bar): + p0_bar = fsolve(solve_p0, x0=x0, xtol=1e-20, args=(model.m0, + model.α, + model.g, + π_bar))[0] + return p0_bar + +# Compute two initial price levels associated with π_l and π_u +p0_l = solve_p0_bar(model, + x0=np.log(220), + π_bar=π_l) +p0_u = solve_p0_bar(model, + x0=np.log(220), + π_bar=π_u) +print(f'Associated initial p_0s are: {p0_l, p0_u}') +``` + +### Verification + +To start, let's write some code to verify that if the initial log price level $p_0$ takes one +of the two values we just calculated, the inflation rate $\pi_t$ will be constant for all $t \geq 0$. + +The following code verifies this. + +```{code-cell} ipython3 +# Implement pseudo-code above +def simulate_seq(p0, model, num_steps): + λ, g = model.λ, model.g + π_seq, μ_seq, m_seq, p_seq = [], [], [model.m0], [p0] + + for t in range(num_steps): + + m_seq.append(np.log(np.exp(m_seq[t]) + g * np.exp(p_seq[t]))) + p_seq.append(1/λ * p_seq[t] + (1 - 1/λ) * m_seq[t+1]) + + μ_seq.append(m_seq[t+1]-m_seq[t]) + π_seq.append(p_seq[t+1]-p_seq[t]) + + return π_seq, μ_seq, m_seq, p_seq +``` + +```{code-cell} ipython3 +π_seq, μ_seq, m_seq, p_seq = simulate_seq(p0_l, model, 150) + +# Check π and μ at steady state +print('π_bar == μ_bar:', π_seq[-1] == μ_seq[-1]) + +# Check steady state m_{t+1} - m_t and p_{t+1} - p_t +print('m_{t+1} - m_t:', m_seq[-1] - m_seq[-2]) +print('p_{t+1} - p_t:', p_seq[-1] - p_seq[-2]) + +# Check if exp(-αx) - exp(-(1 + α)x) = g +eq_g = lambda x: np.exp(-model.α * x) - np.exp(-(1 + model.α) * x) + +print('eq_g == g:', np.isclose(eq_g(m_seq[-1] - m_seq[-2]), model.g)) +``` + +## Computing an Equilibrium Sequence + +We'll deploy a method similar to *Method 2* used in {doc}`money_inflation`. + +We'll take the time $t$ state vector to be the pair $(m_t, p_t)$. + +We'll treat $m_t$ as a ``natural state variable`` and $p_t$ as a ``jump`` variable. + +Let + +$$ +\lambda \equiv \frac{\alpha}{1+ \alpha} +$$ + +Let's rewrite equation {eq}`eq:mdemand` as + +$$ +p_t = (1-\lambda) m_{t+1} + \lambda p_{t+1} +$$ (eq:mdemand2) + +We'll summarize our algorithm with the following pseudo-code. + +**Pseudo-code** + +The heart of the pseudo-code iterates on the following mapping from state vector $(m_t, p_t)$ at time $t$ +to state vector $(m_{t+1}, p_{t+1})$ at time $t+1$. + + +* starting from a given pair $(m_t, p_t)$ at time $t \geq 0$ + + * solve {eq}`eq:msupply` for $m_{t+1}$ + + * solve {eq}`eq:mdemand2` for $p_{t+1} = \lambda^{-1} p_t + (1 - \lambda^{-1}) m_{t+1}$ + + * compute the inflation rate $\pi_t = p_{t+1} - p_t$ and growth of money supply $\mu_t = m_{t+1} - m_t $ + +Next, compute the two functions $\underline p(m_0)$ and $\overline p(m_0)$ described above + +Now initiate the algorithm as follows. + + * set $m_0 >0$ + * set a value of $p_0 \in [\underline p(m_0), \overline p(m_0)]$ and form the pair $(m_0, p_0)$ at time $t =0$ + +Starting from $(m_0, p_0)$ iterate on $t$ to convergence of $\pi_t \rightarrow \overline \pi$ and $\mu_t \rightarrow \overline \mu$ + +It will turn out that + +* if they exist, limiting values $\overline \pi$ and $\overline \mu$ will be equal + +* if limiting values exist, there are two possible limiting values, one high, one low + +* for almost all initial log price levels $p_0$, the limiting $\overline \pi = \overline \mu$ is +the higher value + +* for each of the two possible limiting values $\overline \pi$ ,there is a unique initial log price level $p_0$ that implies that $\pi_t = \mu_t = \overline \mu$ for all $t \geq 0$ + + * this unique initial log price level solves $\log(\exp(m_0) + g \exp(p_0)) - p_0 = - \alpha \overline \pi $ + + * the preceding equation for $p_0$ comes from $m_1 - p_0 = - \alpha \overline \pi$ + + +## Slippery Side of Laffer Curve Dynamics + +We are now equipped to compute time series starting from different $p_0$ settings, like those in {doc}`money_inflation`. + +```{code-cell} ipython3 +:tags: [hide-cell] + +def draw_iterations(p0s, model, line_params, p0_bars, num_steps): + + fig, axes = plt.subplots(4, 1, figsize=(8, 10), sharex=True) + + # Pre-compute time steps + time_steps = np.arange(num_steps) + + # Plot the first two y-axes in log scale + for ax in axes[:2]: + ax.set_yscale('log') + + # Iterate over p_0s and calculate a series of y_t + for p0 in p0s: + π_seq, μ_seq, m_seq, p_seq = simulate_seq(p0, model, num_steps) + + # Plot m_t + axes[0].plot(time_steps, m_seq[1:], **line_params) + + # Plot p_t + axes[1].plot(time_steps, p_seq[1:], **line_params) + + # Plot π_t + axes[2].plot(time_steps, π_seq, **line_params) + + # Plot μ_t + axes[3].plot(time_steps, μ_seq, **line_params) + + # Draw labels + axes[0].set_ylabel('$m_t$') + axes[1].set_ylabel('$p_t$') + axes[2].set_ylabel('$\pi_t$') + axes[3].set_ylabel('$\mu_t$') + axes[3].set_xlabel('timestep') + + for p_0, label in [(p0_bars[0], '$p_0=p_l$'), (p0_bars[1], '$p_0=p_u$')]: + y = simulate_seq(p_0, model, 1)[0] + for ax in axes[2:]: + ax.axhline(y=y[0], color='grey', linestyle='--', lw=1.5, alpha=0.6) + ax.text(num_steps * 1.02, y[0], label, verticalalignment='center', + color='grey', size=10) + + # Enforce integar axis label + axes[3].xaxis.set_major_locator(MaxNLocator(integer=True)) + + plt.tight_layout() + plt.show() +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Starting from different initial values of $p_0$, paths of $m_t$ (top + panel, log scale for $m$), $p_t$ (second panel, log scale for $p$), $\pi_t$ (third panel), and $\mu_t$ (bottom + panel) + name: p0_path_nonlin + width: 500px +--- + +# Generate a sequence from p0_l to p0_u +p0s = np.arange(p0_l, p0_u, 0.1) + +line_params = {'lw': 1.5, + 'marker': 'o', + 'markersize': 3} + +p0_bars = (p0_l, p0_u) + +draw_iterations(p0s, model, line_params, p0_bars, num_steps=20) +``` + +Staring at the paths of price levels in {numref}`p0_path_nonlin` reveals that almost all paths converge to the *higher* inflation tax rate displayed in the stationary state Laffer curve. displayed in figure {numref}`laffer_curve_nonlinear`. + +Thus, we have reconfirmed what we have called the "perverse" dynamics under rational expectations in which the system converges to the higher of two possible stationary inflation tax rates. + +Those dynamics are "perverse" not only in the sense that they imply that the monetary and fiscal authorities that have chosen to finance government expenditures eventually impose a higher inflation tax than required to finance government expenditures, but because of the following "counterintuitive" situation that we can deduce by staring at the stationary state Laffer curve displayed in figure {numref}`laffer_curve_nonlinear`: + +* the figure indicates that inflation can be *reduced* by running *higher* government deficits, i.e., by raising more resources through printing money. + +```{note} +The same qualitative outcomes prevail in {doc}`money_inflation` that studies a linear version of the model in this lecture. +``` + +We discovered that + +* all but one of the equilibrium paths converge to limits in which the higher of two possible stationary inflation tax prevails +* there is a unique equilibrium path associated with "plausible" statements about how reductions in government deficits affect a stationary inflation rate + +As in {doc}`money_inflation`, +on grounds of plausibility, we again recommend selecting the unique equilibrium that converges to the lower stationary inflation tax rate. + +As we shall see, we accepting this recommendation is a key ingredient of outcomes of the "unpleasant arithmetic" that we describe in {doc}`unpleasant`. + +In {doc}`laffer_adaptive`, we shall explore how {cite}`bruno1990seigniorage` and others justified our equilibrium selection in other ways. diff --git a/content/lectures/monte_carlo.ipynb b/book/_build/html/_sources/monte_carlo.ipynb similarity index 83% rename from content/lectures/monte_carlo.ipynb rename to book/_build/html/_sources/monte_carlo.ipynb index af35101..e412895 100644 --- a/content/lectures/monte_carlo.ipynb +++ b/book/_build/html/_sources/monte_carlo.ipynb @@ -2,9 +2,10 @@ "cells": [ { "cell_type": "markdown", - "id": "d4499448", + "id": "38b28c8f", "metadata": {}, "source": [ + "(monte-carlo)=\n", "# Monte Carlo and Option Pricing\n", "\n", "## Overview\n", @@ -38,7 +39,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b447128e", + "id": "24dac750", "metadata": {}, "outputs": [], "source": [ @@ -49,15 +50,15 @@ }, { "cell_type": "markdown", - "id": "3d9450bb", + "id": "9f9dcfd3", "metadata": {}, "source": [ - "## An Introduction to Monte Carlo\n", + "## An introduction to Monte Carlo\n", "\n", "In this section we describe how Monte Carlo can be used to compute\n", "expectations.\n", "\n", - "### Share Price with Known Distribution\n", + "### Share price with known distribution\n", "\n", "Suppose that we are considering buying a share in some company.\n", "\n", @@ -87,7 +88,7 @@ "represented by a lognormal distribution with parameters $\\mu, \\sigma$ .\n", "\n", "* $S$ has the same distribution as $\\exp(\\mu + \\sigma Z)$ where $Z$ is standard normal.\n", - "* we write this statement as $S \\sim LN(\\mu, \\sigma)$.\n", + "* We write this statement as $S \\sim LN(\\mu, \\sigma)$.\n", "\n", "Any good reference on statistics (such as\n", "[Wikipedia](https://en.wikipedia.org/wiki/Log-normal_distribution)) will tell\n", @@ -109,7 +110,7 @@ "\n", "\n", "\n", - "### Share Price with Unknown Distribution\n", + "### Share price with unknown distribution\n", "\n", "But now suppose that we study the distribution of $S$ more carefully.\n", "\n", @@ -138,12 +139,12 @@ "This is the Monte Carlo method, which runs as follows:\n", "\n", "1. Generate $n$ independent draws of $X_1$, $X_2$ and $X_3$ on a computer,\n", - "1. Use these draws to generate $n$ independent draws of $S$, and\n", - "1. Take the average value of these draws of $S$.\n", + "1. use these draws to generate $n$ independent draws of $S$, and\n", + "1. take the average value of these draws of $S$.\n", "\n", "This average will be close to the true mean when $n$ is large.\n", "\n", - "This is due to the law of large numbers, which we discussed in {doc}`another lecture `.\n", + "This is due to the law of large numbers, which we discussed in {doc}`lln_clt`.\n", "\n", "We use the following values for $p$ and each $\\mu_i$ and $\\sigma_i$." ] @@ -151,7 +152,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9cdf20a1", + "id": "0fac57d0", "metadata": {}, "outputs": [], "source": [ @@ -163,10 +164,10 @@ }, { "cell_type": "markdown", - "id": "6e69c0b1", + "id": "6bd926d0", "metadata": {}, "source": [ - "#### A Routine using Loops in Python\n", + "#### A routine using loops in python\n", "\n", "\n", "Here's a routine using native Python loops to calculate the desired mean\n", @@ -180,7 +181,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ab85d294", + "id": "6e9114cd", "metadata": {}, "outputs": [], "source": [ @@ -197,7 +198,7 @@ }, { "cell_type": "markdown", - "id": "d9655ce9", + "id": "77ffb66e", "metadata": {}, "source": [ "We can also construct a function that contains these operations:" @@ -206,7 +207,7 @@ { "cell_type": "code", "execution_count": null, - "id": "79226929", + "id": "f4cdeaaf", "metadata": {}, "outputs": [], "source": [ @@ -222,7 +223,7 @@ }, { "cell_type": "markdown", - "id": "b1c631ba", + "id": "aef7a4f7", "metadata": {}, "source": [ "Now let's call it." @@ -231,7 +232,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f5f494f7", + "id": "95e93663", "metadata": {}, "outputs": [], "source": [ @@ -240,10 +241,10 @@ }, { "cell_type": "markdown", - "id": "7f33861a", + "id": "b1eca15c", "metadata": {}, "source": [ - "### A Vectorized Routine\n", + "### A vectorized routine\n", "\n", "If we want a more accurate estimate we should increase $n$.\n", "\n", @@ -255,7 +256,7 @@ { "cell_type": "code", "execution_count": null, - "id": "42b7d897", + "id": "a922b0e0", "metadata": {}, "outputs": [], "source": [ @@ -270,7 +271,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a5bfec15", + "id": "cf430e5c", "metadata": {}, "outputs": [], "source": [ @@ -281,7 +282,7 @@ }, { "cell_type": "markdown", - "id": "8e4ec4c1", + "id": "96df7786", "metadata": {}, "source": [ "Notice that this routine is much faster.\n", @@ -292,7 +293,7 @@ { "cell_type": "code", "execution_count": null, - "id": "184b4ebb", + "id": "d2157590", "metadata": {}, "outputs": [], "source": [ @@ -303,10 +304,10 @@ }, { "cell_type": "markdown", - "id": "d445edc6", + "id": "b58c5b26", "metadata": {}, "source": [ - "## Pricing a European Call Option under Risk Neutrality\n", + "## Pricing a European call option under risk neutrality\n", "\n", "Next we are going to price a European call option under risk neutrality.\n", "\n", @@ -314,7 +315,7 @@ "\n", "\n", "\n", - "### Risk-Neutral Pricing\n", + "### Risk-neutral pricing\n", "\n", "When we use risk-neutral pricing, we determine the price of a given asset\n", "according to its expected payoff:\n", @@ -353,7 +354,7 @@ "\n", "\n", "\n", - "### A Comment on Risk\n", + "### A comment on risk\n", "\n", "As suggested by the name, the risk-neutral price ignores risk.\n", "\n", @@ -405,7 +406,7 @@ "\n", "\n", "\n", - "### European Call Options\n", + "### European call options\n", "\n", "Now let's price a European call option.\n", "\n", @@ -451,7 +452,7 @@ { "cell_type": "code", "execution_count": null, - "id": "82048a58", + "id": "20ad1ac8", "metadata": {}, "outputs": [], "source": [ @@ -464,7 +465,7 @@ }, { "cell_type": "markdown", - "id": "f8a8b3ed", + "id": "fa7484bf", "metadata": {}, "source": [ "We set the simulation size to" @@ -473,7 +474,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1877e31e", + "id": "fd977d89", "metadata": {}, "outputs": [], "source": [ @@ -482,7 +483,7 @@ }, { "cell_type": "markdown", - "id": "fdbbd967", + "id": "e6fe4e60", "metadata": {}, "source": [ "Here is our code" @@ -491,7 +492,7 @@ { "cell_type": "code", "execution_count": null, - "id": "735568be", + "id": "b5c72928", "metadata": {}, "outputs": [], "source": [ @@ -503,10 +504,10 @@ }, { "cell_type": "markdown", - "id": "e987a554", + "id": "42131440", "metadata": {}, "source": [ - "## Pricing Via a Dynamic Model\n", + "## Pricing via a dynamic model\n", "\n", "In this exercise we investigate a more realistic model for the share price $S_n$.\n", "\n", @@ -516,7 +517,7 @@ "\n", "Then we'll compute the price of the option using Monte Carlo.\n", "\n", - "### Simple Dynamics\n", + "### Simple dynamics\n", "\n", "One simple model for $\\{S_t\\}$ is\n", "\n", @@ -524,7 +525,7 @@ "\n", "where\n", "\n", - "* $S_0$ is normally distributed and\n", + "* $S_0$ is lognormally distributed and\n", "* $\\{ \\xi_t \\}$ is IID and standard normal.\n", "\n", "\n", @@ -546,7 +547,7 @@ "Hence $S_n = \\exp(s_n)$ is lognormal.\n", "\n", "\n", - "### Problems with Simple Dynamics\n", + "### Problems with simple dynamics\n", "\n", "The simple dynamic model we studied above is convenient, since we can work out\n", "the distribution of $S_n$.\n", @@ -560,7 +561,7 @@ "In terms of our model above, this means that $\\sigma$ should not be constant.\n", "\n", "\n", - "### More Realistic Dynamics\n", + "### More realistic dynamics\n", "\n", "This leads us to study the improved version:\n", "\n", @@ -578,7 +579,7 @@ "\n", "\n", "\n", - "### Default Parameters\n", + "### Default parameters\n", "\n", "For the dynamic model, we adopt the following parameter values." ] @@ -586,23 +587,23 @@ { "cell_type": "code", "execution_count": null, - "id": "0a0ea5be", + "id": "d0c84a13", "metadata": {}, "outputs": [], "source": [ - "μ = 0.0001\n", - "ρ = 0.1\n", - "ν = 0.001\n", - "S0 = 10\n", - "h0 = 0" + "default_μ = 0.0001\n", + "default_ρ = 0.1\n", + "default_ν = 0.001\n", + "default_S0 = 10\n", + "default_h0 = 0" ] }, { "cell_type": "markdown", - "id": "2ded65b1", + "id": "177e103d", "metadata": {}, "source": [ - "(Here `S0` is $S_0$ and `h0` is $h_0$.)\n", + "(Here `default_S0` is $S_0$ and `default_h0` is $h_0$.)\n", "\n", "For the option we use the following defaults." ] @@ -610,18 +611,18 @@ { "cell_type": "code", "execution_count": null, - "id": "216f4486", + "id": "33ba7ce3", "metadata": {}, "outputs": [], "source": [ - "K = 100\n", - "n = 10\n", - "β = 0.95" + "default_K = 100\n", + "default_n = 10\n", + "default_β = 0.95" ] }, { "cell_type": "markdown", - "id": "965a6c8f", + "id": "873af95f", "metadata": {}, "source": [ "### Visualizations\n", @@ -636,11 +637,11 @@ { "cell_type": "code", "execution_count": null, - "id": "c6a9affa", + "id": "389963a0", "metadata": {}, "outputs": [], "source": [ - "def simulate_asset_price_path(μ=μ, S0=S0, h0=h0, n=n, ρ=ρ, ν=ν):\n", + "def simulate_asset_price_path(μ=default_μ, S0=default_S0, h0=default_h0, n=default_n, ρ=default_ρ, ν=default_ν):\n", " s = np.empty(n+1)\n", " s[0] = np.log(S0)\n", "\n", @@ -654,7 +655,7 @@ }, { "cell_type": "markdown", - "id": "b0685e0b", + "id": "31edfd1b", "metadata": {}, "source": [ "Here we plot the paths and the log of the paths." @@ -663,7 +664,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6503ffea", + "id": "b14d24f4", "metadata": {}, "outputs": [], "source": [ @@ -683,10 +684,10 @@ }, { "cell_type": "markdown", - "id": "38f7045d", + "id": "1e525d04", "metadata": {}, "source": [ - "### Computing the Price\n", + "### Computing the price\n", "\n", "Now that our model is more complicated, we cannot easily determine the\n", "distribution of $S_n$.\n", @@ -709,18 +710,18 @@ { "cell_type": "code", "execution_count": null, - "id": "ddec5f99", + "id": "473825d5", "metadata": {}, "outputs": [], "source": [ - "def compute_call_price(β=β,\n", - " μ=μ,\n", - " S0=S0,\n", - " h0=h0,\n", - " K=K,\n", - " n=n,\n", - " ρ=ρ,\n", - " ν=ν,\n", + "def compute_call_price(β=default_β,\n", + " μ=default_μ,\n", + " S0=default_S0,\n", + " h0=default_h0,\n", + " K=default_K,\n", + " n=default_n,\n", + " ρ=default_ρ,\n", + " ν=default_ν,\n", " M=10_000):\n", " current_sum = 0.0\n", " # For each sample path\n", @@ -740,7 +741,7 @@ { "cell_type": "code", "execution_count": null, - "id": "bb72e374", + "id": "ff587ca1", "metadata": {}, "outputs": [], "source": [ @@ -750,7 +751,7 @@ }, { "cell_type": "markdown", - "id": "6ac59787", + "id": "180aa7b8", "metadata": {}, "source": [ "## Exercises\n", @@ -774,18 +775,18 @@ { "cell_type": "code", "execution_count": null, - "id": "1576a591", + "id": "deaea9c9", "metadata": {}, "outputs": [], "source": [ - "def compute_call_price(β=β,\n", - " μ=μ,\n", - " S0=S0,\n", - " h0=h0,\n", - " K=K,\n", - " n=n,\n", - " ρ=ρ,\n", - " ν=ν,\n", + "def compute_call_price_vector(β=default_β,\n", + " μ=default_μ,\n", + " S0=default_S0,\n", + " h0=default_h0,\n", + " K=default_K,\n", + " n=default_n,\n", + " ρ=default_ρ,\n", + " ν=default_ν,\n", " M=10_000):\n", "\n", " s = np.full(M, np.log(S0))\n", @@ -802,17 +803,17 @@ { "cell_type": "code", "execution_count": null, - "id": "73d174e2", + "id": "4c6036f8", "metadata": {}, "outputs": [], "source": [ "%%time\n", - "compute_call_price()" + "compute_call_price_vector()" ] }, { "cell_type": "markdown", - "id": "e0022b05", + "id": "7285aa8c", "metadata": {}, "source": [ "Notice that this version is faster than the one using a Python loop.\n", @@ -823,7 +824,7 @@ { "cell_type": "code", "execution_count": null, - "id": "46cbcf78", + "id": "3a13d717", "metadata": {}, "outputs": [], "source": [ @@ -833,7 +834,7 @@ }, { "cell_type": "markdown", - "id": "b8fe299c", + "id": "8d44a3c2", "metadata": {}, "source": [ "```{solution-end}\n", @@ -859,37 +860,37 @@ { "cell_type": "code", "execution_count": null, - "id": "1f95824f", + "id": "9eea9b57", "metadata": {}, "outputs": [], "source": [ - "μ = 0.0001\n", - "ρ = 0.1\n", - "ν = 0.001\n", - "S0 = 10\n", - "h0 = 0\n", - "K = 100\n", - "n = 10\n", - "β = 0.95\n", - "bp = 120" + "default_μ = 0.0001\n", + "default_ρ = 0.1\n", + "default_ν = 0.001\n", + "default_S0 = 10\n", + "default_h0 = 0\n", + "default_K = 100\n", + "default_n = 10\n", + "default_β = 0.95\n", + "default_bp = 120" ] }, { "cell_type": "code", "execution_count": null, - "id": "1c68d8b7", + "id": "13f5416b", "metadata": {}, "outputs": [], "source": [ - "def compute_call_price_with_barrier(β=β,\n", - " μ=μ,\n", - " S0=S0,\n", - " h0=h0,\n", - " K=K,\n", - " n=n,\n", - " ρ=ρ,\n", - " ν=ν,\n", - " bp=bp,\n", + "def compute_call_price_with_barrier(β=default_β,\n", + " μ=default_μ,\n", + " S0=default_S0,\n", + " h0=default_h0,\n", + " K=default_K,\n", + " n=default_n,\n", + " ρ=default_ρ,\n", + " ν=default_ν,\n", + " bp=default_bp,\n", " M=50_000):\n", " current_sum = 0.0\n", " # For each sample path\n", @@ -918,7 +919,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8b48a5df", + "id": "cf2b4376", "metadata": {}, "outputs": [], "source": [ @@ -927,7 +928,7 @@ }, { "cell_type": "markdown", - "id": "8da84458", + "id": "b0cc4455", "metadata": {}, "source": [ "Let's look at the vectorized version which is faster than using Python loops." @@ -936,19 +937,19 @@ { "cell_type": "code", "execution_count": null, - "id": "bfc7ab9e", + "id": "a82789c2", "metadata": {}, "outputs": [], "source": [ - "def compute_call_price_with_barrier_vector(β=β,\n", - " μ=μ,\n", - " S0=S0,\n", - " h0=h0,\n", - " K=K,\n", - " n=n,\n", - " ρ=ρ,\n", - " ν=ν,\n", - " bp=bp,\n", + "def compute_call_price_with_barrier_vector(β=default_β,\n", + " μ=default_μ,\n", + " S0=default_S0,\n", + " h0=default_h0,\n", + " K=default_K,\n", + " n=default_n,\n", + " ρ=default_ρ,\n", + " ν=default_ν,\n", + " bp=default_bp,\n", " M=50_000):\n", " s = np.full(M, np.log(S0))\n", " h = np.full(M, h0)\n", @@ -969,7 +970,7 @@ { "cell_type": "code", "execution_count": null, - "id": "956c9807", + "id": "f6fa3cd1", "metadata": {}, "outputs": [], "source": [ @@ -978,7 +979,7 @@ }, { "cell_type": "markdown", - "id": "8bf99130", + "id": "15eff995", "metadata": {}, "source": [ "```{solution-end}\n", @@ -987,12 +988,67 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.5" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 12, + 45, + 49, + 147, + 152, + 166, + 176, + 182, + 191, + 197, + 199, + 211, + 220, + 224, + 232, + 236, + 381, + 387, + 393, + 395, + 401, + 406, + 486, + 492, + 500, + 504, + 516, + 527, + 533, + 546, + 569, + 594, + 597, + 618, + 640, + 643, + 651, + 654, + 677, + 689, + 724, + 726, + 732, + 759, + 761 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/monte_carlo.md b/book/_build/html/_sources/monte_carlo.md new file mode 100644 index 0000000..9f66c22 --- /dev/null +++ b/book/_build/html/_sources/monte_carlo.md @@ -0,0 +1,764 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.5 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + + +(monte-carlo)= +# Monte Carlo and Option Pricing + +## Overview + +Simple probability calculations can be done either + +* with pencil and paper, or +* by looking up facts about well known probability distributions, or +* in our heads. + +For example, we can easily work out + +* the probability of three heads in five flips of a fair coin +* the expected value of a random variable that equals $-10$ with probability + $1/2$ and $100$ with probability $1/2$. + +But some probability calculations are very complex. + +Complex calculations concerning probabilities and expectations occur in many +economic and financial problems. + +Perhaps the most important tool for handling complicated probability +calculations is [Monte Carlo methods](https://en.wikipedia.org/wiki/Monte_Carlo_method). + +In this lecture we introduce Monte Carlo methods for computing expectations, +with some applications in finance. + +We will use the following imports. + +```{code-cell} ipython3 +import numpy as np +import matplotlib.pyplot as plt +from numpy.random import randn +``` + + +## An introduction to Monte Carlo + +In this section we describe how Monte Carlo can be used to compute +expectations. + +### Share price with known distribution + +Suppose that we are considering buying a share in some company. + +Our plan is either to + +1. buy the share now, hold it for one year and then sell it, or +2. do something else with our money. + +We start by thinking of the share price in one year as a random variable $S$. + +Before deciding whether or not to buy the share, we need to know some features +of the distribution of $S$. + +For example, suppose the mean of $S$ is high relative to the price of buying +the share. + +This suggests we have a good chance of selling at a relatively high price. + +Suppose, however, that the variance of $S$ is also high. + +This suggests that buying the share is risky, so perhaps we should refrain. + +Either way, this discussion shows the importance of understanding the +distribution of $S$. + +Suppose that, after analyzing the data, we guess that $S$ is well +represented by a lognormal distribution with parameters $\mu, \sigma$ . + +* $S$ has the same distribution as $\exp(\mu + \sigma Z)$ where $Z$ is standard normal. +* We write this statement as $S \sim LN(\mu, \sigma)$. + +Any good reference on statistics (such as +[Wikipedia](https://en.wikipedia.org/wiki/Log-normal_distribution)) will tell +us that the mean and variance are + +$$ + \mathbb E S + = \exp \left(\mu + \frac{\sigma^2}{2} \right) +$$ + +and + +$$ + \mathop{\mathrm{Var}} S + = [\exp(\sigma^2) - 1] \exp(2\mu + \sigma^2) +$$ + +So far we have no need for a computer. + + + +### Share price with unknown distribution + +But now suppose that we study the distribution of $S$ more carefully. + +We decide that the share price depends on three variables, $X_1$, $X_2$, and +$X_3$ (e.g., sales, inflation, and interest rates). + +In particular, our study suggests that + +$$ + S = (X_1 + X_2 + X_3)^p +$$ + +where + +* $p$ is a positive number, which is known to us (i.e., has been estimated), +* $X_i \sim LN(\mu_i, \sigma_i)$ for $i=1,2,3$, +* the values $\mu_i, \sigma_i$ are also known, and +* the random variables $X_1$, $X_2$ and $X_3$ are independent. + +How should we compute the mean of $S$? + +To do this with pencil and paper is hard (unless, say, $p=1$). + +But fortunately there's an easy way to do this, at least approximately. + +This is the Monte Carlo method, which runs as follows: + +1. Generate $n$ independent draws of $X_1$, $X_2$ and $X_3$ on a computer, +1. use these draws to generate $n$ independent draws of $S$, and +1. take the average value of these draws of $S$. + +This average will be close to the true mean when $n$ is large. + +This is due to the law of large numbers, which we discussed in {doc}`lln_clt`. + +We use the following values for $p$ and each $\mu_i$ and $\sigma_i$. + +```{code-cell} ipython3 +n = 1_000_000 +p = 0.5 +μ_1, μ_2, μ_3 = 0.2, 0.8, 0.4 +σ_1, σ_2, σ_3 = 0.1, 0.05, 0.2 +``` + + + +#### A routine using loops in python + + +Here's a routine using native Python loops to calculate the desired mean + +$$ + \frac{1}{n} \sum_{i=1}^n S_i + \approx \mathbb E S +$$ + +```{code-cell} ipython3 +%%time + +S = 0.0 +for i in range(n): + X_1 = np.exp(μ_1 + σ_1 * randn()) + X_2 = np.exp(μ_2 + σ_2 * randn()) + X_3 = np.exp(μ_3 + σ_3 * randn()) + S += (X_1 + X_2 + X_3)**p +S / n +``` + + + +We can also construct a function that contains these operations: + +```{code-cell} ipython3 +def compute_mean(n=1_000_000): + S = 0.0 + for i in range(n): + X_1 = np.exp(μ_1 + σ_1 * randn()) + X_2 = np.exp(μ_2 + σ_2 * randn()) + X_3 = np.exp(μ_3 + σ_3 * randn()) + S += (X_1 + X_2 + X_3)**p + return (S / n) +``` + + + +Now let's call it. + +```{code-cell} ipython3 +compute_mean() +``` + + + +### A vectorized routine + +If we want a more accurate estimate we should increase $n$. + +But the code above runs quite slowly. + +To make it faster, let's implement a vectorized routine using NumPy. + +```{code-cell} ipython3 +def compute_mean_vectorized(n=1_000_000): + X_1 = np.exp(μ_1 + σ_1 * randn(n)) + X_2 = np.exp(μ_2 + σ_2 * randn(n)) + X_3 = np.exp(μ_3 + σ_3 * randn(n)) + S = (X_1 + X_2 + X_3)**p + return S.mean() +``` + +```{code-cell} ipython3 +%%time + +compute_mean_vectorized() +``` + + + +Notice that this routine is much faster. + +We can increase $n$ to get more accuracy and still have reasonable speed: + +```{code-cell} ipython3 +%%time + +compute_mean_vectorized(n=10_000_000) +``` + + + +## Pricing a European call option under risk neutrality + +Next we are going to price a European call option under risk neutrality. + +Let's first discuss risk neutrality and then consider European options. + + + +### Risk-neutral pricing + +When we use risk-neutral pricing, we determine the price of a given asset +according to its expected payoff: + +$$ +\text{cost } = \text{ expected benefit} +$$ + +For example, suppose someone promises to pay you + +- 1,000,000 dollars if "heads" is the outcome of a fair coin flip +- 0 dollars if "tails" is the outcome + +Let's denote the payoff as $G$, so that + +$$ + \mathbb P\left\{G = 10^6 \right\} = \mathbb P\{G = 0\} = \frac{1}{2} +$$ + +Suppose in addition that you can sell this promise to anyone who wants it. + +- First they pay you $P$, the price at which you sell it +- Then they get $G$, which could be either 1,000,000 or 0. + +What's a fair price for this asset (this promise)? + +The definition of "fair" is ambiguous, but we can say that the +**risk-neutral price** is 500,000 dollars. + +This is because the risk-neutral price is just the expected payoff of the +asset, which is + +$$ + \mathbb E G = \frac{1}{2} \times 10^6 + \frac{1}{2} \times 0 = 5 \times 10^5 +$$ + + + +### A comment on risk + +As suggested by the name, the risk-neutral price ignores risk. + +To understand this, consider whether you would pay 500,000 dollars for such a +promise. + +Would you prefer to receive 500,000 for sure or 1,000,000 dollars with +50% probability and nothing with 50% probability? + +At least some readers will strictly prefer the first option --- although some +might prefer the second. + +Thinking about this makes us realize that 500,000 is not necessarily the +"right" price --- or the price that we would see if there was a market for +these promises. + +Nonetheless, the risk-neutral price is an important benchmark, which economists +and financial market participants try to calculate every day. + + + +### Discounting + +Another thing we ignored in the previous discussion was time. + +In general, receiving $x$ dollars now is preferable to receiving $x$ dollars +in $n$ periods (e.g., 10 years). + +After all, if we receive $x$ dollars now, we could put it in the bank at +interest rate $r > 0$ and receive $ (1 + r)^n x $ in $n$ periods. + +Hence future payments need to be discounted when we consider their present +value. + +We will implement discounting by + +* multiplying a payment in one period by $\beta < 1$ +* multiplying a payment in $n$ periods by $\beta^n$, etc. + +The same adjustment needs to be applied to our risk-neutral price for the +promise described above. + +Thus, if $G$ is realized in $n$ periods, then the risk-neutral price is + +$$ + P = \beta^n \mathbb E G + = \beta^n 5 \times 10^5 +$$ + + + +### European call options + +Now let's price a European call option. + +The option is described by three things: + +2. $n$, the **expiry date**, +2. $K$, the **strike price**, and +3. $S_n$, the price of the **underlying** asset at date $n$. + +For example, suppose that the underlying is one share in Amazon. + +The owner of this option has the right to buy one share in Amazon at price $K$ after $n$ days. + +If $S_n > K$, then the owner will exercise the option, buy at $K$, sell at +$S_n$, and make profit $S_n - K$. + +If $S_n \leq K$, then the owner will not exercise the option and the payoff is zero. + +Thus, the payoff is $\max\{ S_n - K, 0 \}$. + +Under the assumption of risk neutrality, the price of the option is +the expected discounted payoff: + +$$ P = \beta^n \mathbb E \max\{ S_n - K, 0 \} $$ + +Now all we need to do is specify the distribution of $S_n$, so the expectation +can be calculated. + + +Suppose we know that $S_n \sim LN(\mu, \sigma)$ and $\mu$ and $\sigma$ are known. + +If $S_n^1, \ldots, S_n^M$ are independent draws from this lognormal distribution then, by the law of large numbers, + +$$ + \mathbb E \max\{ S_n - K, 0 \} + \approx + \frac{1}{M} \sum_{m=1}^M \max \{S_n^m - K, 0 \} +$$ + +We suppose that + +```{code-cell} ipython3 +μ = 1.0 +σ = 0.1 +K = 1 +n = 10 +β = 0.95 +``` + + + +We set the simulation size to + +```{code-cell} ipython3 +M = 10_000_000 +``` + + + +Here is our code + +```{code-cell} ipython3 +S = np.exp(μ + σ * np.random.randn(M)) +return_draws = np.maximum(S - K, 0) +P = β**n * np.mean(return_draws) +print(f"The Monte Carlo option price is approximately {P:3f}") +``` + + + +## Pricing via a dynamic model + +In this exercise we investigate a more realistic model for the share price $S_n$. + +This comes from specifying the underlying dynamics of the share price. + +First we specify the dynamics. + +Then we'll compute the price of the option using Monte Carlo. + +### Simple dynamics + +One simple model for $\{S_t\}$ is + +$$ \ln \frac{S_{t+1}}{S_t} = \mu + \sigma \xi_{t+1} $$ + +where + +* $S_0$ is lognormally distributed and +* $\{ \xi_t \}$ is IID and standard normal. + + +Under the stated assumptions, $S_n$ is lognormally distributed. + +To see why, observe that, with $s_t := \ln S_t$, the price dynamics become + +```{math} +:label: s_mc_dyms + +s_{t+1} = s_t + \mu + \sigma \xi_{t+1} +``` + +Since $s_0$ is normal and $\xi_1$ is normal and IID, we see that $s_1$ is +normally distributed. + +Continuing in this way shows that $s_n$ is normally distributed. + +Hence $S_n = \exp(s_n)$ is lognormal. + + +### Problems with simple dynamics + +The simple dynamic model we studied above is convenient, since we can work out +the distribution of $S_n$. + + +However, its predictions are counterfactual because, in the real world, +volatility (measured by $\sigma$) is not stationary. + +Instead it rather changes over time, sometimes high (like during the GFC) and sometimes low. + +In terms of our model above, this means that $\sigma$ should not be constant. + + +### More realistic dynamics + +This leads us to study the improved version: + +$$ \ln \frac{S_{t+1}}{S_t} = \mu + \sigma_t \xi_{t+1} $$ + +where + +$$ + \sigma_t = \exp(h_t), + \quad + h_{t+1} = \rho h_t + \nu \eta_{t+1} +$$ + +Here $\{\eta_t\}$ is also IID and standard normal. + + + +### Default parameters + +For the dynamic model, we adopt the following parameter values. + +```{code-cell} ipython3 +default_μ = 0.0001 +default_ρ = 0.1 +default_ν = 0.001 +default_S0 = 10 +default_h0 = 0 +``` + + + +(Here `default_S0` is $S_0$ and `default_h0` is $h_0$.) + +For the option we use the following defaults. + +```{code-cell} ipython3 +default_K = 100 +default_n = 10 +default_β = 0.95 +``` + + + +### Visualizations + +With $s_t := \ln S_t$, the price dynamics become + +$$ s_{t+1} = s_t + \mu + \exp(h_t) \xi_{t+1} $$ + +Here is a function to simulate a path using this equation: + +```{code-cell} ipython3 +def simulate_asset_price_path(μ=default_μ, S0=default_S0, h0=default_h0, n=default_n, ρ=default_ρ, ν=default_ν): + s = np.empty(n+1) + s[0] = np.log(S0) + + h = h0 + for t in range(n): + s[t+1] = s[t] + μ + np.exp(h) * randn() + h = ρ * h + ν * randn() + + return np.exp(s) +``` + + + +Here we plot the paths and the log of the paths. + +```{code-cell} ipython3 +fig, axes = plt.subplots(2, 1) + +titles = 'log paths', 'paths' +transforms = np.log, lambda x: x +for ax, transform, title in zip(axes, transforms, titles): + for i in range(50): + path = simulate_asset_price_path() + ax.plot(transform(path)) + ax.set_title(title) + +fig.tight_layout() +plt.show() +``` + + + +### Computing the price + +Now that our model is more complicated, we cannot easily determine the +distribution of $S_n$. + +So to compute the price $P$ of the option, we use Monte Carlo. + +We average over realizations $S_n^1, \ldots, S_n^M$ of $S_n$ and appealing to +the law of large numbers: + +$$ + \mathbb E \max\{ S_n - K, 0 \} + \approx + \frac{1}{M} \sum_{m=1}^M \max \{S_n^m - K, 0 \} +$$ + + +Here's a version using Python loops. + +```{code-cell} ipython3 +def compute_call_price(β=default_β, + μ=default_μ, + S0=default_S0, + h0=default_h0, + K=default_K, + n=default_n, + ρ=default_ρ, + ν=default_ν, + M=10_000): + current_sum = 0.0 + # For each sample path + for m in range(M): + s = np.log(S0) + h = h0 + # Simulate forward in time + for t in range(n): + s = s + μ + np.exp(h) * randn() + h = ρ * h + ν * randn() + # And add the value max{S_n - K, 0} to current_sum + current_sum += np.maximum(np.exp(s) - K, 0) + + return β**n * current_sum / M +``` + +```{code-cell} ipython3 +%%time +compute_call_price() +``` + + + +## Exercises + +```{exercise} +:label: monte_carlo_ex1 + +We would like to increase $M$ in the code above to make the calculation more +accurate. + +But this is problematic because Python loops are slow. + +Your task is to write a faster version of this code using NumPy. +``` + +```{solution-start} monte_carlo_ex1 +:class: dropdown +``` + +```{code-cell} ipython3 +def compute_call_price_vector(β=default_β, + μ=default_μ, + S0=default_S0, + h0=default_h0, + K=default_K, + n=default_n, + ρ=default_ρ, + ν=default_ν, + M=10_000): + + s = np.full(M, np.log(S0)) + h = np.full(M, h0) + for t in range(n): + Z = np.random.randn(2, M) + s = s + μ + np.exp(h) * Z[0, :] + h = ρ * h + ν * Z[1, :] + expectation = np.mean(np.maximum(np.exp(s) - K, 0)) + + return β**n * expectation +``` + +```{code-cell} ipython3 +%%time +compute_call_price_vector() +``` + + + +Notice that this version is faster than the one using a Python loop. + +Now let's try with larger $M$ to get a more accurate calculation. + +```{code-cell} ipython3 +%%time +compute_call_price(M=10_000_000) +``` + + + +```{solution-end} +``` + +```{exercise} +:label: monte_carlo_ex2 + +Consider that a European call option may be written on an underlying with spot price of \$100 and a knockout barrier of \$120. + +This option behaves in every way like a vanilla European call, except if the spot price ever moves above \$120, the option "knocks out" and the contract is null and void. + +Note that the option does not reactivate if the spot price falls below \$120 again. + +Use the dynamics defined in {eq}`s_mc_dyms` to price the European call option. +``` + +```{solution-start} monte_carlo_ex2 +:class: dropdown +``` + +```{code-cell} ipython3 +default_μ = 0.0001 +default_ρ = 0.1 +default_ν = 0.001 +default_S0 = 10 +default_h0 = 0 +default_K = 100 +default_n = 10 +default_β = 0.95 +default_bp = 120 +``` + +```{code-cell} ipython3 +def compute_call_price_with_barrier(β=default_β, + μ=default_μ, + S0=default_S0, + h0=default_h0, + K=default_K, + n=default_n, + ρ=default_ρ, + ν=default_ν, + bp=default_bp, + M=50_000): + current_sum = 0.0 + # For each sample path + for m in range(M): + s = np.log(S0) + h = h0 + payoff = 0 + option_is_null = False + # Simulate forward in time + for t in range(n): + s = s + μ + np.exp(h) * randn() + h = ρ * h + ν * randn() + if np.exp(s) > bp: + payoff = 0 + option_is_null = True + break + + if not option_is_null: + payoff = np.maximum(np.exp(s) - K, 0) + # And add the payoff to current_sum + current_sum += payoff + + return β**n * current_sum / M +``` + +```{code-cell} ipython3 +%time compute_call_price_with_barrier() +``` + + + +Let's look at the vectorized version which is faster than using Python loops. + +```{code-cell} ipython3 +def compute_call_price_with_barrier_vector(β=default_β, + μ=default_μ, + S0=default_S0, + h0=default_h0, + K=default_K, + n=default_n, + ρ=default_ρ, + ν=default_ν, + bp=default_bp, + M=50_000): + s = np.full(M, np.log(S0)) + h = np.full(M, h0) + option_is_null = np.full(M, False) + for t in range(n): + Z = np.random.randn(2, M) + s = s + μ + np.exp(h) * Z[0, :] + h = ρ * h + ν * Z[1, :] + # Mark all the options null where S_n > barrier price + option_is_null = np.where(np.exp(s) > bp, True, option_is_null) + + # mark payoff as 0 in the indices where options are null + payoff = np.where(option_is_null, 0, np.maximum(np.exp(s) - K, 0)) + expectation = np.mean(payoff) + return β**n * expectation +``` + +```{code-cell} ipython3 +%time compute_call_price_with_barrier_vector() +``` + +```{solution-end} +``` diff --git a/content/lectures/networks.ipynb b/book/_build/html/_sources/networks.ipynb similarity index 83% rename from content/lectures/networks.ipynb rename to book/_build/html/_sources/networks.ipynb index 5017294..f771b25 100644 --- a/content/lectures/networks.ipynb +++ b/book/_build/html/_sources/networks.ipynb @@ -2,23 +2,16 @@ "cells": [ { "cell_type": "markdown", - "id": "d87ea1f1", + "id": "7e3e9656", "metadata": {}, "source": [ - "# Networks\n", - "\n", - "```{admonition} graphviz\n", - ":class: warning\n", - "If you are running this lecture locally it requires [graphviz](https://www.graphviz.org)\n", - "to be installed on your computer. Installation instructions for graphviz can be found\n", - "[here](https://www.graphviz.org/download/)\n", - "```" + "# Networks" ] }, { "cell_type": "code", "execution_count": null, - "id": "97a0b697", + "id": "e1eda482", "metadata": { "tags": [ "hide-output" @@ -26,13 +19,12 @@ }, "outputs": [], "source": [ - "%pip install quantecon graphviz\n", "%pip install quantecon-book-networks pandas-datareader" ] }, { "cell_type": "markdown", - "id": "9d48a561", + "id": "c7f3b4b8", "metadata": {}, "source": [ "## Outline\n", @@ -69,7 +61,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5ace706e", + "id": "828d2353", "metadata": {}, "outputs": [], "source": [ @@ -79,10 +71,7 @@ "import pandas as pd\n", "import quantecon as qe\n", "\n", - "import graphviz\n", - "\n", "import matplotlib.cm as cm\n", - "import quantecon_book_networks\n", "import quantecon_book_networks.input_output as qbn_io\n", "import quantecon_book_networks.data as qbn_data\n", "\n", @@ -91,10 +80,10 @@ }, { "cell_type": "markdown", - "id": "a3b52ed5", + "id": "59a186a0", "metadata": {}, "source": [ - "## Economic and Financial Networks\n", + "## Economic and financial networks\n", "\n", "Within economics, important examples of networks include\n", "\n", @@ -121,7 +110,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b4d9e9e9", + "id": "7f10efc4", "metadata": { "mystnb": { "figure": { @@ -138,8 +127,8 @@ "ch1_data = qbn_data.introduction()\n", "export_figures = False\n", "\n", - "DG = ch1_data['aircraft_network_2019']\n", - "pos = ch1_data['aircraft_network_2019_pos']\n", + "DG = ch1_data['aircraft_network']\n", + "pos = ch1_data['aircraft_network_pos']\n", "\n", "centrality = nx.eigenvector_centrality(DG)\n", "node_total_exports = qbn_io.node_total_exports(DG)\n", @@ -187,7 +176,7 @@ }, { "cell_type": "markdown", - "id": "dd41ab8d", + "id": "977484bd", "metadata": {}, "source": [ "The circles in the figure are called **nodes** or **vertices** -- in this case they represent countries.\n", @@ -212,53 +201,23 @@ "* \"mr\" = \"mild recession\"\n", "* \"sr\" = \"severe recession\"\n", "\n", - "Let's examine the following figure." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e6c4654a", - "metadata": { - "tags": [ - "hide-input" - ] - }, - "outputs": [], - "source": [ - "dot = graphviz.Digraph(comment='Graph')\n", - "dot.attr(rankdir='LR')\n", - "\n", - "dot.node(\"ng\")\n", - "dot.node(\"mr\")\n", - "dot.node(\"sr\")\n", + "Let's examine the following figure\n", "\n", - "dot.edge(\"ng\", \"ng\", label=\"0.971\")\n", - "dot.edge(\"ng\", \"mr\", label=\"0.029\")\n", - "dot.edge(\"mr\", \"ng\", label=\"0.145\")\n", - "dot.edge(\"mr\", \"mr\", label=\"0.778\")\n", - "dot.edge(\"mr\", \"sr\", label=\"0.077\")\n", - "dot.edge(\"sr\", \"mr\", label=\"0.508\")\n", - "dot.edge(\"sr\", \"sr\", label=\"0.492\")\n", + "```{image} /_static/lecture_specific/networks/mc.png\n", + ":name: mc_networks\n", + ":align: center\n", + "```\n", "\n", - "dot" - ] - }, - { - "cell_type": "markdown", - "id": "23349bde", - "metadata": {}, - "source": [ "This is an example of a network, where the set of nodes $V$ equals the states:\n", "\n", "$$\n", - " V = \\{ \\text{``ng\", ``mr\", ``sr\"} \\}\n", + " V = \\{ \\text{\"ng\", \"mr\", \"sr\"} \\}\n", "$$\n", "\n", "The edges between the nodes show the one month transition probabilities.\n", "\n", "\n", - "## An Introduction to Graph Theory\n", + "## An introduction to graph theory\n", "\n", "Now we've looked at some examples, let's move on to theory.\n", "\n", @@ -286,7 +245,7 @@ "from $A$ to $B$ is paired with another arrow pointing from $B$ to $A$.)\n", "\n", "\n", - "### Key Definitions\n", + "### Key definitions\n", "\n", "A **directed graph** consists of two things:\n", "\n", @@ -309,83 +268,32 @@ "\n", "Let's look at more examples.\n", "\n", - "Two graphs are shown below, each with three nodes." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a5f563e5", - "metadata": { - "mystnb": { - "figure": { - "caption": "Poverty Trap 1 \n", - "name": "poverty_trap_1" - } - } - }, - "outputs": [], - "source": [ - "graph1 = graphviz.Digraph(comment='Graph',engine = \"neato\")\n", - "graph1.attr(rankdir='LR')\n", - "graph1.node(\"poor\", pos='0,0!')\n", - "graph1.node(\"middle class\", pos='2,1!')\n", - "graph1.node(\"rich\", pos='4,0!')\n", + "Two graphs are shown below, each with three nodes.\n", "\n", - "graph1.edge(\"poor\", \"poor\")\n", - "graph1.edge(\"poor\", \"middle class\")\n", - "graph1.edge(\"middle class\", \"poor\")\n", - "graph1.edge(\"middle class\", \"middle class\")\n", - "graph1.edge(\"middle class\", \"rich\")\n", - "graph1.edge(\"rich\", \"poor\")\n", - "graph1.edge(\"rich\", \"middle class\")\n", - "graph1.edge(\"rich\", \"rich\")\n", + "```{figure} /_static/lecture_specific/networks/poverty_trap_1.png\n", + ":name: poverty_trap_1\n", "\n", - "graph1" + "Poverty Trap\n", + "```" ] }, { "cell_type": "markdown", - "id": "2019a0aa", + "id": "36df6ee4", "metadata": {}, "source": [ - "We now construct a graph with the same nodes but different edges." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6f4db0a9", - "metadata": { - "mystnb": { - "figure": { - "caption": "Poverty Trap \n", - "name": "poverty_trap_2" - } - } - }, - "outputs": [], - "source": [ - "graph2 = graphviz.Digraph(comment='Graph',engine=\"neato\")\n", - "graph2.attr(rankdir='LR')\n", - "graph2.node(\"poor\", pos='0,0!')\n", - "graph2.node(\"middle class\", pos='2,1!')\n", - "graph2.node(\"rich\", pos='4,0!')\n", + "We now construct a graph with the same nodes but different edges.\n", "\n", - "graph2.edge(\"poor\", \"poor\")\n", - "graph2.edge(\"middle class\", \"poor\")\n", - "graph2.edge(\"middle class\", \"middle class\")\n", - "graph2.edge(\"middle class\", \"rich\")\n", - "graph2.edge(\"rich\", \"poor\")\n", - "graph2.edge(\"rich\", \"middle class\")\n", - "graph2.edge(\"rich\", \"rich\")\n", + "```{figure} /_static/lecture_specific/networks/poverty_trap_2.png\n", + ":name: poverty_trap_2\n", "\n", - "graph2" + "Poverty Trap\n", + "```" ] }, { "cell_type": "markdown", - "id": "41d9e3cb", + "id": "25a2ac8f", "metadata": {}, "source": [ "For these graphs, the arrows (edges) can be thought of as representing\n", @@ -414,7 +322,7 @@ { "cell_type": "code", "execution_count": null, - "id": "08c1deb9", + "id": "7731d1e2", "metadata": {}, "outputs": [], "source": [ @@ -423,7 +331,7 @@ }, { "cell_type": "markdown", - "id": "df5b8e41", + "id": "208bc77f", "metadata": {}, "source": [ "Next we populate it with nodes and edges.\n", @@ -435,7 +343,7 @@ { "cell_type": "code", "execution_count": null, - "id": "25b914ef", + "id": "b75814cc", "metadata": {}, "outputs": [], "source": [ @@ -446,7 +354,7 @@ }, { "cell_type": "markdown", - "id": "642943ea", + "id": "220c2542", "metadata": {}, "source": [ "Finally, we add the edges to our `DiGraph` object:" @@ -455,7 +363,7 @@ { "cell_type": "code", "execution_count": null, - "id": "646fa4bf", + "id": "befb000b", "metadata": {}, "outputs": [], "source": [ @@ -466,7 +374,7 @@ }, { "cell_type": "markdown", - "id": "4cd026a1", + "id": "d9a73a0b", "metadata": {}, "source": [ "Alternatively, we can use the method `add_edges_from`." @@ -475,7 +383,7 @@ { "cell_type": "code", "execution_count": null, - "id": "450a9004", + "id": "baf1145c", "metadata": {}, "outputs": [], "source": [ @@ -484,7 +392,7 @@ }, { "cell_type": "markdown", - "id": "a223cb17", + "id": "551832fb", "metadata": {}, "source": [ "Adding the edges automatically adds the nodes, so `G_p` is now a\n", @@ -496,7 +404,7 @@ { "cell_type": "code", "execution_count": null, - "id": "884912ce", + "id": "390e9bb7", "metadata": {}, "outputs": [], "source": [ @@ -509,7 +417,7 @@ }, { "cell_type": "markdown", - "id": "ecab4bb9", + "id": "80730db0", "metadata": {}, "source": [ "The figure obtained above matches the original directed graph in {numref}`poverty_trap_2`.\n", @@ -524,7 +432,7 @@ { "cell_type": "code", "execution_count": null, - "id": "0bbabfe4", + "id": "387897ca", "metadata": {}, "outputs": [], "source": [ @@ -533,9 +441,10 @@ }, { "cell_type": "markdown", - "id": "d6149bd9", + "id": "bedaa6b7", "metadata": {}, "source": [ + "(strongly_connected)=\n", "### Communication\n", "\n", "Next, we study communication and connectedness, which have important\n", @@ -568,7 +477,7 @@ { "cell_type": "code", "execution_count": null, - "id": "40bc7c7d", + "id": "eeec62da", "metadata": {}, "outputs": [], "source": [ @@ -585,7 +494,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e9a16d1f", + "id": "b58ff303", "metadata": {}, "outputs": [], "source": [ @@ -595,7 +504,7 @@ { "cell_type": "code", "execution_count": null, - "id": "07900cf3", + "id": "8718a8f8", "metadata": {}, "outputs": [], "source": [ @@ -612,7 +521,7 @@ { "cell_type": "code", "execution_count": null, - "id": "01533760", + "id": "705590a5", "metadata": {}, "outputs": [], "source": [ @@ -621,16 +530,16 @@ }, { "cell_type": "markdown", - "id": "67d53e0f", + "id": "083bcfaf", "metadata": {}, "source": [ - "## Weighted Graphs\n", + "## Weighted graphs\n", "\n", "We now introduce weighted graphs, where weights (numbers) are attached to each\n", "edge.\n", "\n", "\n", - "### International Private Credit Flows by Country\n", + "### International private credit flows by country\n", "\n", "To motivate the idea, consider the following figure which shows flows of funds (i.e.,\n", "loans) between private banks, grouped by country of origin." @@ -639,7 +548,7 @@ { "cell_type": "code", "execution_count": null, - "id": "86cf9034", + "id": "7360ed5a", "metadata": { "mystnb": { "figure": { @@ -653,9 +562,9 @@ }, "outputs": [], "source": [ - "Z = ch1_data[\"adjacency_matrix_2019\"][\"Z\"]\n", - "Z_visual= ch1_data[\"adjacency_matrix_2019\"][\"Z_visual\"]\n", - "countries = ch1_data[\"adjacency_matrix_2019\"][\"countries\"]\n", + "Z = ch1_data[\"adjacency_matrix\"][\"Z\"]\n", + "Z_visual= ch1_data[\"adjacency_matrix\"][\"Z_visual\"]\n", + "countries = ch1_data[\"adjacency_matrix\"][\"countries\"]\n", "\n", "G = qbn_io.adjacency_matrix_to_graph(Z_visual, countries, tol=0.03)\n", "\n", @@ -709,7 +618,7 @@ }, { "cell_type": "markdown", - "id": "db1ea7fb", + "id": "dff6b0a7", "metadata": {}, "source": [ "The country codes are given in the following table\n", @@ -746,7 +655,7 @@ }, { "cell_type": "markdown", - "id": "60141cad", + "id": "e0b3896d", "metadata": {}, "source": [ "### Definitions\n", @@ -757,50 +666,16 @@ "The figure above shows one weighted directed graph, where the weights are the size of fund flows.\n", "\n", "The following figure shows a weighted directed graph, with arrows\n", - "representing edges of the induced directed graph." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "af53461b", - "metadata": { - "mystnb": { - "figure": { - "caption": "Weighted Poverty Trap \n", - "name": "poverty_trap_weighted" - } - }, - "tags": [ - "hide-input" - ] - }, - "outputs": [], - "source": [ - "graph3 = graphviz.Digraph(comment='Graph')\n", + "representing edges of the induced directed graph.\n", "\n", - "graph3.attr(rankdir='LR')\n", - "graph3.node(\"poor\")\n", - "graph3.node(\"middle class\")\n", - "graph3.node(\"rich\")\n", "\n", - "graph3.edge(\"poor\", \"poor\", label='0.9')\n", - "graph3.edge(\"poor\", \"middle class\", label='0.1')\n", - "graph3.edge(\"middle class\", \"poor\", label='0.4')\n", - "graph3.edge(\"middle class\", \"middle class\", label='0.4')\n", - "graph3.edge(\"middle class\", \"rich\", label='0.2')\n", - "graph3.edge(\"rich\", \"poor\", label='0.1')\n", - "graph3.edge(\"rich\", \"middle class\", label='0.1')\n", - "graph3.edge(\"rich\", \"rich\", label='0.8')\n", + "```{figure} /_static/lecture_specific/networks/weighted.png\n", + ":name: poverty_trap_weighted\n", + "\n", + "Weighted Poverty Trap\n", + "```\n", + "\n", "\n", - "graph3" - ] - }, - { - "cell_type": "markdown", - "id": "a72a4d8e", - "metadata": {}, - "source": [ "The numbers next to the edges are the weights.\n", "\n", "In this case, you can think of the numbers on the arrows as transition\n", @@ -809,7 +684,7 @@ "We see that a rich household has a 10\\% chance of becoming poor in one year.\n", "\n", "\n", - "## Adjacency Matrices\n", + "## Adjacency matrices\n", "\n", "Another way that we can represent weights, which turns out to be very\n", "convenient for numerical work, is via a matrix.\n", @@ -817,18 +692,16 @@ "The **adjacency matrix** of a weighted directed graph with nodes $\\{v_1, \\ldots, v_n\\}$, edges $E$ and weight function $w$ is the matrix\n", "\n", "$$\n", - "\\begin{equation*}\n", - " A = (a_{ij})_{1 \\leq i,j \\leq n}\n", - " \\quad \\text{with} \\quad\n", - " a_{ij} =\n", - " %\n", - " \\begin{cases}\n", - " w(v_i, v_j) & \\text{ if } (v_i, v_j) \\in E\n", - " \\\\\n", - " 0 & \\text{ otherwise}.\n", - " \\end{cases}\n", - " %\n", - "\\end{equation*}\n", + "A = (a_{ij})_{1 \\leq i,j \\leq n}\n", + "\\quad \\text{with} \\quad\n", + "a_{ij} =\n", + "%\n", + "\\begin{cases}\n", + " w(v_i, v_j) & \\text{ if } (v_i, v_j) \\in E\n", + " \\\\\n", + " 0 & \\text{ otherwise}.\n", + "\\end{cases}\n", + "%\n", "$$\n", "\n", "Once the nodes in $V$ are enumerated, the weight function and\n", @@ -852,7 +725,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1ca47985", + "id": "98d8c5ed", "metadata": {}, "outputs": [], "source": [ @@ -865,7 +738,7 @@ }, { "cell_type": "markdown", - "id": "81c9aebf", + "id": "dc31c54f", "metadata": {}, "source": [ "One of the key points to remember about adjacency matrices is that taking the\n", @@ -880,7 +753,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f28d0fef", + "id": "f11102d4", "metadata": {}, "outputs": [], "source": [ @@ -907,38 +780,9 @@ "plt.show()" ] }, - { - "cell_type": "code", - "execution_count": null, - "id": "533e24fa", - "metadata": {}, - "outputs": [], - "source": [ - "graph4 = graphviz.Digraph(engine = \"neato\")\n", - "\n", - "graph4.attr(rankdir='LR')\n", - "graph4.node('1', pos='1,0!')\n", - "graph4.node('2', pos='3,0!')\n", - "graph4.node('3', pos='4,2!')\n", - "graph4.node('4', pos='2,3!')\n", - "graph4.node('5', pos='0,2!')\n", - "\n", - "graph4.edge('1','2', label='100')\n", - "graph4.edge('2','1', label='50')\n", - "graph4.edge('2','3', label='200')\n", - "graph4.edge('3','4', label='\\t100')\n", - "graph4.edge('4','2', label='500')\n", - "graph4.edge('4','5', label='\\n50\\t')\n", - "graph4.edge('5','1', label='150')\n", - "graph4.edge('5','3', label='250')\n", - "graph4.edge('5','4', label='300')\n", - "\n", - "graph4" - ] - }, { "cell_type": "markdown", - "id": "937d3115", + "id": "00cfb5fb", "metadata": {}, "source": [ "We see that bank 2 extends a loan of size 200 to bank 3.\n", @@ -977,7 +821,7 @@ { "cell_type": "code", "execution_count": null, - "id": "63b6c5d1", + "id": "a77b72c5", "metadata": {}, "outputs": [], "source": [ @@ -1003,38 +847,9 @@ "plt.show()" ] }, - { - "cell_type": "code", - "execution_count": null, - "id": "49e4d828", - "metadata": {}, - "outputs": [], - "source": [ - "graph5 = graphviz.Digraph(engine = \"neato\")\n", - "\n", - "graph5.attr(rankdir='LR')\n", - "graph5.node('1', pos='1,0!')\n", - "graph5.node('2', pos='3,0!')\n", - "graph5.node('3', pos='4,2!')\n", - "graph5.node('4', pos='2,3!')\n", - "graph5.node('5', pos='0,2!')\n", - "\n", - "graph5.edge('1', '2', label='50')\n", - "graph5.edge('1', '5', label='150')\n", - "graph5.edge('2', '1', label='100')\n", - "graph5.edge('2', '4', label='500')\n", - "graph5.edge('3', '2', label='200')\n", - "graph5.edge('3', '5', label='250')\n", - "graph5.edge('4', '3', label='\\t100')\n", - "graph5.edge('4', '5', label='\\n300\\t')\n", - "graph5.edge('5', '4', label='50')\n", - "\n", - "graph5" - ] - }, { "cell_type": "markdown", - "id": "c645e7bd", + "id": "3cb39e4c", "metadata": {}, "source": [ "In general, every nonnegative $n \\times n$ matrix $A = (a_{ij})$ can be\n", @@ -1062,11 +877,9 @@ "For distinct nodes $i, j$ in $V$ and any integer $k$, we have\n", "\n", "$$\n", - "\\begin{equation*}\n", - " a^k_{i j} > 0\n", - " \\quad \\text{if and only if} \\quad\n", - " \\text{ $j$ is accessible from $i$}.\n", - "\\end{equation*}\n", + "a^k_{i j} > 0\n", + "\\quad \\text{if and only if} \\quad\n", + "\\text{ $j$ is accessible from $i$}.\n", "$$\n", "\n", "````" @@ -1074,7 +887,7 @@ }, { "cell_type": "markdown", - "id": "89bc3e81", + "id": "a92f92a9", "metadata": {}, "source": [ "The above result is obvious when $k=1$ and a proof of the general case can be\n", @@ -1099,40 +912,23 @@ }, { "cell_type": "markdown", - "id": "b6844c7d", + "id": "5f0d66df", "metadata": {}, "source": [ "We illustrate the above theorem with a simple example.\n", "\n", - "Consider the following weighted directed graph." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ecfaf028", - "metadata": {}, - "outputs": [], - "source": [ - "graph6 = graphviz.Digraph()\n", + "Consider the following weighted directed graph.\n", "\n", - "graph6.attr(rankdir='LR')\n", - "graph6.node('1')\n", - "graph6.node('2')\n", - "graph6.node('3')\n", "\n", - "graph6.edge('1', '2', label='0.7')\n", - "graph6.edge('1', '3', label='0.3')\n", - "graph6.edge('2', '1', label='1')\n", - "graph6.edge('3', '1', label='0.4')\n", - "graph6.edge('3', '2', label='0.6')\n", + "```{image} /_static/lecture_specific/networks/properties.png\n", + ":name: properties_graph\n", "\n", - "graph6" + "```" ] }, { "cell_type": "markdown", - "id": "ecabdfa0", + "id": "f06768cc", "metadata": {}, "source": [ "We first create the above network as a Networkx `DiGraph` object." @@ -1141,7 +937,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ed87c167", + "id": "5a3d87dd", "metadata": {}, "outputs": [], "source": [ @@ -1154,7 +950,7 @@ }, { "cell_type": "markdown", - "id": "d1474b8e", + "id": "49b170dd", "metadata": {}, "source": [ "Then we construct the associated adjacency matrix A." @@ -1163,7 +959,7 @@ { "cell_type": "code", "execution_count": null, - "id": "588fd48b", + "id": "9c23b081", "metadata": {}, "outputs": [], "source": [ @@ -1175,7 +971,7 @@ { "cell_type": "code", "execution_count": null, - "id": "49139bf5", + "id": "f23793bf", "metadata": { "tags": [ "hide-input" @@ -1194,7 +990,7 @@ { "cell_type": "code", "execution_count": null, - "id": "41177273", + "id": "f52fef72", "metadata": {}, "outputs": [], "source": [ @@ -1204,7 +1000,7 @@ { "cell_type": "code", "execution_count": null, - "id": "de22c170", + "id": "a76f3788", "metadata": {}, "outputs": [], "source": [ @@ -1213,10 +1009,10 @@ }, { "cell_type": "markdown", - "id": "f9a7679f", + "id": "15f7e2ea", "metadata": {}, "source": [ - "## Network Centrality\n", + "## Network centrality\n", "\n", "When studying networks of all varieties, a recurring topic is the relative\n", "\"centrality\" or \"importance\" of different nodes.\n", @@ -1232,7 +1028,7 @@ "graph a vector $m$ where the $m_i$ is interpreted as the centrality (or rank)\n", "of node $v_i$.\n", "\n", - "### Degree Centrality\n", + "### Degree centrality\n", "\n", "Two elementary measures of \"importance\" of a node in a given directed\n", "graph are its in-degree and out-degree.\n", @@ -1248,7 +1044,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6d9c878c", + "id": "8082220e", "metadata": { "mystnb": { "figure": { @@ -1281,7 +1077,7 @@ }, { "cell_type": "markdown", - "id": "62695276", + "id": "e4c8b047", "metadata": {}, "source": [ "The following code displays the in-degree centrality of all nodes." @@ -1290,7 +1086,7 @@ { "cell_type": "code", "execution_count": null, - "id": "76919111", + "id": "c8e2a3ab", "metadata": {}, "outputs": [], "source": [ @@ -1302,7 +1098,7 @@ }, { "cell_type": "markdown", - "id": "321dd242", + "id": "e5a59a22", "metadata": {}, "source": [ "Consider the international credit network displayed in {numref}`financial_network`.\n", @@ -1313,7 +1109,7 @@ { "cell_type": "code", "execution_count": null, - "id": "296055c0", + "id": "1e297932", "metadata": {}, "outputs": [], "source": [ @@ -1324,7 +1120,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9e5351f4", + "id": "bf8511f4", "metadata": {}, "outputs": [], "source": [ @@ -1339,7 +1135,7 @@ { "cell_type": "code", "execution_count": null, - "id": "35b16daa", + "id": "21ff44b3", "metadata": {}, "outputs": [], "source": [ @@ -1359,7 +1155,7 @@ }, { "cell_type": "markdown", - "id": "ed676ad6", + "id": "a754009a", "metadata": {}, "source": [ "Unfortunately, while in-degree and out-degree centrality are simple to\n", @@ -1399,7 +1195,7 @@ "The next centrality measures will have these recursive features.\n", "\n", "\n", - "### Eigenvector Centrality\n", + "### Eigenvector centrality\n", "\n", "Suppose we have a weighted directed graph with adjacency matrix $A$.\n", "\n", @@ -1410,12 +1206,11 @@ "\n", "The **eigenvector centrality** of the graph is defined as the $n$-vector $e$ that solves\n", "\n", - "```{math}\n", - ":label: ev_central\n", + "$$ \n", "\\begin{aligned}\n", " e = \\frac{1}{r(A)} A e.\n", "\\end{aligned}\n", - "```\n", + "$$ (ev_central)\n", "\n", "In other words, $e$ is the dominant eigenvector of $A$ (the eigenvector of the\n", "largest eigenvalue --- see the discussion of the {ref}`Perron-Frobenius theorem` in the eigenvalue lecture.\n", @@ -1423,12 +1218,11 @@ "To better understand {eq}`ev_central`, we write out the full expression\n", "for some element $e_i$\n", "\n", - "```{math}\n", - ":label: eq_eicen\n", + "$$\n", "\\begin{aligned}\n", " e_i = \\frac{1}{r(A)} \\sum_{1 \\leq j \\leq n} a_{ij} e_j\n", "\\end{aligned}\n", - "```\n", + "$$ (eq_eicen)\n", "\n", "\n", "Note the recursive nature of the definition: the centrality obtained by node\n", @@ -1455,7 +1249,7 @@ { "cell_type": "code", "execution_count": null, - "id": "361e4db8", + "id": "473ba8a5", "metadata": {}, "outputs": [], "source": [ @@ -1474,7 +1268,7 @@ }, { "cell_type": "markdown", - "id": "6884d8a4", + "id": "0e1cf68c", "metadata": {}, "source": [ "Let's compute eigenvector centrality for the graph generated in {numref}`sample_gph_1`." @@ -1483,7 +1277,7 @@ { "cell_type": "code", "execution_count": null, - "id": "934fcbec", + "id": "64b126ed", "metadata": {}, "outputs": [], "source": [ @@ -1493,7 +1287,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4d0aebe7", + "id": "54cddef0", "metadata": {}, "outputs": [], "source": [ @@ -1506,7 +1300,7 @@ }, { "cell_type": "markdown", - "id": "5667259c", + "id": "2868f6d3", "metadata": {}, "source": [ "While nodes $2$ and $4$ had the highest in-degree centrality, we can see that nodes $1$ and $2$ have the\n", @@ -1518,7 +1312,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a04339d7", + "id": "ad4a4294", "metadata": {}, "outputs": [], "source": [ @@ -1528,7 +1322,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4f96e711", + "id": "43efe900", "metadata": { "mystnb": { "figure": { @@ -1553,7 +1347,7 @@ }, { "cell_type": "markdown", - "id": "f2394992", + "id": "230bd9ad", "metadata": {}, "source": [ "Countries that are rated highly according to this rank tend to be important\n", @@ -1570,7 +1364,7 @@ "The main principle is that links from important nodes (as measured by degree centrality) are worth more than links from unimportant nodes.\n", "\n", "\n", - "### Katz Centrality\n", + "### Katz centrality\n", "\n", "One problem with eigenvector centrality is that $r(A)$ might be zero, in which\n", "case $1/r(A)$ is not defined.\n", @@ -1581,21 +1375,19 @@ "Fixing $\\beta$ in $(0, 1/r(A))$, the **Katz centrality** of a weighted\n", "directed graph with adjacency matrix $A$ is defined as the vector $\\kappa$\n", "that solves\n", - "\n", - "```{math}\n", - ":label: katz_central\n", - " \\kappa_i = \\beta \\sum_{1 \\leq j 1} a_{ij} \\kappa_j + 1\n", - " \\qquad \\text{for all } i \\in \\{0, \\ldots, n-1\\}.\n", - "```\n", + " \n", + "$$\n", + "\\kappa_i = \\beta \\sum_{1 \\leq j 1} a_{ij} \\kappa_j + 1\n", + "\\qquad \\text{for all } i \\in \\{0, \\ldots, n-1\\}.\n", + "$$ (katz_central)\n", "\n", "Here $\\beta$ is a parameter that we can choose.\n", "\n", "In vector form we can write\n", "\n", - "```{math}\n", - ":label: katz_central_vec\n", - " \\kappa = \\mathbf 1 + \\beta A \\kappa\n", - "```\n", + "$$\n", + "\\kappa = \\mathbf 1 + \\beta A \\kappa\n", + "$$ (katz_central_vec)\n", "\n", "where $\\mathbf 1$ is a column vector of ones.\n", "\n", @@ -1609,7 +1401,7 @@ "This means that {eq}`katz_central_vec` has the unique solution\n", "\n", "$$\n", - " \\kappa = (I - \\beta A)^{-1} \\mathbf{1}\n", + "\\kappa = (I - \\beta A)^{-1} \\mathbf{1}\n", "$$\n", "\n", "\n", @@ -1620,7 +1412,7 @@ "When $r(A)<1$, we use $\\beta=1$ as the default for Katz centrality computations.\n", "\n", "\n", - "### Authorities vs Hubs\n", + "### Authorities vs hubs\n", "\n", "Search engine designers recognize that web pages can be important in two\n", "different ways.\n", @@ -1651,10 +1443,9 @@ "For example, the **authority-based eigenvector centrality** of a weighted\n", "directed graph with adjacency matrix $A$ is the vector $e$ solving\n", "\n", - "```{math}\n", - ":label: eicena0\n", - " e = \\frac{1}{r(A)} A^\\top e.\n", - "```\n", + "$$\n", + "e = \\frac{1}{r(A)} A^\\top e.\n", + "$$ (eicena0)\n", "\n", "The only difference from the original definition is that $A$ is replaced by\n", "its transpose.\n", @@ -1663,10 +1454,9 @@ "\n", "Element-by-element, this is given by\n", "\n", - "```{math}\n", - ":label: eicena\n", - " e_j = \\frac{1}{r(A)} \\sum_{1 \\leq i \\leq n} a_{ij} e_i\n", - "```\n", + "$$\n", + "e_j = \\frac{1}{r(A)} \\sum_{1 \\leq i \\leq n} a_{ij} e_i\n", + "$$ (eicena)\n", "\n", "We see $e_j$ will be high if many nodes with high authority rankings link to $j$.\n", "\n", @@ -1677,7 +1467,7 @@ { "cell_type": "code", "execution_count": null, - "id": "89f43990", + "id": "04719d5d", "metadata": {}, "outputs": [], "source": [ @@ -1687,7 +1477,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4050ad6c", + "id": "d821fe4c", "metadata": { "mystnb": { "figure": { @@ -1712,7 +1502,7 @@ }, { "cell_type": "markdown", - "id": "4a0d2849", + "id": "f3782d73", "metadata": {}, "source": [ "Highly ranked countries are those that attract large inflows of credit, or\n", @@ -1721,7 +1511,7 @@ "In this case the US clearly dominates the rankings as a target of interbank credit.\n", "\n", "\n", - "## Further Reading\n", + "## Further reading\n", "\n", "We apply the ideas discussed in this lecture to:\n", "\n", @@ -1814,7 +1604,7 @@ { "cell_type": "code", "execution_count": null, - "id": "02639763", + "id": "ceafb439", "metadata": {}, "outputs": [], "source": [ @@ -1841,7 +1631,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c13338ae", + "id": "3e4fd749", "metadata": {}, "outputs": [], "source": [ @@ -1853,7 +1643,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b78d1c07", + "id": "fc249cc3", "metadata": {}, "outputs": [], "source": [ @@ -1866,7 +1656,7 @@ { "cell_type": "code", "execution_count": null, - "id": "7da600fe", + "id": "619c3df0", "metadata": {}, "outputs": [], "source": [ @@ -1879,7 +1669,7 @@ }, { "cell_type": "markdown", - "id": "eb18f21d", + "id": "be3e0f6a", "metadata": {}, "source": [ "```{solution-end}\n", @@ -1914,7 +1704,7 @@ { "cell_type": "code", "execution_count": null, - "id": "192a8cdd", + "id": "6652c1f9", "metadata": {}, "outputs": [], "source": [ @@ -1933,7 +1723,7 @@ { "cell_type": "code", "execution_count": null, - "id": "7b357601", + "id": "010ff57f", "metadata": {}, "outputs": [], "source": [ @@ -1954,7 +1744,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a22baf22", + "id": "625f3d5e", "metadata": {}, "outputs": [], "source": [ @@ -1964,7 +1754,7 @@ { "cell_type": "code", "execution_count": null, - "id": "eec361b0", + "id": "e1599211", "metadata": {}, "outputs": [], "source": [ @@ -1973,7 +1763,7 @@ }, { "cell_type": "markdown", - "id": "8816af7f", + "id": "ff30ceea", "metadata": {}, "source": [ "```{solution-end}\n", @@ -1982,12 +1772,96 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.4" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 12, + 16, + 20, + 52, + 64, + 89, + 145, + 244, + 254, + 278, + 280, + 287, + 291, + 295, + 299, + 303, + 305, + 312, + 318, + 328, + 330, + 360, + 371, + 375, + 386, + 388, + 401, + 461, + 494, + 559, + 565, + 575, + 597, + 631, + 652, + 686, + 707, + 719, + 723, + 729, + 733, + 739, + 750, + 754, + 756, + 786, + 811, + 815, + 820, + 826, + 831, + 840, + 853, + 942, + 954, + 958, + 962, + 968, + 975, + 979, + 996, + 1111, + 1115, + 1132, + 1229, + 1250, + 1256, + 1263, + 1269, + 1299, + 1312, + 1327, + 1331, + 1333 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/networks.md b/book/_build/html/_sources/networks.md new file mode 100644 index 0000000..bfe4438 --- /dev/null +++ b/book/_build/html/_sources/networks.md @@ -0,0 +1,1336 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.4 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Networks + +```{code-cell} ipython3 +:tags: [hide-output] + +%pip install quantecon-book-networks pandas-datareader +``` + +## Outline + +In recent years there has been rapid growth in a field called [network science](https://en.wikipedia.org/wiki/Network_science). + +Network science studies relationships between groups of objects. + +One important example is the [world wide web](https://en.wikipedia.org/wiki/World_Wide_Web#Linking) +, where web pages are connected by hyperlinks. + +Another is the [human brain](https://en.wikipedia.org/wiki/Neural_circuit): studies of brain function emphasize the network of +connections between nerve cells (neurons). + +[Artificial neural networks](https://en.wikipedia.org/wiki/Artificial_neural_network) are based on this idea, using data to build +intricate connections between simple processing units. + +Epidemiologists studying [transmission of diseases](https://en.wikipedia.org/wiki/Network_medicine#Network_epidemics) +like COVID-19 analyze interactions between groups of human hosts. + +In operations research, network analysis is used to study fundamental problems +as on minimum cost flow, the traveling salesman, [shortest paths](https://en.wikipedia.org/wiki/Shortest_path_problem), +and assignment. + +This lecture gives an introduction to economic and financial networks. + +Some parts of this lecture are drawn from the text +https://networks.quantecon.org/ but the level of this lecture is more +introductory. + +We will need the following imports. + +```{code-cell} ipython3 +import numpy as np +import networkx as nx +import matplotlib.pyplot as plt +import pandas as pd +import quantecon as qe + +import matplotlib.cm as cm +import quantecon_book_networks.input_output as qbn_io +import quantecon_book_networks.data as qbn_data + +import matplotlib.patches as mpatches +``` + +## Economic and financial networks + +Within economics, important examples of networks include + +* financial networks +* production networks +* trade networks +* transport networks and +* social networks + +Social networks affect trends in market sentiment and consumer decisions. + +The structure of financial networks helps to determine relative fragility of the financial system. + +The structure of production networks affects trade, innovation and the propagation of local shocks. + +To better understand such networks, let's look at some examples in more depth. + + +### Example: Aircraft Exports + +The following figure shows international trade in large commercial aircraft in 2019 based on International Trade Data SITC Revision 2. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Commercial Aircraft Network \n" + name: aircraft_network +tags: [hide-input] +--- +ch1_data = qbn_data.introduction() +export_figures = False + +DG = ch1_data['aircraft_network'] +pos = ch1_data['aircraft_network_pos'] + +centrality = nx.eigenvector_centrality(DG) +node_total_exports = qbn_io.node_total_exports(DG) +edge_weights = qbn_io.edge_weights(DG) + +node_pos_dict = pos + +node_sizes = qbn_io.normalise_weights(node_total_exports,10000) +edge_widths = qbn_io.normalise_weights(edge_weights,10) + +node_colors = qbn_io.colorise_weights(list(centrality.values()),color_palette=cm.viridis) +node_to_color = dict(zip(DG.nodes,node_colors)) +edge_colors = [] +for src,_ in DG.edges: + edge_colors.append(node_to_color[src]) + +fig, ax = plt.subplots(figsize=(10, 10)) +ax.axis('off') + +nx.draw_networkx_nodes(DG, + node_pos_dict, + node_color=node_colors, + node_size=node_sizes, + linewidths=2, + alpha=0.6, + ax=ax) + +nx.draw_networkx_labels(DG, + node_pos_dict, + ax=ax) + +nx.draw_networkx_edges(DG, + node_pos_dict, + edge_color=edge_colors, + width=edge_widths, + arrows=True, + arrowsize=20, + ax=ax, + arrowstyle='->', + node_size=node_sizes, + connectionstyle='arc3,rad=0.15') + +plt.show() +``` + +The circles in the figure are called **nodes** or **vertices** -- in this case they represent countries. + +The arrows in the figure are called **edges** or **links**. + +Node size is proportional to total exports and edge width is proportional to exports to the target country. + +(The data is for trade in commercial aircraft weighing at least 15,000kg and was sourced from CID Dataverse.) + +The figure shows that the US, France and Germany are major export hubs. + +In the discussion below, we learn to quantify such ideas. + + +### Example: A Markov Chain + +Recall that, in our lecture on {ref}`Markov chains ` we studied a dynamic model of business cycles +where the states are + +* "ng" = "normal growth" +* "mr" = "mild recession" +* "sr" = "severe recession" + +Let's examine the following figure + +```{image} /_static/lecture_specific/networks/mc.png +:name: mc_networks +:align: center +``` + +This is an example of a network, where the set of nodes $V$ equals the states: + +$$ + V = \{ \text{"ng", "mr", "sr"} \} +$$ + +The edges between the nodes show the one month transition probabilities. + + +## An introduction to graph theory + +Now we've looked at some examples, let's move on to theory. + +This theory will allow us to better organize our thoughts. + +The theoretical part of network science is constructed using a major branch of +mathematics called [graph theory](https://en.wikipedia.org/wiki/Graph_theory). + +Graph theory can be complicated and we will cover only the basics. + +However, these concepts will already be enough for us to discuss interesting and +important ideas on economic and financial networks. + +We focus on "directed" graphs, where connections are, in general, asymmetric +(arrows typically point one way, not both ways). + +E.g., + +* bank $A$ lends money to bank $B$ +* firm $A$ supplies goods to firm $B$ +* individual $A$ "follows" individual $B$ on a given social network + +("Undirected" graphs, where connections are symmetric, are a special +case of directed graphs --- we just need to insist that each arrow pointing +from $A$ to $B$ is paired with another arrow pointing from $B$ to $A$.) + + +### Key definitions + +A **directed graph** consists of two things: + +1. a finite set $V$ and +1. a collection of pairs $(u, v)$ where $u$ and $v$ are elements of $V$. + +The elements of $V$ are called the **vertices** or **nodes** of the graph. + +The pairs $(u,v)$ are called the **edges** of the graph and the set of all edges will usually be denoted by $E$ + +Intuitively and visually, an edge $(u,v)$ is understood as an arrow from node $u$ to node $v$. + +(A neat way to represent an arrow is to record the location of the tail and +head of the arrow, and that's exactly what an edge does.) + +In the aircraft export example shown in {numref}`aircraft_network` + +* $V$ is all countries included in the data set. +* $E$ is all the arrows in the figure, each indicating some positive amount of aircraft exports from one country to another. + +Let's look at more examples. + +Two graphs are shown below, each with three nodes. + +```{figure} /_static/lecture_specific/networks/poverty_trap_1.png +:name: poverty_trap_1 + +Poverty Trap +``` + ++++ + +We now construct a graph with the same nodes but different edges. + +```{figure} /_static/lecture_specific/networks/poverty_trap_2.png +:name: poverty_trap_2 + +Poverty Trap +``` + ++++ + +For these graphs, the arrows (edges) can be thought of as representing +positive transition probabilities over a given unit of time. + +In general, if an edge $(u, v)$ exists, then the node $u$ is called a +**direct predecessor** of $v$ and $v$ is called a **direct successor** of $u$. + +Also, for $v \in V$, + +* the **in-degree** is $i_d(v) = $ the number of direct predecessors of $v$ and +* the **out-degree** is $o_d(v) = $ the number of direct successors of $v$. + + +### Digraphs in Networkx + +The Python package [Networkx](https://networkx.org/) provides a convenient +data structure for representing directed graphs and implements many common +routines for analyzing them. + +As an example, let us recreate {numref}`poverty_trap_2` using Networkx. + +To do so, we first create an empty `DiGraph` object: + +```{code-cell} ipython3 +G_p = nx.DiGraph() +``` + +Next we populate it with nodes and edges. + +To do this we write down a list of +all edges, with *poor* represented by *p* and so on: + +```{code-cell} ipython3 +edge_list = [('p', 'p'), + ('m', 'p'), ('m', 'm'), ('m', 'r'), + ('r', 'p'), ('r', 'm'), ('r', 'r')] +``` + +Finally, we add the edges to our `DiGraph` object: + +```{code-cell} ipython3 +for e in edge_list: + u, v = e + G_p.add_edge(u, v) +``` + +Alternatively, we can use the method `add_edges_from`. + +```{code-cell} ipython3 +G_p.add_edges_from(edge_list) +``` + +Adding the edges automatically adds the nodes, so `G_p` is now a +correct representation of our graph. + +We can verify this by plotting the graph via Networkx with the following code: + +```{code-cell} ipython3 +fig, ax = plt.subplots() +nx.draw_spring(G_p, ax=ax, node_size=500, with_labels=True, + font_weight='bold', arrows=True, alpha=0.8, + connectionstyle='arc3,rad=0.25', arrowsize=20) +plt.show() +``` + +The figure obtained above matches the original directed graph in {numref}`poverty_trap_2`. + + +`DiGraph` objects have methods that calculate in-degree and out-degree +of nodes. + +For example, + +```{code-cell} ipython3 +G_p.in_degree('p') +``` +(strongly_connected)= +### Communication + +Next, we study communication and connectedness, which have important +implications for economic networks. + +Node $v$ is called **accessible** from node $u$ if either $u=v$ or there +exists a sequence of edges that lead from $u$ to $v$. + +* in this case, we write $u \to v$ + +(Visually, there is a sequence of arrows leading from $u$ to $v$.) + +For example, suppose we have a directed graph representing a production network, where + +* elements of $V$ are industrial sectors and +* existence of an edge $(i, j)$ means that $i$ supplies products or services to $j$. + +Then $m \to \ell$ means that sector $m$ is an upstream supplier of sector $\ell$. + +Two nodes $u$ and $v$ are said to **communicate** if both $u \to v$ and $v \to u$. + +A graph is called **strongly connected** if all nodes communicate. + +For example, {numref}`poverty_trap_1` is strongly connected +however in {numref}`poverty_trap_2` rich is not accessible from poor, thus it is not strongly connected. + +We can verify this by first constructing the graphs using Networkx and then using `nx.is_strongly_connected`. + +```{code-cell} ipython3 +fig, ax = plt.subplots() +G1 = nx.DiGraph() + +G1.add_edges_from([('p', 'p'),('p','m'),('p','r'), + ('m', 'p'), ('m', 'm'), ('m', 'r'), + ('r', 'p'), ('r', 'm'), ('r', 'r')]) + +nx.draw_networkx(G1, with_labels = True) +``` + +```{code-cell} ipython3 +nx.is_strongly_connected(G1) #checking if above graph is strongly connected +``` + +```{code-cell} ipython3 +fig, ax = plt.subplots() +G2 = nx.DiGraph() + +G2.add_edges_from([('p', 'p'), + ('m', 'p'), ('m', 'm'), ('m', 'r'), + ('r', 'p'), ('r', 'm'), ('r', 'r')]) + +nx.draw_networkx(G2, with_labels = True) +``` + +```{code-cell} ipython3 +nx.is_strongly_connected(G2) #checking if above graph is strongly connected +``` + +## Weighted graphs + +We now introduce weighted graphs, where weights (numbers) are attached to each +edge. + + +### International private credit flows by country + +To motivate the idea, consider the following figure which shows flows of funds (i.e., +loans) between private banks, grouped by country of origin. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "International Credit Network \n" + name: financial_network +tags: [hide-input] +--- +Z = ch1_data["adjacency_matrix"]["Z"] +Z_visual= ch1_data["adjacency_matrix"]["Z_visual"] +countries = ch1_data["adjacency_matrix"]["countries"] + +G = qbn_io.adjacency_matrix_to_graph(Z_visual, countries, tol=0.03) + +centrality = qbn_io.eigenvector_centrality(Z_visual, authority=False) +node_total_exports = qbn_io.node_total_exports(G) +edge_weights = qbn_io.edge_weights(G) + +node_pos_dict = nx.circular_layout(G) + +node_sizes = qbn_io.normalise_weights(node_total_exports,3000) +edge_widths = qbn_io.normalise_weights(edge_weights,10) + + +node_colors = qbn_io.colorise_weights(centrality) +node_to_color = dict(zip(G.nodes,node_colors)) +edge_colors = [] +for src,_ in G.edges: + edge_colors.append(node_to_color[src]) + +fig, ax = plt.subplots(figsize=(10, 10)) +ax.axis('off') + +nx.draw_networkx_nodes(G, + node_pos_dict, + node_color=node_colors, + node_size=node_sizes, + edgecolors='grey', + linewidths=2, + alpha=0.4, + ax=ax) + +nx.draw_networkx_labels(G, + node_pos_dict, + font_size=12, + ax=ax) + +nx.draw_networkx_edges(G, + node_pos_dict, + edge_color=edge_colors, + width=edge_widths, + arrows=True, + arrowsize=20, + alpha=0.8, + ax=ax, + arrowstyle='->', + node_size=node_sizes, + connectionstyle='arc3,rad=0.15') + +plt.show() +``` + +The country codes are given in the following table + +|Code| Country |Code| Country |Code| Country |Code| Country | +|:--:|:--------------|:--:|:-------:|:--:|:-----------:|:--:|:--------------:| +| AU | Australia | DE | Germany | CL | Chile | ES | Spain | +| PT | Portugal | FR | France | TR | Turkey | GB | United Kingdom | +| US | United States | IE | Ireland | AT | Austria | IT | Italy | +| BE | Belgium | JP | Japan | SW | Switzerland | SE | Sweden | + +An arrow from Japan to the US indicates aggregate claims held by Japanese +banks on all US-registered banks, as collected by the Bank of International +Settlements (BIS). + +The size of each node in the figure is increasing in the +total foreign claims of all other nodes on this node. + +The widths of the arrows are proportional to the foreign claims they represent. + +Notice that, in this network, an edge $(u, v)$ exists for almost every choice +of $u$ and $v$ (i.e., almost every country in the network). + +(In fact, there are even more small arrows, which we have dropped for clarity.) + +Hence the existence of an edge from one node to another is not particularly informative. + +To understand the network, we need to record not just the existence or absence +of a credit flow, but also the size of the flow. + +The correct data structure for recording this information is a "weighted +directed graph". + ++++ + +### Definitions + +A **weighted directed graph** is a directed graph to which we have added a +**weight function** $w$ that assigns a positive number to each edge. + +The figure above shows one weighted directed graph, where the weights are the size of fund flows. + +The following figure shows a weighted directed graph, with arrows +representing edges of the induced directed graph. + + +```{figure} /_static/lecture_specific/networks/weighted.png +:name: poverty_trap_weighted + +Weighted Poverty Trap +``` + + +The numbers next to the edges are the weights. + +In this case, you can think of the numbers on the arrows as transition +probabilities for a household over, say, one year. + +We see that a rich household has a 10\% chance of becoming poor in one year. + + +## Adjacency matrices + +Another way that we can represent weights, which turns out to be very +convenient for numerical work, is via a matrix. + +The **adjacency matrix** of a weighted directed graph with nodes $\{v_1, \ldots, v_n\}$, edges $E$ and weight function $w$ is the matrix + +$$ +A = (a_{ij})_{1 \leq i,j \leq n} +\quad \text{with} \quad +a_{ij} = +% +\begin{cases} + w(v_i, v_j) & \text{ if } (v_i, v_j) \in E + \\ + 0 & \text{ otherwise}. +\end{cases} +% +$$ + +Once the nodes in $V$ are enumerated, the weight function and +adjacency matrix provide essentially the same information. + +For example, with $\{$poor, middle, rich$\}$ mapped to $\{1, 2, 3\}$ respectively, +the adjacency matrix corresponding to the weighted directed graph in {numref}`poverty_trap_weighted` is + +$$ +\begin{pmatrix} + 0.9 & 0.1 & 0 \\ + 0.4 & 0.4 & 0.2 \\ + 0.1 & 0.1 & 0.8 +\end{pmatrix}. +$$ + +In QuantEcon's `DiGraph` implementation, weights are recorded via the +keyword `weighted`: + +```{code-cell} ipython3 +A = ((0.9, 0.1, 0.0), + (0.4, 0.4, 0.2), + (0.1, 0.1, 0.8)) +A = np.array(A) +G = qe.DiGraph(A, weighted=True) # store weights +``` + +One of the key points to remember about adjacency matrices is that taking the +transpose _reverses all the arrows_ in the associated directed graph. + + +For example, the following directed graph can be +interpreted as a stylized version of a financial network, with nodes as banks +and edges showing the flow of funds. + +```{code-cell} ipython3 +G4 = nx.DiGraph() + +G4.add_edges_from([('1','2'), + ('2','1'),('2','3'), + ('3','4'), + ('4','2'),('4','5'), + ('5','1'),('5','3'),('5','4')]) +pos = nx.circular_layout(G4) + +edge_labels={('1','2'): '100', + ('2','1'): '50', ('2','3'): '200', + ('3','4'): '100', + ('4','2'): '500', ('4','5'): '50', + ('5','1'): '150',('5','3'): '250', ('5','4'): '300'} + +nx.draw_networkx(G4, pos, node_color = 'none',node_size = 500) +nx.draw_networkx_edge_labels(G4, pos, edge_labels=edge_labels) +nx.draw_networkx_nodes(G4, pos, linewidths= 0.5, edgecolors = 'black', + node_color = 'none',node_size = 500) + +plt.show() +``` + +We see that bank 2 extends a loan of size 200 to bank 3. + +The corresponding adjacency matrix is + +$$ +A = +\begin{pmatrix} + 0 & 100 & 0 & 0 & 0 \\ + 50 & 0 & 200 & 0 & 0 \\ + 0 & 0 & 0 & 100 & 0 \\ + 0 & 500 & 0 & 0 & 50 \\ + 150 & 0 & 250 & 300 & 0 +\end{pmatrix}. +$$ + +The transpose is + +$$ +A^\top = +\begin{pmatrix} + 0 & 50 & 0 & 0 & 150 \\ + 100 & 0 & 0 & 500 & 0 \\ + 0 & 200 & 0 & 0 & 250 \\ + 0 & 0 & 100 & 0 & 300 \\ + 0 & 0 & 0 & 50 & 0 +\end{pmatrix}. +$$ + +The corresponding network is visualized in the following figure which shows the network of liabilities after the loans have been granted. + +Both of these networks (original and transpose) are useful for analyzing financial markets. + +```{code-cell} ipython3 +G5 = nx.DiGraph() + +G5.add_edges_from([('1','2'),('1','5'), + ('2','1'),('2','4'), + ('3','2'),('3','5'), + ('4','3'),('4','5'), + ('5','4')]) + +edge_labels={('1','2'): '50', ('1','5'): '150', + ('2','1'): '100', ('2','4'): '500', + ('3','2'): '200', ('3','5'): '250', + ('4','3'): '100', ('4','5'): '300', + ('5','4'): '50'} + +nx.draw_networkx(G5, pos, node_color = 'none',node_size = 500) +nx.draw_networkx_edge_labels(G5, pos, edge_labels=edge_labels) +nx.draw_networkx_nodes(G5, pos, linewidths= 0.5, edgecolors = 'black', + node_color = 'none',node_size = 500) + +plt.show() +``` + +In general, every nonnegative $n \times n$ matrix $A = (a_{ij})$ can be +viewed as the adjacency matrix of a weighted directed graph. + +To build the graph we set $V = 1, \ldots, n$ and take the edge set $E$ to be +all $(i,j)$ such that $a_{ij} > 0$. + +For the weight function we set $w(i, j) = a_{ij}$ for all edges $(i,j)$. + +We call this graph the weighted directed graph induced by $A$. + + +## Properties + +Consider a weighted directed graph with adjacency matrix $A$. + +Let $a^k_{ij}$ be element $i,j$ of $A^k$, the $k$-th power of $A$. + +The following result is useful in many applications: + +````{prf:theorem} +:label: graph_theory_property1 + +For distinct nodes $i, j$ in $V$ and any integer $k$, we have + +$$ +a^k_{i j} > 0 +\quad \text{if and only if} \quad +\text{ $j$ is accessible from $i$}. +$$ + +```` + ++++ + +The above result is obvious when $k=1$ and a proof of the general case can be +found in {cite}`sargent2022economic`. + +Now recall from the eigenvalues lecture that a +nonnegative matrix $A$ is called {ref}`irreducible` if for each $(i,j)$ there is an integer $k \geq 0$ such that $a^{k}_{ij} > 0$. + +From the preceding theorem, it is not too difficult (see +{cite}`sargent2022economic` for details) to get the next result. + +````{prf:theorem} +:label: graph_theory_property2 + +For a weighted directed graph the following statements are equivalent: + +1. The directed graph is strongly connected. +2. The adjacency matrix of the graph is irreducible. + +```` + ++++ + +We illustrate the above theorem with a simple example. + +Consider the following weighted directed graph. + + +```{image} /_static/lecture_specific/networks/properties.png +:name: properties_graph + +``` + ++++ + +We first create the above network as a Networkx `DiGraph` object. + +```{code-cell} ipython3 +G6 = nx.DiGraph() + +G6.add_edges_from([('1','2'),('1','3'), + ('2','1'), + ('3','1'),('3','2')]) +``` + +Then we construct the associated adjacency matrix A. + +```{code-cell} ipython3 +A = np.array([[0,0.7,0.3], # adjacency matrix A + [1,0,0], + [0.4,0.6,0]]) +``` + +```{code-cell} ipython3 +:tags: [hide-input] + +def is_irreducible(P): + n = len(P) + result = np.zeros((n, n)) + for i in range(n): + result += np.linalg.matrix_power(P, i) + return np.all(result > 0) +``` + +```{code-cell} ipython3 +is_irreducible(A) # check irreducibility of A +``` + +```{code-cell} ipython3 +nx.is_strongly_connected(G6) # check connectedness of graph +``` + +## Network centrality + +When studying networks of all varieties, a recurring topic is the relative +"centrality" or "importance" of different nodes. + +Examples include + +* ranking of web pages by search engines +* determining the most important bank in a financial network (which one a + central bank should rescue if there is a financial crisis) +* determining the most important industrial sector in an economy. + +In what follows, a **centrality measure** associates to each weighted directed +graph a vector $m$ where the $m_i$ is interpreted as the centrality (or rank) +of node $v_i$. + +### Degree centrality + +Two elementary measures of "importance" of a node in a given directed +graph are its in-degree and out-degree. + +Both of these provide a centrality measure. + +In-degree centrality is a vector containing the in-degree of each node in +the graph. + +Consider the following simple example. + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Sample Graph + name: sample_gph_1 +--- +G7 = nx.DiGraph() + +G7.add_nodes_from(['1','2','3','4','5','6','7']) + +G7.add_edges_from([('1','2'),('1','6'), + ('2','1'),('2','4'), + ('3','2'), + ('4','2'), + ('5','3'),('5','4'), + ('6','1'), + ('7','4'),('7','6')]) +pos = nx.planar_layout(G7) + +nx.draw_networkx(G7, pos, node_color='none', node_size=500) +nx.draw_networkx_nodes(G7, pos, linewidths=0.5, edgecolors='black', + node_color='none',node_size=500) + +plt.show() +``` + +The following code displays the in-degree centrality of all nodes. + +```{code-cell} ipython3 +iG7 = [G7.in_degree(v) for v in G7.nodes()] # computing in-degree centrality + +for i, d in enumerate(iG7): + print(i+1, d) +``` + +Consider the international credit network displayed in {numref}`financial_network`. + +The following plot displays the in-degree centrality of each country. + +```{code-cell} ipython3 +D = qbn_io.build_unweighted_matrix(Z) +indegree = D.sum(axis=0) +``` + +```{code-cell} ipython3 +def centrality_plot_data(countries, centrality_measures): + df = pd.DataFrame({'code': countries, + 'centrality':centrality_measures, + 'color': qbn_io.colorise_weights(centrality_measures).tolist() + }) + return df.sort_values('centrality') +``` + +```{code-cell} ipython3 +fig, ax = plt.subplots() + +df = centrality_plot_data(countries, indegree) + +ax.bar('code', 'centrality', data=df, color=df["color"], alpha=0.6) + +patch = mpatches.Patch(color=None, label='in degree', visible=False) +ax.legend(handles=[patch], fontsize=12, loc="upper left", handlelength=0, frameon=False) + +ax.set_ylim((0,20)) + +plt.show() +``` + +Unfortunately, while in-degree and out-degree centrality are simple to +calculate, they are not always informative. + +In {numref}`financial_network`, an edge exists between almost every node, +so the in- or out-degree based centrality ranking fails to effectively separate the countries. + +This can be seen in the above graph as well. + +Another example is the task of a web search engine, which ranks pages +by relevance whenever a user enters a search. + +Suppose web page A has twice as many inbound links as page B. + +In-degree centrality tells us that page A deserves a higher rank. + +But in fact, page A might be less important than page B. + +To see why, suppose that the links to A are from pages that receive almost no traffic, +while the links to B are from pages that receive very heavy traffic. + +In this case, page B probably receives more visitors, which in turn suggests +that page B contains more valuable (or entertaining) content. + +Thinking about this point suggests that importance might be *recursive*. + +This means that the importance of a given node depends on the importance of +other nodes that link to it. + +As another example, we can imagine a production network where the importance of a +given sector depends on the importance of the sectors that it supplies. + +This reverses the order of the previous example: now the importance of a given +node depends on the importance of other nodes that *it links to*. + +The next centrality measures will have these recursive features. + + +### Eigenvector centrality + +Suppose we have a weighted directed graph with adjacency matrix $A$. + +For simplicity, we will suppose that the nodes $V$ of the graph are just the +integers $1, \ldots, n$. + +Let $r(A)$ denote the {ref}`spectral radius` of $A$. + +The **eigenvector centrality** of the graph is defined as the $n$-vector $e$ that solves + +$$ +\begin{aligned} + e = \frac{1}{r(A)} A e. +\end{aligned} +$$ (ev_central) + +In other words, $e$ is the dominant eigenvector of $A$ (the eigenvector of the +largest eigenvalue --- see the discussion of the {ref}`Perron-Frobenius theorem` in the eigenvalue lecture. + +To better understand {eq}`ev_central`, we write out the full expression +for some element $e_i$ + +$$ +\begin{aligned} + e_i = \frac{1}{r(A)} \sum_{1 \leq j \leq n} a_{ij} e_j +\end{aligned} +$$ (eq_eicen) + + +Note the recursive nature of the definition: the centrality obtained by node +$i$ is proportional to a sum of the centrality of all nodes, weighted by +the *rates of flow* from $i$ into these nodes. + +A node $i$ is highly ranked if +1. there are many edges leaving $i$, +2. these edges have large weights, and +3. the edges point to other highly ranked nodes. + +Later, when we study demand shocks in production networks, there will be a more +concrete interpretation of eigenvector centrality. + +We will see that, in production networks, sectors with high eigenvector +centrality are important *suppliers*. + +In particular, they are activated by a wide array of demand shocks once orders +flow backwards through the network. + +To compute eigenvector centrality we can use the following function. + +```{code-cell} ipython3 +def eigenvector_centrality(A, k=40, authority=False): + """ + Computes the dominant eigenvector of A. Assumes A is + primitive and uses the power method. + + """ + A_temp = A.T if authority else A + n = len(A_temp) + r = np.max(np.abs(np.linalg.eigvals(A_temp))) + e = r**(-k) * (np.linalg.matrix_power(A_temp, k) @ np.ones(n)) + return e / np.sum(e) +``` + +Let's compute eigenvector centrality for the graph generated in {numref}`sample_gph_1`. + +```{code-cell} ipython3 +A = nx.to_numpy_array(G7) # compute adjacency matrix of graph +``` + +```{code-cell} ipython3 +e = eigenvector_centrality(A) +n = len(e) + +for i in range(n): + print(i+1,e[i]) +``` + +While nodes $2$ and $4$ had the highest in-degree centrality, we can see that nodes $1$ and $2$ have the +highest eigenvector centrality. + +Let's revisit the international credit network in {numref}`financial_network`. + +```{code-cell} ipython3 +eig_central = eigenvector_centrality(Z) +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Eigenvector centrality + name: eigenvctr_centrality +--- +fig, ax = plt.subplots() + +df = centrality_plot_data(countries, eig_central) + +ax.bar('code', 'centrality', data=df, color=df["color"], alpha=0.6) + +patch = mpatches.Patch(color=None, visible=False) +ax.legend(handles=[patch], fontsize=12, loc="upper left", handlelength=0, frameon=False) + +plt.show() +``` + +Countries that are rated highly according to this rank tend to be important +players in terms of supply of credit. + +Japan takes the highest rank according to this measure, although +countries with large financial sectors such as Great Britain and France are +not far behind. + +The advantage of eigenvector centrality is that it measures a node's importance while considering the importance of its neighbours. + +A variant of eigenvector centrality is at the core of Google's PageRank algorithm, which is used to rank web pages. + +The main principle is that links from important nodes (as measured by degree centrality) are worth more than links from unimportant nodes. + + +### Katz centrality + +One problem with eigenvector centrality is that $r(A)$ might be zero, in which +case $1/r(A)$ is not defined. + +For this and other reasons, some researchers prefer another measure of +centrality for networks called Katz centrality. + +Fixing $\beta$ in $(0, 1/r(A))$, the **Katz centrality** of a weighted +directed graph with adjacency matrix $A$ is defined as the vector $\kappa$ +that solves + +$$ +\kappa_i = \beta \sum_{1 \leq j 1} a_{ij} \kappa_j + 1 +\qquad \text{for all } i \in \{0, \ldots, n-1\}. +$$ (katz_central) + +Here $\beta$ is a parameter that we can choose. + +In vector form we can write + +$$ +\kappa = \mathbf 1 + \beta A \kappa +$$ (katz_central_vec) + +where $\mathbf 1$ is a column vector of ones. + +The intuition behind this centrality measure is similar to that provided for +eigenvector centrality: high centrality is conferred on $i$ when it is linked +to by nodes that themselves have high centrality. + +Provided that $0 < \beta < 1/r(A)$, Katz centrality is always finite and well-defined +because then $r(\beta A) < 1$. + +This means that {eq}`katz_central_vec` has the unique solution + +$$ +\kappa = (I - \beta A)^{-1} \mathbf{1} +$$ + + +This follows from the {ref}`Neumann series theorem`. + +The parameter $\beta$ is used to ensure that $\kappa$ is finite + +When $r(A)<1$, we use $\beta=1$ as the default for Katz centrality computations. + + +### Authorities vs hubs + +Search engine designers recognize that web pages can be important in two +different ways. + +Some pages have high **hub centrality**, meaning that they link to valuable +sources of information (e.g., news aggregation sites). + +Other pages have high **authority centrality**, meaning that they contain +valuable information, as indicated by the number and significance of incoming +links (e.g., websites of respected news organizations). + +Similar ideas can and have been applied to economic networks (often using +different terminology). + +The eigenvector centrality and Katz centrality measures we discussed above +measure hub centrality. + +(Nodes have high centrality if they point to other nodes with high centrality.) + +If we care more about authority centrality, we can use the same definitions +except that we take the transpose of the adjacency matrix. + +This works because taking the transpose reverses the direction of the arrows. + +(Now nodes will have high centrality if they receive links from other nodes +with high centrality.) + +For example, the **authority-based eigenvector centrality** of a weighted +directed graph with adjacency matrix $A$ is the vector $e$ solving + +$$ +e = \frac{1}{r(A)} A^\top e. +$$ (eicena0) + +The only difference from the original definition is that $A$ is replaced by +its transpose. + +(Transposes do not affect the spectral radius of a matrix so we wrote $r(A)$ instead of $r(A^\top)$.) + +Element-by-element, this is given by + +$$ +e_j = \frac{1}{r(A)} \sum_{1 \leq i \leq n} a_{ij} e_i +$$ (eicena) + +We see $e_j$ will be high if many nodes with high authority rankings link to $j$. + +The following figurenshows the authority-based eigenvector centrality ranking for the international +credit network shown in {numref}`financial_network`. + +```{code-cell} ipython3 +ecentral_authority = eigenvector_centrality(Z, authority=True) +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: Eigenvector authority + name: eigenvector_centrality +--- +fig, ax = plt.subplots() + +df = centrality_plot_data(countries, ecentral_authority) + +ax.bar('code', 'centrality', data=df, color=df["color"], alpha=0.6) + +patch = mpatches.Patch(color=None, visible=False) +ax.legend(handles=[patch], fontsize=12, loc="upper left", handlelength=0, frameon=False) + +plt.show() +``` + +Highly ranked countries are those that attract large inflows of credit, or +credit inflows from other major players. + +In this case the US clearly dominates the rankings as a target of interbank credit. + + +## Further reading + +We apply the ideas discussed in this lecture to: + +Textbooks on economic and social networks include {cite}`jackson2010social`, +{cite}`easley2010networks`, {cite}`borgatti2018analyzing`, +{cite}`sargent2022economic` and {cite}`goyal2023networks`. + + +Within the realm of network science, the texts +by {cite}`newman2018networks`, {cite}`menczer2020first` and +{cite}`coscia2021atlas` are excellent. + + +## Exercises + +```{exercise-start} +:label: networks_ex1 +``` + +Here is a mathematical exercise for those who like proofs. + +Let $(V, E)$ be a directed graph and write $u \sim v$ if $u$ and $v$ communicate. + +Show that $\sim$ is an [equivalence relation](https://en.wikipedia.org/wiki/Equivalence_relation) on $V$. + +```{exercise-end} +``` + +```{solution-start} networks_ex1 +:class: dropdown +``` + +**Reflexivity:** + +Trivially, $u = v \Rightarrow u \rightarrow v$. + +Thus, $u \sim u$. + +**Symmetry:** +Suppose, $u \sim v$ + +$\Rightarrow u \rightarrow v$ and $v \rightarrow u$. + +By definition, this implies $v \sim u$. + +**Transitivity:** + +Suppose, $u \sim v$ and $v \sim w$ + +This implies, $u \rightarrow v$ and $v \rightarrow u$ and also $v \rightarrow w$ and $w \rightarrow v$. + +Thus, we can conclude $u \rightarrow v \rightarrow w$ and $w \rightarrow v \rightarrow u$. + +Which means $u \sim w$. + +```{solution-end} +``` + +```{exercise-start} +:label: networks_ex2 +``` + +Consider a directed graph $G$ with the set of nodes + +$$ +V = \{0,1,2,3,4,5,6,7\} +$$ + +and the set of edges + +$$ +E = \{(0, 1), (0, 3), (1, 0), (2, 4), (3, 2), (3, 4), (3, 7), (4, 3), (5, 4), (5, 6), (6, 3), (6, 5), (7, 0)\} +$$ + +1. Use `Networkx` to draw graph $G$. + +2. Find the associated adjacency matrix $A$ for $G$. + +3. Use the functions defined above to compute in-degree centrality, out-degree centrality and eigenvector centrality + of G. + +```{exercise-end} +``` + +```{solution-start} networks_ex2 +:class: dropdown +``` + +```{code-cell} ipython3 +# First, let's plot the given graph + +G = nx.DiGraph() + +G.add_nodes_from(np.arange(8)) # adding nodes + +G.add_edges_from([(0,1),(0,3), # adding edges + (1,0), + (2,4), + (3,2),(3,4),(3,7), + (4,3), + (5,4),(5,6), + (6,3),(6,5), + (7,0)]) + +nx.draw_networkx(G, pos=nx.circular_layout(G), node_color='gray', node_size=500, with_labels=True) + +plt.show() +``` + +```{code-cell} ipython3 +A = nx.to_numpy_array(G) #find adjacency matrix associated with G + +A +``` + +```{code-cell} ipython3 +oG = [G.out_degree(v) for v in G.nodes()] # computing in-degree centrality + +for i, d in enumerate(oG): + print(i, d) +``` + +```{code-cell} ipython3 +e = eigenvector_centrality(A) # computing eigenvector centrality +n = len(e) + +for i in range(n): + print(i+1, e[i]) +``` + +```{solution-end} +``` + +```{exercise-start} +:label: networks_ex3 +``` + +Consider a graph $G$ with $n$ nodes and $n \times n$ adjacency matrix $A$. + +Let $S = \sum_{k=0}^{n-1} A^k$ + +We can say for any two nodes $i$ and $j$, $j$ is accessible from $i$ if and only if +$S_{ij} > 0$. + +Devise a function `is_accessible` that checks if any two nodes of a given graph are accessible. + +Consider the graph in {ref}`networks_ex2` and use this function to check if + +1. $1$ is accessible from $2$ +2. $6$ is accessible from $3$ + +```{exercise-end} +``` + +```{solution-start} networks_ex3 +:class: dropdown +``` + +```{code-cell} ipython3 +def is_accessible(G,i,j): + A = nx.to_numpy_array(G) + n = len(A) + result = np.zeros((n, n)) + for i in range(n): + result += np.linalg.matrix_power(A, i) + if result[i,j]>0: + return True + else: + return False +``` + +```{code-cell} ipython3 +G = nx.DiGraph() + +G.add_nodes_from(np.arange(8)) # adding nodes + +G.add_edges_from([(0,1),(0,3), # adding edges + (1,0), + (2,4), + (3,2),(3,4),(3,7), + (4,3), + (5,4),(5,6), + (6,3),(6,5), + (7,0)]) +``` + +```{code-cell} ipython3 +is_accessible(G, 2, 1) +``` + +```{code-cell} ipython3 +is_accessible(G, 3, 6) +``` + +```{solution-end} +``` diff --git a/content/lectures/olg.ipynb b/book/_build/html/_sources/olg.ipynb similarity index 90% rename from content/lectures/olg.ipynb rename to book/_build/html/_sources/olg.ipynb index 36ae57e..82c41f5 100644 --- a/content/lectures/olg.ipynb +++ b/book/_build/html/_sources/olg.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "b34ea887", + "id": "22401f9f", "metadata": {}, "source": [ "# The Overlapping Generations Model\n", @@ -12,7 +12,7 @@ "\n", "* fiscal policy\n", "* monetary policy \n", - "* long run growth\n", + "* long-run growth\n", "\n", "and many other topics.\n", "\n", @@ -24,8 +24,8 @@ "\n", "## Overview\n", "\n", - "The dynamics of the OLG model are quite similar to those of the Solow-Swan\n", - "growth model.\n", + "The dynamics of the OLG model are quite similar to those of the [Solow-Swan\n", + "growth model](https://intro.quantecon.org/solow.html).\n", "\n", "At the same time, the OLG model adds an important new feature: the choice of\n", "how much to save is endogenous.\n", @@ -51,7 +51,7 @@ "The OLG model takes up this challenge.\n", "\n", "We will present a simple version of the OLG model that clarifies the decision\n", - "problem of households and studies the implications for long run growth.\n", + "problem of households and studies the implications for long-run growth.\n", "\n", "Let's start with some imports." ] @@ -59,32 +59,31 @@ { "cell_type": "code", "execution_count": null, - "id": "f49a12b6", + "id": "14eb5044", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "from scipy import optimize\n", "from collections import namedtuple\n", - "from functools import partial\n", "import matplotlib.pyplot as plt" ] }, { "cell_type": "markdown", - "id": "34022802", + "id": "79354497", "metadata": {}, "source": [ "## Environment\n", "\n", - "We assume that time is discrete, so that $t=0, 1, \\ldots$,\n", + "We assume that time is discrete, so that $t=0, 1, \\ldots$.\n", "\n", "An individual born at time $t$ lives for two periods, $t$ and $t + 1$.\n", "\n", "We call an agent\n", "\n", "- \"young\" during the first period of their lives and\n", - "- \"old\" during the second period of their lives\n", + "- \"old\" during the second period of their lives.\n", "\n", "Young agents work, supplying labor and earning labor income.\n", "\n", @@ -151,7 +150,7 @@ "\n", "- $s_t$ is savings by an individual born at time $t$ \n", "- $w_t$ is the wage rate at time $t$\n", - "- $R_{t+1}$ is the interest rate on savings invested at time $t$, paid at time $t+1$\n", + "- $R_{t+1}$ is the gross interest rate on savings invested at time $t$, paid at time $t+1$\n", "\n", "Since $u$ is strictly increasing, both of these constraints will hold as equalities at the maximum.\n", "\n", @@ -162,7 +161,7 @@ "by plugging $c_{t+1}$ into the objective function, taking the derivative\n", "with respect to $c_t$, and setting it to zero.\n", "\n", - "This leads to the **Euler equation** of the OLG model, which is\n", + "This leads to the **Euler equation** of the OLG model, which describes the optimal intertemporal consumption dynamics:\n", "\n", "```{math}\n", ":label: euler_1_olg\n", @@ -232,14 +231,14 @@ "\n", "## Demand for capital\n", "\n", - "First we describe the firm problem and then we write down an equation\n", + "First we describe the firm's problem and then we write down an equation\n", "describing demand for capital given prices.\n", "\n", "\n", "### Firm's problem\n", "\n", - "For each integer $t \\geq 0$, output $y_t$ in period $t$ is given by\n", - "the **Cobb-Douglas production function**\n", + "For each integer $t \\geq 0$, output $y_t$ in period $t$ is given by the \n", + "**[Cobb-Douglas production function](https://en.wikipedia.org/wiki/Cobb%E2%80%93Douglas_production_function)**\n", "\n", "```{math}\n", ":label: cobb_douglas\n", @@ -253,7 +252,7 @@ "\n", "```{math}\n", ":label: opt_profit_olg\n", - " \\max_{k_t, \\ell_t} \\{ k^{\\alpha}_t \\ell_t^{1-\\alpha} - R_t k_t - \\ell_t w_t \\}\n", + " \\max_{k_t, \\ell_t} \\{ k^{\\alpha}_t \\ell_t^{1-\\alpha} - R_t k_t -w_t \\ell_t \\}\n", "```\n", "\n", "The first-order conditions are obtained by taking the derivative of the\n", @@ -299,7 +298,7 @@ { "cell_type": "code", "execution_count": null, - "id": "99f10a29", + "id": "07db6a94", "metadata": {}, "outputs": [], "source": [ @@ -307,45 +306,27 @@ " return (α/R)**(1/(1-α)) " ] }, - { - "cell_type": "markdown", - "id": "afd3c9c2", - "metadata": {}, - "source": [ - "The next figure plots the supply of capital, as in [](saving_log_2_olg), as well as the demand for capital, as in [](aggregate_demand_capital_olg), as functions of the interest rate $R_{t+1}$.\n", - "\n", - "(For the special case of log utility, supply does not depend on the interest rate, so we have a constant function.)" - ] - }, { "cell_type": "code", "execution_count": null, - "id": "96953394", + "id": "9ef52636", "metadata": {}, "outputs": [], "source": [ - "R_vals = np.linspace(0.3, 1)\n", - "α, β = 0.5, 0.9\n", - "w = 2.0\n", - "\n", - "fig, ax = plt.subplots()\n", - "\n", - "ax.plot(R_vals, capital_demand(R_vals, α), \n", - " label=\"aggregate demand\")\n", - "ax.plot(R_vals, np.ones_like(R_vals) * (β / (1 + β)) * w, \n", - " label=\"aggregate supply\")\n", - "\n", - "ax.set_xlabel(\"$R_{t+1}$\")\n", - "ax.set_ylabel(\"$k_{t+1}$\")\n", - "ax.legend()\n", - "plt.show()" + "def capital_supply(R, β, w):\n", + " R = np.ones_like(R)\n", + " return R * (β / (1 + β)) * w" ] }, { "cell_type": "markdown", - "id": "84d8ee3c", + "id": "5f0eb986", "metadata": {}, "source": [ + "The next figure plots the supply of capital, as in [](saving_log_2_olg), as well as the demand for capital, as in [](aggregate_demand_capital_olg), as functions of the interest rate $R_{t+1}$.\n", + "\n", + "(For the special case of log utility, supply does not depend on the interest rate, so we have a constant function.)\n", + "\n", "## Equilibrium\n", "\n", "In this section we derive equilibrium conditions and investigate an example.\n", @@ -406,7 +387,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e61509a0", + "id": "032acfb6", "metadata": {}, "outputs": [], "source": [ @@ -417,7 +398,7 @@ }, { "cell_type": "markdown", - "id": "6b63bb66", + "id": "5bd829b9", "metadata": {}, "source": [ "In the case of log utility, since capital supply does not depend on the interest rate, the equilibrium quantity is fixed by supply.\n", @@ -435,7 +416,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6fa60835", + "id": "12aa8a07", "metadata": {}, "outputs": [], "source": [ @@ -447,21 +428,13 @@ "\n", "ax.plot(R_vals, capital_demand(R_vals, α), \n", " label=\"aggregate demand\")\n", - "ax.plot(R_vals, np.ones_like(R_vals) * (β / (1 + β)) * w, \n", + "ax.plot(R_vals, capital_supply(R_vals, β, w), \n", " label=\"aggregate supply\")\n", "\n", "R_e = equilibrium_R_log_utility(α, β, w)\n", "k_e = (β / (1 + β)) * w\n", "\n", - "ax.plot(R_e, k_e, 'go', ms=6, alpha=0.6)\n", - "\n", - "ax.annotate(r'equilibrium',\n", - " xy=(R_e, k_e),\n", - " xycoords='data',\n", - " xytext=(0, 60),\n", - " textcoords='offset points',\n", - " fontsize=12,\n", - " arrowprops=dict(arrowstyle=\"->\"))\n", + "ax.plot(R_e, k_e, 'o',label='equilibrium')\n", "\n", "ax.set_xlabel(\"$R_{t+1}$\")\n", "ax.set_ylabel(\"$k_{t+1}$\")\n", @@ -471,7 +444,7 @@ }, { "cell_type": "markdown", - "id": "907d3707", + "id": "0e4cf92b", "metadata": {}, "source": [ "## Dynamics \n", @@ -496,7 +469,7 @@ "If we iterate on this equation, we get a sequence for capital stock.\n", "\n", "\n", - "Let's plot the 45 degree diagram of these dynamics, which we write as\n", + "Let's plot the 45-degree diagram of these dynamics, which we write as\n", "\n", "$$\n", " k_{t+1} = g(k_t)\n", @@ -508,7 +481,7 @@ { "cell_type": "code", "execution_count": null, - "id": "54b51f4f", + "id": "222f3b87", "metadata": {}, "outputs": [], "source": [ @@ -519,18 +492,15 @@ { "cell_type": "code", "execution_count": null, - "id": "897bbb81", + "id": "47787cb6", "metadata": {}, "outputs": [], "source": [ "α, β = 0.5, 0.9\n", "kmin, kmax = 0, 0.1\n", - "x = 1000\n", - "k_grid = np.linspace(kmin, kmax, x)\n", - "k_grid_next = np.empty_like(k_grid)\n", - "\n", - "for i in range(x):\n", - " k_grid_next[i] = k_update(k_grid[i], α, β)\n", + "n = 1000\n", + "k_grid = np.linspace(kmin, kmax, n)\n", + "k_grid_next = k_update(k_grid,α,β)\n", "\n", "fig, ax = plt.subplots(figsize=(6, 6))\n", "\n", @@ -549,7 +519,7 @@ }, { "cell_type": "markdown", - "id": "726f7523", + "id": "31d1159b", "metadata": {}, "source": [ "### Steady state (log case)\n", @@ -584,7 +554,7 @@ { "cell_type": "code", "execution_count": null, - "id": "70627b5e", + "id": "e23ea30a", "metadata": {}, "outputs": [], "source": [ @@ -594,12 +564,12 @@ }, { "cell_type": "markdown", - "id": "699995db", + "id": "66fc8675", "metadata": {}, "source": [ "### Time series\n", "\n", - "The 45 degree diagram above shows that time series of capital with positive initial conditions converge to this steady state.\n", + "The 45-degree diagram above shows that time series of capital with positive initial conditions converge to this steady state.\n", "\n", "Let's plot some time series that visualize this." ] @@ -607,7 +577,7 @@ { "cell_type": "code", "execution_count": null, - "id": "84513abf", + "id": "a2199b70", "metadata": {}, "outputs": [], "source": [ @@ -629,7 +599,7 @@ }, { "cell_type": "markdown", - "id": "fdfe3158", + "id": "7ce5fa6b", "metadata": {}, "source": [ "If you experiment with different positive initial conditions, you will see that the series always converges to $k^*$." @@ -637,7 +607,7 @@ }, { "cell_type": "markdown", - "id": "18b13648", + "id": "81b28116", "metadata": {}, "source": [ "Below we also plot the gross interest rate over time." @@ -646,7 +616,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ae969e38", + "id": "080c99f4", "metadata": {}, "outputs": [], "source": [ @@ -656,6 +626,7 @@ "ax.plot(R_series, label=\"gross interest rate\")\n", "ax.plot(range(ts_length), np.full(ts_length, R_star), 'k--', label=\"$R^*$\")\n", "ax.set_ylim(0, 4)\n", + "ax.set_ylabel(\"gross interest rate\")\n", "ax.set_xlabel(\"$t$\")\n", "ax.legend()\n", "plt.show()" @@ -663,7 +634,7 @@ }, { "cell_type": "markdown", - "id": "517ec2d5", + "id": "3577df05", "metadata": {}, "source": [ "The interest rate reflects the marginal product of capital, which is high when capital stock is low." @@ -671,14 +642,14 @@ }, { "cell_type": "markdown", - "id": "f015c898", + "id": "bd441c54", "metadata": {}, "source": [ "## CRRA preferences\n", "\n", "Previously, in our examples, we looked at the case of log utility.\n", "\n", - "Log utility is a rather special case.\n", + "Log utility is a rather special case of CRRA utility with $\\gamma \\to 1$.\n", "\n", "In this section, we are going to assume that $u(c) = \\frac{ c^{1-\n", "\\gamma}-1}{1-\\gamma}$, where $\\gamma >0, \\gamma\\neq 1$.\n", @@ -693,7 +664,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8ce66938", + "id": "12fd5192", "metadata": {}, "outputs": [], "source": [ @@ -711,7 +682,7 @@ }, { "cell_type": "markdown", - "id": "460d7dbe", + "id": "f2f63632", "metadata": {}, "source": [ "Let's also redefine the capital demand function to work with this `namedtuple`." @@ -720,7 +691,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5b4e9595", + "id": "c225d58c", "metadata": {}, "outputs": [], "source": [ @@ -730,7 +701,7 @@ }, { "cell_type": "markdown", - "id": "c79d5e6a", + "id": "e148456f", "metadata": {}, "source": [ "### Supply\n", @@ -761,7 +732,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b3cfbb55", + "id": "46494572", "metadata": {}, "outputs": [], "source": [ @@ -773,11 +744,10 @@ { "cell_type": "code", "execution_count": null, - "id": "eab3f4a7", + "id": "5f4fc1b7", "metadata": {}, "outputs": [], "source": [ - "R_vals = np.linspace(0.3, 1)\n", "model = create_olg_model()\n", "w = 2.0\n", "\n", @@ -796,7 +766,7 @@ }, { "cell_type": "markdown", - "id": "8235cfeb", + "id": "c63c2013", "metadata": {}, "source": [ "### Equilibrium\n", @@ -831,7 +801,7 @@ }, { "cell_type": "markdown", - "id": "815a4770", + "id": "300ab43c", "metadata": {}, "source": [ "## Exercises\n", @@ -842,7 +812,7 @@ "\n", "Solve for the dynamics of equilibrium capital stock in the CRRA case numerically using [](law_of_motion_capital_crra).\n", "\n", - "Visualize the dynamics using a 45 degree diagram.\n", + "Visualize the dynamics using a 45-degree diagram.\n", "\n", "```\n", "\n", @@ -852,7 +822,7 @@ "```\n", "\n", "\n", - "To solve for $k_{t+1}$ given $k_t$ we use Newton's method.\n", + "To solve for $k_{t+1}$ given $k_t$ we use [Newton's method](https://python.quantecon.org/newton_method.html).\n", "\n", "Let\n", "\n", @@ -879,7 +849,7 @@ { "cell_type": "code", "execution_count": null, - "id": "d0264133", + "id": "7135c3b1", "metadata": {}, "outputs": [], "source": [ @@ -894,7 +864,7 @@ }, { "cell_type": "markdown", - "id": "df62361c", + "id": "d5398608", "metadata": {}, "source": [ "Now let's define a function that finds the value of $k_{t+1}$." @@ -903,7 +873,7 @@ { "cell_type": "code", "execution_count": null, - "id": "7d9207c1", + "id": "471cf9f4", "metadata": {}, "outputs": [], "source": [ @@ -913,25 +883,25 @@ }, { "cell_type": "markdown", - "id": "48b8538d", + "id": "ecae1525", "metadata": {}, "source": [ - "Finally, here is the 45 degree diagram." + "Finally, here is the 45-degree diagram." ] }, { "cell_type": "code", "execution_count": null, - "id": "3aa85781", + "id": "5f500f6a", "metadata": {}, "outputs": [], "source": [ "kmin, kmax = 0, 0.5\n", - "x = 1000\n", - "k_grid = np.linspace(kmin, kmax, x)\n", + "n = 1000\n", + "k_grid = np.linspace(kmin, kmax, n)\n", "k_grid_next = np.empty_like(k_grid)\n", "\n", - "for i in range(x):\n", + "for i in range(n):\n", " k_grid_next[i] = k_update(k_grid[i], model)\n", "\n", "fig, ax = plt.subplots(figsize=(6, 6))\n", @@ -951,7 +921,7 @@ }, { "cell_type": "markdown", - "id": "0ec49c1b", + "id": "ed12c6ce", "metadata": {}, "source": [ "```{solution-end}\n", @@ -961,7 +931,7 @@ "```{exercise}\n", ":label: olg_ex2\n", "\n", - "The 45 degree diagram from the last exercise shows that there is a unique\n", + "The 45-degree diagram from the last exercise shows that there is a unique\n", "positive steady state.\n", "\n", "The positive steady state can be obtained by setting $k_{t+1} = k_t = k^*$ in [](law_of_motion_capital_crra), which yields\n", @@ -1001,7 +971,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9c378804", + "id": "86840a9b", "metadata": {}, "outputs": [], "source": [ @@ -1016,7 +986,7 @@ }, { "cell_type": "markdown", - "id": "96d02d09", + "id": "4e740c2b", "metadata": {}, "source": [ "Let's apply Newton's method to find the root:" @@ -1025,7 +995,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4d36fe1d", + "id": "38e6d3b6", "metadata": {}, "outputs": [], "source": [ @@ -1035,7 +1005,7 @@ }, { "cell_type": "markdown", - "id": "f90714be", + "id": "a58c742c", "metadata": {}, "source": [ "```{solution-end}\n", @@ -1066,7 +1036,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c56f6f25", + "id": "0489911b", "metadata": {}, "outputs": [], "source": [ @@ -1077,7 +1047,7 @@ { "cell_type": "code", "execution_count": null, - "id": "67f5ef2b", + "id": "5d5ac76c", "metadata": {}, "outputs": [], "source": [ @@ -1107,7 +1077,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ecf163fe", + "id": "7b6d6b2d", "metadata": {}, "outputs": [], "source": [ @@ -1116,7 +1086,7 @@ }, { "cell_type": "markdown", - "id": "878613bd", + "id": "75bc48be", "metadata": {}, "source": [ "```{solution-end}\n", @@ -1125,12 +1095,65 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.15.2" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 12, + 64, + 69, + 291, + 296, + 300, + 362, + 366, + 379, + 400, + 432, + 437, + 457, + 487, + 490, + 498, + 513, + 517, + 521, + 532, + 536, + 553, + 564, + 568, + 571, + 597, + 603, + 618, + 649, + 692, + 700, + 704, + 707, + 711, + 733, + 778, + 786, + 790, + 793, + 819, + 824, + 848, + 850 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/olg.md b/book/_build/html/_sources/olg.md new file mode 100644 index 0000000..6530e1b --- /dev/null +++ b/book/_build/html/_sources/olg.md @@ -0,0 +1,853 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.15.2 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# The Overlapping Generations Model + +In this lecture we study the famous overlapping generations (OLG) model, which +is used by policy makers and researchers to examine + +* fiscal policy +* monetary policy +* long-run growth + +and many other topics. + +The first rigorous version of the OLG model was developed by Paul Samuelson +{cite}`samuelson1958exact`. + +Our aim is to gain a good understanding of a simple version of the OLG +model. + +## Overview + +The dynamics of the OLG model are quite similar to those of the [Solow-Swan +growth model](https://intro.quantecon.org/solow.html). + +At the same time, the OLG model adds an important new feature: the choice of +how much to save is endogenous. + +To see why this is important, suppose, for example, that we are interested in +predicting the effect of a new tax on long-run growth. + +We could add a tax to the Solow-Swan model and look at the change in the +steady state. + +But this ignores the fact that households will change their savings and +consumption behavior when they face the new tax rate. + +Such changes can substantially alter the predictions of the model. + +Hence, if we care about accurate predictions, we should model the decision +problems of the agents. + +In particular, households in the model should decide how much to save and how +much to consume, given the environment that they face (technology, taxes, +prices, etc.) + +The OLG model takes up this challenge. + +We will present a simple version of the OLG model that clarifies the decision +problem of households and studies the implications for long-run growth. + +Let's start with some imports. + +```{code-cell} ipython3 +import numpy as np +from scipy import optimize +from collections import namedtuple +import matplotlib.pyplot as plt +``` + +## Environment + +We assume that time is discrete, so that $t=0, 1, \ldots$. + +An individual born at time $t$ lives for two periods, $t$ and $t + 1$. + +We call an agent + +- "young" during the first period of their lives and +- "old" during the second period of their lives. + +Young agents work, supplying labor and earning labor income. + +They also decide how much to save. + +Old agents do not work, so all income is financial. + +Their financial income is from interest on their savings from wage income, +which is then combined with the labor of the new young generation at $t+1$. + +The wage and interest rates are determined in equilibrium by supply and +demand. + +To make the algebra slightly easier, we are going to assume a constant +population size. + +We normalize the constant population size in each period to 1. + +We also suppose that each agent supplies one "unit" of labor hours, so total +labor supply is 1. + + +## Supply of capital + +First let's consider the household side. + +### Consumer's problem + +Suppose that utility for individuals born at time $t$ takes the form + +```{math} +:label: eq_crra + + U_t = u(c_t) + \beta u(c_{t+1}) +``` + +Here + +- $u: \mathbb R_+ \to \mathbb R$ is called the "flow" utility function +- $\beta \in (0, 1)$ is the discount factor +- $c_t$ is time $t$ consumption of the individual born at time $t$ +- $c_{t+1}$ is time $t+1$ consumption of the same individual + +We assume that $u$ is strictly increasing. + +Savings behavior is determined by the optimization problem + + +```{math} +:label: max_sav_olg + \max_{c_t, c_{t+1}} + \, \left \{ u(c_t) + \beta u(c_{t+1}) \right \} +``` + +subject to + +$$ + c_t + s_t \le w_t + \quad \text{and} \quad + c_{t+1} \le R_{t+1} s_t +$$ + +Here + +- $s_t$ is savings by an individual born at time $t$ +- $w_t$ is the wage rate at time $t$ +- $R_{t+1}$ is the gross interest rate on savings invested at time $t$, paid at time $t+1$ + +Since $u$ is strictly increasing, both of these constraints will hold as equalities at the maximum. + +Using this fact and substituting $s_t$ from the first constraint into the second we get +$c_{t+1} = R_{t+1}(w_t - c_t)$. + +The first-order condition for a maximum can be obtained +by plugging $c_{t+1}$ into the objective function, taking the derivative +with respect to $c_t$, and setting it to zero. + +This leads to the **Euler equation** of the OLG model, which describes the optimal intertemporal consumption dynamics: + +```{math} +:label: euler_1_olg + u'(c_t) = \beta R_{t+1} u'( R_{t+1} (w_t - c_t)) +``` + +From the first constraint we get $c_t = w_t - s_t$, so the Euler equation +can also be expressed as + +```{math} +:label: euler_2_olg + u'(w_t - s_t) = \beta R_{t+1} u'( R_{t+1} s_t) +``` + +Suppose that, for each $w_t$ and $R_{t+1}$, there is exactly one $s_t$ that +solves [](euler_2_olg). + +Then savings can be written as a fixed function of $w_t$ and $R_{t+1}$. + +We write this as + +```{math} +:label: saving_1_olg + s_t = s(w_t, R_{t+1}) +``` + +The precise form of the function $s$ will depend on the choice of flow utility +function $u$. + +Together, $w_t$ and $R_{t+1}$ represent the *prices* in the economy (price of +labor and rental rate of capital). + +Thus, [](saving_1_olg) states the quantity of savings given prices. + + +### Example: log preferences + +In the special case $u(c) = \log c$, the Euler equation simplifies to + $s_t= \beta (w_t - s_t)$. + +Solving for saving, we get + +```{math} +:label: saving_log_2_olg + s_t = s(w_t, R_{t+1}) = \frac{\beta}{1+\beta} w_t +``` + +In this special case, savings does not depend on the interest rate. + + + +### Savings and investment + +Since the population size is normalized to 1, $s_t$ is also total savings in +the economy at time $t$. + +In our closed economy, there is no foreign investment, so net savings equals +total investment, which can be understood as supply of capital to firms. + + +In the next section we investigate demand for capital. + +Equating supply and demand will allow us to determine equilibrium in the OLG +economy. + + + +## Demand for capital + +First we describe the firm's problem and then we write down an equation +describing demand for capital given prices. + + +### Firm's problem + +For each integer $t \geq 0$, output $y_t$ in period $t$ is given by the +**[Cobb-Douglas production function](https://en.wikipedia.org/wiki/Cobb%E2%80%93Douglas_production_function)** + +```{math} +:label: cobb_douglas + y_t = k_t^{\alpha} \ell_t^{1-\alpha} +``` + +Here $k_t$ is capital, $\ell_t$ is labor, and $\alpha$ is a parameter +(sometimes called the "output elasticity of capital"). + +The profit maximization problem of the firm is + +```{math} +:label: opt_profit_olg + \max_{k_t, \ell_t} \{ k^{\alpha}_t \ell_t^{1-\alpha} - R_t k_t -w_t \ell_t \} +``` + +The first-order conditions are obtained by taking the derivative of the +objective function with respect to capital and labor respectively and setting +them to zero: + +```{math} + (1-\alpha)(k_t / \ell_t)^{\alpha} = w_t + \quad \text{and} \quad + \alpha (k_t / \ell_t)^{\alpha - 1} = R_t +``` + + +### Demand + +Using our assumption $\ell_t = 1$ allows us to write + +```{math} +:label: wage_one + w_t = (1-\alpha)k_t^\alpha +``` + +and + +```{math} +:label: interest_rate_one + R_t = + \alpha k_t^{\alpha - 1} +``` + +Rearranging [](interest_rate_one) gives the aggregate demand for capital +at time $t+1$ + +```{math} +:label: aggregate_demand_capital_olg + k^d (R_{t+1}) + := \left (\frac{\alpha}{R_{t+1}} \right )^{1/(1-\alpha)} +``` + +In Python code this is + +```{code-cell} ipython3 +def capital_demand(R, α): + return (α/R)**(1/(1-α)) +``` + +```{code-cell} ipython3 +def capital_supply(R, β, w): + R = np.ones_like(R) + return R * (β / (1 + β)) * w +``` + +The next figure plots the supply of capital, as in [](saving_log_2_olg), as well as the demand for capital, as in [](aggregate_demand_capital_olg), as functions of the interest rate $R_{t+1}$. + +(For the special case of log utility, supply does not depend on the interest rate, so we have a constant function.) + +## Equilibrium + +In this section we derive equilibrium conditions and investigate an example. + + +### Equilibrium conditions + +In equilibrium, savings at time $t$ equals investment at time $t$, which +equals capital supply at time $t+1$. + +Equilibrium is computed by equating these quantities, setting + + +```{math} +:label: equilibrium_1 + s(w_t, R_{t+1}) + = k^d(R_{t+1}) + = \left (\frac{\alpha}{R_{t+1}} \right )^{1/(1-\alpha)} +``` + + +In principle, we can now solve for the equilibrium price $R_{t+1}$ given $w_t$. + +(In practice, we first need to specify the function $u$ and hence $s$.) + + +When we solve this equation, which concerns time $t+1$ outcomes, time +$t$ quantities are already determined, so we can treat $w_t$ as a constant. + +From equilibrium $R_{t+1}$ and [](aggregate_demand_capital_olg), we can obtain +the equilibrium quantity $k_{t+1}$. + + +### Example: log utility + +In the case of log utility, we can use [](equilibrium_1) and [](saving_log_2_olg) to obtain + +```{math} +:label: equilibrium_2 + \frac{\beta}{1+\beta} w_t + = \left( \frac{\alpha}{R_{t+1}} \right)^{1/(1-\alpha)} +``` + +Solving for the equilibrium interest rate gives + +```{math} +:label: equilibrium_price + R_{t+1} = + \alpha + \left( + \frac{\beta}{1+\beta} w_t + \right)^{\alpha-1} +``` + +In Python we can compute this via + +```{code-cell} ipython3 +def equilibrium_R_log_utility(α, β, w): + R = α * ( (β * w) / (1 + β))**(α - 1) + return R +``` + +In the case of log utility, since capital supply does not depend on the interest rate, the equilibrium quantity is fixed by supply. + +That is, + +```{math} +:label: equilibrium_quantity + k_{t+1} = s(w_t, R_{t+1}) = \frac{\beta }{1+\beta} w_t +``` + +Let's redo our plot above but now inserting the equilibrium quantity and price. + +```{code-cell} ipython3 +R_vals = np.linspace(0.3, 1) +α, β = 0.5, 0.9 +w = 2.0 + +fig, ax = plt.subplots() + +ax.plot(R_vals, capital_demand(R_vals, α), + label="aggregate demand") +ax.plot(R_vals, capital_supply(R_vals, β, w), + label="aggregate supply") + +R_e = equilibrium_R_log_utility(α, β, w) +k_e = (β / (1 + β)) * w + +ax.plot(R_e, k_e, 'o',label='equilibrium') + +ax.set_xlabel("$R_{t+1}$") +ax.set_ylabel("$k_{t+1}$") +ax.legend() +plt.show() +``` + +## Dynamics + +In this section we discuss dynamics. + +For now we will focus on the case of log utility, so that the equilibrium is determined by [](equilibrium_quantity). + +### Evolution of capital + +The discussion above shows how equilibrium $k_{t+1}$ is obtained given $w_t$. + +From [](wage_one) we can translate this into $k_{t+1}$ as a function of $k_t$ + +In particular, since $w_t = (1-\alpha)k_t^\alpha$, we have + +```{math} +:label: law_of_motion_capital + k_{t+1} = \frac{\beta}{1+\beta} (1-\alpha)(k_t)^{\alpha} +``` + +If we iterate on this equation, we get a sequence for capital stock. + + +Let's plot the 45-degree diagram of these dynamics, which we write as + +$$ + k_{t+1} = g(k_t) + \quad \text{where } + g(k) := \frac{\beta}{1+\beta} (1-\alpha)(k)^{\alpha} +$$ + +```{code-cell} ipython3 +def k_update(k, α, β): + return β * (1 - α) * k**α / (1 + β) +``` + +```{code-cell} ipython3 +α, β = 0.5, 0.9 +kmin, kmax = 0, 0.1 +n = 1000 +k_grid = np.linspace(kmin, kmax, n) +k_grid_next = k_update(k_grid,α,β) + +fig, ax = plt.subplots(figsize=(6, 6)) + +ymin, ymax = np.min(k_grid_next), np.max(k_grid_next) + +ax.plot(k_grid, k_grid_next, lw=2, alpha=0.6, label='$g$') +ax.plot(k_grid, k_grid, 'k-', lw=1, alpha=0.7, label='$45^{\circ}$') + + +ax.legend(loc='upper left', frameon=False, fontsize=12) +ax.set_xlabel('$k_t$', fontsize=12) +ax.set_ylabel('$k_{t+1}$', fontsize=12) + +plt.show() +``` + +### Steady state (log case) + +The diagram shows that the model has a unique positive steady state, which we +denote by $k^*$. + +We can solve for $k^*$ by setting $k^* = g(k^*)$, or + +```{math} +:label: steady_state_1 + k^* = \frac{\beta (1-\alpha) (k^*)^{\alpha}}{(1+\beta)} +``` + +Solving this equation yields + +```{math} +:label: steady_state_2 + k^* = \left (\frac{\beta (1-\alpha)}{1+\beta} \right )^{1/(1-\alpha)} +``` + +We can get the steady state interest rate from [](interest_rate_one), which yields + +$$ + R^* = \alpha (k^*)^{\alpha - 1} + = \frac{\alpha}{1 - \alpha} \frac{1 + \beta}{\beta} +$$ + +In Python we have + +```{code-cell} ipython3 +k_star = ((β * (1 - α))/(1 + β))**(1/(1-α)) +R_star = (α/(1 - α)) * ((1 + β) / β) +``` + +### Time series + +The 45-degree diagram above shows that time series of capital with positive initial conditions converge to this steady state. + +Let's plot some time series that visualize this. + +```{code-cell} ipython3 +ts_length = 25 +k_series = np.empty(ts_length) +k_series[0] = 0.02 +for t in range(ts_length - 1): + k_series[t+1] = k_update(k_series[t], α, β) + +fig, ax = plt.subplots() +ax.plot(k_series, label="capital series") +ax.plot(range(ts_length), np.full(ts_length, k_star), 'k--', label="$k^*$") +ax.set_ylim(0, 0.1) +ax.set_ylabel("capital") +ax.set_xlabel("$t$") +ax.legend() +plt.show() +``` + +If you experiment with different positive initial conditions, you will see that the series always converges to $k^*$. + ++++ + +Below we also plot the gross interest rate over time. + +```{code-cell} ipython3 +R_series = α * k_series**(α - 1) + +fig, ax = plt.subplots() +ax.plot(R_series, label="gross interest rate") +ax.plot(range(ts_length), np.full(ts_length, R_star), 'k--', label="$R^*$") +ax.set_ylim(0, 4) +ax.set_ylabel("gross interest rate") +ax.set_xlabel("$t$") +ax.legend() +plt.show() +``` + +The interest rate reflects the marginal product of capital, which is high when capital stock is low. + ++++ + +## CRRA preferences + +Previously, in our examples, we looked at the case of log utility. + +Log utility is a rather special case of CRRA utility with $\gamma \to 1$. + +In this section, we are going to assume that $u(c) = \frac{ c^{1- +\gamma}-1}{1-\gamma}$, where $\gamma >0, \gamma\neq 1$. + +This function is called the CRRA utility function. + +In other respects, the model is the same. + +Below we define the utility function in Python and construct a `namedtuple` to store the parameters. + +```{code-cell} ipython3 +def crra(c, γ): + return c**(1 - γ) / (1 - γ) + +Model = namedtuple('Model', ['α', # Cobb-Douglas parameter + 'β', # discount factor + 'γ'] # parameter in CRRA utility + ) + +def create_olg_model(α=0.4, β=0.9, γ=0.5): + return Model(α=α, β=β, γ=γ) +``` + +Let's also redefine the capital demand function to work with this `namedtuple`. + +```{code-cell} ipython3 +def capital_demand(R, model): + return (α/R)**(1/(1-model.α)) +``` + +### Supply + + +For households, the Euler equation becomes +```{math} +:label: euler_crra + (w_t - s_t)^{-\gamma} = \beta R^{1-\gamma}_{t+1} (s_t)^{-\gamma} +``` + + +Solving for savings, we have + +```{math} +:label: saving_crra + s_t + = s(w_t, R_{t+1}) + = w_t \left [ + 1 + \beta^{-1/\gamma} R_{t+1}^{(\gamma-1)/\gamma} + \right ]^{-1} +``` + + +Notice how, unlike the log case, savings now depends on the interest rate. + +```{code-cell} ipython3 +def savings_crra(w, R, model): + α, β, γ = model + return w / (1 + β**(-1/γ) * R**((γ-1)/γ)) +``` + +```{code-cell} ipython3 +model = create_olg_model() +w = 2.0 + +fig, ax = plt.subplots() + +ax.plot(R_vals, capital_demand(R_vals, model), + label="aggregate demand") +ax.plot(R_vals, savings_crra(w, R_vals, model), + label="aggregate supply") + +ax.set_xlabel("$R_{t+1}$") +ax.set_ylabel("$k_{t+1}$") +ax.legend() +plt.show() +``` + +### Equilibrium + +Equating aggregate demand for capital (see [](aggregate_demand_capital_olg)) +with our new aggregate supply function yields equilibrium capital. + +Thus, we set + + +```{math} +:label: equilibrium_crra_2 + w_t \left [ 1 + \beta^{-1/\gamma} R_{t+1}^{(\gamma-1)/\gamma} \right ]^{-1} + = \left (\frac{R_{t+1}}{\alpha} \right )^{1/(\alpha - 1)} +``` + +This expression is quite complex and we cannot solve for $R_{t+1}$ analytically. + + +Combining [](interest_rate_one) and [](equilibrium_crra_2) yields + +```{math} +:label: law_of_motion_capital_crra + k_{t+1} = \left [ 1 + \beta^{-1/\gamma} (\alpha k^{\alpha - 1}_{t+1})^{(\gamma-1)/\gamma} \right ]^{-1} (1-\alpha)(k_t)^{\alpha} +``` + +Again, with this equation and $k_t$ as given, we cannot solve for $k_{t+1}$ by pencil and paper. + + +In the exercise below, you will be asked to solve these equations numerically. + ++++ + +## Exercises + + +```{exercise} +:label: olg_ex1 + +Solve for the dynamics of equilibrium capital stock in the CRRA case numerically using [](law_of_motion_capital_crra). + +Visualize the dynamics using a 45-degree diagram. + +``` + + +```{solution-start} olg_ex1 +:class: dropdown +``` + + +To solve for $k_{t+1}$ given $k_t$ we use [Newton's method](https://python.quantecon.org/newton_method.html). + +Let + +```{math} +:label: crra_newton_1 + f(k_{t+1}, k_t) + = + k_{t+1} + \left[ + 1 + \beta^{-1/\gamma} + \left ( + \alpha k^{\alpha-1}_{t+1} + \right )^{(\gamma-1)/\gamma} + \right] - (1-\alpha) k^{\alpha}_t =0 +``` + +If $k_t$ is given then $f$ is a function of unknown $k_{t+1}$. + +Then we can use `scipy.optimize.newton` to solve $f(k_{t+1}, k_t)=0$ for $k_{t+1}$. + +First let's define $f$. + +```{code-cell} ipython3 +def f(k_prime, k, model): + α, β, γ = model.α, model.β, model.γ + z = (1 - α) * k**α + a = α**(1-1/γ) + b = k_prime**((α * γ - α + 1) / γ) + p = k_prime + k_prime * β**(-1/γ) * a * b + return p - z +``` + +Now let's define a function that finds the value of $k_{t+1}$. + +```{code-cell} ipython3 +def k_update(k, model): + return optimize.newton(lambda k_prime: f(k_prime, k, model), 0.1) +``` + +Finally, here is the 45-degree diagram. + +```{code-cell} ipython3 +kmin, kmax = 0, 0.5 +n = 1000 +k_grid = np.linspace(kmin, kmax, n) +k_grid_next = np.empty_like(k_grid) + +for i in range(n): + k_grid_next[i] = k_update(k_grid[i], model) + +fig, ax = plt.subplots(figsize=(6, 6)) + +ymin, ymax = np.min(k_grid_next), np.max(k_grid_next) + +ax.plot(k_grid, k_grid_next, lw=2, alpha=0.6, label='$g$') +ax.plot(k_grid, k_grid, 'k-', lw=1, alpha=0.7, label='$45^{\circ}$') + + +ax.legend(loc='upper left', frameon=False, fontsize=12) +ax.set_xlabel('$k_t$', fontsize=12) +ax.set_ylabel('$k_{t+1}$', fontsize=12) + +plt.show() +``` + +```{solution-end} +``` + + +```{exercise} +:label: olg_ex2 + +The 45-degree diagram from the last exercise shows that there is a unique +positive steady state. + +The positive steady state can be obtained by setting $k_{t+1} = k_t = k^*$ in [](law_of_motion_capital_crra), which yields + +$$ + k^* = + \frac{(1-\alpha)(k^*)^{\alpha}} + {1 + \beta^{-1/\gamma} (\alpha (k^*)^{\alpha-1})^{(\gamma-1)/\gamma}} +$$ + +Unlike the log preference case, the CRRA utility steady state $k^*$ +cannot be obtained analytically. + +Instead, we solve for $k^*$ using Newton's method. + +``` + + +```{solution-start} olg_ex2 +:class: dropdown +``` + +We introduce a function $h$ such that +positive steady state is the root of $h$. + +```{math} +:label: crra_newton_2 + h(k^*) = k^* + \left [ + 1 + \beta^{-1/\gamma} (\alpha (k^*)^{\alpha-1})^{(\gamma-1)/\gamma} + \right ] - (1-\alpha)(k^*)^{\alpha} +``` + +Here it is in Python + +```{code-cell} ipython3 +def h(k_star, model): + α, β, γ = model.α, model.β, model.γ + z = (1 - α) * k_star**α + R1 = α ** (1-1/γ) + R2 = k_star**((α * γ - α + 1) / γ) + p = k_star + k_star * β**(-1/γ) * R1 * R2 + return p - z +``` + +Let's apply Newton's method to find the root: + +```{code-cell} ipython3 +k_star = optimize.newton(h, 0.2, args=(model,)) +print(f"k_star = {k_star}") +``` + +```{solution-end} +``` + + + + +```{exercise} +:label: olg_ex3 + +Generate three time paths for capital, from +three distinct initial conditions, under the parameterization listed above. + +Use initial conditions for $k_0$ of $0.001, 1.2, 2.6$ and time series length 10. + +``` + + +```{solution-start} olg_ex3 +:class: dropdown +``` + + +Let's define the constants and three distinct intital conditions + +```{code-cell} ipython3 +ts_length = 10 +k0 = np.array([0.001, 1.2, 2.6]) +``` + +```{code-cell} ipython3 +def simulate_ts(model, k0_values, ts_length): + + fig, ax = plt.subplots() + + ts = np.zeros(ts_length) + + # simulate and plot time series + for k_init in k0_values: + ts[0] = k_init + for t in range(1, ts_length): + ts[t] = k_update(ts[t-1], model) + ax.plot(np.arange(ts_length), ts, '-o', ms=4, alpha=0.6, + label=r'$k_0=%g$' %k_init) + ax.plot(np.arange(ts_length), np.full(ts_length, k_star), + alpha=0.6, color='red', label=r'$k^*$') + ax.legend(fontsize=10) + + ax.set_xlabel(r'$t$', fontsize=14) + ax.set_ylabel(r'$k_t$', fontsize=14) + + plt.show() +``` + +```{code-cell} ipython3 +simulate_ts(model, k0, ts_length) +``` + +```{solution-end} +``` diff --git a/content/lectures/prob_dist.ipynb b/book/_build/html/_sources/prob_dist.ipynb similarity index 61% rename from content/lectures/prob_dist.ipynb rename to book/_build/html/_sources/prob_dist.ipynb index 113674c..1fcaba5 100644 --- a/content/lectures/prob_dist.ipynb +++ b/book/_build/html/_sources/prob_dist.ipynb @@ -2,30 +2,28 @@ "cells": [ { "cell_type": "markdown", - "id": "3c8bde72", - "metadata": { - "user_expressions": [] - }, + "id": "2ac377cd", + "metadata": {}, "source": [ "# Distributions and Probabilities\n", "\n", "```{index} single: Distributions and Probabilities\n", "```\n", "\n", - "```{contents} Contents\n", - ":depth: 2\n", - "```\n", - "\n", "## Outline\n", "\n", - "In this lecture we give a quick introduction to data and probability distributions using Python" + "In this lecture we give a quick introduction to data and probability distributions using Python." ] }, { "cell_type": "code", "execution_count": null, - "id": "cf4b15de", - "metadata": {}, + "id": "e27c322b", + "metadata": { + "tags": [ + "hide-output" + ] + }, "outputs": [], "source": [ "%pip install --upgrade yfinance " @@ -34,7 +32,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6f54d0ca", + "id": "0d053bd5", "metadata": {}, "outputs": [], "source": [ @@ -48,14 +46,12 @@ }, { "cell_type": "markdown", - "id": "fb482af5", - "metadata": { - "user_expressions": [] - }, + "id": "997b639e", + "metadata": {}, "source": [ "## Common distributions\n", "\n", - "In this section we recall the definitions of some well-known distributions and show how to manipulate them with SciPy.\n", + "In this section we recall the definitions of some well-known distributions and explore how to manipulate them with SciPy.\n", "\n", "### Discrete distributions\n", "\n", @@ -63,18 +59,22 @@ "\n", "A discrete distribution is defined by a set of numbers $S = \\{x_1, \\ldots, x_n\\}$ and a **probability mass function** (PMF) on $S$, which is a function $p$ from $S$ to $[0,1]$ with the property \n", "\n", - "$$ \\sum_{i=1}^n p(x_i) = 1 $$\n", + "$$ \n", + "\\sum_{i=1}^n p(x_i) = 1 \n", + "$$\n", "\n", "We say that a random variable $X$ **has distribution** $p$ if $X$ takes value $x_i$ with probability $p(x_i)$.\n", "\n", "That is,\n", "\n", - "$$ \\mathbb P\\{X = x_i\\} = p(x_i) \\quad \\text{for } i= 1, \\ldots, n $$\n", + "$$ \n", + "\\mathbb P\\{X = x_i\\} = p(x_i) \\quad \\text{for } i= 1, \\ldots, n \n", + "$$\n", "\n", "The **mean** or **expected value** of a random variable $X$ with distribution $p$ is \n", "\n", "$$ \n", - " \\mathbb E X = \\sum_{i=1}^n x_i p(x_i)\n", + "\\mathbb{E}[X] = \\sum_{i=1}^n x_i p(x_i)\n", "$$\n", "\n", "Expectation is also called the *first moment* of the distribution.\n", @@ -84,7 +84,7 @@ "The **variance** of $X$ is defined as \n", "\n", "$$ \n", - " \\mathbb V X = \\sum_{i=1}^n (x_i - \\mathbb E X)^2 p(x_i)\n", + "\\mathbb{V}[X] = \\sum_{i=1}^n (x_i - \\mathbb{E}[X])^2 p(x_i)\n", "$$\n", "\n", "Variance is also called the *second central moment* of the distribution.\n", @@ -92,8 +92,8 @@ "The **cumulative distribution function** (CDF) of $X$ is defined by\n", "\n", "$$\n", - " F(x) = \\mathbb P\\{X \\leq x\\}\n", - " = \\sum_{i=1}^n \\mathbb 1\\{x_i \\leq x\\} p(x_i)\n", + "F(x) = \\mathbb{P}\\{X \\leq x\\}\n", + " = \\sum_{i=1}^n \\mathbb 1\\{x_i \\leq x\\} p(x_i)\n", "$$\n", "\n", "Here $\\mathbb 1\\{ \\textrm{statement} \\} = 1$ if \"statement\" is true and zero otherwise.\n", @@ -103,7 +103,7 @@ "\n", "#### Uniform distribution\n", "\n", - "One simple example is the **uniform distribution**, where $p(x_i) = 1/n$ for all $n$.\n", + "One simple example is the **uniform distribution**, where $p(x_i) = 1/n$ for all $i$.\n", "\n", "We can import the uniform distribution on $S = \\{1, \\ldots, n\\}$ from SciPy like so:" ] @@ -111,7 +111,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3d1accc6", + "id": "5675218c", "metadata": {}, "outputs": [], "source": [ @@ -121,18 +121,16 @@ }, { "cell_type": "markdown", - "id": "eabf5709", - "metadata": { - "user_expressions": [] - }, + "id": "93a99d99", + "metadata": {}, "source": [ - "Here's the mean and variance" + "Here's the mean and variance:" ] }, { "cell_type": "code", "execution_count": null, - "id": "2132ed4c", + "id": "2f2a42ef", "metadata": {}, "outputs": [], "source": [ @@ -141,26 +139,19 @@ }, { "cell_type": "markdown", - "id": "2c82fb09", + "id": "ac47330c", "metadata": {}, "source": [ - "The formula for the mean is $(n+1)/2$, and the formula for the variance is $(n^2 - 1)/12$." - ] - }, - { - "cell_type": "markdown", - "id": "5986394a", - "metadata": { - "user_expressions": [] - }, - "source": [ - "Now let's evaluate the PMF" + "The formula for the mean is $(n+1)/2$, and the formula for the variance is $(n^2 - 1)/12$.\n", + "\n", + "\n", + "Now let's evaluate the PMF:" ] }, { "cell_type": "code", "execution_count": null, - "id": "5cdcd929", + "id": "a18db241", "metadata": {}, "outputs": [], "source": [ @@ -170,7 +161,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f2650e00", + "id": "a1ba348a", "metadata": {}, "outputs": [], "source": [ @@ -179,10 +170,8 @@ }, { "cell_type": "markdown", - "id": "ae8b2478", - "metadata": { - "user_expressions": [] - }, + "id": "1b4e3a52", + "metadata": {}, "source": [ "Here's a plot of the probability mass function:" ] @@ -190,7 +179,7 @@ { "cell_type": "code", "execution_count": null, - "id": "002c7e08", + "id": "033696a6", "metadata": {}, "outputs": [], "source": [ @@ -199,15 +188,15 @@ "ax.plot(S, u.pmf(S), linestyle='', marker='o', alpha=0.8, ms=4)\n", "ax.vlines(S, 0, u.pmf(S), lw=0.2)\n", "ax.set_xticks(S)\n", + "ax.set_xlabel('S')\n", + "ax.set_ylabel('PMF')\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "373d1778", - "metadata": { - "user_expressions": [] - }, + "id": "fb46b57a", + "metadata": {}, "source": [ "Here's a plot of the CDF:" ] @@ -215,7 +204,7 @@ { "cell_type": "code", "execution_count": null, - "id": "52f1c557", + "id": "75708695", "metadata": {}, "outputs": [], "source": [ @@ -224,55 +213,125 @@ "ax.step(S, u.cdf(S))\n", "ax.vlines(S, 0, u.cdf(S), lw=0.2)\n", "ax.set_xticks(S)\n", + "ax.set_xlabel('S')\n", + "ax.set_ylabel('CDF')\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "53fb5ab1", - "metadata": { - "user_expressions": [] - }, - "source": [ - "The CDF jumps up by $p(x_i)$ and $x_i$." - ] - }, - { - "cell_type": "markdown", - "id": "18c2ad49", - "metadata": { - "user_expressions": [] - }, + "id": "b1d70f5b", + "metadata": {}, "source": [ + "The CDF jumps up by $p(x_i)$ at $x_i$.\n", + "\n", "```{exercise}\n", ":label: prob_ex1\n", "\n", - "Calculate the mean and variance directly from the PMF, using the expressions given above.\n", + "Calculate the mean and variance for this parameterization (i.e., $n=10$)\n", + "directly from the PMF, using the expressions given above.\n", "\n", - "Check that your answers agree with `u.mean()` and `u.var()`.\n", + "Check that your answers agree with `u.mean()` and `u.var()`. \n", "```\n", "\n", + "\n", + "#### Bernoulli distribution\n", + "\n", + "Another useful distribution is the Bernoulli distribution on $S = \\{0,1\\}$, which has PMF:\n", + "\n", + "$$\n", + "p(i) = \\theta^i (1 - \\theta)^{1-i}\n", + "\\qquad (i = 0, 1)\n", + "$$\n", + "\n", + "Here $\\theta \\in [0,1]$ is a parameter.\n", + "\n", + "We can think of this distribution as modeling probabilities for a random trial with success probability $\\theta$.\n", + "\n", + "* $p(1) = \\theta$ means that the trial succeeds (takes value 1) with probability $\\theta$\n", + "* $p(0) = 1 - \\theta$ means that the trial fails (takes value 0) with\n", + " probability $1-\\theta$\n", + "\n", + "The formula for the mean is $\\theta$, and the formula for the variance is $\\theta(1-\\theta)$.\n", + "\n", + "We can import the Bernoulli distribution on $S = \\{0,1\\}$ from SciPy like so:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "162caef8", + "metadata": {}, + "outputs": [], + "source": [ + "θ = 0.4\n", + "u = scipy.stats.bernoulli(θ)" + ] + }, + { + "cell_type": "markdown", + "id": "b831c8f2", + "metadata": {}, + "source": [ + "Here's the mean and variance at $\\theta=0.4$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "11907b24", + "metadata": {}, + "outputs": [], + "source": [ + "u.mean(), u.var()" + ] + }, + { + "cell_type": "markdown", + "id": "bdcfb289", + "metadata": {}, + "source": [ + "We can evaluate the PMF as follows" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "320dd3a3", + "metadata": {}, + "outputs": [], + "source": [ + "u.pmf(0), u.pmf(1)" + ] + }, + { + "cell_type": "markdown", + "id": "e4ab8977", + "metadata": {}, + "source": [ "#### Binomial distribution\n", "\n", - "Another useful (and more interesting) distribution is the **binomial distribution** on $S=\\{0, \\ldots, n\\}$, which has PMF\n", + "Another useful (and more interesting) distribution is the **binomial distribution** on $S=\\{0, \\ldots, n\\}$, which has PMF:\n", "\n", "$$ \n", - " p(i) = \\binom{n}{i} \\theta^i (1-\\theta)^{n-i}\n", + "p(i) = \\binom{n}{i} \\theta^i (1-\\theta)^{n-i}\n", "$$\n", "\n", - "Here $\\theta \\in [0,1]$ is a parameter.\n", + "Again, $\\theta \\in [0,1]$ is a parameter.\n", "\n", - "The interpretation of $p(i)$ is: the number of successes in $n$ independent trials with success probability $\\theta$.\n", + "The interpretation of $p(i)$ is: the probability of $i$ successes in $n$ independent trials with success probability $\\theta$.\n", "\n", - "(If $\\theta=0.5$, this is \"how many heads in $n$ flips of a fair coin\")\n", + "For example, if $\\theta=0.5$, then $p(i)$ is the probability of $i$ heads in $n$ flips of a fair coin.\n", "\n", - "The mean and variance are" + "The formula for the mean is $n \\theta$ and the formula for the variance is $n \\theta (1-\\theta)$.\n", + "\n", + "Let's investigate an example" ] }, { "cell_type": "code", "execution_count": null, - "id": "1bde3103", + "id": "94d14f20", "metadata": {}, "outputs": [], "source": [ @@ -281,10 +340,36 @@ "u = scipy.stats.binom(n, θ)" ] }, + { + "cell_type": "markdown", + "id": "3815b6ee", + "metadata": {}, + "source": [ + "According to our formulas, the mean and variance are" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3197b6e5", + "metadata": {}, + "outputs": [], + "source": [ + "n * θ, n * θ * (1 - θ) " + ] + }, + { + "cell_type": "markdown", + "id": "e0e64e2a", + "metadata": {}, + "source": [ + "Let's see if SciPy gives us the same results:" + ] + }, { "cell_type": "code", "execution_count": null, - "id": "ff0797ab", + "id": "2afeb55f", "metadata": {}, "outputs": [], "source": [ @@ -293,18 +378,16 @@ }, { "cell_type": "markdown", - "id": "99b015c7", + "id": "40e7c0da", "metadata": {}, "source": [ - "The formula for the mean is $n \\theta$ and the formula for the variance is $n \\theta (1-\\theta)$.\n", - "\n", - "Here's the PDF" + "Here's the PMF:" ] }, { "cell_type": "code", "execution_count": null, - "id": "2c3ece5e", + "id": "67db1a5e", "metadata": {}, "outputs": [], "source": [ @@ -314,7 +397,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f374eb9e", + "id": "9da86060", "metadata": {}, "outputs": [], "source": [ @@ -323,23 +406,23 @@ "ax.plot(S, u.pmf(S), linestyle='', marker='o', alpha=0.8, ms=4)\n", "ax.vlines(S, 0, u.pmf(S), lw=0.2)\n", "ax.set_xticks(S)\n", + "ax.set_xlabel('S')\n", + "ax.set_ylabel('PMF')\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "1b4c3de7", - "metadata": { - "user_expressions": [] - }, + "id": "07ab264e", + "metadata": {}, "source": [ - "Here's the CDF" + "Here's the CDF:" ] }, { "cell_type": "code", "execution_count": null, - "id": "b9141169", + "id": "99aeefd5", "metadata": {}, "outputs": [], "source": [ @@ -348,33 +431,33 @@ "ax.step(S, u.cdf(S))\n", "ax.vlines(S, 0, u.cdf(S), lw=0.2)\n", "ax.set_xticks(S)\n", + "ax.set_xlabel('S')\n", + "ax.set_ylabel('CDF')\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "e225fd09", - "metadata": { - "user_expressions": [] - }, + "id": "1e9ec5ca", + "metadata": {}, "source": [ "```{exercise}\n", - ":label: prob_ex2\n", + ":label: prob_ex3\n", "\n", "Using `u.pmf`, check that our definition of the CDF given above calculates the same function as `u.cdf`.\n", "```\n", "\n", - "```{solution-start} prob_ex2\n", + "```{solution-start} prob_ex3\n", ":class: dropdown\n", "```\n", "\n", - "Here is one solution" + "Here is one solution:" ] }, { "cell_type": "code", "execution_count": null, - "id": "9cab46de", + "id": "1e9d5ba1", "metadata": {}, "outputs": [], "source": [ @@ -384,12 +467,14 @@ "ax.step(S, u_sum)\n", "ax.vlines(S, 0, u_sum, lw=0.2)\n", "ax.set_xticks(S)\n", + "ax.set_xlabel('S')\n", + "ax.set_ylabel('CDF')\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "8256c671", + "id": "c450c570", "metadata": {}, "source": [ "We can see that the output graph is the same as the one above.\n", @@ -397,65 +482,109 @@ "```{solution-end}\n", "```\n", "\n", - "#### Poisson distribution\n", + "#### Geometric distribution\n", "\n", - "Poisson distribution on $S = \\{0, 1, \\ldots\\}$ with parameter $\\lambda > 0$ has PMF\n", + "The geometric distribution has infinite support $S = \\{0, 1, 2, \\ldots\\}$ and its PMF is given by \n", "\n", "$$\n", - " p(i) = \\frac{\\lambda^i}{i!} e^{-\\lambda}\n", + "p(i) = (1 - \\theta)^i \\theta\n", "$$\n", "\n", - "The interpretation of $p(i)$ is: the number of events in a fixed time interval, where the events occur at a constant rate $\\lambda$ and independently of each other.\n", + "where $\\theta \\in [0,1]$ is a parameter\n", + "\n", + "(A discrete distribution has infinite support if the set of points to which it assigns positive probability is infinite.)\n", + "\n", + "To understand the distribution, think of repeated independent random trials, each with success probability $\\theta$.\n", + "\n", + "The interpretation of $p(i)$ is: the probability there are $i$ failures before the first success occurs.\n", + "\n", + "It can be shown that the mean of the distribution is $1/\\theta$ and the variance is $(1-\\theta)/\\theta$.\n", "\n", - "The mean and variance are" + "Here's an example." ] }, { "cell_type": "code", "execution_count": null, - "id": "f4d4876e", + "id": "bbc450be", "metadata": {}, "outputs": [], "source": [ - "λ = 2\n", - "u = scipy.stats.poisson(λ)" + "θ = 0.1\n", + "u = scipy.stats.geom(θ)\n", + "u.mean(), u.var()" + ] + }, + { + "cell_type": "markdown", + "id": "00addfc5", + "metadata": {}, + "source": [ + "Here's part of the PMF:" ] }, { "cell_type": "code", "execution_count": null, - "id": "c87d0e6f", + "id": "40bab3ff", "metadata": {}, "outputs": [], "source": [ - "u.mean(), u.var()" + "fig, ax = plt.subplots()\n", + "n = 20\n", + "S = np.arange(n)\n", + "ax.plot(S, u.pmf(S), linestyle='', marker='o', alpha=0.8, ms=4)\n", + "ax.vlines(S, 0, u.pmf(S), lw=0.2)\n", + "ax.set_xticks(S)\n", + "ax.set_xlabel('S')\n", + "ax.set_ylabel('PMF')\n", + "plt.show()" ] }, { "cell_type": "markdown", - "id": "0bb36098", + "id": "6a37ca4c", "metadata": {}, "source": [ - "The the expectation of Poisson distribution is $\\lambda$ and the variance is also $\\lambda$.\n", + "#### Poisson distribution\n", + "\n", + "The Poisson distribution on $S = \\{0, 1, \\ldots\\}$ with parameter $\\lambda > 0$ has PMF\n", + "\n", + "$$\n", + "p(i) = \\frac{\\lambda^i}{i!} e^{-\\lambda}\n", + "$$\n", + "\n", + "The interpretation of $p(i)$ is: the probability of $i$ events in a fixed time interval, where the events occur independently at a constant rate $\\lambda$.\n", "\n", - "Here's the PMF" + "It can be shown that the mean is $\\lambda$ and the variance is also $\\lambda$.\n", + "\n", + "Here's an example." ] }, { "cell_type": "code", "execution_count": null, - "id": "4959e726", + "id": "bf863847", "metadata": {}, "outputs": [], "source": [ "λ = 2\n", - "u = scipy.stats.poisson(λ)" + "u = scipy.stats.poisson(λ)\n", + "u.mean(), u.var()" + ] + }, + { + "cell_type": "markdown", + "id": "58e5ce24", + "metadata": {}, + "source": [ + "Here's the PMF:" ] }, { "cell_type": "code", "execution_count": null, - "id": "6070146f", + "id": "411d8046", "metadata": {}, "outputs": [], "source": [ @@ -465,7 +594,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3135c24a", + "id": "908a00da", "metadata": {}, "outputs": [], "source": [ @@ -474,34 +603,29 @@ "ax.plot(S, u.pmf(S), linestyle='', marker='o', alpha=0.8, ms=4)\n", "ax.vlines(S, 0, u.pmf(S), lw=0.2)\n", "ax.set_xticks(S)\n", + "ax.set_xlabel('S')\n", + "ax.set_ylabel('PMF')\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "86f7fbe4", - "metadata": { - "user_expressions": [] - }, - "source": [ - "### Continuous distributions" - ] - }, - { - "cell_type": "markdown", - "id": "a10e3bd1", - "metadata": { - "user_expressions": [] - }, + "id": "332c49ab", + "metadata": {}, "source": [ - "Continuous distributions are represented by a **density function**, which is a function $p$ over $\\mathbb R$ (the set of all numbers) such that $p(x) \\geq 0$ for all $x$ and\n", + "### Continuous distributions\n", + "\n", "\n", - "$$ \\int_{-\\infty}^\\infty p(x) dx = 1 $$\n", + "A continuous distribution is represented by a **probability density function**, which is a function $p$ over $\\mathbb R$ (the set of all real numbers) such that $p(x) \\geq 0$ for all $x$ and\n", + "\n", + "$$ \n", + "\\int_{-\\infty}^\\infty p(x) dx = 1 \n", + "$$\n", "\n", "We say that random variable $X$ has distribution $p$ if\n", "\n", "$$\n", - " \\mathbb P\\{a < X < b\\} = \\int_a^b p(x) dx\n", + "\\mathbb P\\{a < X < b\\} = \\int_a^b p(x) dx\n", "$$\n", "\n", "for all $a \\leq b$.\n", @@ -511,44 +635,37 @@ "For example, the mean of $X$ is\n", "\n", "$$\n", - " \\mathbb E X = \\int_{-\\infty}^\\infty x p(x) dx\n", + "\\mathbb{E}[X] = \\int_{-\\infty}^\\infty x p(x) dx\n", "$$\n", "\n", "The **cumulative distribution function** (CDF) of $X$ is defined by\n", "\n", "$$\n", - " F(x) = \\mathbb P\\{X \\leq x\\}\n", - " = \\int_{-\\infty}^x p(x) dx\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "43a7b053", - "metadata": { - "user_expressions": [] - }, - "source": [ + "F(x) = \\mathbb P\\{X \\leq x\\}\n", + " = \\int_{-\\infty}^x p(x) dx\n", + "$$\n", + "\n", + "\n", "#### Normal distribution\n", "\n", "Perhaps the most famous distribution is the **normal distribution**, which has density\n", "\n", "$$\n", - " p(x) = \\frac{1}{\\sqrt{2\\pi}\\sigma}\n", - " \\exp\\left(-\\frac{(x-\\mu)^2}{2\\sigma^2}\\right)\n", + "p(x) = \\frac{1}{\\sqrt{2\\pi}\\sigma}\n", + " \\exp\\left(-\\frac{(x-\\mu)^2}{2\\sigma^2}\\right)\n", "$$\n", "\n", - "This distribution has two parameters, $\\mu$ and $\\sigma$. \n", + "This distribution has two parameters, $\\mu \\in \\mathbb R$ and $\\sigma \\in (0, \\infty)$. \n", "\n", - "It can be shown that, for this distribution, the mean is $\\mu$ and the variance is $\\sigma^2$.\n", + "Using calculus, it can be shown that, for this distribution, the mean is $\\mu$ and the variance is $\\sigma^2$.\n", "\n", - "We can obtain the moments, PDF, and CDF of the normal density as follows:" + "We can obtain the moments, PDF and CDF of the normal density via SciPy as follows:" ] }, { "cell_type": "code", "execution_count": null, - "id": "2c029f7d", + "id": "d7099f38", "metadata": {}, "outputs": [], "source": [ @@ -559,7 +676,7 @@ { "cell_type": "code", "execution_count": null, - "id": "27484744", + "id": "092365e8", "metadata": {}, "outputs": [], "source": [ @@ -568,7 +685,7 @@ }, { "cell_type": "markdown", - "id": "4acae62f", + "id": "5364b41c", "metadata": {}, "source": [ "Here's a plot of the density --- the famous \"bell-shaped curve\":" @@ -577,7 +694,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6279841c", + "id": "ad801530", "metadata": {}, "outputs": [], "source": [ @@ -590,18 +707,17 @@ " u = scipy.stats.norm(μ, σ)\n", " ax.plot(x_grid, u.pdf(x_grid),\n", " alpha=0.5, lw=2,\n", - " label=f'$\\mu={μ}, \\sigma={σ}$')\n", - "\n", + " label=rf'$\\mu={μ}, \\sigma={σ}$')\n", + "ax.set_xlabel('x')\n", + "ax.set_ylabel('PDF')\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "e60e48f7", - "metadata": { - "user_expressions": [] - }, + "id": "3b0677c0", + "metadata": {}, "source": [ "Here's a plot of the CDF:" ] @@ -609,7 +725,7 @@ { "cell_type": "code", "execution_count": null, - "id": "19571bde", + "id": "26014ed7", "metadata": {}, "outputs": [], "source": [ @@ -618,43 +734,44 @@ " u = scipy.stats.norm(μ, σ)\n", " ax.plot(x_grid, u.cdf(x_grid),\n", " alpha=0.5, lw=2,\n", - " label=f'$\\mu={μ}, \\sigma={σ}$')\n", + " label=rf'$\\mu={μ}, \\sigma={σ}$')\n", " ax.set_ylim(0, 1)\n", + "ax.set_xlabel('x')\n", + "ax.set_ylabel('CDF')\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "a11c15c4", - "metadata": { - "user_expressions": [] - }, + "id": "75832bd8", + "metadata": {}, "source": [ "#### Lognormal distribution\n", "\n", "The **lognormal distribution** is a distribution on $\\left(0, \\infty\\right)$ with density\n", "\n", "$$\n", - " p(x) = \\frac{1}{\\sigma x \\sqrt{2\\pi}}\n", - " \\exp \\left(- \\frac{\\left(\\log x - \\mu\\right)^2}{2 \\sigma^2} \\right)\n", + "p(x) = \\frac{1}{\\sigma x \\sqrt{2\\pi}}\n", + " \\exp \\left(- \\frac{\\left(\\log x - \\mu\\right)^2}{2 \\sigma^2} \\right)\n", "$$\n", "\n", "This distribution has two parameters, $\\mu$ and $\\sigma$.\n", "\n", "It can be shown that, for this distribution, the mean is $\\exp\\left(\\mu + \\sigma^2/2\\right)$ and the variance is $\\left[\\exp\\left(\\sigma^2\\right) - 1\\right] \\exp\\left(2\\mu + \\sigma^2\\right)$.\n", "\n", - "It has a nice interpretation: if $X$ is lognormally distributed, then $\\log X$ is normally distributed.\n", + "It can be proved that \n", "\n", - "It is often used to model variables that are \"multiplicative\" in nature, such as income or asset prices.\n", + "* if $X$ is lognormally distributed, then $\\log X$ is normally distributed, and\n", + "* if $X$ is normally distributed, then $\\exp X$ is lognormally distributed.\n", "\n", - "We can obtain the moments, PDF, and CDF of the normal density as follows:" + "We can obtain the moments, PDF, and CDF of the lognormal density as follows:" ] }, { "cell_type": "code", "execution_count": null, - "id": "21da70d9", + "id": "3542d4e0", "metadata": {}, "outputs": [], "source": [ @@ -665,7 +782,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4d821092", + "id": "448861fd", "metadata": {}, "outputs": [], "source": [ @@ -675,7 +792,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3fd1a9bb", + "id": "64639e1d", "metadata": {}, "outputs": [], "source": [ @@ -689,7 +806,8 @@ " ax.plot(x_grid, u.pdf(x_grid),\n", " alpha=0.5, lw=2,\n", " label=f'$\\mu={μ}, \\sigma={σ}$')\n", - "\n", + "ax.set_xlabel('x')\n", + "ax.set_ylabel('PDF')\n", "plt.legend()\n", "plt.show()" ] @@ -697,7 +815,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f10ed958", + "id": "fb0dbe1f", "metadata": {}, "outputs": [], "source": [ @@ -707,39 +825,42 @@ " u = scipy.stats.norm(μ, σ)\n", " ax.plot(x_grid, u.cdf(x_grid),\n", " alpha=0.5, lw=2,\n", - " label=f'$\\mu={μ}, \\sigma={σ}$')\n", + " label=rf'$\\mu={μ}, \\sigma={σ}$')\n", " ax.set_ylim(0, 1)\n", " ax.set_xlim(0, 3)\n", + "ax.set_xlabel('x')\n", + "ax.set_ylabel('CDF')\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "ddb57a2f", + "id": "fb57d10c", "metadata": {}, "source": [ "#### Exponential distribution\n", "\n", - "The **exponential distribution** is a distribution on $\\left(0, \\infty\\right)$ with density\n", + "The **exponential distribution** is a distribution supported on $\\left(0, \\infty\\right)$ with density\n", "\n", "$$\n", - " p(x) = \\lambda \\exp \\left( - \\lambda x \\right)\n", + "p(x) = \\lambda \\exp \\left( - \\lambda x \\right)\n", + "\\qquad (x > 0)\n", "$$\n", "\n", - "This distribution has one parameter, $\\lambda$.\n", + "This distribution has one parameter $\\lambda$.\n", "\n", - "It is related to the Poisson distribution as it describes the distribution of the length of the time interval between two consecutive events in a Poisson process.\n", + "The exponential distribution can be thought of as the continuous analog of the geometric distribution.\n", "\n", "It can be shown that, for this distribution, the mean is $1/\\lambda$ and the variance is $1/\\lambda^2$.\n", "\n", - "We can obtain the moments, PDF, and CDF of the normal density as follows:" + "We can obtain the moments, PDF, and CDF of the exponential density as follows:" ] }, { "cell_type": "code", "execution_count": null, - "id": "1346dd2e", + "id": "f680aabd", "metadata": {}, "outputs": [], "source": [ @@ -750,7 +871,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4b2939c5", + "id": "86c578ce", "metadata": {}, "outputs": [], "source": [ @@ -760,7 +881,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9674589b", + "id": "04a3b066", "metadata": {}, "outputs": [], "source": [ @@ -772,7 +893,9 @@ " u = scipy.stats.expon(scale=1/λ)\n", " ax.plot(x_grid, u.pdf(x_grid),\n", " alpha=0.5, lw=2,\n", - " label=f'$\\lambda={λ}$')\n", + " label=rf'$\\lambda={λ}$')\n", + "ax.set_xlabel('x')\n", + "ax.set_ylabel('PDF')\n", "plt.legend()\n", "plt.show()" ] @@ -780,7 +903,7 @@ { "cell_type": "code", "execution_count": null, - "id": "33bd7d17", + "id": "4ca39d78", "metadata": {}, "outputs": [], "source": [ @@ -789,46 +912,45 @@ " u = scipy.stats.expon(scale=1/λ)\n", " ax.plot(x_grid, u.cdf(x_grid),\n", " alpha=0.5, lw=2,\n", - " label=f'$\\lambda={λ}$')\n", + " label=rf'$\\lambda={λ}$')\n", " ax.set_ylim(0, 1)\n", + "ax.set_xlabel('x')\n", + "ax.set_ylabel('CDF')\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "20142f10", + "id": "3cc7d44e", "metadata": {}, "source": [ "#### Beta distribution\n", "\n", - "The **beta distribution** is a distribution on $\\left(0, 1\\right)$ with density\n", + "The **beta distribution** is a distribution on $(0, 1)$ with density\n", "\n", "$$\n", - " p(x) = \\frac{\\Gamma(\\alpha + \\beta)}{\\Gamma(\\alpha) \\Gamma(\\beta)}\n", - " x^{\\alpha - 1} (1 - x)^{\\beta - 1}\n", + "p(x) = \\frac{\\Gamma(\\alpha + \\beta)}{\\Gamma(\\alpha) \\Gamma(\\beta)}\n", + " x^{\\alpha - 1} (1 - x)^{\\beta - 1}\n", "$$\n", "\n", - "where $\\Gamma$ is the gamma function ($\\Gamma(n) = (n - 1)!$ for $n \\in \\mathbb{N}$).\n", - "\n", - "This distribution has two parameters, $\\alpha$ and $\\beta$.\n", - "\n", - "It has a nice interpretation: if $X$ is beta distributed, then $X$ is the probability of success in a Bernoulli trial with a number of successes $\\alpha$ and a number of failures $\\beta$.\n", + "where $\\Gamma$ is the [gamma function](https://en.wikipedia.org/wiki/Gamma_function).\n", "\n", - "For example, if $\\alpha = \\beta = 1$, then the beta distribution is uniform on $\\left(0, 1\\right)$ as the number of successes and failures are both 1.\n", + "(The role of the gamma function is just to normalize the density, so that it\n", + "integrates to one.)\n", "\n", - "While, if $\\alpha = 3$ and $\\beta = 2$, then the beta distribution is located more towards 1 as there are more successes than failures.\n", + "This distribution has two parameters, $\\alpha > 0$ and $\\beta > 0$.\n", "\n", "It can be shown that, for this distribution, the mean is $\\alpha / (\\alpha + \\beta)$ and \n", "the variance is $\\alpha \\beta / (\\alpha + \\beta)^2 (\\alpha + \\beta + 1)$.\n", "\n", - "We can obtain the moments, PDF, and CDF of the normal density as follows:" + "We can obtain the moments, PDF, and CDF of the Beta density as follows:" ] }, { "cell_type": "code", "execution_count": null, - "id": "cbd38894", + "id": "02e963e1", "metadata": {}, "outputs": [], "source": [ @@ -839,7 +961,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c75d6140", + "id": "c96e2f33", "metadata": {}, "outputs": [], "source": [ @@ -849,7 +971,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3af5b072", + "id": "75bfe4a8", "metadata": {}, "outputs": [], "source": [ @@ -862,7 +984,9 @@ " u = scipy.stats.beta(α, β)\n", " ax.plot(x_grid, u.pdf(x_grid),\n", " alpha=0.5, lw=2,\n", - " label=fr'$\\alpha={α}, \\beta={β}$')\n", + " label=rf'$\\alpha={α}, \\beta={β}$')\n", + "ax.set_xlabel('x')\n", + "ax.set_ylabel('PDF')\n", "plt.legend()\n", "plt.show()" ] @@ -870,7 +994,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1dfb005c", + "id": "d275881b", "metadata": {}, "outputs": [], "source": [ @@ -879,15 +1003,17 @@ " u = scipy.stats.beta(α, β)\n", " ax.plot(x_grid, u.cdf(x_grid),\n", " alpha=0.5, lw=2,\n", - " label=fr'$\\alpha={α}, \\beta={β}$')\n", + " label=rf'$\\alpha={α}, \\beta={β}$')\n", " ax.set_ylim(0, 1)\n", + "ax.set_xlabel('x')\n", + "ax.set_ylabel('CDF')\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "fdd76076", + "id": "44fec723", "metadata": {}, "source": [ "#### Gamma distribution\n", @@ -895,23 +1021,26 @@ "The **gamma distribution** is a distribution on $\\left(0, \\infty\\right)$ with density\n", "\n", "$$\n", - " p(x) = \\frac{\\beta^\\alpha}{\\Gamma(\\alpha)}\n", - " x^{\\alpha - 1} \\exp(-\\beta x)\n", + "p(x) = \\frac{\\beta^\\alpha}{\\Gamma(\\alpha)}\n", + " x^{\\alpha - 1} \\exp(-\\beta x)\n", "$$\n", "\n", - "This distribution has two parameters, $\\alpha$ and $\\beta$.\n", + "This distribution has two parameters, $\\alpha > 0$ and $\\beta > 0$.\n", "\n", - "It can be shown that, for this distribution, the mean is $\\alpha / \\beta$ and the variance is $\\alpha / \\beta^2$.\n", + "It can be shown that, for this distribution, the mean is $\\alpha / \\beta$ and\n", + "the variance is $\\alpha / \\beta^2$.\n", "\n", - "One interpretation is that if $X$ is gamma distributed, then $X$ is the sum of $\\alpha$ independent exponentially distributed random variables with mean $1/\\beta$.\n", + "One interpretation is that if $X$ is gamma distributed and $\\alpha$ is an\n", + "integer, then $X$ is the sum of $\\alpha$ independent exponentially distributed\n", + "random variables with mean $1/\\beta$.\n", "\n", - "We can obtain the moments, PDF, and CDF of the normal density as follows:" + "We can obtain the moments, PDF, and CDF of the Gamma density as follows:" ] }, { "cell_type": "code", "execution_count": null, - "id": "ce57192a", + "id": "106d86b2", "metadata": {}, "outputs": [], "source": [ @@ -922,7 +1051,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c8ef261a", + "id": "40fb4e54", "metadata": {}, "outputs": [], "source": [ @@ -932,7 +1061,7 @@ { "cell_type": "code", "execution_count": null, - "id": "221d5445", + "id": "778c86bb", "metadata": {}, "outputs": [], "source": [ @@ -945,7 +1074,9 @@ " u = scipy.stats.gamma(α, scale=1/β)\n", " ax.plot(x_grid, u.pdf(x_grid),\n", " alpha=0.5, lw=2,\n", - " label=fr'$\\alpha={α}, \\beta={β}$')\n", + " label=rf'$\\alpha={α}, \\beta={β}$')\n", + "ax.set_xlabel('x')\n", + "ax.set_ylabel('PDF')\n", "plt.legend()\n", "plt.show()" ] @@ -953,7 +1084,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b758e7f3", + "id": "760edacb", "metadata": {}, "outputs": [], "source": [ @@ -962,27 +1093,22 @@ " u = scipy.stats.gamma(α, scale=1/β)\n", " ax.plot(x_grid, u.cdf(x_grid),\n", " alpha=0.5, lw=2,\n", - " label=fr'$\\alpha={α}, \\beta={β}$')\n", + " label=rf'$\\alpha={α}, \\beta={β}$')\n", " ax.set_ylim(0, 1)\n", + "ax.set_xlabel('x')\n", + "ax.set_ylabel('CDF')\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "90a501fe", + "id": "ea817025", "metadata": {}, "source": [ - "## Observed distributions" - ] - }, - { - "cell_type": "markdown", - "id": "0caea309", - "metadata": { - "user_expressions": [] - }, - "source": [ + "## Observed distributions\n", + "\n", + "\n", "Sometimes we refer to observed data or measurements as \"distributions\".\n", "\n", "For example, let's say we observe the income of 10 people over a year:" @@ -991,7 +1117,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c48964ef", + "id": "05c8cba6", "metadata": {}, "outputs": [], "source": [ @@ -1012,27 +1138,20 @@ }, { "cell_type": "markdown", - "id": "332f9787", - "metadata": { - "user_expressions": [] - }, + "id": "58875e77", + "metadata": {}, "source": [ "In this situation, we might refer to the set of their incomes as the \"income distribution.\"\n", "\n", - "The terminology is confusing because this is not the same thing as a probability distribution --- it's just a collection of numbers.\n", + "The terminology is confusing because this set is not a probability distribution\n", + "--- it's just a collection of numbers.\n", + "\n", + "However, as we will see, there are connections between observed distributions (i.e., sets of\n", + "numbers like the income distribution above) and probability distributions.\n", "\n", "Below we explore some observed distributions.\n", "\n", - "We will see that there are connections between observed distributions---like the income distribution above---and probability distributions, as we'll see below." - ] - }, - { - "cell_type": "markdown", - "id": "91237ce7", - "metadata": { - "user_expressions": [] - }, - "source": [ + "\n", "### Summary statistics\n", "\n", "Suppose we have an observed distribution with values $\\{x_1, \\ldots, x_n\\}$\n", @@ -1040,59 +1159,45 @@ "The **sample mean** of this distribution is defined as\n", "\n", "$$\n", - " \\bar x = \\frac{1}{n} \\sum_{i=1}^n x_i\n", + "\\bar x = \\frac{1}{n} \\sum_{i=1}^n x_i\n", "$$\n", "\n", "The **sample variance** is defined as \n", "\n", "$$\n", - " \\frac{1}{n} \\sum_{i=1}^n (x_i - \\bar x)^2\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e10e8187", - "metadata": { - "user_expressions": [] - }, - "source": [ + "\\frac{1}{n} \\sum_{i=1}^n (x_i - \\bar x)^2\n", + "$$\n", + "\n", "For the income distribution given above, we can calculate these numbers via" ] }, { "cell_type": "code", "execution_count": null, - "id": "30753d8a", - "metadata": {}, - "outputs": [], - "source": [ - "x = np.asarray(df['income'])" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fe29c1ba", + "id": "f189765f", "metadata": {}, "outputs": [], "source": [ + "x = df['income']\n", "x.mean(), x.var()" ] }, { "cell_type": "markdown", - "id": "7fbdb027", - "metadata": { - "user_expressions": [] - }, + "id": "4753483f", + "metadata": {}, "source": [ "```{exercise}\n", - ":label: prob_ex3\n", + ":label: prob_ex4\n", "\n", - "Check that the formulas given above produce the same numbers.\n", + "If you try to check that the formulas given above for the sample mean and sample\n", + "variance produce the same numbers, you will see that the variance isn't quite\n", + "right. This is because SciPy uses $1/(n-1)$ instead of $1/n$ as the term at the\n", + "front of the variance. (Some books define the sample variance this way.)\n", + "Confirm.\n", "```\n", "\n", + "\n", "### Visualization\n", "\n", "Let's look at different ways that we can visualize one or more observed distributions.\n", @@ -1101,52 +1206,36 @@ "\n", "- histograms\n", "- kernel density estimates and\n", - "- violin plots" - ] - }, - { - "cell_type": "markdown", - "id": "00eacdb3", - "metadata": { - "user_expressions": [] - }, - "source": [ - "#### Histograms" - ] - }, - { - "cell_type": "markdown", - "id": "1652dae5", - "metadata": { - "user_expressions": [] - }, - "source": [ + "- violin plots\n", + "\n", + "\n", + "#### Histograms\n", + "\n", "We can histogram the income distribution we just constructed as follows" ] }, { "cell_type": "code", "execution_count": null, - "id": "e698b780", + "id": "d6ef556d", "metadata": {}, "outputs": [], "source": [ - "x = df['income']\n", "fig, ax = plt.subplots()\n", "ax.hist(x, bins=5, density=True, histtype='bar')\n", + "ax.set_xlabel('income')\n", + "ax.set_ylabel('density')\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "f3b17b2f", - "metadata": { - "user_expressions": [] - }, + "id": "53e7709f", + "metadata": {}, "source": [ "Let's look at a distribution from real data.\n", "\n", - "In particular, we will look at the monthly return on Amazon shares between 2000/1/1 and 2023/1/1.\n", + "In particular, we will look at the monthly return on Amazon shares between 2000/1/1 and 2024/1/1.\n", "\n", "The monthly return is calculated as the percent change in the share price over each month.\n", "\n", @@ -1156,22 +1245,24 @@ { "cell_type": "code", "execution_count": null, - "id": "53afb479", - "metadata": {}, + "id": "d7c34a50", + "metadata": { + "tags": [ + "hide-output" + ] + }, "outputs": [], "source": [ - "df = yf.download('AMZN', '2000-1-1', '2023-1-1', interval='1mo' )\n", - "prices = df['Adj Close']\n", - "data = prices.pct_change()[1:] * 100\n", - "data.head()" + "df = yf.download('AMZN', '2000-1-1', '2024-1-1', interval='1mo')\n", + "prices = df['Close']\n", + "x_amazon = prices.pct_change()[1:] * 100\n", + "x_amazon.head()" ] }, { "cell_type": "markdown", - "id": "90f12a15", - "metadata": { - "user_expressions": [] - }, + "id": "26ab6700", + "metadata": {}, "source": [ "The first observation is the monthly return (percent change) over January 2000, which was" ] @@ -1179,74 +1270,67 @@ { "cell_type": "code", "execution_count": null, - "id": "e9fab719", + "id": "60beca22", "metadata": {}, "outputs": [], "source": [ - "data[0] " + "x_amazon.iloc[0]" ] }, { "cell_type": "markdown", - "id": "2a8250fb", - "metadata": { - "user_expressions": [] - }, - "source": [ - "Let's turn the return observations into an array and histogram it." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "86cc87ae", + "id": "fb4c2077", "metadata": {}, - "outputs": [], "source": [ - "x_amazon = np.asarray(data)" + "Let's turn the return observations into an array and histogram it." ] }, { "cell_type": "code", "execution_count": null, - "id": "500c5d10", + "id": "488e666d", "metadata": {}, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", "ax.hist(x_amazon, bins=20)\n", + "ax.set_xlabel('monthly return (percent change)')\n", + "ax.set_ylabel('density')\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "7b6d6bb4", - "metadata": { - "user_expressions": [] - }, + "id": "3615cb43", + "metadata": {}, "source": [ "#### Kernel density estimates\n", "\n", - "Kernel density estimate (KDE) is a non-parametric way to estimate and visualize the PDF of a distribution.\n", + "Kernel density estimates (KDE) provide a simple way to estimate and visualize the density of a distribution.\n", + "\n", + "If you are not familiar with KDEs, you can think of them as a smoothed\n", + "histogram.\n", "\n", - "KDE will generate a smooth curve that approximates the PDF." + "Let's have a look at a KDE formed from the Amazon return data." ] }, { "cell_type": "code", "execution_count": null, - "id": "4d5793b8", + "id": "7f4e0860", "metadata": {}, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", "sns.kdeplot(x_amazon, ax=ax)\n", + "ax.set_xlabel('monthly return (percent change)')\n", + "ax.set_ylabel('KDE')\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "15ee3c4b", + "id": "84e169a6", "metadata": {}, "source": [ "The smoothness of the KDE is dependent on how we choose the bandwidth." @@ -1255,7 +1339,7 @@ { "cell_type": "code", "execution_count": null, - "id": "09f90f7a", + "id": "257249ea", "metadata": {}, "outputs": [], "source": [ @@ -1263,13 +1347,15 @@ "sns.kdeplot(x_amazon, ax=ax, bw_adjust=0.1, alpha=0.5, label=\"bw=0.1\")\n", "sns.kdeplot(x_amazon, ax=ax, bw_adjust=0.5, alpha=0.5, label=\"bw=0.5\")\n", "sns.kdeplot(x_amazon, ax=ax, bw_adjust=1, alpha=0.5, label=\"bw=1\")\n", + "ax.set_xlabel('monthly return (percent change)')\n", + "ax.set_ylabel('KDE')\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "34230698", + "id": "89ebf544", "metadata": {}, "source": [ "When we use a larger bandwidth, the KDE is smoother.\n", @@ -1277,94 +1363,87 @@ "A suitable bandwidth is not too smooth (underfitting) or too wiggly (overfitting).\n", "\n", "\n", - "#### Violin plots" - ] - }, - { - "cell_type": "markdown", - "id": "fac535fc", - "metadata": { - "user_expressions": [] - }, - "source": [ - "Yet another way to display an observed distribution is via a violin plot." + "#### Violin plots\n", + "\n", + "\n", + "Another way to display an observed distribution is via a violin plot." ] }, { "cell_type": "code", "execution_count": null, - "id": "8c49db2b", + "id": "cb1b49d0", "metadata": {}, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", "ax.violinplot(x_amazon)\n", + "ax.set_ylabel('monthly return (percent change)')\n", + "ax.set_xlabel('KDE')\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "69f66dc1", - "metadata": { - "user_expressions": [] - }, + "id": "5875d923", + "metadata": {}, "source": [ "Violin plots are particularly useful when we want to compare different distributions.\n", "\n", - "For example, let's compare the monthly returns on Amazon shares with the monthly return on Apple shares." + "For example, let's compare the monthly returns on Amazon shares with the monthly return on Costco shares." ] }, { "cell_type": "code", "execution_count": null, - "id": "cf093c8d", - "metadata": {}, + "id": "b0b7dc88", + "metadata": { + "tags": [ + "hide-output" + ] + }, "outputs": [], "source": [ - "df = yf.download('AAPL', '2000-1-1', '2023-1-1', interval='1mo' )\n", - "prices = df['Adj Close']\n", - "data = prices.pct_change()[1:] * 100\n", - "x_apple = np.asarray(data)" + "df = yf.download('COST', '2000-1-1', '2024-1-1', interval='1mo')\n", + "prices = df['Close']\n", + "x_costco = prices.pct_change()[1:] * 100" ] }, { "cell_type": "code", "execution_count": null, - "id": "beb7cf66", + "id": "b0a870a6", "metadata": {}, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", - "ax.violinplot([x_amazon, x_apple])\n", + "ax.violinplot([x_amazon['AMZN'], x_costco['COST']])\n", + "ax.set_ylabel('monthly return (percent change)')\n", + "ax.set_xlabel('retailers')\n", + "\n", + "ax.set_xticks([1, 2])\n", + "ax.set_xticklabels(['Amazon', 'Costco'])\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "db4b1096", - "metadata": { - "user_expressions": [] - }, - "source": [ - "### Connection to probability distributions" - ] - }, - { - "cell_type": "markdown", - "id": "690a12fa", - "metadata": { - "user_expressions": [] - }, + "id": "94cc4f14", + "metadata": {}, "source": [ + "### Connection to probability distributions\n", + "\n", "Let's discuss the connection between observed distributions and probability distributions.\n", "\n", "Sometimes it's helpful to imagine that an observed distribution is generated by a particular probability distribution.\n", "\n", "For example, we might look at the returns from Amazon above and imagine that they were generated by a normal distribution.\n", "\n", - "Even though this is not true, it might be a helpful way to think about the data.\n", + "(Even though this is not true, it *might* be a helpful way to think about the data.)\n", "\n", - "Here we match a normal distribution to the Amazon monthly returns by setting the sample mean to the mean of the normal distribution and the sample variance equal to the variance.\n", + "Here we match a normal distribution to the Amazon monthly returns by setting the\n", + "sample mean to the mean of the normal distribution and the sample variance equal\n", + "to the variance.\n", "\n", "Then we plot the density and the histogram." ] @@ -1372,7 +1451,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4b9d8ae7", + "id": "9a6692d4", "metadata": {}, "outputs": [], "source": [ @@ -1385,7 +1464,7 @@ { "cell_type": "code", "execution_count": null, - "id": "0f58da90", + "id": "d0d98d81", "metadata": {}, "outputs": [], "source": [ @@ -1393,28 +1472,20 @@ "fig, ax = plt.subplots()\n", "ax.plot(x_grid, u.pdf(x_grid))\n", "ax.hist(x_amazon, density=True, bins=40)\n", + "ax.set_xlabel('monthly return (percent change)')\n", + "ax.set_ylabel('density')\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "1d2e4656", - "metadata": { - "user_expressions": [] - }, + "id": "d91e4dc6", + "metadata": {}, "source": [ - "The match between the histogram and the density is not very bad but also not very good.\n", + "The match between the histogram and the density is not bad but also not very good.\n", + "\n", + "One reason is that the normal distribution is not really a good fit for this observed data --- we will discuss this point again when we talk about {ref}`heavy tailed distributions`.\n", "\n", - "One reason is that the normal distribution is not really a good fit for this observed data --- we will discuss this point again when we talk about {ref}`heavy tailed distributions`." - ] - }, - { - "cell_type": "markdown", - "id": "09121fbd", - "metadata": { - "user_expressions": [] - }, - "source": [ "Of course, if the data really *is* generated by the normal distribution, then the fit will be better.\n", "\n", "Let's see this in action\n", @@ -1426,7 +1497,7 @@ { "cell_type": "code", "execution_count": null, - "id": "936e8893", + "id": "20c856d6", "metadata": {}, "outputs": [], "source": [ @@ -1438,15 +1509,15 @@ "fig, ax = plt.subplots()\n", "ax.plot(x_grid, u.pdf(x_grid))\n", "ax.hist(x_draws, density=True, bins=40)\n", + "ax.set_xlabel('x')\n", + "ax.set_ylabel('density')\n", "plt.show()" ] }, { "cell_type": "markdown", - "id": "7b477a6b", - "metadata": { - "user_expressions": [] - }, + "id": "2d3713a5", + "metadata": {}, "source": [ "Note that if you keep increasing $N$, which is the number of observations, the fit will get better and better.\n", "\n", @@ -1455,12 +1526,118 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.16.6" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 12, + 23, + 29, + 36, + 96, + 99, + 103, + 105, + 112, + 116, + 118, + 122, + 131, + 135, + 144, + 179, + 182, + 186, + 188, + 192, + 194, + 214, + 218, + 222, + 224, + 228, + 230, + 234, + 238, + 247, + 251, + 260, + 274, + 284, + 311, + 315, + 319, + 329, + 345, + 349, + 353, + 357, + 366, + 416, + 421, + 423, + 427, + 442, + 446, + 458, + 480, + 485, + 489, + 506, + 520, + 539, + 544, + 548, + 564, + 576, + 599, + 604, + 608, + 625, + 637, + 659, + 664, + 668, + 685, + 697, + 706, + 720, + 751, + 754, + 782, + 788, + 798, + 805, + 809, + 811, + 815, + 821, + 832, + 838, + 842, + 851, + 863, + 869, + 875, + 883, + 892, + 910, + 917, + 925, + 938, + 950 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/prob_dist.md b/book/_build/html/_sources/prob_dist.md new file mode 100644 index 0000000..8db7371 --- /dev/null +++ b/book/_build/html/_sources/prob_dist.md @@ -0,0 +1,954 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.16.6 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Distributions and Probabilities + +```{index} single: Distributions and Probabilities +``` + +## Outline + +In this lecture we give a quick introduction to data and probability distributions using Python. + +```{code-cell} ipython3 +:tags: [hide-output] + +%pip install --upgrade yfinance +``` + +```{code-cell} ipython3 +import matplotlib.pyplot as plt +import pandas as pd +import numpy as np +import yfinance as yf +import scipy.stats +import seaborn as sns +``` + +## Common distributions + +In this section we recall the definitions of some well-known distributions and explore how to manipulate them with SciPy. + +### Discrete distributions + +Let's start with discrete distributions. + +A discrete distribution is defined by a set of numbers $S = \{x_1, \ldots, x_n\}$ and a **probability mass function** (PMF) on $S$, which is a function $p$ from $S$ to $[0,1]$ with the property + +$$ +\sum_{i=1}^n p(x_i) = 1 +$$ + +We say that a random variable $X$ **has distribution** $p$ if $X$ takes value $x_i$ with probability $p(x_i)$. + +That is, + +$$ +\mathbb P\{X = x_i\} = p(x_i) \quad \text{for } i= 1, \ldots, n +$$ + +The **mean** or **expected value** of a random variable $X$ with distribution $p$ is + +$$ +\mathbb{E}[X] = \sum_{i=1}^n x_i p(x_i) +$$ + +Expectation is also called the *first moment* of the distribution. + +We also refer to this number as the mean of the distribution (represented by) $p$. + +The **variance** of $X$ is defined as + +$$ +\mathbb{V}[X] = \sum_{i=1}^n (x_i - \mathbb{E}[X])^2 p(x_i) +$$ + +Variance is also called the *second central moment* of the distribution. + +The **cumulative distribution function** (CDF) of $X$ is defined by + +$$ +F(x) = \mathbb{P}\{X \leq x\} + = \sum_{i=1}^n \mathbb 1\{x_i \leq x\} p(x_i) +$$ + +Here $\mathbb 1\{ \textrm{statement} \} = 1$ if "statement" is true and zero otherwise. + +Hence the second term takes all $x_i \leq x$ and sums their probabilities. + + +#### Uniform distribution + +One simple example is the **uniform distribution**, where $p(x_i) = 1/n$ for all $i$. + +We can import the uniform distribution on $S = \{1, \ldots, n\}$ from SciPy like so: + +```{code-cell} ipython3 +n = 10 +u = scipy.stats.randint(1, n+1) +``` + +Here's the mean and variance: + +```{code-cell} ipython3 +u.mean(), u.var() +``` + +The formula for the mean is $(n+1)/2$, and the formula for the variance is $(n^2 - 1)/12$. + + +Now let's evaluate the PMF: + +```{code-cell} ipython3 +u.pmf(1) +``` + +```{code-cell} ipython3 +u.pmf(2) +``` + +Here's a plot of the probability mass function: + +```{code-cell} ipython3 +fig, ax = plt.subplots() +S = np.arange(1, n+1) +ax.plot(S, u.pmf(S), linestyle='', marker='o', alpha=0.8, ms=4) +ax.vlines(S, 0, u.pmf(S), lw=0.2) +ax.set_xticks(S) +ax.set_xlabel('S') +ax.set_ylabel('PMF') +plt.show() +``` + +Here's a plot of the CDF: + +```{code-cell} ipython3 +fig, ax = plt.subplots() +S = np.arange(1, n+1) +ax.step(S, u.cdf(S)) +ax.vlines(S, 0, u.cdf(S), lw=0.2) +ax.set_xticks(S) +ax.set_xlabel('S') +ax.set_ylabel('CDF') +plt.show() +``` + +The CDF jumps up by $p(x_i)$ at $x_i$. + +```{exercise} +:label: prob_ex1 + +Calculate the mean and variance for this parameterization (i.e., $n=10$) +directly from the PMF, using the expressions given above. + +Check that your answers agree with `u.mean()` and `u.var()`. +``` + + +#### Bernoulli distribution + +Another useful distribution is the Bernoulli distribution on $S = \{0,1\}$, which has PMF: + +$$ +p(i) = \theta^i (1 - \theta)^{1-i} +\qquad (i = 0, 1) +$$ + +Here $\theta \in [0,1]$ is a parameter. + +We can think of this distribution as modeling probabilities for a random trial with success probability $\theta$. + +* $p(1) = \theta$ means that the trial succeeds (takes value 1) with probability $\theta$ +* $p(0) = 1 - \theta$ means that the trial fails (takes value 0) with + probability $1-\theta$ + +The formula for the mean is $\theta$, and the formula for the variance is $\theta(1-\theta)$. + +We can import the Bernoulli distribution on $S = \{0,1\}$ from SciPy like so: + +```{code-cell} ipython3 +θ = 0.4 +u = scipy.stats.bernoulli(θ) +``` + +Here's the mean and variance at $\theta=0.4$ + +```{code-cell} ipython3 +u.mean(), u.var() +``` + +We can evaluate the PMF as follows + +```{code-cell} ipython3 +u.pmf(0), u.pmf(1) +``` + +#### Binomial distribution + +Another useful (and more interesting) distribution is the **binomial distribution** on $S=\{0, \ldots, n\}$, which has PMF: + +$$ +p(i) = \binom{n}{i} \theta^i (1-\theta)^{n-i} +$$ + +Again, $\theta \in [0,1]$ is a parameter. + +The interpretation of $p(i)$ is: the probability of $i$ successes in $n$ independent trials with success probability $\theta$. + +For example, if $\theta=0.5$, then $p(i)$ is the probability of $i$ heads in $n$ flips of a fair coin. + +The formula for the mean is $n \theta$ and the formula for the variance is $n \theta (1-\theta)$. + +Let's investigate an example + +```{code-cell} ipython3 +n = 10 +θ = 0.5 +u = scipy.stats.binom(n, θ) +``` + +According to our formulas, the mean and variance are + +```{code-cell} ipython3 +n * θ, n * θ * (1 - θ) +``` + +Let's see if SciPy gives us the same results: + +```{code-cell} ipython3 +u.mean(), u.var() +``` + +Here's the PMF: + +```{code-cell} ipython3 +u.pmf(1) +``` + +```{code-cell} ipython3 +fig, ax = plt.subplots() +S = np.arange(1, n+1) +ax.plot(S, u.pmf(S), linestyle='', marker='o', alpha=0.8, ms=4) +ax.vlines(S, 0, u.pmf(S), lw=0.2) +ax.set_xticks(S) +ax.set_xlabel('S') +ax.set_ylabel('PMF') +plt.show() +``` + +Here's the CDF: + +```{code-cell} ipython3 +fig, ax = plt.subplots() +S = np.arange(1, n+1) +ax.step(S, u.cdf(S)) +ax.vlines(S, 0, u.cdf(S), lw=0.2) +ax.set_xticks(S) +ax.set_xlabel('S') +ax.set_ylabel('CDF') +plt.show() +``` + +```{exercise} +:label: prob_ex3 + +Using `u.pmf`, check that our definition of the CDF given above calculates the same function as `u.cdf`. +``` + +```{solution-start} prob_ex3 +:class: dropdown +``` + +Here is one solution: + +```{code-cell} ipython3 +fig, ax = plt.subplots() +S = np.arange(1, n+1) +u_sum = np.cumsum(u.pmf(S)) +ax.step(S, u_sum) +ax.vlines(S, 0, u_sum, lw=0.2) +ax.set_xticks(S) +ax.set_xlabel('S') +ax.set_ylabel('CDF') +plt.show() +``` + +We can see that the output graph is the same as the one above. + +```{solution-end} +``` + +#### Geometric distribution + +The geometric distribution has infinite support $S = \{0, 1, 2, \ldots\}$ and its PMF is given by + +$$ +p(i) = (1 - \theta)^i \theta +$$ + +where $\theta \in [0,1]$ is a parameter + +(A discrete distribution has infinite support if the set of points to which it assigns positive probability is infinite.) + +To understand the distribution, think of repeated independent random trials, each with success probability $\theta$. + +The interpretation of $p(i)$ is: the probability there are $i$ failures before the first success occurs. + +It can be shown that the mean of the distribution is $1/\theta$ and the variance is $(1-\theta)/\theta$. + +Here's an example. + +```{code-cell} ipython3 +θ = 0.1 +u = scipy.stats.geom(θ) +u.mean(), u.var() +``` + +Here's part of the PMF: + +```{code-cell} ipython3 +fig, ax = plt.subplots() +n = 20 +S = np.arange(n) +ax.plot(S, u.pmf(S), linestyle='', marker='o', alpha=0.8, ms=4) +ax.vlines(S, 0, u.pmf(S), lw=0.2) +ax.set_xticks(S) +ax.set_xlabel('S') +ax.set_ylabel('PMF') +plt.show() +``` + +#### Poisson distribution + +The Poisson distribution on $S = \{0, 1, \ldots\}$ with parameter $\lambda > 0$ has PMF + +$$ +p(i) = \frac{\lambda^i}{i!} e^{-\lambda} +$$ + +The interpretation of $p(i)$ is: the probability of $i$ events in a fixed time interval, where the events occur independently at a constant rate $\lambda$. + +It can be shown that the mean is $\lambda$ and the variance is also $\lambda$. + +Here's an example. + +```{code-cell} ipython3 +λ = 2 +u = scipy.stats.poisson(λ) +u.mean(), u.var() +``` + +Here's the PMF: + +```{code-cell} ipython3 +u.pmf(1) +``` + +```{code-cell} ipython3 +fig, ax = plt.subplots() +S = np.arange(1, n+1) +ax.plot(S, u.pmf(S), linestyle='', marker='o', alpha=0.8, ms=4) +ax.vlines(S, 0, u.pmf(S), lw=0.2) +ax.set_xticks(S) +ax.set_xlabel('S') +ax.set_ylabel('PMF') +plt.show() +``` + +### Continuous distributions + + +A continuous distribution is represented by a **probability density function**, which is a function $p$ over $\mathbb R$ (the set of all real numbers) such that $p(x) \geq 0$ for all $x$ and + +$$ +\int_{-\infty}^\infty p(x) dx = 1 +$$ + +We say that random variable $X$ has distribution $p$ if + +$$ +\mathbb P\{a < X < b\} = \int_a^b p(x) dx +$$ + +for all $a \leq b$. + +The definition of the mean and variance of a random variable $X$ with distribution $p$ are the same as the discrete case, after replacing the sum with an integral. + +For example, the mean of $X$ is + +$$ +\mathbb{E}[X] = \int_{-\infty}^\infty x p(x) dx +$$ + +The **cumulative distribution function** (CDF) of $X$ is defined by + +$$ +F(x) = \mathbb P\{X \leq x\} + = \int_{-\infty}^x p(x) dx +$$ + + +#### Normal distribution + +Perhaps the most famous distribution is the **normal distribution**, which has density + +$$ +p(x) = \frac{1}{\sqrt{2\pi}\sigma} + \exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right) +$$ + +This distribution has two parameters, $\mu \in \mathbb R$ and $\sigma \in (0, \infty)$. + +Using calculus, it can be shown that, for this distribution, the mean is $\mu$ and the variance is $\sigma^2$. + +We can obtain the moments, PDF and CDF of the normal density via SciPy as follows: + +```{code-cell} ipython3 +μ, σ = 0.0, 1.0 +u = scipy.stats.norm(μ, σ) +``` + +```{code-cell} ipython3 +u.mean(), u.var() +``` + +Here's a plot of the density --- the famous "bell-shaped curve": + +```{code-cell} ipython3 +μ_vals = [-1, 0, 1] +σ_vals = [0.4, 1, 1.6] +fig, ax = plt.subplots() +x_grid = np.linspace(-4, 4, 200) + +for μ, σ in zip(μ_vals, σ_vals): + u = scipy.stats.norm(μ, σ) + ax.plot(x_grid, u.pdf(x_grid), + alpha=0.5, lw=2, + label=rf'$\mu={μ}, \sigma={σ}$') +ax.set_xlabel('x') +ax.set_ylabel('PDF') +plt.legend() +plt.show() +``` + +Here's a plot of the CDF: + +```{code-cell} ipython3 +fig, ax = plt.subplots() +for μ, σ in zip(μ_vals, σ_vals): + u = scipy.stats.norm(μ, σ) + ax.plot(x_grid, u.cdf(x_grid), + alpha=0.5, lw=2, + label=rf'$\mu={μ}, \sigma={σ}$') + ax.set_ylim(0, 1) +ax.set_xlabel('x') +ax.set_ylabel('CDF') +plt.legend() +plt.show() +``` + +#### Lognormal distribution + +The **lognormal distribution** is a distribution on $\left(0, \infty\right)$ with density + +$$ +p(x) = \frac{1}{\sigma x \sqrt{2\pi}} + \exp \left(- \frac{\left(\log x - \mu\right)^2}{2 \sigma^2} \right) +$$ + +This distribution has two parameters, $\mu$ and $\sigma$. + +It can be shown that, for this distribution, the mean is $\exp\left(\mu + \sigma^2/2\right)$ and the variance is $\left[\exp\left(\sigma^2\right) - 1\right] \exp\left(2\mu + \sigma^2\right)$. + +It can be proved that + +* if $X$ is lognormally distributed, then $\log X$ is normally distributed, and +* if $X$ is normally distributed, then $\exp X$ is lognormally distributed. + +We can obtain the moments, PDF, and CDF of the lognormal density as follows: + +```{code-cell} ipython3 +μ, σ = 0.0, 1.0 +u = scipy.stats.lognorm(s=σ, scale=np.exp(μ)) +``` + +```{code-cell} ipython3 +u.mean(), u.var() +``` + +```{code-cell} ipython3 +μ_vals = [-1, 0, 1] +σ_vals = [0.25, 0.5, 1] +x_grid = np.linspace(0, 3, 200) + +fig, ax = plt.subplots() +for μ, σ in zip(μ_vals, σ_vals): + u = scipy.stats.lognorm(σ, scale=np.exp(μ)) + ax.plot(x_grid, u.pdf(x_grid), + alpha=0.5, lw=2, + label=f'$\mu={μ}, \sigma={σ}$') +ax.set_xlabel('x') +ax.set_ylabel('PDF') +plt.legend() +plt.show() +``` + +```{code-cell} ipython3 +fig, ax = plt.subplots() +μ = 1 +for σ in σ_vals: + u = scipy.stats.norm(μ, σ) + ax.plot(x_grid, u.cdf(x_grid), + alpha=0.5, lw=2, + label=rf'$\mu={μ}, \sigma={σ}$') + ax.set_ylim(0, 1) + ax.set_xlim(0, 3) +ax.set_xlabel('x') +ax.set_ylabel('CDF') +plt.legend() +plt.show() +``` + +#### Exponential distribution + +The **exponential distribution** is a distribution supported on $\left(0, \infty\right)$ with density + +$$ +p(x) = \lambda \exp \left( - \lambda x \right) +\qquad (x > 0) +$$ + +This distribution has one parameter $\lambda$. + +The exponential distribution can be thought of as the continuous analog of the geometric distribution. + +It can be shown that, for this distribution, the mean is $1/\lambda$ and the variance is $1/\lambda^2$. + +We can obtain the moments, PDF, and CDF of the exponential density as follows: + +```{code-cell} ipython3 +λ = 1.0 +u = scipy.stats.expon(scale=1/λ) +``` + +```{code-cell} ipython3 +u.mean(), u.var() +``` + +```{code-cell} ipython3 +fig, ax = plt.subplots() +λ_vals = [0.5, 1, 2] +x_grid = np.linspace(0, 6, 200) + +for λ in λ_vals: + u = scipy.stats.expon(scale=1/λ) + ax.plot(x_grid, u.pdf(x_grid), + alpha=0.5, lw=2, + label=rf'$\lambda={λ}$') +ax.set_xlabel('x') +ax.set_ylabel('PDF') +plt.legend() +plt.show() +``` + +```{code-cell} ipython3 +fig, ax = plt.subplots() +for λ in λ_vals: + u = scipy.stats.expon(scale=1/λ) + ax.plot(x_grid, u.cdf(x_grid), + alpha=0.5, lw=2, + label=rf'$\lambda={λ}$') + ax.set_ylim(0, 1) +ax.set_xlabel('x') +ax.set_ylabel('CDF') +plt.legend() +plt.show() +``` + +#### Beta distribution + +The **beta distribution** is a distribution on $(0, 1)$ with density + +$$ +p(x) = \frac{\Gamma(\alpha + \beta)}{\Gamma(\alpha) \Gamma(\beta)} + x^{\alpha - 1} (1 - x)^{\beta - 1} +$$ + +where $\Gamma$ is the [gamma function](https://en.wikipedia.org/wiki/Gamma_function). + +(The role of the gamma function is just to normalize the density, so that it +integrates to one.) + +This distribution has two parameters, $\alpha > 0$ and $\beta > 0$. + +It can be shown that, for this distribution, the mean is $\alpha / (\alpha + \beta)$ and +the variance is $\alpha \beta / (\alpha + \beta)^2 (\alpha + \beta + 1)$. + +We can obtain the moments, PDF, and CDF of the Beta density as follows: + +```{code-cell} ipython3 +α, β = 3.0, 1.0 +u = scipy.stats.beta(α, β) +``` + +```{code-cell} ipython3 +u.mean(), u.var() +``` + +```{code-cell} ipython3 +α_vals = [0.5, 1, 5, 25, 3] +β_vals = [3, 1, 10, 20, 0.5] +x_grid = np.linspace(0, 1, 200) + +fig, ax = plt.subplots() +for α, β in zip(α_vals, β_vals): + u = scipy.stats.beta(α, β) + ax.plot(x_grid, u.pdf(x_grid), + alpha=0.5, lw=2, + label=rf'$\alpha={α}, \beta={β}$') +ax.set_xlabel('x') +ax.set_ylabel('PDF') +plt.legend() +plt.show() +``` + +```{code-cell} ipython3 +fig, ax = plt.subplots() +for α, β in zip(α_vals, β_vals): + u = scipy.stats.beta(α, β) + ax.plot(x_grid, u.cdf(x_grid), + alpha=0.5, lw=2, + label=rf'$\alpha={α}, \beta={β}$') + ax.set_ylim(0, 1) +ax.set_xlabel('x') +ax.set_ylabel('CDF') +plt.legend() +plt.show() +``` + +#### Gamma distribution + +The **gamma distribution** is a distribution on $\left(0, \infty\right)$ with density + +$$ +p(x) = \frac{\beta^\alpha}{\Gamma(\alpha)} + x^{\alpha - 1} \exp(-\beta x) +$$ + +This distribution has two parameters, $\alpha > 0$ and $\beta > 0$. + +It can be shown that, for this distribution, the mean is $\alpha / \beta$ and +the variance is $\alpha / \beta^2$. + +One interpretation is that if $X$ is gamma distributed and $\alpha$ is an +integer, then $X$ is the sum of $\alpha$ independent exponentially distributed +random variables with mean $1/\beta$. + +We can obtain the moments, PDF, and CDF of the Gamma density as follows: + +```{code-cell} ipython3 +α, β = 3.0, 2.0 +u = scipy.stats.gamma(α, scale=1/β) +``` + +```{code-cell} ipython3 +u.mean(), u.var() +``` + +```{code-cell} ipython3 +α_vals = [1, 3, 5, 10] +β_vals = [3, 5, 3, 3] +x_grid = np.linspace(0, 7, 200) + +fig, ax = plt.subplots() +for α, β in zip(α_vals, β_vals): + u = scipy.stats.gamma(α, scale=1/β) + ax.plot(x_grid, u.pdf(x_grid), + alpha=0.5, lw=2, + label=rf'$\alpha={α}, \beta={β}$') +ax.set_xlabel('x') +ax.set_ylabel('PDF') +plt.legend() +plt.show() +``` + +```{code-cell} ipython3 +fig, ax = plt.subplots() +for α, β in zip(α_vals, β_vals): + u = scipy.stats.gamma(α, scale=1/β) + ax.plot(x_grid, u.cdf(x_grid), + alpha=0.5, lw=2, + label=rf'$\alpha={α}, \beta={β}$') + ax.set_ylim(0, 1) +ax.set_xlabel('x') +ax.set_ylabel('CDF') +plt.legend() +plt.show() +``` + +## Observed distributions + + +Sometimes we refer to observed data or measurements as "distributions". + +For example, let's say we observe the income of 10 people over a year: + +```{code-cell} ipython3 +data = [['Hiroshi', 1200], + ['Ako', 1210], + ['Emi', 1400], + ['Daiki', 990], + ['Chiyo', 1530], + ['Taka', 1210], + ['Katsuhiko', 1240], + ['Daisuke', 1124], + ['Yoshi', 1330], + ['Rie', 1340]] + +df = pd.DataFrame(data, columns=['name', 'income']) +df +``` + +In this situation, we might refer to the set of their incomes as the "income distribution." + +The terminology is confusing because this set is not a probability distribution +--- it's just a collection of numbers. + +However, as we will see, there are connections between observed distributions (i.e., sets of +numbers like the income distribution above) and probability distributions. + +Below we explore some observed distributions. + + +### Summary statistics + +Suppose we have an observed distribution with values $\{x_1, \ldots, x_n\}$ + +The **sample mean** of this distribution is defined as + +$$ +\bar x = \frac{1}{n} \sum_{i=1}^n x_i +$$ + +The **sample variance** is defined as + +$$ +\frac{1}{n} \sum_{i=1}^n (x_i - \bar x)^2 +$$ + +For the income distribution given above, we can calculate these numbers via + +```{code-cell} ipython3 +x = df['income'] +x.mean(), x.var() +``` + +```{exercise} +:label: prob_ex4 + +If you try to check that the formulas given above for the sample mean and sample +variance produce the same numbers, you will see that the variance isn't quite +right. This is because SciPy uses $1/(n-1)$ instead of $1/n$ as the term at the +front of the variance. (Some books define the sample variance this way.) +Confirm. +``` + + +### Visualization + +Let's look at different ways that we can visualize one or more observed distributions. + +We will cover + +- histograms +- kernel density estimates and +- violin plots + + +#### Histograms + +We can histogram the income distribution we just constructed as follows + +```{code-cell} ipython3 +fig, ax = plt.subplots() +ax.hist(x, bins=5, density=True, histtype='bar') +ax.set_xlabel('income') +ax.set_ylabel('density') +plt.show() +``` + +Let's look at a distribution from real data. + +In particular, we will look at the monthly return on Amazon shares between 2000/1/1 and 2024/1/1. + +The monthly return is calculated as the percent change in the share price over each month. + +So we will have one observation for each month. + +```{code-cell} ipython3 +:tags: [hide-output] + +df = yf.download('AMZN', '2000-1-1', '2024-1-1', interval='1mo') +prices = df['Close'] +x_amazon = prices.pct_change()[1:] * 100 +x_amazon.head() +``` + +The first observation is the monthly return (percent change) over January 2000, which was + +```{code-cell} ipython3 +x_amazon.iloc[0] +``` + +Let's turn the return observations into an array and histogram it. + +```{code-cell} ipython3 +fig, ax = plt.subplots() +ax.hist(x_amazon, bins=20) +ax.set_xlabel('monthly return (percent change)') +ax.set_ylabel('density') +plt.show() +``` + +#### Kernel density estimates + +Kernel density estimates (KDE) provide a simple way to estimate and visualize the density of a distribution. + +If you are not familiar with KDEs, you can think of them as a smoothed +histogram. + +Let's have a look at a KDE formed from the Amazon return data. + +```{code-cell} ipython3 +fig, ax = plt.subplots() +sns.kdeplot(x_amazon, ax=ax) +ax.set_xlabel('monthly return (percent change)') +ax.set_ylabel('KDE') +plt.show() +``` + +The smoothness of the KDE is dependent on how we choose the bandwidth. + +```{code-cell} ipython3 +fig, ax = plt.subplots() +sns.kdeplot(x_amazon, ax=ax, bw_adjust=0.1, alpha=0.5, label="bw=0.1") +sns.kdeplot(x_amazon, ax=ax, bw_adjust=0.5, alpha=0.5, label="bw=0.5") +sns.kdeplot(x_amazon, ax=ax, bw_adjust=1, alpha=0.5, label="bw=1") +ax.set_xlabel('monthly return (percent change)') +ax.set_ylabel('KDE') +plt.legend() +plt.show() +``` + +When we use a larger bandwidth, the KDE is smoother. + +A suitable bandwidth is not too smooth (underfitting) or too wiggly (overfitting). + + +#### Violin plots + + +Another way to display an observed distribution is via a violin plot. + +```{code-cell} ipython3 +fig, ax = plt.subplots() +ax.violinplot(x_amazon) +ax.set_ylabel('monthly return (percent change)') +ax.set_xlabel('KDE') +plt.show() +``` + +Violin plots are particularly useful when we want to compare different distributions. + +For example, let's compare the monthly returns on Amazon shares with the monthly return on Costco shares. + +```{code-cell} ipython3 +:tags: [hide-output] + +df = yf.download('COST', '2000-1-1', '2024-1-1', interval='1mo') +prices = df['Close'] +x_costco = prices.pct_change()[1:] * 100 +``` + +```{code-cell} ipython3 +fig, ax = plt.subplots() +ax.violinplot([x_amazon['AMZN'], x_costco['COST']]) +ax.set_ylabel('monthly return (percent change)') +ax.set_xlabel('retailers') + +ax.set_xticks([1, 2]) +ax.set_xticklabels(['Amazon', 'Costco']) +plt.show() +``` + +### Connection to probability distributions + +Let's discuss the connection between observed distributions and probability distributions. + +Sometimes it's helpful to imagine that an observed distribution is generated by a particular probability distribution. + +For example, we might look at the returns from Amazon above and imagine that they were generated by a normal distribution. + +(Even though this is not true, it *might* be a helpful way to think about the data.) + +Here we match a normal distribution to the Amazon monthly returns by setting the +sample mean to the mean of the normal distribution and the sample variance equal +to the variance. + +Then we plot the density and the histogram. + +```{code-cell} ipython3 +μ = x_amazon.mean() +σ_squared = x_amazon.var() +σ = np.sqrt(σ_squared) +u = scipy.stats.norm(μ, σ) +``` + +```{code-cell} ipython3 +x_grid = np.linspace(-50, 65, 200) +fig, ax = plt.subplots() +ax.plot(x_grid, u.pdf(x_grid)) +ax.hist(x_amazon, density=True, bins=40) +ax.set_xlabel('monthly return (percent change)') +ax.set_ylabel('density') +plt.show() +``` + +The match between the histogram and the density is not bad but also not very good. + +One reason is that the normal distribution is not really a good fit for this observed data --- we will discuss this point again when we talk about {ref}`heavy tailed distributions`. + +Of course, if the data really *is* generated by the normal distribution, then the fit will be better. + +Let's see this in action + +- first we generate random draws from the normal distribution +- then we histogram them and compare with the density. + +```{code-cell} ipython3 +μ, σ = 0, 1 +u = scipy.stats.norm(μ, σ) +N = 2000 # Number of observations +x_draws = u.rvs(N) +x_grid = np.linspace(-4, 4, 200) +fig, ax = plt.subplots() +ax.plot(x_grid, u.pdf(x_grid)) +ax.hist(x_draws, density=True, bins=40) +ax.set_xlabel('x') +ax.set_ylabel('density') +plt.show() +``` + +Note that if you keep increasing $N$, which is the number of observations, the fit will get better and better. + +This convergence is a version of the "law of large numbers", which we will discuss {ref}`later`. diff --git a/book/_build/html/_sources/pv.ipynb b/book/_build/html/_sources/pv.ipynb new file mode 100644 index 0000000..a532b33 --- /dev/null +++ b/book/_build/html/_sources/pv.ipynb @@ -0,0 +1,620 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "966eb0e6", + "metadata": {}, + "source": [ + "# Present Values\n", + "\n", + "## Overview \n", + "\n", + "This lecture describes the **present value model** that is a starting point\n", + "of much asset pricing theory.\n", + "\n", + "Asset pricing theory is a component of theories about many economic decisions including\n", + "\n", + " * consumption\n", + " * labor supply\n", + " * education choice \n", + " * demand for money\n", + "\n", + "In asset pricing theory, and in economic dynamics more generally, a basic topic is the relationship\n", + "among different **time series**.\n", + "\n", + "A **time series** is a **sequence** indexed by time.\n", + "\n", + "In this lecture, we'll represent a sequence as a vector.\n", + "\n", + "So our analysis will typically boil down to studying relationships among vectors.\n", + "\n", + "Our main tools in this lecture will be \n", + "\n", + " * matrix multiplication, and\n", + " * matrix inversion.\n", + "\n", + "We'll use the calculations described here in subsequent lectures, including {doc}`consumption smoothing `, {doc}`equalizing difference model `, and\n", + "{doc}`monetarist theory of price levels `.\n", + "\n", + "Let's dive in.\n", + "\n", + "## Analysis \n", + "\n", + "\n", + "\n", + "Let \n", + "\n", + " * $\\{d_t\\}_{t=0}^T $ be a sequence of dividends or \"payouts\"\n", + " * $\\{p_t\\}_{t=0}^T $ be a sequence of prices of a claim on the continuation of\n", + " the asset's payout stream from date $t$ on, namely, $\\{d_s\\}_{s=t}^T $ \n", + " * $ \\delta \\in (0,1) $ be a one-period \"discount factor\" \n", + " * $p_{T+1}^*$ be a terminal price of the asset at time $T+1$\n", + " \n", + "We assume that the dividend stream $\\{d_t\\}_{t=0}^T $ and the terminal price \n", + "$p_{T+1}^*$ are both exogenous.\n", + "\n", + "This means that they are determined outside the model.\n", + "\n", + "Assume the sequence of asset pricing equations\n", + "\n", + "$$\n", + " p_t = d_t + \\delta p_{t+1}, \\quad t = 0, 1, \\ldots , T\n", + "$$ (eq:Euler1)\n", + "\n", + "We say equation**s**, plural, because there are $T+1$ equations, one for each $t =0, 1, \\ldots, T$.\n", + "\n", + "\n", + "Equations {eq}`eq:Euler1` assert that price paid to purchase the asset at time $t$ equals the payout $d_t$ plus the price at time $t+1$ multiplied by a time discount factor $\\delta$.\n", + "\n", + "Discounting tomorrow's price by multiplying it by $\\delta$ accounts for the \"value of waiting one period\".\n", + "\n", + "We want to solve the system of $T+1$ equations {eq}`eq:Euler1` for the asset price sequence $\\{p_t\\}_{t=0}^T $ as a function of the dividend sequence $\\{d_t\\}_{t=0}^T $ and the exogenous terminal\n", + "price $p_{T+1}^*$.\n", + "\n", + "A system of equations like {eq}`eq:Euler1` is an example of a linear **difference equation**.\n", + "\n", + "There are powerful mathematical methods available for solving such systems and they are well worth\n", + "studying in their own right, being the foundation for the analysis of many interesting economic models. \n", + "\n", + "For an example, see {doc}`Samuelson multiplier-accelerator `\n", + "\n", + "In this lecture, we'll solve system {eq}`eq:Euler1` using matrix multiplication and matrix inversion, basic tools from linear algebra introduced in {doc}`linear equations and matrix algebra `.\n", + "\n", + "We will use the following imports" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ca2146a6", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt" + ] + }, + { + "cell_type": "markdown", + "id": "e8e6fdb2", + "metadata": {}, + "source": [ + "## Representing sequences as vectors\n", + "\n", + "The equations in system {eq}`eq:Euler1` can be arranged as follows:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + " p_0 & = d_0 + \\delta p_1 \\\\\n", + " p_1 & = d_1 + \\delta p_2 \\\\\n", + " \\vdots \\\\\n", + " p_{T-1} & = d_{T-1} + \\delta p_T \\\\\n", + " p_T & = d_T + \\delta p^*_{T+1}\n", + "\\end{aligned}\n", + "$$ (eq:Euler_stack)\n", + "\n", + "Write the system {eq}`eq:Euler_stack` of $T+1$ asset pricing equations as the single matrix equation\n", + "\n", + "$$\n", + " \\begin{bmatrix} 1 & -\\delta & 0 & 0 & \\cdots & 0 & 0 \\cr\n", + " 0 & 1 & -\\delta & 0 & \\cdots & 0 & 0 \\cr\n", + " 0 & 0 & 1 & -\\delta & \\cdots & 0 & 0 \\cr\n", + " \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & 0 & 0 \\cr\n", + " 0 & 0 & 0 & 0 & \\cdots & 1 & -\\delta \\cr\n", + " 0 & 0 & 0 & 0 & \\cdots & 0 & 1 \\end{bmatrix}\n", + " \\begin{bmatrix} p_0 \\cr p_1 \\cr p_2 \\cr \\vdots \\cr p_{T-1} \\cr p_T \n", + " \\end{bmatrix} \n", + " = \\begin{bmatrix} \n", + " d_0 \\cr d_1 \\cr d_2 \\cr \\vdots \\cr d_{T-1} \\cr d_T\n", + " \\end{bmatrix}\n", + " + \\begin{bmatrix} \n", + " 0 \\cr 0 \\cr 0 \\cr \\vdots \\cr 0 \\cr \\delta p_{T+1}^*\n", + " \\end{bmatrix}\n", + "$$ (eq:pvpieq)" + ] + }, + { + "cell_type": "markdown", + "id": "5783b1dc", + "metadata": {}, + "source": [ + "```{exercise-start} \n", + ":label: pv_ex_1\n", + "```\n", + "\n", + "Carry out the matrix multiplication in [](eq:pvpieq) by hand and confirm that you\n", + "recover the equations in [](eq:Euler_stack).\n", + "\n", + "```{exercise-end}\n", + "```\n", + "\n", + "In vector-matrix notation, we can write system {eq}`eq:pvpieq` as \n", + "\n", + "$$\n", + " A p = d + b\n", + "$$ (eq:apdb)\n", + "\n", + "Here $A$ is the matrix on the left side of equation {eq}`eq:pvpieq`, while\n", + "\n", + "$$\n", + " p = \n", + " \\begin{bmatrix}\n", + " p_0 \\\\\n", + " p_1 \\\\\n", + " \\vdots \\\\\n", + " p_T\n", + " \\end{bmatrix},\n", + " \\quad\n", + " d = \n", + " \\begin{bmatrix}\n", + " d_0 \\\\\n", + " d_1 \\\\\n", + " \\vdots \\\\\n", + " d_T\n", + " \\end{bmatrix},\n", + " \\quad \\text{and} \\quad\n", + " b = \n", + " \\begin{bmatrix}\n", + " 0 \\\\\n", + " 0 \\\\\n", + " \\vdots \\\\\n", + " p^*_{T+1}\n", + " \\end{bmatrix}\n", + "$$\n", + "\n", + "The solution for the vector of prices is \n", + "\n", + "$$\n", + " p = A^{-1}(d + b)\n", + "$$ (eq:apdb_sol)\n", + "\n", + "\n", + "For example, suppose that the dividend stream is \n", + "\n", + "$$\n", + " d_{t+1} = 1.05 d_t, \\quad t = 0, 1, \\ldots , T-1.\n", + "$$\n", + "\n", + "Let's write Python code to compute and plot the dividend stream." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "28d4b25b", + "metadata": {}, + "outputs": [], + "source": [ + "T = 6\n", + "current_d = 1.0\n", + "d = []\n", + "for t in range(T+1):\n", + " d.append(current_d)\n", + " current_d = current_d * 1.05 \n", + "\n", + "fig, ax = plt.subplots()\n", + "ax.plot(d, 'o', label='dividends')\n", + "ax.legend()\n", + "ax.set_xlabel('time')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "eed7254d", + "metadata": {}, + "source": [ + "Now let's compute and plot the asset price.\n", + "\n", + "We set $\\delta$ and $p_{T+1}^*$ to" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5d616582", + "metadata": {}, + "outputs": [], + "source": [ + "δ = 0.99\n", + "p_star = 10.0" + ] + }, + { + "cell_type": "markdown", + "id": "78d87f30", + "metadata": {}, + "source": [ + "Let's build the matrix $A$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4649d577", + "metadata": {}, + "outputs": [], + "source": [ + "A = np.zeros((T+1, T+1))\n", + "for i in range(T+1):\n", + " for j in range(T+1):\n", + " if i == j:\n", + " A[i, j] = 1\n", + " if j < T:\n", + " A[i, j+1] = -δ\n" + ] + }, + { + "cell_type": "markdown", + "id": "e7672e01", + "metadata": {}, + "source": [ + "Let's inspect $A$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "16959c48", + "metadata": {}, + "outputs": [], + "source": [ + "A" + ] + }, + { + "cell_type": "markdown", + "id": "9fd1f743", + "metadata": {}, + "source": [ + "Now let's solve for prices using {eq}`eq:apdb_sol`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ff44eed4", + "metadata": {}, + "outputs": [], + "source": [ + "b = np.zeros(T+1)\n", + "b[-1] = δ * p_star\n", + "p = np.linalg.solve(A, d + b)\n", + "fig, ax = plt.subplots()\n", + "ax.plot(p, 'o', label='asset price')\n", + "ax.legend()\n", + "ax.set_xlabel('time')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "c3f72404", + "metadata": {}, + "source": [ + "Now let's consider a cyclically growing dividend sequence:\n", + "\n", + "$$\n", + " d_{t+1} = 1.01 d_t + 0.1 \\sin t, \\quad t = 0, 1, \\ldots , T-1.\n", + "$$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8d3aa5c5", + "metadata": {}, + "outputs": [], + "source": [ + "T = 100\n", + "current_d = 1.0\n", + "d = []\n", + "for t in range(T+1):\n", + " d.append(current_d)\n", + " current_d = current_d * 1.01 + 0.1 * np.sin(t)\n", + "\n", + "fig, ax = plt.subplots()\n", + "ax.plot(d, 'o-', ms=4, alpha=0.8, label='dividends')\n", + "ax.legend()\n", + "ax.set_xlabel('time')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "cfbc6e2f", + "metadata": {}, + "source": [ + "```{exercise-start} \n", + ":label: pv_ex_cyc\n", + "```\n", + "\n", + "Compute the corresponding asset price sequence when $p^*_{T+1} = 0$ and $\\delta\n", + "= 0.98$.\n", + "\n", + "```{exercise-end}\n", + "```\n", + "\n", + "```{solution-start} pv_ex_cyc\n", + ":class: dropdown\n", + "```\n", + "\n", + "We proceed as above after modifying parameters and consequently the matrix $A$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "15b06eb0", + "metadata": {}, + "outputs": [], + "source": [ + "δ = 0.98\n", + "p_star = 0.0\n", + "A = np.zeros((T+1, T+1))\n", + "for i in range(T+1):\n", + " for j in range(T+1):\n", + " if i == j:\n", + " A[i, j] = 1\n", + " if j < T:\n", + " A[i, j+1] = -δ\n", + "\n", + "b = np.zeros(T+1)\n", + "b[-1] = δ * p_star\n", + "p = np.linalg.solve(A, d + b)\n", + "fig, ax = plt.subplots()\n", + "ax.plot(p, 'o-', ms=4, alpha=0.8, label='asset price')\n", + "ax.legend()\n", + "ax.set_xlabel('time')\n", + "plt.show()\n" + ] + }, + { + "cell_type": "markdown", + "id": "adb94165", + "metadata": {}, + "source": [ + "The weighted averaging associated with the present value calculation largely\n", + "eliminates the cycles.\n", + "\n", + "\n", + "```{solution-end} \n", + "```\n", + "\n", + "## Analytical expressions\n", + "\n", + "By the [inverse matrix theorem](https://en.wikipedia.org/wiki/Invertible_matrix), a matrix $B$ is the inverse of $A$ whenever $A B$ is the identity.\n", + "\n", + "It can be verified that the inverse of the matrix $A$ in {eq}`eq:pvpieq` is\n", + "\n", + "\n", + "$$ A^{-1} = \n", + " \\begin{bmatrix}\n", + " 1 & \\delta & \\delta^2 & \\cdots & \\delta^{T-1} & \\delta^T \\cr\n", + " 0 & 1 & \\delta & \\cdots & \\delta^{T-2} & \\delta^{T-1} \\cr\n", + " \\vdots & \\vdots & \\vdots & \\cdots & \\vdots & \\vdots \\cr\n", + " 0 & 0 & 0 & \\cdots & 1 & \\delta \\cr\n", + " 0 & 0 & 0 & \\cdots & 0 & 1 \\cr\n", + " \\end{bmatrix}\n", + "$$ (eq:Ainv)\n", + "\n", + "\n", + "\n", + "```{exercise-start} \n", + ":label: pv_ex_2\n", + "```\n", + "\n", + "Check this by showing that $A A^{-1}$ is equal to the identity matrix.\n", + "\n", + "\n", + "\n", + "```{exercise-end}\n", + "```\n", + "\n", + "\n", + "If we use the expression {eq}`eq:Ainv` in {eq}`eq:apdb_sol` and perform the indicated matrix multiplication, we shall find that\n", + "\n", + "$$\n", + " p_t = \\sum_{s=t}^T \\delta^{s-t} d_s + \\delta^{T+1-t} p_{T+1}^*\n", + "$$ (eq:ptpveq)\n", + "\n", + "Pricing formula {eq}`eq:ptpveq` asserts that two components sum to the asset price \n", + "$p_t$:\n", + "\n", + " * a **fundamental component** $\\sum_{s=t}^T \\delta^{s-t} d_s$ that equals the **discounted present value** of prospective dividends\n", + " \n", + " * a **bubble component** $\\delta^{T+1-t} p_{T+1}^*$\n", + " \n", + "The fundamental component is pinned down by the discount factor $\\delta$ and the\n", + "payout of the asset (in this case, dividends).\n", + "\n", + "The bubble component is the part of the price that is not pinned down by\n", + "fundamentals.\n", + "\n", + "It is sometimes convenient to rewrite the bubble component as\n", + "\n", + "$$ \n", + "c \\delta^{-t}\n", + "$$\n", + "\n", + "where \n", + "\n", + "$$ \n", + "c \\equiv \\delta^{T+1}p_{T+1}^*\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "735c3328", + "metadata": {}, + "source": [ + "## More about bubbles\n", + "\n", + "For a few moments, let's focus on the special case of an asset that never pays dividends, in which case\n", + "\n", + "$$\n", + "\\begin{bmatrix} \n", + "d_0 \\cr d_1 \\cr d_2 \\cr \\vdots \\cr d_{T-1} \\cr d_T\n", + "\\end{bmatrix} = \n", + "\\begin{bmatrix} \n", + "0 \\cr 0 \\cr 0 \\cr \\vdots \\cr 0 \\cr 0\n", + "\\end{bmatrix}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "143d5772", + "metadata": {}, + "source": [ + "In this case system {eq}`eq:Euler1` of our $T+1$ asset pricing equations takes the\n", + "form of the single matrix equation\n", + "\n", + "$$\n", + "\\begin{bmatrix} 1 & -\\delta & 0 & 0 & \\cdots & 0 & 0 \\cr\n", + " 0 & 1 & -\\delta & 0 & \\cdots & 0 & 0 \\cr\n", + " 0 & 0 & 1 & -\\delta & \\cdots & 0 & 0 \\cr\n", + " \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & 0 & 0 \\cr\n", + " 0 & 0 & 0 & 0 & \\cdots & 1 & -\\delta \\cr\n", + " 0 & 0 & 0 & 0 & \\cdots & 0 & 1 \\end{bmatrix}\n", + "\\begin{bmatrix} p_0 \\cr p_1 \\cr p_2 \\cr \\vdots \\cr p_{T-1} \\cr p_T \n", + "\\end{bmatrix} =\n", + "\\begin{bmatrix} \n", + "0 \\cr 0 \\cr 0 \\cr \\vdots \\cr 0 \\cr \\delta p_{T+1}^*\n", + "\\end{bmatrix}\n", + "$$ (eq:pieq2)\n", + "\n", + "Evidently, if $p_{T+1}^* = 0$, a price vector $p$ of all entries zero\n", + "solves this equation and the only the **fundamental** component of our pricing \n", + "formula {eq}`eq:ptpveq` is present. \n", + "\n", + "But let's activate the **bubble** component by setting \n", + "\n", + "$$\n", + "p_{T+1}^* = c \\delta^{-(T+1)} \n", + "$$ (eq:eqbubbleterm)\n", + "\n", + "for some positive constant $c$.\n", + "\n", + "In this case, when we multiply both sides of {eq}`eq:pieq2` by\n", + "the matrix $A^{-1}$ presented in equation {eq}`eq:Ainv`, we \n", + " find that\n", + "\n", + "$$\n", + "p_t = c \\delta^{-t}\n", + "$$ (eq:bubble)\n", + "\n", + "\n", + "## Gross rate of return\n", + "\n", + "Define the gross rate of return on holding the asset from period $t$ to period $t+1$\n", + "as \n", + "\n", + "$$\n", + "R_t = \\frac{p_{t+1}}{p_t}\n", + "$$ (eq:rateofreturn)\n", + "\n", + "Substituting equation {eq}`eq:bubble` into equation {eq}`eq:rateofreturn` confirms that an asset whose sole source of value is a bubble earns a gross rate of return\n", + "\n", + "$$\n", + "R_t = \\delta^{-1} > 1 , t = 0, 1, \\ldots, T\n", + "$$\n", + "\n", + "\n", + "## Exercises\n", + "\n", + "\n", + "```{exercise-start} \n", + ":label: pv_ex_a\n", + "```\n", + "\n", + "Give analytical expressions for an asset price $p_t$ under the \n", + "following settings for $d$ and $p_{T+1}^*$:\n", + "\n", + "1. $p_{T+1}^* = 0, d_t = g^t d_0$ (a modified version of the Gordon growth formula)\n", + "1. $p_{T+1}^* = g^{T+1} d_0, d_t = g^t d_0$ (the plain vanilla Gordon growth formula)\n", + "1. $p_{T+1}^* = 0, d_t = 0$ (price of a worthless stock)\n", + "1. $p_{T+1}^* = c \\delta^{-(T+1)}, d_t = 0$ (price of a pure bubble stock)\n", + "\n", + "\n", + "```{exercise-end} \n", + "```\n", + "\n", + "```{solution-start} pv_ex_a\n", + ":class: dropdown\n", + "```\n", + "\n", + "Plugging each pair of the above $p_{T+1}^*, d_t$ into Equation {eq}`eq:ptpveq` yields:\n", + "\n", + "1. $p_t = \\sum^T_{s=t} \\delta^{s-t} g^s d_0$\n", + "1. $p_t = \\sum^T_{s=t} \\delta^{s-t} g^s d_0 + \\delta^{T+1-t} g^{T+1} d_0$\n", + "1. $p_t = 0$\n", + "1. $p_t = c \\delta^{-t}$\n", + "\n", + "\n", + "```{solution-end}\n", + "```" + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.5" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 93, + 98, + 133, + 194, + 207, + 212, + 215, + 219, + 228, + 232, + 234, + 238, + 247, + 257, + 270, + 288, + 308, + 379, + 394 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/pv.md b/book/_build/html/_sources/pv.md new file mode 100644 index 0000000..595f749 --- /dev/null +++ b/book/_build/html/_sources/pv.md @@ -0,0 +1,482 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.5 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Present Values + +## Overview + +This lecture describes the **present value model** that is a starting point +of much asset pricing theory. + +Asset pricing theory is a component of theories about many economic decisions including + + * consumption + * labor supply + * education choice + * demand for money + +In asset pricing theory, and in economic dynamics more generally, a basic topic is the relationship +among different **time series**. + +A **time series** is a **sequence** indexed by time. + +In this lecture, we'll represent a sequence as a vector. + +So our analysis will typically boil down to studying relationships among vectors. + +Our main tools in this lecture will be + + * matrix multiplication, and + * matrix inversion. + +We'll use the calculations described here in subsequent lectures, including {doc}`consumption smoothing `, {doc}`equalizing difference model `, and +{doc}`monetarist theory of price levels `. + +Let's dive in. + +## Analysis + + + +Let + + * $\{d_t\}_{t=0}^T $ be a sequence of dividends or "payouts" + * $\{p_t\}_{t=0}^T $ be a sequence of prices of a claim on the continuation of + the asset's payout stream from date $t$ on, namely, $\{d_s\}_{s=t}^T $ + * $ \delta \in (0,1) $ be a one-period "discount factor" + * $p_{T+1}^*$ be a terminal price of the asset at time $T+1$ + +We assume that the dividend stream $\{d_t\}_{t=0}^T $ and the terminal price +$p_{T+1}^*$ are both exogenous. + +This means that they are determined outside the model. + +Assume the sequence of asset pricing equations + +$$ + p_t = d_t + \delta p_{t+1}, \quad t = 0, 1, \ldots , T +$$ (eq:Euler1) + +We say equation**s**, plural, because there are $T+1$ equations, one for each $t =0, 1, \ldots, T$. + + +Equations {eq}`eq:Euler1` assert that price paid to purchase the asset at time $t$ equals the payout $d_t$ plus the price at time $t+1$ multiplied by a time discount factor $\delta$. + +Discounting tomorrow's price by multiplying it by $\delta$ accounts for the "value of waiting one period". + +We want to solve the system of $T+1$ equations {eq}`eq:Euler1` for the asset price sequence $\{p_t\}_{t=0}^T $ as a function of the dividend sequence $\{d_t\}_{t=0}^T $ and the exogenous terminal +price $p_{T+1}^*$. + +A system of equations like {eq}`eq:Euler1` is an example of a linear **difference equation**. + +There are powerful mathematical methods available for solving such systems and they are well worth +studying in their own right, being the foundation for the analysis of many interesting economic models. + +For an example, see {doc}`Samuelson multiplier-accelerator ` + +In this lecture, we'll solve system {eq}`eq:Euler1` using matrix multiplication and matrix inversion, basic tools from linear algebra introduced in {doc}`linear equations and matrix algebra `. + +We will use the following imports + ++++ + +```{code-cell} ipython3 +import numpy as np +import matplotlib.pyplot as plt +``` + ++++ + +## Representing sequences as vectors + +The equations in system {eq}`eq:Euler1` can be arranged as follows: + +$$ +\begin{aligned} + p_0 & = d_0 + \delta p_1 \\ + p_1 & = d_1 + \delta p_2 \\ + \vdots \\ + p_{T-1} & = d_{T-1} + \delta p_T \\ + p_T & = d_T + \delta p^*_{T+1} +\end{aligned} +$$ (eq:Euler_stack) + +Write the system {eq}`eq:Euler_stack` of $T+1$ asset pricing equations as the single matrix equation + +$$ + \begin{bmatrix} 1 & -\delta & 0 & 0 & \cdots & 0 & 0 \cr + 0 & 1 & -\delta & 0 & \cdots & 0 & 0 \cr + 0 & 0 & 1 & -\delta & \cdots & 0 & 0 \cr + \vdots & \vdots & \vdots & \vdots & \vdots & 0 & 0 \cr + 0 & 0 & 0 & 0 & \cdots & 1 & -\delta \cr + 0 & 0 & 0 & 0 & \cdots & 0 & 1 \end{bmatrix} + \begin{bmatrix} p_0 \cr p_1 \cr p_2 \cr \vdots \cr p_{T-1} \cr p_T + \end{bmatrix} + = \begin{bmatrix} + d_0 \cr d_1 \cr d_2 \cr \vdots \cr d_{T-1} \cr d_T + \end{bmatrix} + + \begin{bmatrix} + 0 \cr 0 \cr 0 \cr \vdots \cr 0 \cr \delta p_{T+1}^* + \end{bmatrix} +$$ (eq:pvpieq) + ++++ + +```{exercise-start} +:label: pv_ex_1 +``` + +Carry out the matrix multiplication in [](eq:pvpieq) by hand and confirm that you +recover the equations in [](eq:Euler_stack). + +```{exercise-end} +``` + +In vector-matrix notation, we can write system {eq}`eq:pvpieq` as + +$$ + A p = d + b +$$ (eq:apdb) + +Here $A$ is the matrix on the left side of equation {eq}`eq:pvpieq`, while + +$$ + p = + \begin{bmatrix} + p_0 \\ + p_1 \\ + \vdots \\ + p_T + \end{bmatrix}, + \quad + d = + \begin{bmatrix} + d_0 \\ + d_1 \\ + \vdots \\ + d_T + \end{bmatrix}, + \quad \text{and} \quad + b = + \begin{bmatrix} + 0 \\ + 0 \\ + \vdots \\ + p^*_{T+1} + \end{bmatrix} +$$ + +The solution for the vector of prices is + +$$ + p = A^{-1}(d + b) +$$ (eq:apdb_sol) + + +For example, suppose that the dividend stream is + +$$ + d_{t+1} = 1.05 d_t, \quad t = 0, 1, \ldots , T-1. +$$ + +Let's write Python code to compute and plot the dividend stream. + +```{code-cell} ipython3 +T = 6 +current_d = 1.0 +d = [] +for t in range(T+1): + d.append(current_d) + current_d = current_d * 1.05 + +fig, ax = plt.subplots() +ax.plot(d, 'o', label='dividends') +ax.legend() +ax.set_xlabel('time') +plt.show() +``` +Now let's compute and plot the asset price. + +We set $\delta$ and $p_{T+1}^*$ to + +```{code-cell} ipython3 +δ = 0.99 +p_star = 10.0 +``` + +Let's build the matrix $A$ + +```{code-cell} ipython3 +A = np.zeros((T+1, T+1)) +for i in range(T+1): + for j in range(T+1): + if i == j: + A[i, j] = 1 + if j < T: + A[i, j+1] = -δ + +``` + +Let's inspect $A$ + +```{code-cell} ipython3 +A +``` + +Now let's solve for prices using {eq}`eq:apdb_sol`. + +```{code-cell} ipython3 +b = np.zeros(T+1) +b[-1] = δ * p_star +p = np.linalg.solve(A, d + b) +fig, ax = plt.subplots() +ax.plot(p, 'o', label='asset price') +ax.legend() +ax.set_xlabel('time') +plt.show() +``` + + +Now let's consider a cyclically growing dividend sequence: + +$$ + d_{t+1} = 1.01 d_t + 0.1 \sin t, \quad t = 0, 1, \ldots , T-1. +$$ + + +```{code-cell} ipython3 +T = 100 +current_d = 1.0 +d = [] +for t in range(T+1): + d.append(current_d) + current_d = current_d * 1.01 + 0.1 * np.sin(t) + +fig, ax = plt.subplots() +ax.plot(d, 'o-', ms=4, alpha=0.8, label='dividends') +ax.legend() +ax.set_xlabel('time') +plt.show() +``` + +```{exercise-start} +:label: pv_ex_cyc +``` + +Compute the corresponding asset price sequence when $p^*_{T+1} = 0$ and $\delta += 0.98$. + +```{exercise-end} +``` + +```{solution-start} pv_ex_cyc +:class: dropdown +``` + +We proceed as above after modifying parameters and consequently the matrix $A$. + +```{code-cell} ipython3 +δ = 0.98 +p_star = 0.0 +A = np.zeros((T+1, T+1)) +for i in range(T+1): + for j in range(T+1): + if i == j: + A[i, j] = 1 + if j < T: + A[i, j+1] = -δ + +b = np.zeros(T+1) +b[-1] = δ * p_star +p = np.linalg.solve(A, d + b) +fig, ax = plt.subplots() +ax.plot(p, 'o-', ms=4, alpha=0.8, label='asset price') +ax.legend() +ax.set_xlabel('time') +plt.show() + +``` + +The weighted averaging associated with the present value calculation largely +eliminates the cycles. + + +```{solution-end} +``` + +## Analytical expressions + +By the [inverse matrix theorem](https://en.wikipedia.org/wiki/Invertible_matrix), a matrix $B$ is the inverse of $A$ whenever $A B$ is the identity. + +It can be verified that the inverse of the matrix $A$ in {eq}`eq:pvpieq` is + + +$$ A^{-1} = + \begin{bmatrix} + 1 & \delta & \delta^2 & \cdots & \delta^{T-1} & \delta^T \cr + 0 & 1 & \delta & \cdots & \delta^{T-2} & \delta^{T-1} \cr + \vdots & \vdots & \vdots & \cdots & \vdots & \vdots \cr + 0 & 0 & 0 & \cdots & 1 & \delta \cr + 0 & 0 & 0 & \cdots & 0 & 1 \cr + \end{bmatrix} +$$ (eq:Ainv) + + + +```{exercise-start} +:label: pv_ex_2 +``` + +Check this by showing that $A A^{-1}$ is equal to the identity matrix. + + + +```{exercise-end} +``` + + +If we use the expression {eq}`eq:Ainv` in {eq}`eq:apdb_sol` and perform the indicated matrix multiplication, we shall find that + +$$ + p_t = \sum_{s=t}^T \delta^{s-t} d_s + \delta^{T+1-t} p_{T+1}^* +$$ (eq:ptpveq) + +Pricing formula {eq}`eq:ptpveq` asserts that two components sum to the asset price +$p_t$: + + * a **fundamental component** $\sum_{s=t}^T \delta^{s-t} d_s$ that equals the **discounted present value** of prospective dividends + + * a **bubble component** $\delta^{T+1-t} p_{T+1}^*$ + +The fundamental component is pinned down by the discount factor $\delta$ and the +payout of the asset (in this case, dividends). + +The bubble component is the part of the price that is not pinned down by +fundamentals. + +It is sometimes convenient to rewrite the bubble component as + +$$ +c \delta^{-t} +$$ + +where + +$$ +c \equiv \delta^{T+1}p_{T+1}^* +$$ + ++++ + +## More about bubbles + +For a few moments, let's focus on the special case of an asset that never pays dividends, in which case + +$$ +\begin{bmatrix} +d_0 \cr d_1 \cr d_2 \cr \vdots \cr d_{T-1} \cr d_T +\end{bmatrix} = +\begin{bmatrix} +0 \cr 0 \cr 0 \cr \vdots \cr 0 \cr 0 +\end{bmatrix} +$$ + ++++ + +In this case system {eq}`eq:Euler1` of our $T+1$ asset pricing equations takes the +form of the single matrix equation + +$$ +\begin{bmatrix} 1 & -\delta & 0 & 0 & \cdots & 0 & 0 \cr + 0 & 1 & -\delta & 0 & \cdots & 0 & 0 \cr + 0 & 0 & 1 & -\delta & \cdots & 0 & 0 \cr + \vdots & \vdots & \vdots & \vdots & \vdots & 0 & 0 \cr + 0 & 0 & 0 & 0 & \cdots & 1 & -\delta \cr + 0 & 0 & 0 & 0 & \cdots & 0 & 1 \end{bmatrix} +\begin{bmatrix} p_0 \cr p_1 \cr p_2 \cr \vdots \cr p_{T-1} \cr p_T +\end{bmatrix} = +\begin{bmatrix} +0 \cr 0 \cr 0 \cr \vdots \cr 0 \cr \delta p_{T+1}^* +\end{bmatrix} +$$ (eq:pieq2) + +Evidently, if $p_{T+1}^* = 0$, a price vector $p$ of all entries zero +solves this equation and the only the **fundamental** component of our pricing +formula {eq}`eq:ptpveq` is present. + +But let's activate the **bubble** component by setting + +$$ +p_{T+1}^* = c \delta^{-(T+1)} +$$ (eq:eqbubbleterm) + +for some positive constant $c$. + +In this case, when we multiply both sides of {eq}`eq:pieq2` by +the matrix $A^{-1}$ presented in equation {eq}`eq:Ainv`, we + find that + +$$ +p_t = c \delta^{-t} +$$ (eq:bubble) + + +## Gross rate of return + +Define the gross rate of return on holding the asset from period $t$ to period $t+1$ +as + +$$ +R_t = \frac{p_{t+1}}{p_t} +$$ (eq:rateofreturn) + +Substituting equation {eq}`eq:bubble` into equation {eq}`eq:rateofreturn` confirms that an asset whose sole source of value is a bubble earns a gross rate of return + +$$ +R_t = \delta^{-1} > 1 , t = 0, 1, \ldots, T +$$ + + +## Exercises + + +```{exercise-start} +:label: pv_ex_a +``` + +Give analytical expressions for an asset price $p_t$ under the +following settings for $d$ and $p_{T+1}^*$: + +1. $p_{T+1}^* = 0, d_t = g^t d_0$ (a modified version of the Gordon growth formula) +1. $p_{T+1}^* = g^{T+1} d_0, d_t = g^t d_0$ (the plain vanilla Gordon growth formula) +1. $p_{T+1}^* = 0, d_t = 0$ (price of a worthless stock) +1. $p_{T+1}^* = c \delta^{-(T+1)}, d_t = 0$ (price of a pure bubble stock) + + +```{exercise-end} +``` + +```{solution-start} pv_ex_a +:class: dropdown +``` + +Plugging each pair of the above $p_{T+1}^*, d_t$ into Equation {eq}`eq:ptpveq` yields: + +1. $p_t = \sum^T_{s=t} \delta^{s-t} g^s d_0$ +1. $p_t = \sum^T_{s=t} \delta^{s-t} g^s d_0 + \delta^{T+1-t} g^{T+1} d_0$ +1. $p_t = 0$ +1. $p_t = c \delta^{-t}$ + + +```{solution-end} +``` \ No newline at end of file diff --git a/content/lectures/scalar_dynam.ipynb b/book/_build/html/_sources/scalar_dynam.ipynb similarity index 76% rename from content/lectures/scalar_dynam.ipynb rename to book/_build/html/_sources/scalar_dynam.ipynb index 58b22e5..687f8ce 100644 --- a/content/lectures/scalar_dynam.ipynb +++ b/book/_build/html/_sources/scalar_dynam.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "d8a8b1e3", + "id": "84510552", "metadata": {}, "source": [ "```{raw} html\n", @@ -13,22 +13,34 @@ "
\n", "```\n", "\n", - "# {index}`Dynamics in One Dimension `\n", + "(scalar_dynam)=\n", + "# Dynamics in One Dimension\n", "\n", - "```{contents} Contents\n", - ":depth: 2\n", - "```\n", "\n", "## Overview\n", "\n", - "In this lecture we give a quick introduction to discrete time dynamics in one dimension.\n", + "In economics many variables depend on their past values\n", + "\n", + "For example, it seems reasonable to believe that inflation last year with affects inflation this year.\n", + "\n", + "(Perhaps high inflation last year will lead people to demand higher wages to\n", + "compensate, which will feed into higher prices this year.)\n", + "\n", + "Letting $\\pi_t$ be inflation this year and $\\pi_{t-1}$ be inflation last year, we\n", + "can write this relationship in a general form as\n", "\n", - "* In one-dimensional models, the state of the system is described by a single variable.\n", - "* The variable is a number (that is, a point in $\\mathbb R$).\n", + "$$ \\pi_t = f(\\pi_{t-1}) $$\n", "\n", - "While most quantitative models have two or more state variables, the\n", - "one-dimensional setting is a good place to learn the foundations of dynamics\n", - "and understand key concepts.\n", + "where $f$ is some function describing the relationship between the variables.\n", + "\n", + "This equation is an example of one-dimensional discrete time dynamic system.\n", + "\n", + "In this lecture we cover the foundations of one-dimensional discrete time\n", + "dynamics.\n", + "\n", + "(While most quantitative models have two or more state variables, the\n", + "one-dimensional setting is a good place to learn foundations \n", + "and understand key concepts.)\n", "\n", "Let's start with some standard imports:" ] @@ -36,25 +48,24 @@ { "cell_type": "code", "execution_count": null, - "id": "c5aeb01a", + "id": "98362056", "metadata": {}, "outputs": [], "source": [ - "%matplotlib inline\n", "import matplotlib.pyplot as plt\n", "import numpy as np" ] }, { "cell_type": "markdown", - "id": "b4dcd341", + "id": "2b076430", "metadata": {}, "source": [ - "## Some Definitions\n", + "## Some definitions\n", "\n", "This section sets out the objects of interest and the kinds of properties we study.\n", "\n", - "### Composition of Functions\n", + "### Composition of functions\n", "\n", "For this lecture you should know the following.\n", "\n", @@ -84,14 +95,14 @@ " f^2(x) = \\sqrt{\\sqrt{x}} = x^{1/4}\n", "$$\n", "\n", - "Similarly, if $n$ is an integer, then $f^n$ is $n$ compositions of $f$ with\n", + "Similarly, if $n$ is a positive integer, then $f^n$ is $n$ compositions of $f$ with\n", "itself.\n", "\n", "In the example above, $f^n(x) = x^{1/(2^n)}$.\n", "\n", "\n", "\n", - "### Dynamic Systems\n", + "### Dynamic systems\n", "\n", "A **(discrete time) dynamic system** is a set $S$ and a function $g$ that sends\n", "set $S$ back into to itself.\n", @@ -109,10 +120,6 @@ "\n", "* $g$ does not always send points in $S$ back into $S$.\n", "\n", - "\n", - "\n", - "### Dynamic Systems\n", - "\n", "We care about dynamic systems because we can use them to study dynamics!\n", "\n", "Given a dynamic system consisting of set $S$ and function $g$, we can create\n", @@ -143,7 +150,7 @@ "we can write the trajectory more simply as \n", "\n", "$$\n", - " x_t = g^t(x_0) \\quad \\text{ for } t \\geq 0.\n", + " x_t = g^t(x_0) \\quad \\text{ for } t = 0, 1, 2, \\ldots\n", "$$\n", "\n", "In all of what follows, we are going to assume that $S$ is a subset of\n", @@ -155,10 +162,10 @@ "\n", "\n", "\n", - "### Example: A Linear Model\n", + "### Example: a linear model\n", "\n", "One simple example of a dynamic system is when $S=\\mathbb R$ and $g(x)=ax +\n", - "b$, where $a, b$ are fixed constants.\n", + "b$, where $a, b$ are constants (sometimes called ``parameters'').\n", "\n", "This leads to the **linear difference equation**\n", "\n", @@ -180,14 +187,14 @@ "```\n", "\n", "Continuing in this way, and using our knowledge of {doc}`geometric series\n", - "`, we find that, for any $t \\geq 0$,\n", + "`, we find that, for any $t = 0, 1, 2, \\ldots$,\n", "\n", "```{math}\n", ":label: sdslinmod\n", " x_t = a^t x_0 + b \\frac{1 - a^t}{1 - a}\n", "```\n", "\n", - "We have an exact expression for $x_t$ for all $t$ and hence a full\n", + "We have an exact expression for $x_t$ for all non-negative integer $t$ and hence a full\n", "understanding of the dynamics.\n", "\n", "Notice in particular that $|a| < 1$, then, by {eq}`sdslinmod`, we have\n", @@ -198,7 +205,7 @@ "x_t \\to \\frac{b}{1 - a} \\text{ as } t \\to \\infty\n", "```\n", "\n", - "regardless of $x_0$\n", + "regardless of $x_0$.\n", "\n", "This is an example of what is called global stability, a topic we return to\n", "below.\n", @@ -206,25 +213,26 @@ "\n", "\n", "\n", - "### Example: A Nonlinear Model\n", + "### Example: a nonlinear model\n", "\n", "In the linear example above, we obtained an exact analytical expression for\n", - "$x_t$ in terms of arbitrary $t$ and $x_0$.\n", + "$x_t$ in terms of arbitrary non-negative integer $t$ and $x_0$.\n", "\n", "This made analysis of dynamics very easy.\n", "\n", "When models are nonlinear, however, the situation can be quite different.\n", "\n", - "For example, recall how we [previously studied](https://python-programming.quantecon.org/python_oop.html#example-the-solow-growth-model) the law of motion for the Solow growth model, a simplified version of which is\n", + "For example, in a later lecture {doc}`solow`, we will study the Solow-Swan growth model, which has dynamics \n", "\n", "```{math}\n", ":label: solow_lom2\n", "\n", - "k_{t+1} = s z k_t^{\\alpha} + (1 - \\delta) k_t\n", + "k_{t+1} = s A k_t^{\\alpha} + (1 - \\delta) k_t\n", "```\n", "\n", - "Here $k$ is capital stock and $s, z, \\alpha, \\delta$ are positive\n", - "parameters with $0 < \\alpha, \\delta < 1$.\n", + "Here $k=K/L$ is the per capita capital stock, $s$ is the saving rate, $A$ is the total factor productivity, $\\alpha$ is the capital share, and $\\delta$ is the depreciation rate. \n", + "\n", + "All these parameter are positive and $0 < \\alpha, \\delta < 1$.\n", "\n", "If you try to iterate like we did in {eq}`sdslinmodpath`, you will find that\n", "the algebra gets messy quickly.\n", @@ -238,10 +246,11 @@ "\n", "## Stability\n", "\n", - "Consider a fixed dynamic system consisting of set $S \\subset \\mathbb R$ and\n", + "Consider a dynamic system consisting of set $S \\subset \\mathbb R$ and\n", "$g$ mapping $S$ to $S$.\n", "\n", - "### Steady States\n", + "(scalar-dynam:steady-state)=\n", + "### Steady states\n", "\n", "A **steady state** of this system is a\n", "point $x^*$ in $S$ such that $x^* = g(x^*)$.\n", @@ -252,15 +261,16 @@ "For example, for the linear model $x_{t+1} = a x_t + b$, you can use the\n", "definition to check that\n", "\n", - "* $x^* := b/(1-a)$ is a steady state whenever $a \\not= 1$.\n", + "* $x^* := b/(1-a)$ is a steady state whenever $a \\not= 1$,\n", "* if $a = 1$ and $b=0$, then every $x \\in \\mathbb R$ is a\n", - " steady state.\n", + " steady state,\n", "* if $a = 1$ and $b \\not= 0$, then the linear model has no steady\n", " state in $\\mathbb R$.\n", "\n", "\n", "\n", - "### Global Stability\n", + "(scalar-dynam:global-stability)=\n", + "### Global stability\n", "\n", "A steady state $x^*$ of the dynamic system is called\n", "**globally stable** if, for all $x_0 \\in S$,\n", @@ -278,7 +288,7 @@ "This follows directly from {eq}`sdslinmod`.\n", "\n", "\n", - "### Local Stability\n", + "### Local stability\n", "\n", "A steady state $x^*$ of the dynamic system is called\n", "**locally stable** if there exists an $\\epsilon > 0$ such that\n", @@ -291,15 +301,20 @@ "\n", "Obviously every globally stable steady state is also locally stable.\n", "\n", - "We will see examples below where the converse is not true.\n", - "\n", + "Here is an example where the converse is not true.\n", "\n", + "```{prf:example}\n", + "Consider the self-map $g$ on $\\mathbb{R}$ defined by $g(x)=x^2$. The fixed point $1$ is not stable.\n", "\n", + "For example, $g^t (x)\\to\\infty$ for any $x>1$.\n", "\n", + "However, $0$ is locally stable, because $-1 k_t$.\n", - "* If $g$ lies below the 45 degree line at this point, then we have $k_{t+1} < k_t$.\n", - "* If $g$ hits the 45 degree line at this point, then we have $k_{t+1} = k_t$, so $k_t$ is a steady state.\n", + "* If $g$ lies above the 45-degree line at this point, then we have $k_{t+1} > k_t$.\n", + "* If $g$ lies below the 45-degree line at this point, then we have $k_{t+1} < k_t$.\n", + "* If $g$ hits the 45-degree line at this point, then we have $k_{t+1} = k_t$, so $k_t$ is a steady state.\n", "\n", - "For the Solow model, there are two steady states when $S = \\mathbb R_+ =\n", + "For the Solow-Swan model, there are two steady states when $S = \\mathbb R_+ =\n", "[0, \\infty)$.\n", "\n", "* the origin $k=0$\n", @@ -504,7 +503,7 @@ "\n", "### Trajectories\n", "\n", - "By the preceding discussion, in regions where $g$ lies above the 45 degree line, we know that the trajectory is increasing.\n", + "By the preceding discussion, in regions where $g$ lies above the 45-degree line, we know that the trajectory is increasing.\n", "\n", "The next figure traces out a trajectory in such a region so we can see this more clearly.\n", "\n", @@ -514,7 +513,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f293fe5f", + "id": "2e76b8e9", "metadata": {}, "outputs": [], "source": [ @@ -525,17 +524,17 @@ }, { "cell_type": "markdown", - "id": "526f96a6", + "id": "384b411f", "metadata": {}, "source": [ - "We can plot the time series of capital corresponding to the figure above as\n", + "We can plot the time series of per capita capital corresponding to the figure above as\n", "follows:" ] }, { "cell_type": "code", "execution_count": null, - "id": "5b2c618d", + "id": "603c391a", "metadata": {}, "outputs": [], "source": [ @@ -544,7 +543,7 @@ }, { "cell_type": "markdown", - "id": "3c0fb1cc", + "id": "d2bbaefa", "metadata": {}, "source": [ "Here's a somewhat longer view:" @@ -553,7 +552,7 @@ { "cell_type": "code", "execution_count": null, - "id": "cbbc075a", + "id": "cc7d795c", "metadata": {}, "outputs": [], "source": [ @@ -562,17 +561,17 @@ }, { "cell_type": "markdown", - "id": "282d3c6c", + "id": "7e7ea40b", "metadata": {}, "source": [ - "When capital stock is higher than the unique positive steady state, we see that\n", + "When per capita capital stock is higher than the unique positive steady state, we see that\n", "it declines:" ] }, { "cell_type": "code", "execution_count": null, - "id": "3e1745a9", + "id": "a861dfee", "metadata": {}, "outputs": [], "source": [ @@ -583,7 +582,7 @@ }, { "cell_type": "markdown", - "id": "b41d401b", + "id": "1bde242d", "metadata": {}, "source": [ "Here is the time series:" @@ -592,7 +591,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ed74945a", + "id": "3e1a3683", "metadata": {}, "outputs": [], "source": [ @@ -601,12 +600,12 @@ }, { "cell_type": "markdown", - "id": "ba27a40c", + "id": "bc2b6cee", "metadata": {}, "source": [ - "### Complex Dynamics\n", + "### Complex dynamics\n", "\n", - "The Solow model is nonlinear but still generates very regular dynamics.\n", + "The Solow-Swan model is nonlinear but still generates very regular dynamics.\n", "\n", "One model that generates irregular dynamics is the **quadratic map**\n", "\n", @@ -615,13 +614,13 @@ "\\qquad x \\in [0, 1]\n", "$$\n", "\n", - "Let's have a look at the 45 degree diagram." + "Let's have a look at the 45-degree diagram." ] }, { "cell_type": "code", "execution_count": null, - "id": "6b2cec7f", + "id": "890f95fa", "metadata": {}, "outputs": [], "source": [ @@ -634,7 +633,7 @@ }, { "cell_type": "markdown", - "id": "c78f4034", + "id": "ac9664ec", "metadata": {}, "source": [ "Now let's look at a typical trajectory." @@ -643,7 +642,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4b0c3f3e", + "id": "886fe677", "metadata": {}, "outputs": [], "source": [ @@ -652,7 +651,7 @@ }, { "cell_type": "markdown", - "id": "0f41740d", + "id": "c02a1c4b", "metadata": {}, "source": [ "Notice how irregular it is.\n", @@ -663,7 +662,7 @@ { "cell_type": "code", "execution_count": null, - "id": "36006f35", + "id": "9d3a4167", "metadata": {}, "outputs": [], "source": [ @@ -672,7 +671,7 @@ }, { "cell_type": "markdown", - "id": "ab57f653", + "id": "9025fd5e", "metadata": {}, "source": [ "The irregularity is even clearer over a longer time horizon:" @@ -681,7 +680,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3f244342", + "id": "d3812d88", "metadata": {}, "outputs": [], "source": [ @@ -690,7 +689,7 @@ }, { "cell_type": "markdown", - "id": "ae34e800", + "id": "221f0730", "metadata": {}, "source": [ "## Exercises\n", @@ -710,7 +709,7 @@ "What differences do you notice in the cases $a \\in (-1, 0)$ and $a\n", "\\in (0, 1)$?\n", "\n", - "Use $a=0.5$ and then $a=-0.5$ and study the trajectories\n", + "Use $a=0.5$ and then $a=-0.5$ and study the trajectories.\n", "\n", "Set $b=1$ throughout.\n", "```\n", @@ -727,7 +726,7 @@ { "cell_type": "code", "execution_count": null, - "id": "83c74276", + "id": "0887907f", "metadata": {}, "outputs": [], "source": [ @@ -738,7 +737,7 @@ }, { "cell_type": "markdown", - "id": "ad663fd2", + "id": "18f4b021", "metadata": {}, "source": [ "Now let's plot a trajectory:" @@ -747,7 +746,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6d8a689a", + "id": "3bec2603", "metadata": {}, "outputs": [], "source": [ @@ -757,7 +756,7 @@ }, { "cell_type": "markdown", - "id": "58e69a62", + "id": "946d881e", "metadata": {}, "source": [ "Here is the corresponding time series, which converges towards the steady\n", @@ -767,7 +766,7 @@ { "cell_type": "code", "execution_count": null, - "id": "248b2dc3", + "id": "9a53fe6d", "metadata": {}, "outputs": [], "source": [ @@ -776,7 +775,7 @@ }, { "cell_type": "markdown", - "id": "4c20cca1", + "id": "63ec18f2", "metadata": {}, "source": [ "Now let's try $a=-0.5$ and see what differences we observe.\n", @@ -787,7 +786,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c8ea1d41", + "id": "28b8c13f", "metadata": {}, "outputs": [], "source": [ @@ -798,7 +797,7 @@ }, { "cell_type": "markdown", - "id": "d786395a", + "id": "3074e458", "metadata": {}, "source": [ "Now let's plot a trajectory:" @@ -807,7 +806,7 @@ { "cell_type": "code", "execution_count": null, - "id": "de161be2", + "id": "81fd6aa5", "metadata": {}, "outputs": [], "source": [ @@ -817,7 +816,7 @@ }, { "cell_type": "markdown", - "id": "89e7419b", + "id": "5fbff293", "metadata": {}, "source": [ "Here is the corresponding time series, which converges towards the steady\n", @@ -827,7 +826,7 @@ { "cell_type": "code", "execution_count": null, - "id": "dc7fd851", + "id": "73d3a1d3", "metadata": {}, "outputs": [], "source": [ @@ -836,7 +835,7 @@ }, { "cell_type": "markdown", - "id": "393972ac", + "id": "0ac7c4fd", "metadata": {}, "source": [ "Once again, we have convergence to the steady state but the nature of\n", @@ -853,12 +852,59 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst" + } + }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" - } + }, + "source_map": [ + 10, + 51, + 54, + 330, + 419, + 424, + 427, + 431, + 435, + 470, + 474, + 479, + 481, + 485, + 487, + 492, + 496, + 500, + 502, + 517, + 523, + 527, + 529, + 535, + 537, + 541, + 543, + 575, + 579, + 583, + 586, + 591, + 593, + 599, + 603, + 607, + 610, + 615, + 617 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/scalar_dynam.md b/book/_build/html/_sources/scalar_dynam.md new file mode 100644 index 0000000..5926a3f --- /dev/null +++ b/book/_build/html/_sources/scalar_dynam.md @@ -0,0 +1,628 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst +kernelspec: + display_name: Python 3 + language: python + name: python3 +--- + +```{raw} html + +``` + +(scalar_dynam)= +# Dynamics in One Dimension + + +## Overview + +In economics many variables depend on their past values + +For example, it seems reasonable to believe that inflation last year with affects inflation this year. + +(Perhaps high inflation last year will lead people to demand higher wages to +compensate, which will feed into higher prices this year.) + +Letting $\pi_t$ be inflation this year and $\pi_{t-1}$ be inflation last year, we +can write this relationship in a general form as + +$$ \pi_t = f(\pi_{t-1}) $$ + +where $f$ is some function describing the relationship between the variables. + +This equation is an example of one-dimensional discrete time dynamic system. + +In this lecture we cover the foundations of one-dimensional discrete time +dynamics. + +(While most quantitative models have two or more state variables, the +one-dimensional setting is a good place to learn foundations +and understand key concepts.) + +Let's start with some standard imports: + +```{code-cell} ipython +import matplotlib.pyplot as plt +import numpy as np +``` + + +## Some definitions + +This section sets out the objects of interest and the kinds of properties we study. + +### Composition of functions + +For this lecture you should know the following. + +If + +* $g$ is a function from $A$ to $B$ and +* $f$ is a function from $B$ to $C$, + +then the **composition** $f \circ g$ of $f$ and $g$ is defined by + +$$ + (f \circ g)(x) = f(g(x)) +$$ + +For example, if + +* $A=B=C=\mathbb R$, the set of real numbers, +* $g(x)=x^2$ and $f(x)=\sqrt{x}$, then $(f \circ g)(x) = \sqrt{x^2} = |x|$. + +If $f$ is a function from $A$ to itself, then $f^2$ is the composition of $f$ +with itself. + +For example, if $A = (0, \infty)$, the set of positive numbers, and $f(x) = +\sqrt{x}$, then + +$$ + f^2(x) = \sqrt{\sqrt{x}} = x^{1/4} +$$ + +Similarly, if $n$ is a positive integer, then $f^n$ is $n$ compositions of $f$ with +itself. + +In the example above, $f^n(x) = x^{1/(2^n)}$. + + + +### Dynamic systems + +A **(discrete time) dynamic system** is a set $S$ and a function $g$ that sends +set $S$ back into to itself. + + +Examples of dynamic systems include + +* $S = (0, 1)$ and $g(x) = \sqrt{x}$ +* $S = (0, 1)$ and $g(x) = x^2$ +* $S = \mathbb Z$ (the integers) and $g(x) = 2 x$ + + +On the other hand, if $S = (-1, 1)$ and $g(x) = x+1$, then $S$ and $g$ do not +form a dynamic system, since $g(1) = 2$. + +* $g$ does not always send points in $S$ back into $S$. + +We care about dynamic systems because we can use them to study dynamics! + +Given a dynamic system consisting of set $S$ and function $g$, we can create +a sequence $\{x_t\}$ of points in $S$ by setting + +```{math} +:label: sdsod + x_{t+1} = g(x_t) + \quad \text{ with } + x_0 \text{ given}. +``` + +This means that we choose some number $x_0$ in $S$ and then take + +```{math} +:label: sdstraj + x_0, \quad + x_1 = g(x_0), \quad + x_2 = g(x_1) = g(g(x_0)), \quad \text{etc.} +``` + +This sequence $\{x_t\}$ is called the **trajectory** of $x_0$ under $g$. + +In this setting, $S$ is called the **state space** and $x_t$ is called the +**state variable**. + +Recalling that $g^n$ is the $n$ compositions of $g$ with itself, +we can write the trajectory more simply as + +$$ + x_t = g^t(x_0) \quad \text{ for } t = 0, 1, 2, \ldots +$$ + +In all of what follows, we are going to assume that $S$ is a subset of +$\mathbb R$, the real numbers. + +Equation {eq}`sdsod` is sometimes called a **first order difference equation** + +* first order means dependence on only one lag (i.e., earlier states such as $x_{t-1}$ do not enter into {eq}`sdsod`). + + + +### Example: a linear model + +One simple example of a dynamic system is when $S=\mathbb R$ and $g(x)=ax + +b$, where $a, b$ are constants (sometimes called ``parameters''). + +This leads to the **linear difference equation** + +$$ + x_{t+1} = a x_t + b + \quad \text{ with } + x_0 \text{ given}. +$$ + + +The trajectory of $x_0$ is + +```{math} +:label: sdslinmodpath + +x_0, \quad +a x_0 + b, \quad +a^2 x_0 + a b + b, \quad \text{etc.} +``` + +Continuing in this way, and using our knowledge of {doc}`geometric series +`, we find that, for any $t = 0, 1, 2, \ldots$, + +```{math} +:label: sdslinmod + x_t = a^t x_0 + b \frac{1 - a^t}{1 - a} +``` + +We have an exact expression for $x_t$ for all non-negative integer $t$ and hence a full +understanding of the dynamics. + +Notice in particular that $|a| < 1$, then, by {eq}`sdslinmod`, we have + +```{math} +:label: sdslinmodc + +x_t \to \frac{b}{1 - a} \text{ as } t \to \infty +``` + +regardless of $x_0$. + +This is an example of what is called global stability, a topic we return to +below. + + + + +### Example: a nonlinear model + +In the linear example above, we obtained an exact analytical expression for +$x_t$ in terms of arbitrary non-negative integer $t$ and $x_0$. + +This made analysis of dynamics very easy. + +When models are nonlinear, however, the situation can be quite different. + +For example, in a later lecture {doc}`solow`, we will study the Solow-Swan growth model, which has dynamics + +```{math} +:label: solow_lom2 + +k_{t+1} = s A k_t^{\alpha} + (1 - \delta) k_t +``` + +Here $k=K/L$ is the per capita capital stock, $s$ is the saving rate, $A$ is the total factor productivity, $\alpha$ is the capital share, and $\delta$ is the depreciation rate. + +All these parameter are positive and $0 < \alpha, \delta < 1$. + +If you try to iterate like we did in {eq}`sdslinmodpath`, you will find that +the algebra gets messy quickly. + +Analyzing the dynamics of this model requires a different method (see below). + + + + + + +## Stability + +Consider a dynamic system consisting of set $S \subset \mathbb R$ and +$g$ mapping $S$ to $S$. + +(scalar-dynam:steady-state)= +### Steady states + +A **steady state** of this system is a +point $x^*$ in $S$ such that $x^* = g(x^*)$. + +In other words, $x^*$ is a **fixed point** of the function $g$ in +$S$. + +For example, for the linear model $x_{t+1} = a x_t + b$, you can use the +definition to check that + +* $x^* := b/(1-a)$ is a steady state whenever $a \not= 1$, +* if $a = 1$ and $b=0$, then every $x \in \mathbb R$ is a + steady state, +* if $a = 1$ and $b \not= 0$, then the linear model has no steady + state in $\mathbb R$. + + + +(scalar-dynam:global-stability)= +### Global stability + +A steady state $x^*$ of the dynamic system is called +**globally stable** if, for all $x_0 \in S$, + +$$ +x_t = g^t(x_0) \to x^* \text{ as } t \to \infty +$$ + +For example, in the linear model $x_{t+1} = a x_t + b$ with $a +\not= 1$, the steady state $x^*$ + +* is globally stable if $|a| < 1$ and +* fails to be globally stable otherwise. + +This follows directly from {eq}`sdslinmod`. + + +### Local stability + +A steady state $x^*$ of the dynamic system is called +**locally stable** if there exists an $\epsilon > 0$ such that + +$$ +| x_0 - x^* | < \epsilon +\; \implies \; +x_t = g^t(x_0) \to x^* \text{ as } t \to \infty +$$ + +Obviously every globally stable steady state is also locally stable. + +Here is an example where the converse is not true. + +```{prf:example} +Consider the self-map $g$ on $\mathbb{R}$ defined by $g(x)=x^2$. The fixed point $1$ is not stable. + +For example, $g^t (x)\to\infty$ for any $x>1$. + +However, $0$ is locally stable, because $-1 k_t$. +* If $g$ lies below the 45-degree line at this point, then we have $k_{t+1} < k_t$. +* If $g$ hits the 45-degree line at this point, then we have $k_{t+1} = k_t$, so $k_t$ is a steady state. + +For the Solow-Swan model, there are two steady states when $S = \mathbb R_+ = +[0, \infty)$. + +* the origin $k=0$ +* the unique positive number such that $k = s z k^{\alpha} + (1 - \delta) k$. + +By using some algebra, we can show that in the second case, the steady state is + +$$ +k^* = \left( \frac{sz}{\delta} \right)^{1/(1-\alpha)} +$$ + +### Trajectories + +By the preceding discussion, in regions where $g$ lies above the 45-degree line, we know that the trajectory is increasing. + +The next figure traces out a trajectory in such a region so we can see this more clearly. + +The initial condition is $k_0 = 0.25$. + +```{code-cell} ipython +k0 = 0.25 + +plot45(g, xmin, xmax, k0, num_arrows=5, var='k') +``` + +We can plot the time series of per capita capital corresponding to the figure above as +follows: + +```{code-cell} ipython +ts_plot(g, xmin, xmax, k0, var='k') +``` + +Here's a somewhat longer view: + +```{code-cell} ipython +ts_plot(g, xmin, xmax, k0, ts_length=20, var='k') +``` + +When per capita capital stock is higher than the unique positive steady state, we see that +it declines: + +```{code-cell} ipython +k0 = 2.95 + +plot45(g, xmin, xmax, k0, num_arrows=5, var='k') +``` + +Here is the time series: + +```{code-cell} ipython +ts_plot(g, xmin, xmax, k0, var='k') +``` + +### Complex dynamics + +The Solow-Swan model is nonlinear but still generates very regular dynamics. + +One model that generates irregular dynamics is the **quadratic map** + +$$ +g(x) = 4 x (1 - x), +\qquad x \in [0, 1] +$$ + +Let's have a look at the 45-degree diagram. + +```{code-cell} ipython +xmin, xmax = 0, 1 +g = lambda x: 4 * x * (1 - x) + +x0 = 0.3 +plot45(g, xmin, xmax, x0, num_arrows=0) +``` + +Now let's look at a typical trajectory. + +```{code-cell} ipython +plot45(g, xmin, xmax, x0, num_arrows=6) +``` + +Notice how irregular it is. + +Here is the corresponding time series plot. + +```{code-cell} ipython +ts_plot(g, xmin, xmax, x0, ts_length=6) +``` + +The irregularity is even clearer over a longer time horizon: + +```{code-cell} ipython +ts_plot(g, xmin, xmax, x0, ts_length=20) +``` + +## Exercises + +```{exercise} +:label: sd_ex1 + +Consider again the linear model $x_{t+1} = a x_t + b$ with $a +\not=1$. + +The unique steady state is $b / (1 - a)$. + +The steady state is globally stable if $|a| < 1$. + +Try to illustrate this graphically by looking at a range of initial conditions. + +What differences do you notice in the cases $a \in (-1, 0)$ and $a +\in (0, 1)$? + +Use $a=0.5$ and then $a=-0.5$ and study the trajectories. + +Set $b=1$ throughout. +``` + +```{solution-start} sd_ex1 +:class: dropdown +``` + +We will start with the case $a=0.5$. + +Let's set up the model and plotting region: + +```{code-cell} ipython +a, b = 0.5, 1 +xmin, xmax = -1, 3 +g = lambda x: a * x + b +``` + +Now let's plot a trajectory: + +```{code-cell} ipython +x0 = -0.5 +plot45(g, xmin, xmax, x0, num_arrows=5) +``` + +Here is the corresponding time series, which converges towards the steady +state. + +```{code-cell} ipython +ts_plot(g, xmin, xmax, x0, ts_length=10) +``` + +Now let's try $a=-0.5$ and see what differences we observe. + +Let's set up the model and plotting region: + +```{code-cell} ipython +a, b = -0.5, 1 +xmin, xmax = -1, 3 +g = lambda x: a * x + b +``` + +Now let's plot a trajectory: + +```{code-cell} ipython +x0 = -0.5 +plot45(g, xmin, xmax, x0, num_arrows=5) +``` + +Here is the corresponding time series, which converges towards the steady +state. + +```{code-cell} ipython +ts_plot(g, xmin, xmax, x0, ts_length=10) +``` + +Once again, we have convergence to the steady state but the nature of +convergence differs. + +In particular, the time series jumps from above the steady state to below it +and back again. + +In the current context, the series is said to exhibit **damped oscillations**. + +```{solution-end} +``` diff --git a/content/lectures/schelling.ipynb b/book/_build/html/_sources/schelling.ipynb similarity index 91% rename from content/lectures/schelling.ipynb rename to book/_build/html/_sources/schelling.ipynb index 06957d1..69681db 100644 --- a/content/lectures/schelling.ipynb +++ b/book/_build/html/_sources/schelling.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "54c2700e", + "id": "638e64a9", "metadata": {}, "source": [ "(schelling)=\n", @@ -14,7 +14,7 @@ "\n", "```\n", "\n", - "# Racial Segregation \n", + "# Racial Segregation\n", "\n", "```{index} single: Schelling Segregation Model\n", "```\n", @@ -22,10 +22,6 @@ "```{index} single: Models; Schelling's Segregation Model\n", "```\n", "\n", - "```{contents} Contents\n", - ":depth: 2\n", - "```\n", - "\n", "## Outline\n", "\n", "In 1969, Thomas C. Schelling developed a simple but striking model of racial\n", @@ -67,11 +63,10 @@ { "cell_type": "code", "execution_count": null, - "id": "1fe33c76", + "id": "0bd481b7", "metadata": {}, "outputs": [], "source": [ - "%matplotlib inline\n", "import matplotlib.pyplot as plt\n", "from random import uniform, seed\n", "from math import sqrt\n", @@ -80,10 +75,10 @@ }, { "cell_type": "markdown", - "id": "a727e04a", + "id": "72be2419", "metadata": {}, "source": [ - "## The Model\n", + "## The model\n", "\n", "In this section we will build a version of Schelling's model.\n", "\n", @@ -108,7 +103,7 @@ }, { "cell_type": "markdown", - "id": "a80eff12", + "id": "630c963a", "metadata": {}, "source": [ "### Preferences\n", @@ -131,7 +126,7 @@ }, { "cell_type": "markdown", - "id": "e45e0c71", + "id": "e37c4052", "metadata": {}, "source": [ "### Behavior\n", @@ -167,7 +162,7 @@ }, { "cell_type": "markdown", - "id": "b924cffb", + "id": "b78fa2b7", "metadata": {}, "source": [ "## Results\n", @@ -197,7 +192,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4bb1628e", + "id": "39a62ad8", "metadata": {}, "outputs": [], "source": [ @@ -216,30 +211,30 @@ " b = (self.location[1] - other.location[1])**2\n", " return sqrt(a + b)\n", "\n", - " def happy(self, \n", + " def happy(self,\n", " agents, # List of other agents\n", " num_neighbors=10, # No. of agents viewed as neighbors\n", " require_same_type=5): # How many neighbors must be same type\n", " \"\"\"\n", " True if a sufficient number of nearest neighbors are of the same\n", - " type. \n", + " type.\n", " \"\"\"\n", "\n", " distances = []\n", - " \n", + "\n", " # Distances is a list of pairs (d, agent), where d is distance from\n", " # agent to self\n", " for agent in agents:\n", " if self != agent:\n", " distance = self.get_distance(agent)\n", " distances.append((distance, agent))\n", - " \n", + "\n", " # Sort from smallest to largest, according to distance\n", " distances.sort()\n", - " \n", + "\n", " # Extract the neighboring agents\n", " neighbors = [agent for d, agent in distances[:num_neighbors]]\n", - " \n", + "\n", " # Count how many neighbors have the same type as self\n", " num_same_type = sum(self.type == agent.type for agent in neighbors)\n", " return num_same_type >= require_same_type\n", @@ -252,7 +247,7 @@ }, { "cell_type": "markdown", - "id": "384b5ea3", + "id": "dc47a542", "metadata": {}, "source": [ "Here's some code that takes a list of agents and produces a plot showing their\n", @@ -265,7 +260,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5d1bcf81", + "id": "2119c858", "metadata": {}, "outputs": [], "source": [ @@ -285,9 +280,9 @@ " fig, ax = plt.subplots()\n", " plot_args = {'markersize': 8, 'alpha': 0.8}\n", " ax.set_facecolor('azure')\n", - " ax.plot(x_values_0, y_values_0, \n", + " ax.plot(x_values_0, y_values_0,\n", " 'o', markerfacecolor='orange', **plot_args)\n", - " ax.plot(x_values_1, y_values_1, \n", + " ax.plot(x_values_1, y_values_1,\n", " 'o', markerfacecolor='green', **plot_args)\n", " ax.set_title(f'Cycle {cycle_num-1}')\n", " plt.show()" @@ -295,7 +290,7 @@ }, { "cell_type": "markdown", - "id": "34284ec1", + "id": "81de02d5", "metadata": {}, "source": [ "And here's some pseudocode for the main loop, where we cycle through the\n", @@ -317,18 +312,18 @@ { "cell_type": "code", "execution_count": null, - "id": "12c1ec53", + "id": "61e87234", "metadata": {}, "outputs": [], "source": [ "def run_simulation(num_of_type_0=600,\n", " num_of_type_1=600,\n", - " max_iter=100_000, # Maximum number of iterations \n", - " set_seed=1234): \n", + " max_iter=100_000, # Maximum number of iterations\n", + " set_seed=1234):\n", "\n", " # Set the seed for reproducibility\n", - " seed(set_seed) \n", - " \n", + " seed(set_seed)\n", + "\n", " # Create a list of agents of type 0\n", " agents = [Agent(0) for i in range(num_of_type_0)]\n", " # Append a list of agents of type 1\n", @@ -336,11 +331,11 @@ "\n", " # Initialize a counter\n", " count = 1\n", - " \n", + "\n", " # Plot the initial distribution\n", " plot_distribution(agents, count)\n", - " \n", - " # Loop until no agent wishes to move \n", + "\n", + " # Loop until no agent wishes to move\n", " while count < max_iter:\n", " print('Entering loop ', count)\n", " count += 1\n", @@ -352,20 +347,19 @@ " no_one_moved = False\n", " if no_one_moved:\n", " break\n", - " \n", + "\n", " # Plot final distribution\n", " plot_distribution(agents, count)\n", "\n", " if count < max_iter:\n", " print(f'Converged after {count} iterations.')\n", " else:\n", - " print('Hit iteration bound and terminated.')\n", - " " + " print('Hit iteration bound and terminated.')\n" ] }, { "cell_type": "markdown", - "id": "73ae91c2", + "id": "a7b1bb7a", "metadata": {}, "source": [ "Let's have a look at the results." @@ -374,7 +368,7 @@ { "cell_type": "code", "execution_count": null, - "id": "0f2eefd4", + "id": "d1dbd1c4", "metadata": {}, "outputs": [], "source": [ @@ -383,7 +377,7 @@ }, { "cell_type": "markdown", - "id": "31194751", + "id": "5d887438", "metadata": {}, "source": [ "As discussed above, agents are initially mixed randomly together.\n", @@ -412,7 +406,7 @@ "optimize than procedural code (i.e., code based around functions rather than\n", "objects and methods).\n", "\n", - "Try writing a new version of the model that stores \n", + "Try writing a new version of the model that stores\n", "\n", "* the locations of all agents as a 2D NumPy array of floats.\n", "* the types of all agents as a flat NumPy array of integers.\n", @@ -443,12 +437,11 @@ { "cell_type": "code", "execution_count": null, - "id": "61addfdd", + "id": "9e4f7f73", "metadata": {}, "outputs": [], "source": [ "from numpy.random import uniform, randint\n", - "from numba import njit\n", "\n", "n = 1000 # number of agents (agents = 0, ..., n-1)\n", "k = 10 # number of agents regarded as neighbors\n", @@ -459,13 +452,10 @@ " types = randint(0, high=2, size=n) # label zero or one\n", " return locations, types\n", "\n", - "@njit # Use Numba to accelerate computation\n", + "\n", "def compute_distances_from_loc(loc, locations):\n", - " \" Compute distance from location loc to all other points. \"\n", - " distances = np.empty(n)\n", - " for j in range(n):\n", - " distances[j] = np.linalg.norm(loc - locations[j, :])\n", - " return distances\n", + " \"\"\" Compute distance from location loc to all other points. \"\"\"\n", + " return np.linalg.norm(loc - locations, axis=1)\n", "\n", "def get_neighbors(loc, locations):\n", " \" Get all neighbors of a given location. \"\n", @@ -490,7 +480,7 @@ " for i in range(n):\n", " happy_sum += is_happy(i, locations, types)\n", " return happy_sum\n", - " \n", + "\n", "def update_agent(i, locations, types):\n", " \" Move agent if unhappy. \"\n", " moved = False\n", @@ -505,11 +495,11 @@ " colors = 'orange', 'green'\n", " for agent_type, color in zip((0, 1), colors):\n", " idx = (types == agent_type)\n", - " ax.plot(locations[idx, 0], \n", - " locations[idx, 1], \n", - " 'o', \n", + " ax.plot(locations[idx, 0],\n", + " locations[idx, 1],\n", + " 'o',\n", " markersize=8,\n", - " markerfacecolor=color, \n", + " markerfacecolor=color,\n", " alpha=0.8)\n", " ax.set_title(title)\n", " plt.show()\n", @@ -531,7 +521,7 @@ " i = randint(0, n)\n", " moved = update_agent(i, locations, types)\n", "\n", - " if flip_prob > 0: \n", + " if flip_prob > 0:\n", " # flip agent i's type with probability epsilon\n", " U = uniform()\n", " if U < flip_prob:\n", @@ -539,7 +529,7 @@ " types[i] = 0 if current_type == 1 else 1\n", "\n", " # Every so many updates, plot and test for convergence\n", - " if current_iter % test_freq == 0: \n", + " if current_iter % test_freq == 0:\n", " cycle = current_iter / n\n", " plot_distribution(locations, types, f'iteration {current_iter}')\n", " if count_happy(locations, types) == n:\n", @@ -554,7 +544,7 @@ }, { "cell_type": "markdown", - "id": "eb443685", + "id": "146255dd", "metadata": {}, "source": [ "```{solution-end}\n", @@ -563,7 +553,7 @@ }, { "cell_type": "markdown", - "id": "3f86f0fc", + "id": "cac7366c", "metadata": {}, "source": [ "When we run this we again find that mixed neighborhoods break down and segregation emerges.\n", @@ -574,7 +564,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6a40b10c", + "id": "d2fdf117", "metadata": {}, "outputs": [], "source": [ @@ -584,19 +574,48 @@ { "cell_type": "code", "execution_count": null, - "id": "ebb75eda", + "id": "88ba0e02", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.1" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 12, + 68, + 73, + 97, + 116, + 148, + 173, + 221, + 229, + 252, + 269, + 310, + 314, + 316, + 371, + 471, + 476, + 482, + 486 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/schelling.md b/book/_build/html/_sources/schelling.md new file mode 100644 index 0000000..8032e10 --- /dev/null +++ b/book/_build/html/_sources/schelling.md @@ -0,0 +1,488 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.1 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +(schelling)= +```{raw} html + +``` + +# Racial Segregation + +```{index} single: Schelling Segregation Model +``` + +```{index} single: Models; Schelling's Segregation Model +``` + +## Outline + +In 1969, Thomas C. Schelling developed a simple but striking model of racial +segregation {cite}`Schelling1969`. + +His model studies the dynamics of racially mixed neighborhoods. + +Like much of Schelling's work, the model shows how local interactions can lead +to surprising aggregate outcomes. + +It studies a setting where agents (think of households) have relatively mild +preference for neighbors of the same race. + +For example, these agents might be comfortable with a mixed race neighborhood +but uncomfortable when they feel "surrounded" by people from a different race. + +Schelling illustrated the follow surprising result: in such a setting, mixed +race neighborhoods are likely to be unstable, tending to collapse over time. + +In fact the model predicts strongly divided neighborhoods, with high levels of +segregation. + +In other words, extreme segregation outcomes arise even though people's +preferences are not particularly extreme. + +These extreme outcomes happen because of *interactions* between agents in the +model (e.g., households in a city) that drive self-reinforcing dynamics in the +model. + +These ideas will become clearer as the lecture unfolds. + +In recognition of his work on segregation and other research, Schelling was +awarded the 2005 Nobel Prize in Economic Sciences (joint with Robert Aumann). + + +Let's start with some imports: + +```{code-cell} ipython3 +import matplotlib.pyplot as plt +from random import uniform, seed +from math import sqrt +import numpy as np +``` + +## The model + +In this section we will build a version of Schelling's model. + +### Set-Up + +We will cover a variation of Schelling's model that is different from the +original but also easy to program and, at the same time, captures his main +idea. + +Suppose we have two types of people: orange people and green people. + +Assume there are $n$ of each type. + +These agents all live on a single unit square. + +Thus, the location (e.g, address) of an agent is just a point $(x, y)$, where +$0 < x, y < 1$. + +* The set of all points $(x,y)$ satisfying $0 < x, y < 1$ is called the **unit square** +* Below we denote the unit square by $S$ + ++++ + +### Preferences + +We will say that an agent is *happy* if 5 or more of her 10 nearest neighbors are of the same type. + +An agent who is not happy is called *unhappy*. + +For example, + +* if an agent is orange and 5 of her 10 nearest neighbors are orange, then she is happy. +* if an agent is green and 8 of her 10 nearest neighbors are orange, then she is unhappy. + +'Nearest' is in terms of [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance). + +An important point to note is that agents are **not** averse to living in mixed areas. + +They are perfectly happy if half of their neighbors are of the other color. + ++++ + +### Behavior + +Initially, agents are mixed together (integrated). + +In particular, we assume that the initial location of each agent is an +independent draw from a bivariate uniform distribution on the unit square $S$. + +* First their $x$ coordinate is drawn from a uniform distribution on $(0,1)$ +* Then, independently, their $y$ coordinate is drawn from the same distribution. + +Now, cycling through the set of all agents, each agent is now given the chance to stay or move. + +Each agent stays if they are happy and moves if they are unhappy. + +The algorithm for moving is as follows + +```{prf:algorithm} Jump Chain Algorithm +:label: move_algo + +1. Draw a random location in $S$ +1. If happy at new location, move there +1. Otherwise, go to step 1 + +``` + +We cycle continuously through the agents, each time allowing an unhappy agent +to move. + +We continue to cycle until no one wishes to move. + ++++ + +## Results + +Let's now implement and run this simulation. + +In what follows, agents are modeled as [objects](https://python-programming.quantecon.org/python_oop.html). + +Here's an indication of their structure: + +```{code-block} none +* Data: + + * type (green or orange) + * location + +* Methods: + + * determine whether happy or not given locations of other agents + * If not happy, move + * find a new location where happy +``` + +Let's build them. + +```{code-cell} ipython3 +class Agent: + + def __init__(self, type): + self.type = type + self.draw_location() + + def draw_location(self): + self.location = uniform(0, 1), uniform(0, 1) + + def get_distance(self, other): + "Computes the euclidean distance between self and other agent." + a = (self.location[0] - other.location[0])**2 + b = (self.location[1] - other.location[1])**2 + return sqrt(a + b) + + def happy(self, + agents, # List of other agents + num_neighbors=10, # No. of agents viewed as neighbors + require_same_type=5): # How many neighbors must be same type + """ + True if a sufficient number of nearest neighbors are of the same + type. + """ + + distances = [] + + # Distances is a list of pairs (d, agent), where d is distance from + # agent to self + for agent in agents: + if self != agent: + distance = self.get_distance(agent) + distances.append((distance, agent)) + + # Sort from smallest to largest, according to distance + distances.sort() + + # Extract the neighboring agents + neighbors = [agent for d, agent in distances[:num_neighbors]] + + # Count how many neighbors have the same type as self + num_same_type = sum(self.type == agent.type for agent in neighbors) + return num_same_type >= require_same_type + + def update(self, agents): + "If not happy, then randomly choose new locations until happy." + while not self.happy(agents): + self.draw_location() +``` + +Here's some code that takes a list of agents and produces a plot showing their +locations on the unit square. + +Orange agents are represented by orange dots and green ones are represented by +green dots. + +```{code-cell} ipython3 +def plot_distribution(agents, cycle_num): + "Plot the distribution of agents after cycle_num rounds of the loop." + x_values_0, y_values_0 = [], [] + x_values_1, y_values_1 = [], [] + # == Obtain locations of each type == # + for agent in agents: + x, y = agent.location + if agent.type == 0: + x_values_0.append(x) + y_values_0.append(y) + else: + x_values_1.append(x) + y_values_1.append(y) + fig, ax = plt.subplots() + plot_args = {'markersize': 8, 'alpha': 0.8} + ax.set_facecolor('azure') + ax.plot(x_values_0, y_values_0, + 'o', markerfacecolor='orange', **plot_args) + ax.plot(x_values_1, y_values_1, + 'o', markerfacecolor='green', **plot_args) + ax.set_title(f'Cycle {cycle_num-1}') + plt.show() +``` + +And here's some pseudocode for the main loop, where we cycle through the +agents until no one wishes to move. + +The pseudocode is + +```{code-block} none +plot the distribution +while agents are still moving + for agent in agents + give agent the opportunity to move +plot the distribution +``` + +The real code is below + +```{code-cell} ipython3 +def run_simulation(num_of_type_0=600, + num_of_type_1=600, + max_iter=100_000, # Maximum number of iterations + set_seed=1234): + + # Set the seed for reproducibility + seed(set_seed) + + # Create a list of agents of type 0 + agents = [Agent(0) for i in range(num_of_type_0)] + # Append a list of agents of type 1 + agents.extend(Agent(1) for i in range(num_of_type_1)) + + # Initialize a counter + count = 1 + + # Plot the initial distribution + plot_distribution(agents, count) + + # Loop until no agent wishes to move + while count < max_iter: + print('Entering loop ', count) + count += 1 + no_one_moved = True + for agent in agents: + old_location = agent.location + agent.update(agents) + if agent.location != old_location: + no_one_moved = False + if no_one_moved: + break + + # Plot final distribution + plot_distribution(agents, count) + + if count < max_iter: + print(f'Converged after {count} iterations.') + else: + print('Hit iteration bound and terminated.') + +``` + +Let's have a look at the results. + +```{code-cell} ipython3 +run_simulation() +``` + +As discussed above, agents are initially mixed randomly together. + +But after several cycles, they become segregated into distinct regions. + +In this instance, the program terminated after a small number of cycles +through the set of agents, indicating that all agents had reached a state of +happiness. + +What is striking about the pictures is how rapidly racial integration breaks down. + +This is despite the fact that people in the model don't actually mind living mixed with the other type. + +Even with these preferences, the outcome is a high degree of segregation. + + + +## Exercises + +```{exercise-start} +:label: schelling_ex1 +``` + +The object oriented style that we used for coding above is neat but harder to +optimize than procedural code (i.e., code based around functions rather than +objects and methods). + +Try writing a new version of the model that stores + +* the locations of all agents as a 2D NumPy array of floats. +* the types of all agents as a flat NumPy array of integers. + +Write functions that act on this data to update the model using the logic +similar to that described above. + +However, implement the following two changes: + +1. Agents are offered a move at random (i.e., selected randomly and given the + opportunity to move). +2. After an agent has moved, flip their type with probability 0.01 + +The second change introduces extra randomness into the model. + +(We can imagine that, every so often, an agent moves to a different city and, +with small probability, is replaced by an agent of the other type.) + +```{exercise-end} +``` + +```{solution-start} schelling_ex1 +:class: dropdown +``` +solution here + +```{code-cell} ipython3 +from numpy.random import uniform, randint + +n = 1000 # number of agents (agents = 0, ..., n-1) +k = 10 # number of agents regarded as neighbors +require_same_type = 5 # want >= require_same_type neighbors of the same type + +def initialize_state(): + locations = uniform(size=(n, 2)) + types = randint(0, high=2, size=n) # label zero or one + return locations, types + + +def compute_distances_from_loc(loc, locations): + """ Compute distance from location loc to all other points. """ + return np.linalg.norm(loc - locations, axis=1) + +def get_neighbors(loc, locations): + " Get all neighbors of a given location. " + all_distances = compute_distances_from_loc(loc, locations) + indices = np.argsort(all_distances) # sort agents by distance to loc + neighbors = indices[:k] # keep the k closest ones + return neighbors + +def is_happy(i, locations, types): + happy = True + agent_loc = locations[i, :] + agent_type = types[i] + neighbors = get_neighbors(agent_loc, locations) + neighbor_types = types[neighbors] + if sum(neighbor_types == agent_type) < require_same_type: + happy = False + return happy + +def count_happy(locations, types): + " Count the number of happy agents. " + happy_sum = 0 + for i in range(n): + happy_sum += is_happy(i, locations, types) + return happy_sum + +def update_agent(i, locations, types): + " Move agent if unhappy. " + moved = False + while not is_happy(i, locations, types): + moved = True + locations[i, :] = uniform(), uniform() + return moved + +def plot_distribution(locations, types, title, savepdf=False): + " Plot the distribution of agents after cycle_num rounds of the loop." + fig, ax = plt.subplots() + colors = 'orange', 'green' + for agent_type, color in zip((0, 1), colors): + idx = (types == agent_type) + ax.plot(locations[idx, 0], + locations[idx, 1], + 'o', + markersize=8, + markerfacecolor=color, + alpha=0.8) + ax.set_title(title) + plt.show() + +def sim_random_select(max_iter=100_000, flip_prob=0.01, test_freq=10_000): + """ + Simulate by randomly selecting one household at each update. + + Flip the color of the household with probability `flip_prob`. + + """ + + locations, types = initialize_state() + current_iter = 0 + + while current_iter <= max_iter: + + # Choose a random agent and update them + i = randint(0, n) + moved = update_agent(i, locations, types) + + if flip_prob > 0: + # flip agent i's type with probability epsilon + U = uniform() + if U < flip_prob: + current_type = types[i] + types[i] = 0 if current_type == 1 else 1 + + # Every so many updates, plot and test for convergence + if current_iter % test_freq == 0: + cycle = current_iter / n + plot_distribution(locations, types, f'iteration {current_iter}') + if count_happy(locations, types) == n: + print(f"Converged at iteration {current_iter}") + break + + current_iter += 1 + + if current_iter > max_iter: + print(f"Terminating at iteration {current_iter}") +``` + +```{solution-end} +``` + ++++ + +When we run this we again find that mixed neighborhoods break down and segregation emerges. + +Here's a sample run. + +```{code-cell} ipython3 +sim_random_select(max_iter=50_000, flip_prob=0.01, test_freq=10_000) +``` + +```{code-cell} ipython3 + +``` diff --git a/content/lectures/short_path.ipynb b/book/_build/html/_sources/short_path.ipynb similarity index 93% rename from content/lectures/short_path.ipynb rename to book/_build/html/_sources/short_path.ipynb index 98d791f..1b029cc 100644 --- a/content/lectures/short_path.ipynb +++ b/book/_build/html/_sources/short_path.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "9156396f", + "id": "cd30f18a", "metadata": {}, "source": [ "(short_path)=\n", @@ -19,10 +19,6 @@ "```{index} single: Dynamic Programming; Shortest Paths\n", "```\n", "\n", - "```{contents} Contents\n", - ":depth: 2\n", - "```\n", - "\n", "## Overview\n", "\n", "The shortest path problem is a [classic problem](https://en.wikipedia.org/wiki/Shortest_path) in mathematics and computer science with applications in\n", @@ -48,7 +44,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b8fb1690", + "id": "0496fef5", "metadata": {}, "outputs": [], "source": [ @@ -57,10 +53,10 @@ }, { "cell_type": "markdown", - "id": "441c5fd7", + "id": "c75fe860", "metadata": {}, "source": [ - "## Outline of the Problem\n", + "## Outline of the problem\n", "\n", "The shortest path problem is one of finding how to traverse a [graph](https://en.wikipedia.org/wiki/Graph_%28mathematics%29) from one specified node to another at minimum cost.\n", "\n", @@ -81,7 +77,7 @@ "\n", "* Minimum cost for supplier to reach a destination.\n", "* Routing of packets on the internet (minimize time).\n", - "* Etc., etc.\n", + "* etc., etc.\n", "\n", "For this simple graph, a quick scan of the edges shows that the optimal paths are\n", "\n", @@ -97,13 +93,13 @@ "\n", "```\n", "\n", - "## Finding Least-Cost Paths\n", + "## Finding least-cost paths\n", "\n", "For large graphs, we need a systematic solution.\n", "\n", "Let $J(v)$ denote the minimum cost-to-go from node $v$, understood as the total cost from $v$ if we take the best route.\n", "\n", - "Suppose that we know $J(v)$ for each node $v$, as shown below for the graph from the preceding example\n", + "Suppose that we know $J(v)$ for each node $v$, as shown below for the graph from the preceding example.\n", "\n", "```{figure} /_static/lecture_specific/short_path/graph2.png\n", "\n", @@ -140,19 +136,19 @@ "J(v) = \\min_{w \\in F_v} \\{ c(v, w) + J(w) \\}\n", "```\n", "\n", - "This is known as the *Bellman equation*, after the mathematician Richard Bellman.\n", + "This is known as the **Bellman equation**, after the mathematician [Richard Bellman](https://en.wikipedia.org/wiki/Richard_E._Bellman).\n", "\n", "The Bellman equation can be thought of as a restriction that $J$ must\n", "satisfy.\n", "\n", "What we want to do now is use this restriction to compute $J$.\n", "\n", - "## Solving for Minimum Cost-to-Go\n", + "## Solving for minimum cost-to-go\n", "\n", "Let's look at an algorithm for computing $J$ and then think about how to\n", "implement it.\n", "\n", - "### The Algorithm\n", + "### The algorithm\n", "\n", "The standard algorithm for finding $J$ is to start an initial guess and then iterate.\n", "\n", @@ -211,7 +207,7 @@ { "cell_type": "code", "execution_count": null, - "id": "2661fc5b", + "id": "08dd4541", "metadata": {}, "outputs": [], "source": [ @@ -228,12 +224,12 @@ }, { "cell_type": "markdown", - "id": "9fb4ad16", + "id": "48a6eba9", "metadata": {}, "source": [ "Notice that the cost of staying still (on the principle diagonal) is set to\n", "\n", - "* np.inf for non-destination nodes --- moving on is required.\n", + "* `np.inf` for non-destination nodes --- moving on is required.\n", "* 0 for the destination node --- here is where we stop.\n", "\n", "For the sequence of approximations $\\{J_n\\}$ of the cost-to-go functions, we can use NumPy arrays.\n", @@ -244,7 +240,7 @@ { "cell_type": "code", "execution_count": null, - "id": "dfeebde2", + "id": "8a1c526b", "metadata": {}, "outputs": [], "source": [ @@ -257,25 +253,21 @@ "\n", "while i < max_iter:\n", " for v in nodes:\n", - " # minimize Q[v, w] + J[w] over all choices of w\n", - " lowest_cost = inf\n", - " for w in nodes:\n", - " cost = Q[v, w] + J[w]\n", - " if cost < lowest_cost:\n", - " lowest_cost = cost\n", - " next_J[v] = lowest_cost\n", - " if np.equal(next_J, J).all():\n", + " # Minimize Q[v, w] + J[w] over all choices of w\n", + " next_J[v] = np.min(Q[v, :] + J)\n", + " \n", + " if np.array_equal(next_J, J): \n", " break\n", - " else:\n", - " J[:] = next_J # Copy contents of next_J to J\n", - " i += 1\n", + " \n", + " J[:] = next_J # Copy contents of next_J to J\n", + " i += 1\n", "\n", "print(\"The cost-to-go function is\", J)" ] }, { "cell_type": "markdown", - "id": "5ba658bb", + "id": "46a33c27", "metadata": {}, "source": [ "This matches with the numbers we obtained by inspection above.\n", @@ -312,7 +304,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5c7af7f5", + "id": "3ae4e525", "metadata": {}, "outputs": [], "source": [ @@ -421,7 +413,7 @@ }, { "cell_type": "markdown", - "id": "7cda6c24", + "id": "2cbd502a", "metadata": {}, "source": [ "```{exercise-end}\n", @@ -437,7 +429,7 @@ { "cell_type": "code", "execution_count": null, - "id": "81d7f3e5", + "id": "39712dd1", "metadata": {}, "outputs": [], "source": [ @@ -466,7 +458,7 @@ }, { "cell_type": "markdown", - "id": "b820d74a", + "id": "1c038572", "metadata": {}, "source": [ "In addition, let's write\n", @@ -482,16 +474,12 @@ { "cell_type": "code", "execution_count": null, - "id": "c7102951", + "id": "6134ca95", "metadata": {}, "outputs": [], "source": [ "def bellman(J, Q):\n", - " num_nodes = Q.shape[0]\n", - " next_J = np.empty_like(J)\n", - " for v in range(num_nodes):\n", - " next_J[v] = np.min(Q[v, :] + J)\n", - " return next_J\n", + " return np.min(Q + J, axis=1)\n", "\n", "\n", "def compute_cost_to_go(Q):\n", @@ -513,7 +501,7 @@ }, { "cell_type": "markdown", - "id": "330ca8e1", + "id": "0d15e800", "metadata": {}, "source": [ "We used np.allclose() rather than testing exact equality because we are\n", @@ -526,7 +514,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8368151d", + "id": "b97b41b4", "metadata": {}, "outputs": [], "source": [ @@ -546,7 +534,7 @@ }, { "cell_type": "markdown", - "id": "dba50533", + "id": "56ad5a8f", "metadata": {}, "source": [ "Okay, now we have the necessary functions, let's call them to do the job we were assigned." @@ -555,7 +543,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ca8cec8c", + "id": "57a6b0cc", "metadata": {}, "outputs": [], "source": [ @@ -566,7 +554,7 @@ }, { "cell_type": "markdown", - "id": "0d5334a1", + "id": "1e8eb877", "metadata": {}, "source": [ "The total cost of the path should agree with $J[0]$ so let's check this." @@ -575,7 +563,7 @@ { "cell_type": "code", "execution_count": null, - "id": "eb56ba97", + "id": "e630d945", "metadata": {}, "outputs": [], "source": [ @@ -584,7 +572,7 @@ }, { "cell_type": "markdown", - "id": "0f94a3ef", + "id": "e0cfce96", "metadata": {}, "source": [ "```{solution-end}\n", @@ -593,12 +581,39 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst" + } + }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" - } + }, + "source_map": [ + 10, + 47, + 49, + 198, + 208, + 219, + 239, + 271, + 373, + 384, + 406, + 417, + 437, + 445, + 458, + 462, + 466, + 470, + 472 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/short_path.md b/book/_build/html/_sources/short_path.md new file mode 100644 index 0000000..ce547ef --- /dev/null +++ b/book/_build/html/_sources/short_path.md @@ -0,0 +1,475 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst +kernelspec: + display_name: Python 3 + language: python + name: python3 +--- + +(short_path)= +```{raw} html + +``` + +# Shortest Paths + +```{index} single: Dynamic Programming; Shortest Paths +``` + +## Overview + +The shortest path problem is a [classic problem](https://en.wikipedia.org/wiki/Shortest_path) in mathematics and computer science with applications in + +* Economics (sequential decision making, analysis of social networks, etc.) +* Operations research and transportation +* Robotics and artificial intelligence +* Telecommunication network design and routing +* etc., etc. + +Variations of the methods we discuss in this lecture are used millions of times every day, in applications such as + +* Google Maps +* routing packets on the internet + +For us, the shortest path problem also provides a nice introduction to the logic of **dynamic programming**. + +Dynamic programming is an extremely powerful optimization technique that we apply in many lectures on this site. + +The only scientific library we'll need in what follows is NumPy: + +```{code-cell} python3 +import numpy as np +``` + +## Outline of the problem + +The shortest path problem is one of finding how to traverse a [graph](https://en.wikipedia.org/wiki/Graph_%28mathematics%29) from one specified node to another at minimum cost. + +Consider the following graph + +```{figure} /_static/lecture_specific/short_path/graph.png + +``` + +We wish to travel from node (vertex) A to node G at minimum cost + +* Arrows (edges) indicate the movements we can take. +* Numbers on edges indicate the cost of traveling that edge. + +(Graphs such as the one above are called weighted [directed graphs](https://en.wikipedia.org/wiki/Directed_graph).) + +Possible interpretations of the graph include + +* Minimum cost for supplier to reach a destination. +* Routing of packets on the internet (minimize time). +* etc., etc. + +For this simple graph, a quick scan of the edges shows that the optimal paths are + +* A, C, F, G at cost 8 + +```{figure} /_static/lecture_specific/short_path/graph4.png + +``` + +* A, D, F, G at cost 8 + +```{figure} /_static/lecture_specific/short_path/graph3.png + +``` + +## Finding least-cost paths + +For large graphs, we need a systematic solution. + +Let $J(v)$ denote the minimum cost-to-go from node $v$, understood as the total cost from $v$ if we take the best route. + +Suppose that we know $J(v)$ for each node $v$, as shown below for the graph from the preceding example. + +```{figure} /_static/lecture_specific/short_path/graph2.png + +``` + +Note that $J(G) = 0$. + +The best path can now be found as follows + +1. Start at node $v = A$ +1. From current node $v$, move to any node that solves + +```{math} +:label: spprebell + +\min_{w \in F_v} \{ c(v, w) + J(w) \} +``` + +where + +* $F_v$ is the set of nodes that can be reached from $v$ in one step. +* $c(v, w)$ is the cost of traveling from $v$ to $w$. + +Hence, if we know the function $J$, then finding the best path is almost trivial. + +But how can we find the cost-to-go function $J$? + +Some thought will convince you that, for every node $v$, +the function $J$ satisfies + +```{math} +:label: spbell + +J(v) = \min_{w \in F_v} \{ c(v, w) + J(w) \} +``` + +This is known as the **Bellman equation**, after the mathematician [Richard Bellman](https://en.wikipedia.org/wiki/Richard_E._Bellman). + +The Bellman equation can be thought of as a restriction that $J$ must +satisfy. + +What we want to do now is use this restriction to compute $J$. + +## Solving for minimum cost-to-go + +Let's look at an algorithm for computing $J$ and then think about how to +implement it. + +### The algorithm + +The standard algorithm for finding $J$ is to start an initial guess and then iterate. + +This is a standard approach to solving nonlinear equations, often called +the method of **successive approximations**. + +Our initial guess will be + +```{math} +:label: spguess + +J_0(v) = 0 \text{ for all } v +``` + +Now + +1. Set $n = 0$ +1. Set $J_{n+1} (v) = \min_{w \in F_v} \{ c(v, w) + J_n(w) \}$ for all $v$ +1. If $J_{n+1}$ and $J_n$ are not equal then increment $n$, go to 2 + +This sequence converges to $J$. + +Although we omit the proof, we'll prove similar claims in our other lectures +on dynamic programming. + +### Implementation + +Having an algorithm is a good start, but we also need to think about how to +implement it on a computer. + +First, for the cost function $c$, we'll implement it as a matrix +$Q$, where a typical element is + +$$ +Q(v, w) += +\begin{cases} + & c(v, w) \text{ if } w \in F_v \\ + & +\infty \text{ otherwise } +\end{cases} +$$ + +In this context $Q$ is usually called the **distance matrix**. + +We're also numbering the nodes now, with $A = 0$, so, for example + +$$ +Q(1, 2) += +\text{ the cost of traveling from B to C } +$$ + +For example, for the simple graph above, we set + +```{code-cell} python3 +from numpy import inf + +Q = np.array([[inf, 1, 5, 3, inf, inf, inf], + [inf, inf, inf, 9, 6, inf, inf], + [inf, inf, inf, inf, inf, 2, inf], + [inf, inf, inf, inf, inf, 4, 8], + [inf, inf, inf, inf, inf, inf, 4], + [inf, inf, inf, inf, inf, inf, 1], + [inf, inf, inf, inf, inf, inf, 0]]) +``` + +Notice that the cost of staying still (on the principle diagonal) is set to + +* `np.inf` for non-destination nodes --- moving on is required. +* 0 for the destination node --- here is where we stop. + +For the sequence of approximations $\{J_n\}$ of the cost-to-go functions, we can use NumPy arrays. + +Let's try with this example and see how we go: + +```{code-cell} python3 +nodes = range(7) # Nodes = 0, 1, ..., 6 +J = np.zeros_like(nodes, dtype=int) # Initial guess +next_J = np.empty_like(nodes, dtype=int) # Stores updated guess + +max_iter = 500 +i = 0 + +while i < max_iter: + for v in nodes: + # Minimize Q[v, w] + J[w] over all choices of w + next_J[v] = np.min(Q[v, :] + J) + + if np.array_equal(next_J, J): + break + + J[:] = next_J # Copy contents of next_J to J + i += 1 + +print("The cost-to-go function is", J) +``` + +This matches with the numbers we obtained by inspection above. + +But, importantly, we now have a methodology for tackling large graphs. + +## Exercises + + +```{exercise-start} +:label: short_path_ex1 +``` + +The text below describes a weighted directed graph. + +The line `node0, node1 0.04, node8 11.11, node14 72.21` means that from node0 we can go to + +* node1 at cost 0.04 +* node8 at cost 11.11 +* node14 at cost 72.21 + +No other nodes can be reached directly from node0. + +Other lines have a similar interpretation. + +Your task is to use the algorithm given above to find the optimal path and its cost. + +```{note} +You will be dealing with floating point numbers now, rather than +integers, so consider replacing `np.equal()` with `np.allclose()`. +``` + +```{code-cell} python3 +%%file graph.txt +node0, node1 0.04, node8 11.11, node14 72.21 +node1, node46 1247.25, node6 20.59, node13 64.94 +node2, node66 54.18, node31 166.80, node45 1561.45 +node3, node20 133.65, node6 2.06, node11 42.43 +node4, node75 3706.67, node5 0.73, node7 1.02 +node5, node45 1382.97, node7 3.33, node11 34.54 +node6, node31 63.17, node9 0.72, node10 13.10 +node7, node50 478.14, node9 3.15, node10 5.85 +node8, node69 577.91, node11 7.45, node12 3.18 +node9, node70 2454.28, node13 4.42, node20 16.53 +node10, node89 5352.79, node12 1.87, node16 25.16 +node11, node94 4961.32, node18 37.55, node20 65.08 +node12, node84 3914.62, node24 34.32, node28 170.04 +node13, node60 2135.95, node38 236.33, node40 475.33 +node14, node67 1878.96, node16 2.70, node24 38.65 +node15, node91 3597.11, node17 1.01, node18 2.57 +node16, node36 392.92, node19 3.49, node38 278.71 +node17, node76 783.29, node22 24.78, node23 26.45 +node18, node91 3363.17, node23 16.23, node28 55.84 +node19, node26 20.09, node20 0.24, node28 70.54 +node20, node98 3523.33, node24 9.81, node33 145.80 +node21, node56 626.04, node28 36.65, node31 27.06 +node22, node72 1447.22, node39 136.32, node40 124.22 +node23, node52 336.73, node26 2.66, node33 22.37 +node24, node66 875.19, node26 1.80, node28 14.25 +node25, node70 1343.63, node32 36.58, node35 45.55 +node26, node47 135.78, node27 0.01, node42 122.00 +node27, node65 480.55, node35 48.10, node43 246.24 +node28, node82 2538.18, node34 21.79, node36 15.52 +node29, node64 635.52, node32 4.22, node33 12.61 +node30, node98 2616.03, node33 5.61, node35 13.95 +node31, node98 3350.98, node36 20.44, node44 125.88 +node32, node97 2613.92, node34 3.33, node35 1.46 +node33, node81 1854.73, node41 3.23, node47 111.54 +node34, node73 1075.38, node42 51.52, node48 129.45 +node35, node52 17.57, node41 2.09, node50 78.81 +node36, node71 1171.60, node54 101.08, node57 260.46 +node37, node75 269.97, node38 0.36, node46 80.49 +node38, node93 2767.85, node40 1.79, node42 8.78 +node39, node50 39.88, node40 0.95, node41 1.34 +node40, node75 548.68, node47 28.57, node54 53.46 +node41, node53 18.23, node46 0.28, node54 162.24 +node42, node59 141.86, node47 10.08, node72 437.49 +node43, node98 2984.83, node54 95.06, node60 116.23 +node44, node91 807.39, node46 1.56, node47 2.14 +node45, node58 79.93, node47 3.68, node49 15.51 +node46, node52 22.68, node57 27.50, node67 65.48 +node47, node50 2.82, node56 49.31, node61 172.64 +node48, node99 2564.12, node59 34.52, node60 66.44 +node49, node78 53.79, node50 0.51, node56 10.89 +node50, node85 251.76, node53 1.38, node55 20.10 +node51, node98 2110.67, node59 23.67, node60 73.79 +node52, node94 1471.80, node64 102.41, node66 123.03 +node53, node72 22.85, node56 4.33, node67 88.35 +node54, node88 967.59, node59 24.30, node73 238.61 +node55, node84 86.09, node57 2.13, node64 60.80 +node56, node76 197.03, node57 0.02, node61 11.06 +node57, node86 701.09, node58 0.46, node60 7.01 +node58, node83 556.70, node64 29.85, node65 34.32 +node59, node90 820.66, node60 0.72, node71 0.67 +node60, node76 48.03, node65 4.76, node67 1.63 +node61, node98 1057.59, node63 0.95, node64 4.88 +node62, node91 132.23, node64 2.94, node76 38.43 +node63, node66 4.43, node72 70.08, node75 56.34 +node64, node80 47.73, node65 0.30, node76 11.98 +node65, node94 594.93, node66 0.64, node73 33.23 +node66, node98 395.63, node68 2.66, node73 37.53 +node67, node82 153.53, node68 0.09, node70 0.98 +node68, node94 232.10, node70 3.35, node71 1.66 +node69, node99 247.80, node70 0.06, node73 8.99 +node70, node76 27.18, node72 1.50, node73 8.37 +node71, node89 104.50, node74 8.86, node91 284.64 +node72, node76 15.32, node84 102.77, node92 133.06 +node73, node83 52.22, node76 1.40, node90 243.00 +node74, node81 1.07, node76 0.52, node78 8.08 +node75, node92 68.53, node76 0.81, node77 1.19 +node76, node85 13.18, node77 0.45, node78 2.36 +node77, node80 8.94, node78 0.98, node86 64.32 +node78, node98 355.90, node81 2.59 +node79, node81 0.09, node85 1.45, node91 22.35 +node80, node92 121.87, node88 28.78, node98 264.34 +node81, node94 99.78, node89 39.52, node92 99.89 +node82, node91 47.44, node88 28.05, node93 11.99 +node83, node94 114.95, node86 8.75, node88 5.78 +node84, node89 19.14, node94 30.41, node98 121.05 +node85, node97 94.51, node87 2.66, node89 4.90 +node86, node97 85.09 +node87, node88 0.21, node91 11.14, node92 21.23 +node88, node93 1.31, node91 6.83, node98 6.12 +node89, node97 36.97, node99 82.12 +node90, node96 23.53, node94 10.47, node99 50.99 +node91, node97 22.17 +node92, node96 10.83, node97 11.24, node99 34.68 +node93, node94 0.19, node97 6.71, node99 32.77 +node94, node98 5.91, node96 2.03 +node95, node98 6.17, node99 0.27 +node96, node98 3.32, node97 0.43, node99 5.87 +node97, node98 0.30 +node98, node99 0.33 +node99, +``` + +```{exercise-end} +``` + +```{solution-start} short_path_ex1 +:class: dropdown +``` + +First let's write a function that reads in the graph data above and builds a distance matrix. + +```{code-cell} python3 +num_nodes = 100 +destination_node = 99 + +def map_graph_to_distance_matrix(in_file): + + # First let's set of the distance matrix Q with inf everywhere + Q = np.full((num_nodes, num_nodes), np.inf) + + # Now we read in the data and modify Q + with open(in_file) as infile: + for line in infile: + elements = line.split(',') + node = elements.pop(0) + node = int(node[4:]) # convert node description to integer + if node != destination_node: + for element in elements: + destination, cost = element.split() + destination = int(destination[4:]) + Q[node, destination] = float(cost) + Q[destination_node, destination_node] = 0 + return Q +``` + +In addition, let's write + +1. a "Bellman operator" function that takes a distance matrix and current guess of J and returns an updated guess of J, and +1. a function that takes a distance matrix and returns a cost-to-go function. + +We'll use the algorithm described above. + +The minimization step is vectorized to make it faster. + +```{code-cell} python3 +def bellman(J, Q): + return np.min(Q + J, axis=1) + + +def compute_cost_to_go(Q): + num_nodes = Q.shape[0] + J = np.zeros(num_nodes) # Initial guess + max_iter = 500 + i = 0 + + while i < max_iter: + next_J = bellman(J, Q) + if np.allclose(next_J, J): + break + else: + J[:] = next_J # Copy contents of next_J to J + i += 1 + + return(J) +``` + +We used np.allclose() rather than testing exact equality because we are +dealing with floating point numbers now. + +Finally, here's a function that uses the cost-to-go function to obtain the +optimal path (and its cost). + +```{code-cell} python3 +def print_best_path(J, Q): + sum_costs = 0 + current_node = 0 + while current_node != destination_node: + print(current_node) + # Move to the next node and increment costs + next_node = np.argmin(Q[current_node, :] + J) + sum_costs += Q[current_node, next_node] + current_node = next_node + + print(destination_node) + print('Cost: ', sum_costs) +``` + +Okay, now we have the necessary functions, let's call them to do the job we were assigned. + +```{code-cell} python3 +Q = map_graph_to_distance_matrix('graph.txt') +J = compute_cost_to_go(Q) +print_best_path(J, Q) +``` + +The total cost of the path should agree with $J[0]$ so let's check this. + +```{code-cell} python3 +J[0] +``` + +```{solution-end} +``` \ No newline at end of file diff --git a/content/lectures/simple_linear_regression.ipynb b/book/_build/html/_sources/simple_linear_regression.ipynb similarity index 76% rename from content/lectures/simple_linear_regression.ipynb rename to book/_build/html/_sources/simple_linear_regression.ipynb index 3404edf..d60ff08 100644 --- a/content/lectures/simple_linear_regression.ipynb +++ b/book/_build/html/_sources/simple_linear_regression.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "42f9b4c0", + "id": "22a5ab66", "metadata": {}, "source": [ "# Simple Linear Regression Model" @@ -11,7 +11,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5064b6e7", + "id": "64ad22f1", "metadata": {}, "outputs": [], "source": [ @@ -22,7 +22,7 @@ }, { "cell_type": "markdown", - "id": "01f8eed6", + "id": "5def18fc", "metadata": {}, "source": [ "The simple regression model estimates the relationship between two variables $x_i$ and $y_i$\n", @@ -56,7 +56,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ad04aaa8", + "id": "fe268a5e", "metadata": {}, "outputs": [], "source": [ @@ -69,7 +69,7 @@ }, { "cell_type": "markdown", - "id": "35f26989", + "id": "f616806d", "metadata": {}, "source": [ "We can use a scatter plot of the data to see the relationship between $y_i$ (ice-cream sales in dollars (\\$\\'s)) and $x_i$ (degrees Celsius)." @@ -78,22 +78,29 @@ { "cell_type": "code", "execution_count": null, - "id": "b0b7d317", - "metadata": {}, + "id": "3278055c", + "metadata": { + "mystnb": { + "figure": { + "caption": "Scatter plot", + "name": "sales-v-temp1" + } + } + }, "outputs": [], "source": [ "ax = df.plot(\n", " x='X', \n", " y='Y', \n", " kind='scatter', \n", - " ylabel='Ice-Cream Sales ($\\'s)', \n", - " xlabel='Degrees Celcius'\n", + " ylabel='Ice-cream sales ($\\'s)', \n", + " xlabel='Degrees celcius'\n", ")" ] }, { "cell_type": "markdown", - "id": "88f323c0", + "id": "80f15333", "metadata": {}, "source": [ "as you can see the data suggests that more ice-cream is typically sold on hotter days. \n", @@ -110,7 +117,7 @@ { "cell_type": "code", "execution_count": null, - "id": "09b9612a", + "id": "12d4645d", "metadata": {}, "outputs": [], "source": [ @@ -122,18 +129,26 @@ { "cell_type": "code", "execution_count": null, - "id": "f4dd5e1d", - "metadata": {}, + "id": "7b173c15", + "metadata": { + "mystnb": { + "figure": { + "caption": "Scatter plot with a line of fit", + "name": "sales-v-temp2" + } + } + }, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", - "df.plot(x='X',y='Y', kind='scatter', ax=ax)\n", - "df.plot(x='X',y='Y_hat', kind='line', ax=ax)" + "ax = df.plot(x='X',y='Y', kind='scatter', ax=ax)\n", + "ax = df.plot(x='X',y='Y_hat', kind='line', ax=ax)\n", + "plt.show()" ] }, { "cell_type": "markdown", - "id": "9e22412f", + "id": "f28222f7", "metadata": {}, "source": [ "We can see that this model does a poor job of estimating the relationship.\n", @@ -144,7 +159,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5c4d3677", + "id": "b589a51f", "metadata": {}, "outputs": [], "source": [ @@ -155,19 +170,27 @@ { "cell_type": "code", "execution_count": null, - "id": "abcc5425", - "metadata": {}, + "id": "37e62d3e", + "metadata": { + "mystnb": { + "figure": { + "caption": "Scatter plot with a line of fit #2", + "name": "sales-v-temp3" + } + } + }, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", - "df.plot(x='X',y='Y', kind='scatter', ax=ax)\n", - "df.plot(x='X',y='Y_hat', kind='line', ax=ax)" + "ax = df.plot(x='X',y='Y', kind='scatter', ax=ax)\n", + "ax = df.plot(x='X',y='Y_hat', kind='line', ax=ax)\n", + "plt.show()" ] }, { "cell_type": "code", "execution_count": null, - "id": "41ef80a6", + "id": "e137e489", "metadata": {}, "outputs": [], "source": [ @@ -178,21 +201,29 @@ { "cell_type": "code", "execution_count": null, - "id": "2644963d", - "metadata": {}, + "id": "fee3a55d", + "metadata": { + "mystnb": { + "figure": { + "caption": "Scatter plot with a line of fit #3", + "name": "sales-v-temp4" + } + } + }, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", - "df.plot(x='X',y='Y', kind='scatter', ax=ax)\n", - "df.plot(x='X',y='Y_hat', kind='line', ax=ax, color='g')" + "ax = df.plot(x='X',y='Y', kind='scatter', ax=ax)\n", + "ax = df.plot(x='X',y='Y_hat', kind='line', ax=ax, color='g')\n", + "plt.show()" ] }, { "cell_type": "markdown", - "id": "2b098af9", + "id": "7ebfb1b3", "metadata": {}, "source": [ - "However we need to think about formalising this guessing process by thinking of this problem as an optimization problem. \n", + "However we need to think about formalizing this guessing process by thinking of this problem as an optimization problem. \n", "\n", "Let's consider the error $\\epsilon_i$ and define the difference between the observed values $y_i$ and the estimated values $\\hat{y}_i$ which we will call the residuals\n", "\n", @@ -207,7 +238,7 @@ { "cell_type": "code", "execution_count": null, - "id": "78962405", + "id": "8e83a2c8", "metadata": {}, "outputs": [], "source": [ @@ -217,7 +248,7 @@ { "cell_type": "code", "execution_count": null, - "id": "40de595c", + "id": "01a93f4e", "metadata": {}, "outputs": [], "source": [ @@ -227,22 +258,30 @@ { "cell_type": "code", "execution_count": null, - "id": "858244d1", - "metadata": {}, + "id": "bb65e0e3", + "metadata": { + "mystnb": { + "figure": { + "caption": "Plot of the residuals", + "name": "plt-residuals" + } + } + }, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", - "df.plot(x='X',y='Y', kind='scatter', ax=ax)\n", - "df.plot(x='X',y='Y_hat', kind='line', ax=ax, color='g')\n", - "plt.vlines(df['X'], df['Y_hat'], df['Y'], color='r');" + "ax = df.plot(x='X',y='Y', kind='scatter', ax=ax)\n", + "ax = df.plot(x='X',y='Y_hat', kind='line', ax=ax, color='g')\n", + "plt.vlines(df['X'], df['Y_hat'], df['Y'], color='r')\n", + "plt.show()" ] }, { "cell_type": "markdown", - "id": "2db7b9a5", + "id": "61903bf2", "metadata": {}, "source": [ - "The Ordinary Least Squares (OLS) method, as the name suggests, chooses $\\alpha$ and $\\beta$ in such a way that **minimises** the Sum of the Squared Residuals (SSR). \n", + "The Ordinary Least Squares (OLS) method chooses $\\alpha$ and $\\beta$ in such a way that **minimizes** the sum of the squared residuals (SSR). \n", "\n", "$$\n", "\\min_{\\alpha,\\beta} \\sum_{i=1}^{N}{\\hat{e}_i^2} = \\min_{\\alpha,\\beta} \\sum_{i=1}^{N}{(y_i - \\alpha - \\beta x_i)^2}\n", @@ -254,7 +293,7 @@ "C = \\sum_{i=1}^{N}{(y_i - \\alpha - \\beta x_i)^2}\n", "$$\n", "\n", - "that we would like to minimise with parameters $\\alpha$ and $\\beta$.\n", + "that we would like to minimize with parameters $\\alpha$ and $\\beta$.\n", "\n", "## How does error change with respect to $\\alpha$ and $\\beta$\n", "\n", @@ -266,7 +305,7 @@ { "cell_type": "code", "execution_count": null, - "id": "37e6df1b", + "id": "5db5d677", "metadata": {}, "outputs": [], "source": [ @@ -276,7 +315,7 @@ }, { "cell_type": "markdown", - "id": "e4336dba", + "id": "b33122a8", "metadata": {}, "source": [ "We can then calculate the error for a range of $\\beta$ values" @@ -285,7 +324,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b9b703e9", + "id": "e3a10384", "metadata": {}, "outputs": [], "source": [ @@ -296,17 +335,24 @@ }, { "cell_type": "markdown", - "id": "b69659aa", + "id": "c08f3d06", "metadata": {}, "source": [ - "Ploting the error" + "Plotting the error" ] }, { "cell_type": "code", "execution_count": null, - "id": "28d48003", - "metadata": {}, + "id": "95b9b40d", + "metadata": { + "mystnb": { + "figure": { + "caption": "Plotting the error", + "name": "plt-errors" + } + } + }, "outputs": [], "source": [ "ax = pd.Series(errors).plot(xlabel='β', ylabel='error')\n", @@ -315,7 +361,7 @@ }, { "cell_type": "markdown", - "id": "fdeee7ba", + "id": "e68ca037", "metadata": {}, "source": [ "Now let us vary $\\alpha$ (holding $\\beta$ constant)" @@ -324,7 +370,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5511e518", + "id": "f28f446b", "metadata": {}, "outputs": [], "source": [ @@ -335,17 +381,24 @@ }, { "cell_type": "markdown", - "id": "4192ba4a", + "id": "693e3ab9", "metadata": {}, "source": [ - "Ploting the error" + "Plotting the error" ] }, { "cell_type": "code", "execution_count": null, - "id": "a2410b18", - "metadata": {}, + "id": "ffd945fb", + "metadata": { + "mystnb": { + "figure": { + "caption": "Plotting the error (2)", + "name": "plt-errors-2" + } + } + }, "outputs": [], "source": [ "ax = pd.Series(errors).plot(xlabel='α', ylabel='error')\n", @@ -354,11 +407,11 @@ }, { "cell_type": "markdown", - "id": "e3a1a2a6", + "id": "dc3045a1", "metadata": {}, "source": [ "(slr:optimal-values)=\n", - "## Calculating Optimal Values\n", + "## Calculating optimal values\n", "\n", "Now let us use calculus to solve the optimization problem and compute the optimal values for $\\alpha$ and $\\beta$ to find the ordinary least squares solution.\n", "\n", @@ -460,20 +513,20 @@ { "cell_type": "code", "execution_count": null, - "id": "1f36ba79", + "id": "7838f7f2", "metadata": {}, "outputs": [], "source": [ "df = df[['X','Y']].copy() # Original Data\n", "\n", - "# Calcuate the sample means\n", + "# Calculate the sample means\n", "x_bar = df['X'].mean()\n", "y_bar = df['Y'].mean()" ] }, { "cell_type": "markdown", - "id": "0d423b6b", + "id": "b34ad3e3", "metadata": {}, "source": [ "Now computing across the 10 observations and then summing the numerator and denominator" @@ -482,7 +535,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a74fc923", + "id": "5409ff1a", "metadata": {}, "outputs": [], "source": [ @@ -495,7 +548,7 @@ }, { "cell_type": "markdown", - "id": "91d13a4a", + "id": "b6327213", "metadata": {}, "source": [ "Calculating $\\alpha$" @@ -504,7 +557,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9ee6bed4", + "id": "23eaf8bc", "metadata": {}, "outputs": [], "source": [ @@ -514,7 +567,7 @@ }, { "cell_type": "markdown", - "id": "b59f03c5", + "id": "73010edb", "metadata": {}, "source": [ "Now we can plot the OLS solution" @@ -523,31 +576,31 @@ { "cell_type": "code", "execution_count": null, - "id": "d7230f9e", - "metadata": {}, + "id": "f60828b2", + "metadata": { + "mystnb": { + "figure": { + "caption": "OLS line of best fit", + "name": "plt-ols" + } + } + }, "outputs": [], "source": [ "df['Y_hat'] = α + β * df['X']\n", "df['error'] = df['Y_hat'] - df['Y']\n", "\n", "fig, ax = plt.subplots()\n", - "df.plot(x='X',y='Y', kind='scatter', ax=ax)\n", - "df.plot(x='X',y='Y_hat', kind='line', ax=ax, color='g')\n", + "ax = df.plot(x='X',y='Y', kind='scatter', ax=ax)\n", + "ax = df.plot(x='X',y='Y_hat', kind='line', ax=ax, color='g')\n", "plt.vlines(df['X'], df['Y_hat'], df['Y'], color='r');" ] }, { "cell_type": "markdown", - "id": "74ba0e40", + "id": "80beb480", "metadata": {}, "source": [ - ":::{admonition} Why use OLS?\n", - "TODO\n", - "\n", - "1. Discuss mathematical properties for why we have chosen OLS\n", - ":::\n", - "\n", - "\n", ":::{exercise}\n", ":label: slr-ex1\n", "\n", @@ -557,7 +610,7 @@ "\n", "1. What do you think their relationship would be?\n", "2. Gather some data [from our world in data](https://ourworldindata.org)\n", - "3. Use `pandas` to import the `csv` formated data and plot a few different countries of interest\n", + "3. Use `pandas` to import the `csv` formatted data and plot a few different countries of interest\n", "4. Use {eq}`eq:optimal-alpha` and {eq}`eq:optimal-beta` to compute optimal values for $\\alpha$ and $\\beta$\n", "5. Plot the line of best fit found using OLS\n", "6. Interpret the coefficients and write a summary sentence of the relationship between GDP per capita and Life Expectancy\n", @@ -573,7 +626,7 @@ "\n", ":::\n", "\n", - "You can download {download}`a copy of the data here <_static/lecture_specific/simple_linear_regression/life-expectancy-vs-gdp-per-capita.csv>` if you get stuck\n", + "You can download {download}`a copy of the data here ` if you get stuck\n", "\n", "**Q3:** Use `pandas` to import the `csv` formatted data and plot a few different countries of interest" ] @@ -581,18 +634,18 @@ { "cell_type": "code", "execution_count": null, - "id": "4f71b466", + "id": "eedab539", "metadata": {}, "outputs": [], "source": [ - "fl = \"_static/lecture_specific/simple_linear_regression/life-expectancy-vs-gdp-per-capita.csv\" # TODO: Replace with GitHub link\n", - "df = pd.read_csv(fl, nrows=10)" + "data_url = \"https://github.com/QuantEcon/lecture-python-intro/raw/main/lectures/_static/lecture_specific/simple_linear_regression/life-expectancy-vs-gdp-per-capita.csv\"\n", + "df = pd.read_csv(data_url, nrows=10)" ] }, { "cell_type": "code", "execution_count": null, - "id": "3d25f4ba", + "id": "d27a9e52", "metadata": {}, "outputs": [], "source": [ @@ -601,7 +654,7 @@ }, { "cell_type": "markdown", - "id": "7bc25088", + "id": "74ae9410", "metadata": {}, "source": [ "You can see that the data downloaded from Our World in Data has provided a global set of countries with the GDP per capita and Life Expectancy Data.\n", @@ -616,18 +669,18 @@ { "cell_type": "code", "execution_count": null, - "id": "c45d5967", + "id": "21ea2277", "metadata": {}, "outputs": [], "source": [ "cols = ['Code', 'Year', 'Life expectancy at birth (historical)', 'GDP per capita']\n", - "df = pd.read_csv(fl, usecols=cols)\n", + "df = pd.read_csv(data_url, usecols=cols)\n", "df" ] }, { "cell_type": "markdown", - "id": "5307f3f9", + "id": "50d4a3b3", "metadata": {}, "source": [ "Sometimes it can be useful to rename your columns to make it easier to work with in the DataFrame" @@ -636,17 +689,17 @@ { "cell_type": "code", "execution_count": null, - "id": "7727695f", + "id": "86abda5b", "metadata": {}, "outputs": [], "source": [ - "df.columns = [\"cntry\", \"year\", \"life_expectency\", \"gdppc\"]\n", + "df.columns = [\"cntry\", \"year\", \"life_expectancy\", \"gdppc\"]\n", "df" ] }, { "cell_type": "markdown", - "id": "a5e801b1", + "id": "12a7770a", "metadata": {}, "source": [ "We can see there are `NaN` values which represents missing data so let us go ahead and drop those" @@ -655,7 +708,7 @@ { "cell_type": "code", "execution_count": null, - "id": "d340c231", + "id": "a1ffb39c", "metadata": {}, "outputs": [], "source": [ @@ -665,7 +718,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c7ca0e82", + "id": "28f68c1c", "metadata": {}, "outputs": [], "source": [ @@ -674,7 +727,7 @@ }, { "cell_type": "markdown", - "id": "499856c9", + "id": "71842265", "metadata": {}, "source": [ "We have now dropped the number of rows in our DataFrame from 62156 to 12445 removing a lot of empty data relationships.\n", @@ -685,23 +738,23 @@ "\n", "For example, you may want to explore this data to see if there is consistent reporting for all countries across years\n", "\n", - "Let's first look at the Life Expectency Data" + "Let's first look at the Life Expectancy Data" ] }, { "cell_type": "code", "execution_count": null, - "id": "666653c3", + "id": "2fb32504", "metadata": {}, "outputs": [], "source": [ - "le_years = df[['cntry', 'year', 'life_expectency']].set_index(['cntry', 'year']).unstack()['life_expectency']\n", + "le_years = df[['cntry', 'year', 'life_expectancy']].set_index(['cntry', 'year']).unstack()['life_expectancy']\n", "le_years" ] }, { "cell_type": "markdown", - "id": "08620061", + "id": "d2836675", "metadata": {}, "source": [ "As you can see there are a lot of countries where data is not available for the Year 1543!\n", @@ -712,7 +765,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5ef52fc2", + "id": "b85bf985", "metadata": {}, "outputs": [], "source": [ @@ -721,7 +774,7 @@ }, { "cell_type": "markdown", - "id": "60007a50", + "id": "44a4b3d9", "metadata": {}, "source": [ "You can see that Great Britain (GBR) is the only one available\n", @@ -732,7 +785,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9091df2a", + "id": "6328e690", "metadata": {}, "outputs": [], "source": [ @@ -741,7 +794,7 @@ }, { "cell_type": "markdown", - "id": "71bec900", + "id": "5d5d858e", "metadata": {}, "source": [ "In fact we can use pandas to quickly check how many countries are captured in each year" @@ -750,7 +803,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f8386093", + "id": "f951ca10", "metadata": {}, "outputs": [], "source": [ @@ -759,7 +812,7 @@ }, { "cell_type": "markdown", - "id": "1916e084", + "id": "0abee961", "metadata": {}, "source": [ "So it is clear that if you are doing cross-sectional comparisons then more recent data will include a wider set of countries\n", @@ -770,7 +823,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5e643825", + "id": "1bb749c8", "metadata": {}, "outputs": [], "source": [ @@ -780,28 +833,24 @@ { "cell_type": "code", "execution_count": null, - "id": "11c21bab", + "id": "d785aa89", "metadata": {}, "outputs": [], "source": [ - "df.plot(x='gdppc', y='life_expectency', kind='scatter', xlabel=\"GDP per capita\", ylabel=\"Life Expectency (Years)\",);" + "df.plot(x='gdppc', y='life_expectancy', kind='scatter', xlabel=\"GDP per capita\", ylabel=\"Life expectancy (years)\",);" ] }, { "cell_type": "markdown", - "id": "3e993aea", + "id": "fcb75b10", "metadata": {}, "source": [ "This data shows a couple of interesting relationships.\n", "\n", "1. there are a number of countries with similar GDP per capita levels but a wide range in Life Expectancy\n", - "2. there appears to be a positive relationship between GDP per capita and life expectancy. Countries with higher GDP per capita tend to have higher life expectency outcomes\n", + "2. there appears to be a positive relationship between GDP per capita and life expectancy. Countries with higher GDP per capita tend to have higher life expectancy outcomes\n", "\n", - "Even though OLS is solving linear equations -- one option we have is to transform the variables, such as through a log transform, and then use OLS to estimate the transformed variables\n", - "\n", - ":::{tip}\n", - "ln -> ln == elasticities\n", - ":::\n", + "Even though OLS is solving linear equations -- one option we have is to transform the variables, such as through a log transform, and then use OLS to estimate the transformed variables.\n", "\n", "By specifying `logx` you can plot the GDP per Capita data on a log scale" ] @@ -809,16 +858,16 @@ { "cell_type": "code", "execution_count": null, - "id": "be844bb2", + "id": "980376ba", "metadata": {}, "outputs": [], "source": [ - "df.plot(x='gdppc', y='life_expectency', kind='scatter', xlabel=\"GDP per capita\", ylabel=\"Life Expectancy (Years)\", logx=True);" + "df.plot(x='gdppc', y='life_expectancy', kind='scatter', xlabel=\"GDP per capita\", ylabel=\"Life expectancy (years)\", logx=True);" ] }, { "cell_type": "markdown", - "id": "d58ce1b6", + "id": "1a001f1c", "metadata": {}, "source": [ "As you can see from this transformation -- a linear model fits the shape of the data more closely." @@ -827,7 +876,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4d3d1a44", + "id": "26ea82ad", "metadata": {}, "outputs": [], "source": [ @@ -837,7 +886,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b03737c8", + "id": "531e05b6", "metadata": {}, "outputs": [], "source": [ @@ -846,7 +895,7 @@ }, { "cell_type": "markdown", - "id": "88cdf442", + "id": "0ed1153a", "metadata": {}, "source": [ "**Q4:** Use {eq}`eq:optimal-alpha` and {eq}`eq:optimal-beta` to compute optimal values for $\\alpha$ and $\\beta$" @@ -855,21 +904,21 @@ { "cell_type": "code", "execution_count": null, - "id": "c201f3fd", + "id": "c8e5a743", "metadata": {}, "outputs": [], "source": [ - "data = df[['log_gdppc', 'life_expectency']].copy() # Get Data from DataFrame\n", + "data = df[['log_gdppc', 'life_expectancy']].copy() # Get Data from DataFrame\n", "\n", "# Calculate the sample means\n", "x_bar = data['log_gdppc'].mean()\n", - "y_bar = data['life_expectency'].mean()" + "y_bar = data['life_expectancy'].mean()" ] }, { "cell_type": "code", "execution_count": null, - "id": "c11388ea", + "id": "61177203", "metadata": {}, "outputs": [], "source": [ @@ -879,12 +928,12 @@ { "cell_type": "code", "execution_count": null, - "id": "2a7672fd", + "id": "b5181988", "metadata": {}, "outputs": [], "source": [ "# Compute the Sums\n", - "data['num'] = data['log_gdppc'] * data['life_expectency'] - y_bar * data['log_gdppc']\n", + "data['num'] = data['log_gdppc'] * data['life_expectancy'] - y_bar * data['log_gdppc']\n", "data['den'] = pow(data['log_gdppc'],2) - x_bar * data['log_gdppc']\n", "β = data['num'].sum() / data['den'].sum()\n", "print(β)" @@ -893,7 +942,7 @@ { "cell_type": "code", "execution_count": null, - "id": "cc3a7f79", + "id": "2436826e", "metadata": {}, "outputs": [], "source": [ @@ -903,7 +952,7 @@ }, { "cell_type": "markdown", - "id": "971cdaf3", + "id": "f692e427", "metadata": {}, "source": [ "**Q5:** Plot the line of best fit found using OLS" @@ -912,22 +961,22 @@ { "cell_type": "code", "execution_count": null, - "id": "da63bfab", + "id": "6515f862", "metadata": {}, "outputs": [], "source": [ - "data['life_expectency_hat'] = α + β * df['log_gdppc']\n", - "data['error'] = data['life_expectency_hat'] - data['life_expectency']\n", + "data['life_expectancy_hat'] = α + β * df['log_gdppc']\n", + "data['error'] = data['life_expectancy_hat'] - data['life_expectancy']\n", "\n", "fig, ax = plt.subplots()\n", - "data.plot(x='log_gdppc',y='life_expectency', kind='scatter', ax=ax)\n", - "data.plot(x='log_gdppc',y='life_expectency_hat', kind='line', ax=ax, color='g')\n", - "plt.vlines(data['log_gdppc'], data['life_expectency_hat'], data['life_expectency'], color='r')" + "data.plot(x='log_gdppc',y='life_expectancy', kind='scatter', ax=ax)\n", + "data.plot(x='log_gdppc',y='life_expectancy_hat', kind='line', ax=ax, color='g')\n", + "plt.vlines(data['log_gdppc'], data['life_expectancy_hat'], data['life_expectancy'], color='r')" ] }, { "cell_type": "markdown", - "id": "60a2aef6", + "id": "cc408af1", "metadata": {}, "source": [ ":::{solution-end}\n", @@ -936,9 +985,9 @@ ":::{exercise}\n", ":label: slr-ex2\n", "\n", - "Minimising the sum of squares is not the **only** way to generate the line of best fit. \n", + "Minimizing the sum of squares is not the **only** way to generate the line of best fit. \n", "\n", - "For example, we could also consider minimising the sum of the **absolute values**, that would give less weight to outliers. \n", + "For example, we could also consider minimizing the sum of the **absolute values**, that would give less weight to outliers. \n", "\n", "Solve for $\\alpha$ and $\\beta$ using the least absolute values\n", ":::" @@ -946,12 +995,92 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.4" + } + }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" - } + }, + "source_map": [ + 12, + 16, + 20, + 49, + 55, + 59, + 73, + 85, + 91, + 102, + 108, + 113, + 126, + 131, + 142, + 155, + 159, + 163, + 175, + 197, + 200, + 204, + 208, + 212, + 221, + 225, + 229, + 233, + 242, + 343, + 349, + 353, + 359, + 363, + 366, + 370, + 384, + 415, + 420, + 422, + 432, + 436, + 440, + 443, + 447, + 451, + 453, + 465, + 468, + 474, + 476, + 482, + 484, + 488, + 490, + 496, + 500, + 502, + 513, + 515, + 519, + 523, + 525, + 529, + 537, + 541, + 549, + 552, + 556, + 564 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/simple_linear_regression.md b/book/_build/html/_sources/simple_linear_regression.md new file mode 100644 index 0000000..137d453 --- /dev/null +++ b/book/_build/html/_sources/simple_linear_regression.md @@ -0,0 +1,577 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.4 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Simple Linear Regression Model + +```{code-cell} ipython3 +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +``` + +The simple regression model estimates the relationship between two variables $x_i$ and $y_i$ + +$$ +y_i = \alpha + \beta x_i + \epsilon_i, i = 1,2,...,N +$$ + +where $\epsilon_i$ represents the error between the line of best fit and the sample values for $y_i$ given $x_i$. + +Our goal is to choose values for $\alpha$ and $\beta$ to build a line of "best" fit for some data that is available for variables $x_i$ and $y_i$. + +Let us consider a simple dataset of 10 observations for variables $x_i$ and $y_i$: + +| | $y_i$ | $x_i$ | +|-|---|---| +|1| 2000 | 32 | +|2| 1000 | 21 | +|3| 1500 | 24 | +|4| 2500 | 35 | +|5| 500 | 10 | +|6| 900 | 11 | +|7| 1100 | 22 | +|8| 1500 | 21 | +|9| 1800 | 27 | +|10 | 250 | 2 | + +Let us think about $y_i$ as sales for an ice-cream cart, while $x_i$ is a variable that records the day's temperature in Celsius. + +```{code-cell} ipython3 +x = [32, 21, 24, 35, 10, 11, 22, 21, 27, 2] +y = [2000,1000,1500,2500,500,900,1100,1500,1800, 250] +df = pd.DataFrame([x,y]).T +df.columns = ['X', 'Y'] +df +``` + +We can use a scatter plot of the data to see the relationship between $y_i$ (ice-cream sales in dollars (\$\'s)) and $x_i$ (degrees Celsius). + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Scatter plot" + name: sales-v-temp1 +--- +ax = df.plot( + x='X', + y='Y', + kind='scatter', + ylabel='Ice-cream sales ($\'s)', + xlabel='Degrees celcius' +) +``` + +as you can see the data suggests that more ice-cream is typically sold on hotter days. + +To build a linear model of the data we need to choose values for $\alpha$ and $\beta$ that represents a line of "best" fit such that + +$$ +\hat{y_i} = \hat{\alpha} + \hat{\beta} x_i +$$ + +Let's start with $\alpha = 5$ and $\beta = 10$ + +```{code-cell} ipython3 +α = 5 +β = 10 +df['Y_hat'] = α + β * df['X'] +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Scatter plot with a line of fit" + name: sales-v-temp2 +--- +fig, ax = plt.subplots() +ax = df.plot(x='X',y='Y', kind='scatter', ax=ax) +ax = df.plot(x='X',y='Y_hat', kind='line', ax=ax) +plt.show() +``` + +We can see that this model does a poor job of estimating the relationship. + +We can continue to guess and iterate towards a line of "best" fit by adjusting the parameters + +```{code-cell} ipython3 +β = 100 +df['Y_hat'] = α + β * df['X'] +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Scatter plot with a line of fit #2" + name: sales-v-temp3 +--- +fig, ax = plt.subplots() +ax = df.plot(x='X',y='Y', kind='scatter', ax=ax) +ax = df.plot(x='X',y='Y_hat', kind='line', ax=ax) +plt.show() +``` + +```{code-cell} ipython3 +β = 65 +df['Y_hat'] = α + β * df['X'] +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Scatter plot with a line of fit #3" + name: sales-v-temp4 +--- +fig, ax = plt.subplots() +ax = df.plot(x='X',y='Y', kind='scatter', ax=ax) +ax = df.plot(x='X',y='Y_hat', kind='line', ax=ax, color='g') +plt.show() +``` + +However we need to think about formalizing this guessing process by thinking of this problem as an optimization problem. + +Let's consider the error $\epsilon_i$ and define the difference between the observed values $y_i$ and the estimated values $\hat{y}_i$ which we will call the residuals + +$$ +\begin{aligned} +\hat{e}_i &= y_i - \hat{y}_i \\ + &= y_i - \hat{\alpha} - \hat{\beta} x_i +\end{aligned} +$$ + +```{code-cell} ipython3 +df['error'] = df['Y_hat'] - df['Y'] +``` + +```{code-cell} ipython3 +df +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Plot of the residuals" + name: plt-residuals +--- +fig, ax = plt.subplots() +ax = df.plot(x='X',y='Y', kind='scatter', ax=ax) +ax = df.plot(x='X',y='Y_hat', kind='line', ax=ax, color='g') +plt.vlines(df['X'], df['Y_hat'], df['Y'], color='r') +plt.show() +``` + +The Ordinary Least Squares (OLS) method chooses $\alpha$ and $\beta$ in such a way that **minimizes** the sum of the squared residuals (SSR). + +$$ +\min_{\alpha,\beta} \sum_{i=1}^{N}{\hat{e}_i^2} = \min_{\alpha,\beta} \sum_{i=1}^{N}{(y_i - \alpha - \beta x_i)^2} +$$ + +Let's call this a cost function + +$$ +C = \sum_{i=1}^{N}{(y_i - \alpha - \beta x_i)^2} +$$ + +that we would like to minimize with parameters $\alpha$ and $\beta$. + +## How does error change with respect to $\alpha$ and $\beta$ + +Let us first look at how the total error changes with respect to $\beta$ (holding the intercept $\alpha$ constant) + +We know from [the next section](slr:optimal-values) the optimal values for $\alpha$ and $\beta$ are: + +```{code-cell} ipython3 +β_optimal = 64.38 +α_optimal = -14.72 +``` + +We can then calculate the error for a range of $\beta$ values + +```{code-cell} ipython3 +errors = {} +for β in np.arange(20,100,0.5): + errors[β] = abs((α_optimal + β * df['X']) - df['Y']).sum() +``` + +Plotting the error + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Plotting the error" + name: plt-errors +--- +ax = pd.Series(errors).plot(xlabel='β', ylabel='error') +plt.axvline(β_optimal, color='r'); +``` + +Now let us vary $\alpha$ (holding $\beta$ constant) + +```{code-cell} ipython3 +errors = {} +for α in np.arange(-500,500,5): + errors[α] = abs((α + β_optimal * df['X']) - df['Y']).sum() +``` + +Plotting the error + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Plotting the error (2)" + name: plt-errors-2 +--- +ax = pd.Series(errors).plot(xlabel='α', ylabel='error') +plt.axvline(α_optimal, color='r'); +``` + +(slr:optimal-values)= +## Calculating optimal values + +Now let us use calculus to solve the optimization problem and compute the optimal values for $\alpha$ and $\beta$ to find the ordinary least squares solution. + +First taking the partial derivative with respect to $\alpha$ + +$$ +\frac{\partial C}{\partial \alpha}[\sum_{i=1}^{N}{(y_i - \alpha - \beta x_i)^2}] +$$ + +and setting it equal to $0$ + +$$ +0 = \sum_{i=1}^{N}{-2(y_i - \alpha - \beta x_i)} +$$ + +we can remove the constant $-2$ from the summation by dividing both sides by $-2$ + +$$ +0 = \sum_{i=1}^{N}{(y_i - \alpha - \beta x_i)} +$$ + +Now we can split this equation up into the components + +$$ +0 = \sum_{i=1}^{N}{y_i} - \sum_{i=1}^{N}{\alpha} - \beta \sum_{i=1}^{N}{x_i} +$$ + +The middle term is a straight forward sum from $i=1,...N$ by a constant $\alpha$ + +$$ +0 = \sum_{i=1}^{N}{y_i} - N*\alpha - \beta \sum_{i=1}^{N}{x_i} +$$ + +and rearranging terms + +$$ +\alpha = \frac{\sum_{i=1}^{N}{y_i} - \beta \sum_{i=1}^{N}{x_i}}{N} +$$ + +We observe that both fractions resolve to the means $\bar{y_i}$ and $\bar{x_i}$ + +$$ +\alpha = \bar{y_i} - \beta\bar{x_i} +$$ (eq:optimal-alpha) + +Now let's take the partial derivative of the cost function $C$ with respect to $\beta$ + +$$ +\frac{\partial C}{\partial \beta}[\sum_{i=1}^{N}{(y_i - \alpha - \beta x_i)^2}] +$$ + +and setting it equal to $0$ + +$$ +0 = \sum_{i=1}^{N}{-2 x_i (y_i - \alpha - \beta x_i)} +$$ + +we can again take the constant outside of the summation and divide both sides by $-2$ + +$$ +0 = \sum_{i=1}^{N}{x_i (y_i - \alpha - \beta x_i)} +$$ + +which becomes + +$$ +0 = \sum_{i=1}^{N}{(x_i y_i - \alpha x_i - \beta x_i^2)} +$$ + +now substituting for $\alpha$ + +$$ +0 = \sum_{i=1}^{N}{(x_i y_i - (\bar{y_i} - \beta \bar{x_i}) x_i - \beta x_i^2)} +$$ + +and rearranging terms + +$$ +0 = \sum_{i=1}^{N}{(x_i y_i - \bar{y_i} x_i - \beta \bar{x_i} x_i - \beta x_i^2)} +$$ + +This can be split into two summations + +$$ +0 = \sum_{i=1}^{N}(x_i y_i - \bar{y_i} x_i) + \beta \sum_{i=1}^{N}(\bar{x_i} x_i - x_i^2) +$$ + +and solving for $\beta$ yields + +$$ +\beta = \frac{\sum_{i=1}^{N}(x_i y_i - \bar{y_i} x_i)}{\sum_{i=1}^{N}(x_i^2 - \bar{x_i} x_i)} +$$ (eq:optimal-beta) + +We can now use {eq}`eq:optimal-alpha` and {eq}`eq:optimal-beta` to calculate the optimal values for $\alpha$ and $\beta$ + +Calculating $\beta$ + +```{code-cell} ipython3 +df = df[['X','Y']].copy() # Original Data + +# Calculate the sample means +x_bar = df['X'].mean() +y_bar = df['Y'].mean() +``` + +Now computing across the 10 observations and then summing the numerator and denominator + +```{code-cell} ipython3 +# Compute the Sums +df['num'] = df['X'] * df['Y'] - y_bar * df['X'] +df['den'] = pow(df['X'],2) - x_bar * df['X'] +β = df['num'].sum() / df['den'].sum() +print(β) +``` + +Calculating $\alpha$ + +```{code-cell} ipython3 +α = y_bar - β * x_bar +print(α) +``` + +Now we can plot the OLS solution + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "OLS line of best fit" + name: plt-ols +--- +df['Y_hat'] = α + β * df['X'] +df['error'] = df['Y_hat'] - df['Y'] + +fig, ax = plt.subplots() +ax = df.plot(x='X',y='Y', kind='scatter', ax=ax) +ax = df.plot(x='X',y='Y_hat', kind='line', ax=ax, color='g') +plt.vlines(df['X'], df['Y_hat'], df['Y'], color='r'); +``` + +:::{exercise} +:label: slr-ex1 + +Now that you know the equations that solve the simple linear regression model using OLS you can now run your own regressions to build a model between $y$ and $x$. + +Let's consider two economic variables GDP per capita and Life Expectancy. + +1. What do you think their relationship would be? +2. Gather some data [from our world in data](https://ourworldindata.org) +3. Use `pandas` to import the `csv` formatted data and plot a few different countries of interest +4. Use {eq}`eq:optimal-alpha` and {eq}`eq:optimal-beta` to compute optimal values for $\alpha$ and $\beta$ +5. Plot the line of best fit found using OLS +6. Interpret the coefficients and write a summary sentence of the relationship between GDP per capita and Life Expectancy + +::: + +:::{solution-start} slr-ex1 +::: + +**Q2:** Gather some data [from our world in data](https://ourworldindata.org) + +:::{raw} html + +::: + +You can download {download}`a copy of the data here ` if you get stuck + +**Q3:** Use `pandas` to import the `csv` formatted data and plot a few different countries of interest + +```{code-cell} ipython3 +data_url = "https://github.com/QuantEcon/lecture-python-intro/raw/main/lectures/_static/lecture_specific/simple_linear_regression/life-expectancy-vs-gdp-per-capita.csv" +df = pd.read_csv(data_url, nrows=10) +``` + +```{code-cell} ipython3 +df +``` + +You can see that the data downloaded from Our World in Data has provided a global set of countries with the GDP per capita and Life Expectancy Data. + +It is often a good idea to at first import a few lines of data from a csv to understand its structure so that you can then choose the columns that you want to read into your DataFrame. + +You can observe that there are a bunch of columns we won't need to import such as `Continent` + +So let's built a list of the columns we want to import + +```{code-cell} ipython3 +cols = ['Code', 'Year', 'Life expectancy at birth (historical)', 'GDP per capita'] +df = pd.read_csv(data_url, usecols=cols) +df +``` + +Sometimes it can be useful to rename your columns to make it easier to work with in the DataFrame + +```{code-cell} ipython3 +df.columns = ["cntry", "year", "life_expectancy", "gdppc"] +df +``` + +We can see there are `NaN` values which represents missing data so let us go ahead and drop those + +```{code-cell} ipython3 +df.dropna(inplace=True) +``` + +```{code-cell} ipython3 +df +``` + +We have now dropped the number of rows in our DataFrame from 62156 to 12445 removing a lot of empty data relationships. + +Now we have a dataset containing life expectancy and GDP per capita for a range of years. + +It is always a good idea to spend a bit of time understanding what data you actually have. + +For example, you may want to explore this data to see if there is consistent reporting for all countries across years + +Let's first look at the Life Expectancy Data + +```{code-cell} ipython3 +le_years = df[['cntry', 'year', 'life_expectancy']].set_index(['cntry', 'year']).unstack()['life_expectancy'] +le_years +``` + +As you can see there are a lot of countries where data is not available for the Year 1543! + +Which country does report this data? + +```{code-cell} ipython3 +le_years[~le_years[1543].isna()] +``` + +You can see that Great Britain (GBR) is the only one available + +You can also take a closer look at the time series to find that it is also non-continuous, even for GBR. + +```{code-cell} ipython3 +le_years.loc['GBR'].plot() +``` + +In fact we can use pandas to quickly check how many countries are captured in each year + +```{code-cell} ipython3 +le_years.stack().unstack(level=0).count(axis=1).plot(xlabel="Year", ylabel="Number of countries"); +``` + +So it is clear that if you are doing cross-sectional comparisons then more recent data will include a wider set of countries + +Now let us consider the most recent year in the dataset 2018 + +```{code-cell} ipython3 +df = df[df.year == 2018].reset_index(drop=True).copy() +``` + +```{code-cell} ipython3 +df.plot(x='gdppc', y='life_expectancy', kind='scatter', xlabel="GDP per capita", ylabel="Life expectancy (years)",); +``` + +This data shows a couple of interesting relationships. + +1. there are a number of countries with similar GDP per capita levels but a wide range in Life Expectancy +2. there appears to be a positive relationship between GDP per capita and life expectancy. Countries with higher GDP per capita tend to have higher life expectancy outcomes + +Even though OLS is solving linear equations -- one option we have is to transform the variables, such as through a log transform, and then use OLS to estimate the transformed variables. + +By specifying `logx` you can plot the GDP per Capita data on a log scale + +```{code-cell} ipython3 +df.plot(x='gdppc', y='life_expectancy', kind='scatter', xlabel="GDP per capita", ylabel="Life expectancy (years)", logx=True); +``` + +As you can see from this transformation -- a linear model fits the shape of the data more closely. + +```{code-cell} ipython3 +df['log_gdppc'] = df['gdppc'].apply(np.log10) +``` + +```{code-cell} ipython3 +df +``` + +**Q4:** Use {eq}`eq:optimal-alpha` and {eq}`eq:optimal-beta` to compute optimal values for $\alpha$ and $\beta$ + +```{code-cell} ipython3 +data = df[['log_gdppc', 'life_expectancy']].copy() # Get Data from DataFrame + +# Calculate the sample means +x_bar = data['log_gdppc'].mean() +y_bar = data['life_expectancy'].mean() +``` + +```{code-cell} ipython3 +data +``` + +```{code-cell} ipython3 +# Compute the Sums +data['num'] = data['log_gdppc'] * data['life_expectancy'] - y_bar * data['log_gdppc'] +data['den'] = pow(data['log_gdppc'],2) - x_bar * data['log_gdppc'] +β = data['num'].sum() / data['den'].sum() +print(β) +``` + +```{code-cell} ipython3 +α = y_bar - β * x_bar +print(α) +``` + +**Q5:** Plot the line of best fit found using OLS + +```{code-cell} ipython3 +data['life_expectancy_hat'] = α + β * df['log_gdppc'] +data['error'] = data['life_expectancy_hat'] - data['life_expectancy'] + +fig, ax = plt.subplots() +data.plot(x='log_gdppc',y='life_expectancy', kind='scatter', ax=ax) +data.plot(x='log_gdppc',y='life_expectancy_hat', kind='line', ax=ax, color='g') +plt.vlines(data['log_gdppc'], data['life_expectancy_hat'], data['life_expectancy'], color='r') +``` + +:::{solution-end} +::: + +:::{exercise} +:label: slr-ex2 + +Minimizing the sum of squares is not the **only** way to generate the line of best fit. + +For example, we could also consider minimizing the sum of the **absolute values**, that would give less weight to outliers. + +Solve for $\alpha$ and $\beta$ using the least absolute values +::: diff --git a/content/lectures/solow.ipynb b/book/_build/html/_sources/solow.ipynb similarity index 88% rename from content/lectures/solow.ipynb rename to book/_build/html/_sources/solow.ipynb index 8c771d0..82bc5df 100644 --- a/content/lectures/solow.ipynb +++ b/book/_build/html/_sources/solow.ipynb @@ -2,27 +2,27 @@ "cells": [ { "cell_type": "markdown", - "id": "5f8ce0da", + "id": "86f9c185", "metadata": {}, "source": [ "(solow)=\n", "# The Solow-Swan Growth Model\n", "\n", "In this lecture we review a famous model due\n", - "to [Robert Solow (1925--2014)](https://en.wikipedia.org/wiki/Robert_Solow) and [Trevor Swan (1918--1989)](https://en.wikipedia.org/wiki/Trevor_Swan).\n", + "to [Robert Solow (1925--2023)](https://en.wikipedia.org/wiki/Robert_Solow) and [Trevor Swan (1918--1989)](https://en.wikipedia.org/wiki/Trevor_Swan).\n", "\n", "The model is used to study growth over the long run.\n", "\n", "Although the model is simple, it contains some interesting lessons.\n", "\n", "\n", - "We will use the following imports" + "We will use the following imports." ] }, { "cell_type": "code", "execution_count": null, - "id": "de963928", + "id": "7f442c67", "metadata": {}, "outputs": [], "source": [ @@ -32,10 +32,10 @@ }, { "cell_type": "markdown", - "id": "4bccaeed", + "id": "fdee4981", "metadata": {}, "source": [ - "## The Model\n", + "## The model\n", "\n", "In a Solow--Swan economy, agents save a fixed fraction of their current\n", "incomes.\n", @@ -63,11 +63,13 @@ "Production functions with this property include\n", "\n", "* the **Cobb-Douglas** function $F(K, L) = A K^{\\alpha}\n", - " L^{1-\\alpha}$ with $0 \\leq \\alpha \\leq 1$ and\n", + " L^{1-\\alpha}$ with $0 \\leq \\alpha \\leq 1$. \n", "* the **CES** function $F(K, L) = \\left\\{ a K^\\rho + b L^\\rho \\right\\}^{1/\\rho}$\n", - " with $a, b, \\rho > 0$.\n", + " with $a, b, \\rho > 0$. \n", + " \n", + "Here, $\\alpha$ is the output elasticity of capital and $\\rho$ is a parameter that determines the elasticity of substitution between capital and labor.\n", "\n", - "We assume a closed economy, so domestic investment equals aggregate domestic\n", + "We assume a closed economy, so aggregate domestic investment equals aggregate domestic\n", "saving.\n", "\n", "The saving rate is a constant $s$ satisfying $0 \\leq s \\leq 1$, so that aggregate\n", @@ -89,6 +91,7 @@ "\n", "$$\n", " k_{t+1}\n", + " = s \\frac{F(K_t, L)}{L} + (1 - \\delta) \\frac{K_t}{L}\n", " = s \\frac{F(K_t, L)}{L} + (1 - \\delta) k_t\n", " = s F(k_t, 1) + (1 - \\delta) k_t\n", "$$\n", @@ -106,10 +109,9 @@ "given an exogenous initial capital stock $k_0$.\n", "\n", "\n", - "## A Graphical Perspective\n", + "## A graphical perspective\n", "\n", - "To understand the dynamics of the sequence $(k_t)_{t \\geq 0}$ we use a 45\n", - "degree diagram.\n", + "To understand the dynamics of the sequence $(k_t)_{t \\geq 0}$ we use a 45-degree diagram.\n", "\n", "To do so, we first\n", "need to specify the functional form for $f$ and assign values to the parameters.\n", @@ -117,8 +119,7 @@ "We choose the Cobb--Douglas specification $f(k) = A k^\\alpha$ and set $A=2.0$,\n", "$\\alpha=0.3$, $s=0.3$ and $\\delta=0.4$.\n", "\n", - "The function $g$ from {eq}`solow` is then plotted, along with the 45\n", - "degree line.\n", + "The function $g$ from {eq}`solow` is then plotted, along with the 45-degree line.\n", "\n", "\n", "Let's define the constants." @@ -127,7 +128,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e87f9206", + "id": "00705135", "metadata": {}, "outputs": [], "source": [ @@ -138,16 +139,16 @@ }, { "cell_type": "markdown", - "id": "adad9f3e", + "id": "adbd2e69", "metadata": {}, "source": [ - "Now, we define the function $g$" + "Now, we define the function $g$." ] }, { "cell_type": "code", "execution_count": null, - "id": "54cc33ce", + "id": "75e6c76e", "metadata": {}, "outputs": [], "source": [ @@ -157,16 +158,16 @@ }, { "cell_type": "markdown", - "id": "c0445260", + "id": "bedfd8cb", "metadata": {}, "source": [ - "Let's plot the 45 degree diagram of $g$" + "Let's plot the 45-degree diagram of $g$." ] }, { "cell_type": "code", "execution_count": null, - "id": "0d5da377", + "id": "10b714f8", "metadata": {}, "outputs": [], "source": [ @@ -184,7 +185,7 @@ "\n", " lb = r'$g(k) = sAk^{\\alpha} + (1 - \\delta)k$'\n", " ax.plot(xgrid, g_values, lw=2, alpha=0.6, label=lb)\n", - " ax.plot(xgrid, xgrid, 'k-', lw=1, alpha=0.7, label='45')\n", + " ax.plot(xgrid, xgrid, 'k-', lw=1, alpha=0.7, label='$45^{\\circ}$')\n", "\n", " if kstar:\n", " fps = (kstar,)\n", @@ -213,7 +214,7 @@ { "cell_type": "code", "execution_count": null, - "id": "35fb287a", + "id": "7094ac12", "metadata": {}, "outputs": [], "source": [ @@ -222,10 +223,10 @@ }, { "cell_type": "markdown", - "id": "3a6d8047", + "id": "a6e43aaf", "metadata": {}, "source": [ - "Suppose, at some $k_t$, the value $g(k_t)$ lies strictly above the 45 degree line.\n", + "Suppose, at some $k_t$, the value $g(k_t)$ lies strictly above the 45-degree line.\n", "\n", "Then we have $k_{t+1} = g(k_t) > k_t$ and capital per worker rises.\n", "\n", @@ -233,7 +234,7 @@ "\n", "If $g(k_t) = k_t$, then we are at a **steady state** and $k_t$ remains constant.\n", "\n", - "(A steady state of the model is a [fixed point](https://en.wikipedia.org/wiki/Fixed_point_(mathematics)) of the mapping $g$.)\n", + "(A {ref}`steady state ` of the model is a [fixed point](https://en.wikipedia.org/wiki/Fixed_point_(mathematics)) of the mapping $g$.)\n", "\n", "From the shape of the function $g$ in the figure, we see that\n", "there is a unique steady state in $(0, \\infty)$.\n", @@ -248,13 +249,13 @@ "\n", "If initial capital is above this level, then the reverse is true.\n", "\n", - "Let's plot the 45 degree diagram to show the $k^*$ in the plot" + "Let's plot the 45-degree diagram to show the $k^*$ in the plot." ] }, { "cell_type": "code", "execution_count": null, - "id": "b2c4249f", + "id": "7c2f9621", "metadata": {}, "outputs": [], "source": [ @@ -264,13 +265,13 @@ }, { "cell_type": "markdown", - "id": "a69bbeef", + "id": "5fe2c540", "metadata": {}, "source": [ "From our graphical analysis, it appears that $(k_t)$ converges to $k^*$, regardless of initial capital\n", "$k_0$.\n", "\n", - "This is a form of global stability.\n", + "This is a form of {ref}`global stability `.\n", "\n", "\n", "The next figure shows three time paths for capital, from\n", @@ -284,7 +285,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ae5a29ba", + "id": "5388017c", "metadata": {}, "outputs": [], "source": [ @@ -299,7 +300,7 @@ { "cell_type": "code", "execution_count": null, - "id": "296863fb", + "id": "d6f973b5", "metadata": {}, "outputs": [], "source": [ @@ -332,7 +333,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b2290a46", + "id": "c0ba5a05", "metadata": {}, "outputs": [], "source": [ @@ -341,18 +342,18 @@ }, { "cell_type": "markdown", - "id": "bf54f73d", + "id": "2d234d3e", "metadata": {}, "source": [ - "As expected, the time paths in the figure both converge to this value.\n", + "As expected, the time paths in the figure all converge to $k^*$.\n", "\n", - "## Growth in Continuous Time\n", + "## Growth in continuous time\n", "\n", - "In this section we investigate a continuous time version of the Solow--Swan\n", + "In this section, we investigate a continuous time version of the Solow--Swan\n", "growth model.\n", "\n", "We will see how the smoothing provided by continuous time can\n", - "simplify analysis.\n", + "simplify our analysis.\n", "\n", "\n", "Recall that the discrete time dynamics for capital are\n", @@ -376,7 +377,7 @@ "```\n", "\n", "Our aim is to learn about the evolution of $k_t$ over time,\n", - "given initial stock $k_0$.\n", + "given an initial stock $k_0$.\n", "\n", "A **steady state** for {eq}`solowc` is a value $k^*$\n", "at which capital is unchanging, meaning $k'_t = 0$ or, equivalently,\n", @@ -393,7 +394,7 @@ "above.\n", "\n", "Writing $k'_t = g(k_t)$ with $g(k) =\n", - "s Ak^\\alpha - \\delta k$, values of $k$ with $g(k) > 0$ imply that $k'_t > 0$, so\n", + "s Ak^\\alpha - \\delta k$, values of $k$ with $g(k) > 0$ imply $k'_t > 0$, so\n", "capital is increasing.\n", "\n", "When $g(k) < 0$, the opposite occurs. Once again, high marginal returns to\n", @@ -406,7 +407,7 @@ { "cell_type": "code", "execution_count": null, - "id": "27ebad46", + "id": "3c3acf45", "metadata": {}, "outputs": [], "source": [ @@ -415,7 +416,7 @@ }, { "cell_type": "markdown", - "id": "05c97bd9", + "id": "7d5b0096", "metadata": {}, "source": [ "Next we define the function $g$ for growth in continuous time" @@ -424,7 +425,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f4366c70", + "id": "7dc85bb0", "metadata": {}, "outputs": [], "source": [ @@ -435,7 +436,7 @@ { "cell_type": "code", "execution_count": null, - "id": "35b66d24", + "id": "62ea06b6", "metadata": {}, "outputs": [], "source": [ @@ -475,7 +476,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8b1f22d9", + "id": "2a95bb75", "metadata": {}, "outputs": [], "source": [ @@ -485,7 +486,7 @@ }, { "cell_type": "markdown", - "id": "f45b7d6a", + "id": "0b83f2f6", "metadata": {}, "source": [ "This shows global stability heuristically for a fixed parameterization, but\n", @@ -508,7 +509,7 @@ " x'_t = (1-\\alpha) (sA - \\delta x_t)\n", "```\n", "\n", - "This equation has the exact solution\n", + "This equation, which is a [linear ordinary differential equation](https://math.libretexts.org/Bookshelves/Calculus/Calculus_(Guichard)/17%3A_Differential_Equations/17.01%3A_First_Order_Differential_Equations), has the solution\n", "\n", "$$\n", " x_t\n", @@ -572,7 +573,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9dfaa123", + "id": "755cf1c3", "metadata": {}, "outputs": [], "source": [ @@ -584,7 +585,7 @@ { "cell_type": "code", "execution_count": null, - "id": "815451fc", + "id": "ec02a1f1", "metadata": {}, "outputs": [], "source": [ @@ -595,7 +596,7 @@ }, { "cell_type": "markdown", - "id": "173ae2de", + "id": "f80973c2", "metadata": {}, "source": [ "Let's find the value of $s$ that maximizes $c^*$ using [scipy.optimize.minimize_scalar](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize_scalar.html#scipy.optimize.minimize_scalar).\n", @@ -605,7 +606,7 @@ { "cell_type": "code", "execution_count": null, - "id": "add3bc1e", + "id": "183230d1", "metadata": {}, "outputs": [], "source": [ @@ -615,7 +616,7 @@ { "cell_type": "code", "execution_count": null, - "id": "0b34830a", + "id": "99c42775", "metadata": {}, "outputs": [], "source": [ @@ -627,7 +628,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6e911456", + "id": "5201ca76", "metadata": {}, "outputs": [], "source": [ @@ -640,7 +641,7 @@ { "cell_type": "code", "execution_count": null, - "id": "44b9029f", + "id": "cb4ad1b3", "metadata": {}, "outputs": [], "source": [ @@ -672,7 +673,7 @@ }, { "cell_type": "markdown", - "id": "751d8c2e", + "id": "6f9db7de", "metadata": {}, "source": [ "One can also try to solve this mathematically by differentiating $c^*(s)$ and solve for $\\frac{d}{ds}c^*(s)=0$ using [sympy](https://www.sympy.org/en/index.html)." @@ -681,7 +682,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1a0d1c8b", + "id": "b9a2b15e", "metadata": {}, "outputs": [], "source": [ @@ -691,7 +692,7 @@ { "cell_type": "code", "execution_count": null, - "id": "671f1881", + "id": "64542983", "metadata": {}, "outputs": [], "source": [ @@ -702,7 +703,7 @@ }, { "cell_type": "markdown", - "id": "ed02a43a", + "id": "d5dfe2f3", "metadata": {}, "source": [ "Let's differentiate $c$ and solve using [sympy.solve](https://docs.sympy.org/latest/modules/solvers/solvers.html#sympy.solvers.solvers.solve)" @@ -711,7 +712,7 @@ { "cell_type": "code", "execution_count": null, - "id": "596b7347", + "id": "24a57529", "metadata": {}, "outputs": [], "source": [ @@ -722,7 +723,7 @@ }, { "cell_type": "markdown", - "id": "885e3539", + "id": "9e87dbfa", "metadata": {}, "source": [ "Incidentally, the rate of savings which maximizes steady state level of per capita consumption is called the [Golden Rule savings rate](https://en.wikipedia.org/wiki/Golden_Rule_savings_rate).\n", @@ -776,7 +777,7 @@ { "cell_type": "code", "execution_count": null, - "id": "d9e48f3e", + "id": "ce9c4125", "metadata": {}, "outputs": [], "source": [ @@ -792,7 +793,7 @@ }, { "cell_type": "markdown", - "id": "dd3dd551", + "id": "2f3f2031", "metadata": {}, "source": [ "Let's define the function *k_next* to find the next value of $k$" @@ -801,7 +802,7 @@ { "cell_type": "code", "execution_count": null, - "id": "71ebbdeb", + "id": "8a5903b1", "metadata": {}, "outputs": [], "source": [ @@ -815,7 +816,7 @@ { "cell_type": "code", "execution_count": null, - "id": "468053a7", + "id": "f6b5a290", "metadata": {}, "outputs": [], "source": [ @@ -843,7 +844,7 @@ { "cell_type": "code", "execution_count": null, - "id": "624087ee", + "id": "5d829ffa", "metadata": {}, "outputs": [], "source": [ @@ -852,7 +853,7 @@ }, { "cell_type": "markdown", - "id": "d80289c6", + "id": "d28f351a", "metadata": {}, "source": [ "```{solution-end}\n", @@ -861,12 +862,61 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst" + } + }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" - } + }, + "source_map": [ + 10, + 25, + 28, + 119, + 123, + 127, + 130, + 134, + 175, + 177, + 204, + 207, + 223, + 232, + 259, + 261, + 321, + 323, + 327, + 332, + 366, + 369, + 451, + 457, + 461, + 466, + 470, + 476, + 483, + 508, + 512, + 516, + 520, + 524, + 528, + 577, + 586, + 590, + 598, + 620, + 622 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/solow.md b/book/_build/html/_sources/solow.md new file mode 100644 index 0000000..0a5160b --- /dev/null +++ b/book/_build/html/_sources/solow.md @@ -0,0 +1,627 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst +kernelspec: + display_name: Python 3 + language: python + name: python3 +--- + +(solow)= +# The Solow-Swan Growth Model + +In this lecture we review a famous model due +to [Robert Solow (1925--2023)](https://en.wikipedia.org/wiki/Robert_Solow) and [Trevor Swan (1918--1989)](https://en.wikipedia.org/wiki/Trevor_Swan). + +The model is used to study growth over the long run. + +Although the model is simple, it contains some interesting lessons. + + +We will use the following imports. + +```{code-cell} ipython3 +import matplotlib.pyplot as plt +import numpy as np +``` + +## The model + +In a Solow--Swan economy, agents save a fixed fraction of their current +incomes. + +Savings sustain or increase the stock of capital. + +Capital is combined with labor to produce output, which in turn is paid out to +workers and owners of capital. + +To keep things simple, we ignore population and productivity growth. + +For each integer $t \geq 0$, output $Y_t$ in period $t$ is given by $Y_t = +F(K_t, L_t)$, where $K_t$ is capital, $L_t$ is labor and $F$ is an aggregate +production function. + +The function $F$ is assumed to be nonnegative and +**homogeneous of degree one**, meaning +that + +$$ + F(\lambda K, \lambda L) = \lambda F(K, L) + \quad \text{for all } \lambda \geq 0 +$$ + +Production functions with this property include + +* the **Cobb-Douglas** function $F(K, L) = A K^{\alpha} + L^{1-\alpha}$ with $0 \leq \alpha \leq 1$. +* the **CES** function $F(K, L) = \left\{ a K^\rho + b L^\rho \right\}^{1/\rho}$ + with $a, b, \rho > 0$. + +Here, $\alpha$ is the output elasticity of capital and $\rho$ is a parameter that determines the elasticity of substitution between capital and labor. + +We assume a closed economy, so aggregate domestic investment equals aggregate domestic +saving. + +The saving rate is a constant $s$ satisfying $0 \leq s \leq 1$, so that aggregate +investment and saving both equal $s Y_t$. + +Capital depreciates: without replenishing through investment, one unit of capital today +becomes $1-\delta$ units tomorrow. + +Thus, + +$$ + K_{t+1} = s F(K_t, L_t) + (1 - \delta) K_t +$$ + + +Without population growth, $L_t$ equals some constant $L$. + +Setting $k_t := K_t / L$ and using homogeneity of degree one now yields + +$$ + k_{t+1} + = s \frac{F(K_t, L)}{L} + (1 - \delta) \frac{K_t}{L} + = s \frac{F(K_t, L)}{L} + (1 - \delta) k_t + = s F(k_t, 1) + (1 - \delta) k_t +$$ + + +With $f(k) := F(k, 1)$, the final expression for capital dynamics is + +```{math} +:label: solow + k_{t+1} = g(k_t) + \text{ where } g(k) := s f(k) + (1 - \delta) k +``` + +Our aim is to learn about the evolution of $k_t$ over time, +given an exogenous initial capital stock $k_0$. + + +## A graphical perspective + +To understand the dynamics of the sequence $(k_t)_{t \geq 0}$ we use a 45-degree diagram. + +To do so, we first +need to specify the functional form for $f$ and assign values to the parameters. + +We choose the Cobb--Douglas specification $f(k) = A k^\alpha$ and set $A=2.0$, +$\alpha=0.3$, $s=0.3$ and $\delta=0.4$. + +The function $g$ from {eq}`solow` is then plotted, along with the 45-degree line. + + +Let's define the constants. + +```{code-cell} ipython3 +A, s, alpha, delta = 2, 0.3, 0.3, 0.4 +x0 = 0.25 +xmin, xmax = 0, 3 +``` + +Now, we define the function $g$. + +```{code-cell} ipython3 +def g(A, s, alpha, delta, k): + return A * s * k**alpha + (1 - delta) * k +``` + +Let's plot the 45-degree diagram of $g$. + +```{code-cell} ipython3 +def plot45(kstar=None): + xgrid = np.linspace(xmin, xmax, 12000) + + fig, ax = plt.subplots() + + ax.set_xlim(xmin, xmax) + + g_values = g(A, s, alpha, delta, xgrid) + + ymin, ymax = np.min(g_values), np.max(g_values) + ax.set_ylim(ymin, ymax) + + lb = r'$g(k) = sAk^{\alpha} + (1 - \delta)k$' + ax.plot(xgrid, g_values, lw=2, alpha=0.6, label=lb) + ax.plot(xgrid, xgrid, 'k-', lw=1, alpha=0.7, label='$45^{\circ}$') + + if kstar: + fps = (kstar,) + + ax.plot(fps, fps, 'go', ms=10, alpha=0.6) + + ax.annotate(r'$k^* = (sA / \delta)^{(1/(1-\alpha))}$', + xy=(kstar, kstar), + xycoords='data', + xytext=(-40, -60), + textcoords='offset points', + fontsize=14, + arrowprops=dict(arrowstyle="->")) + + ax.legend(loc='upper left', frameon=False, fontsize=12) + + ax.set_xticks((0, 1, 2, 3)) + ax.set_yticks((0, 1, 2, 3)) + + ax.set_xlabel('$k_t$', fontsize=12) + ax.set_ylabel('$k_{t+1}$', fontsize=12) + + plt.show() +``` + +```{code-cell} ipython3 +plot45() +``` + +Suppose, at some $k_t$, the value $g(k_t)$ lies strictly above the 45-degree line. + +Then we have $k_{t+1} = g(k_t) > k_t$ and capital per worker rises. + +If $g(k_t) < k_t$ then capital per worker falls. + +If $g(k_t) = k_t$, then we are at a **steady state** and $k_t$ remains constant. + +(A {ref}`steady state ` of the model is a [fixed point](https://en.wikipedia.org/wiki/Fixed_point_(mathematics)) of the mapping $g$.) + +From the shape of the function $g$ in the figure, we see that +there is a unique steady state in $(0, \infty)$. + +It solves $k = s Ak^{\alpha} + (1-\delta)k$ and hence is given by + +```{math} +:label: kstarss + k^* := \left( \frac{s A}{\delta} \right)^{1/(1 - \alpha)} +``` +If initial capital is below $k^*$, then capital increases over time. + +If initial capital is above this level, then the reverse is true. + +Let's plot the 45-degree diagram to show the $k^*$ in the plot. + +```{code-cell} ipython3 +kstar = ((s * A) / delta)**(1/(1 - alpha)) +plot45(kstar) +``` + + +From our graphical analysis, it appears that $(k_t)$ converges to $k^*$, regardless of initial capital +$k_0$. + +This is a form of {ref}`global stability `. + + +The next figure shows three time paths for capital, from +three distinct initial conditions, under the parameterization listed above. + +At this parameterization, $k^* \approx 1.78$. + +Let's define the constants and three distinct initial conditions + +```{code-cell} ipython3 +A, s, alpha, delta = 2, 0.3, 0.3, 0.4 +x0 = np.array([.25, 1.25, 3.25]) + +ts_length = 20 +xmin, xmax = 0, ts_length +ymin, ymax = 0, 3.5 +``` + +```{code-cell} ipython3 +def simulate_ts(x0_values, ts_length): + + k_star = (s * A / delta)**(1/(1-alpha)) + fig, ax = plt.subplots(figsize=[11, 5]) + ax.set_xlim(xmin, xmax) + ax.set_ylim(ymin, ymax) + + ts = np.zeros(ts_length) + + # simulate and plot time series + for x_init in x0_values: + ts[0] = x_init + for t in range(1, ts_length): + ts[t] = g(A, s, alpha, delta, ts[t-1]) + ax.plot(np.arange(ts_length), ts, '-o', ms=4, alpha=0.6, + label=r'$k_0=%g$' %x_init) + ax.plot(np.arange(ts_length), np.full(ts_length,k_star), + alpha=0.6, color='red', label=r'$k^*$') + ax.legend(fontsize=10) + + ax.set_xlabel(r'$t$', fontsize=14) + ax.set_ylabel(r'$k_t$', fontsize=14) + + plt.show() +``` + +```{code-cell} ipython3 +simulate_ts(x0, ts_length) +``` + +As expected, the time paths in the figure all converge to $k^*$. + +## Growth in continuous time + +In this section, we investigate a continuous time version of the Solow--Swan +growth model. + +We will see how the smoothing provided by continuous time can +simplify our analysis. + + +Recall that the discrete time dynamics for capital are +given by $k_{t+1} = s f(k_t) + (1 - \delta) k_t$. + +A simple rearrangement gives the rate of change per unit of time: + +$$ + \Delta k_t = s f(k_t) - \delta k_t + \quad \text{where} \quad + \Delta k_t := k_{t+1} - k_t +$$ + +Taking the time step to zero gives the continuous time limit + +```{math} +:label: solowc + k'_t = s f(k_t) - \delta k_t + \qquad \text{with} \qquad + k'_t := \frac{d}{dt} k_t +``` + +Our aim is to learn about the evolution of $k_t$ over time, +given an initial stock $k_0$. + +A **steady state** for {eq}`solowc` is a value $k^*$ +at which capital is unchanging, meaning $k'_t = 0$ or, equivalently, +$s f(k^*) = \delta k^*$. + +We assume +$f(k) = Ak^\alpha$, so $k^*$ solves +$s A k^\alpha = \delta k$. + +The solution is the same as the discrete time case---see {eq}`kstarss`. + +The dynamics are represented in +the next figure, maintaining the parameterization we used +above. + +Writing $k'_t = g(k_t)$ with $g(k) = +s Ak^\alpha - \delta k$, values of $k$ with $g(k) > 0$ imply $k'_t > 0$, so +capital is increasing. + +When $g(k) < 0$, the opposite occurs. Once again, high marginal returns to +savings at low levels of capital combined with low rates of return at high +levels of capital combine to yield global stability. + +To see this in a figure, let's define the constants + +```{code-cell} ipython3 +A, s, alpha, delta = 2, 0.3, 0.3, 0.4 +``` + +Next we define the function $g$ for growth in continuous time + +```{code-cell} ipython3 +def g_con(A, s, alpha, delta, k): + return A * s * k**alpha - delta * k +``` + +```{code-cell} ipython3 +def plot_gcon(kstar=None): + + k_grid = np.linspace(0, 2.8, 10000) + + fig, ax = plt.subplots(figsize=[11, 5]) + ax.plot(k_grid, g_con(A, s, alpha, delta, k_grid), label='$g(k)$') + ax.plot(k_grid, 0 * k_grid, label="$k'=0$") + + if kstar: + fps = (kstar,) + + ax.plot(fps, 0, 'go', ms=10, alpha=0.6) + + + ax.annotate(r'$k^* = (sA / \delta)^{(1/(1-\alpha))}$', + xy=(kstar, 0), + xycoords='data', + xytext=(0, 60), + textcoords='offset points', + fontsize=12, + arrowprops=dict(arrowstyle="->")) + + ax.legend(loc='lower left', fontsize=12) + + ax.set_xlabel("$k$",fontsize=10) + ax.set_ylabel("$k'$", fontsize=10) + + ax.set_xticks((0, 1, 2, 3)) + ax.set_yticks((-0.3, 0, 0.3)) + + plt.show() +``` + +```{code-cell} ipython3 +kstar = ((s * A) / delta)**(1/(1 - alpha)) +plot_gcon(kstar) +``` + +This shows global stability heuristically for a fixed parameterization, but +how would we show the same thing formally for a continuum of plausible parameters? + +In the discrete time case, a neat expression for $k_t$ is hard to obtain. + +In continuous time the process is easier: we can obtain a relatively simple +expression for $k_t$ that specifies the entire path. + +The first step is +to set $x_t := k_t^{1-\alpha}$, so that $x'_t = (1-\alpha) k_t^{-\alpha} +k'_t$. + +Substituting into $k'_t = sAk_t^\alpha - \delta k_t$ leads to the +linear differential equation + +```{math} +:label: xsolow + x'_t = (1-\alpha) (sA - \delta x_t) +``` + +This equation, which is a [linear ordinary differential equation](https://math.libretexts.org/Bookshelves/Calculus/Calculus_(Guichard)/17%3A_Differential_Equations/17.01%3A_First_Order_Differential_Equations), has the solution + +$$ + x_t + = \left( + k_0^{1-\alpha} - \frac{sA}{\delta} + \right) + \mathrm{e}^{-\delta (1-\alpha) t} + + \frac{sA}{\delta} +$$ + +(You can confirm that this function $x_t$ satisfies {eq}`xsolow` by +differentiating it with respect to $t$.) + +Converting back to $k_t$ yields + +```{math} +:label: ssivs + k_t + = + \left[ + \left( + k_0^{1-\alpha} - \frac{sA}{\delta} + \right) + \mathrm{e}^{-\delta (1-\alpha) t} + + \frac{sA}{\delta} + \right]^{1/(1-\alpha)} +``` + +Since $\delta > 0$ and $\alpha \in (0, 1)$, we see immediately that $k_t \to +k^*$ as $t \to \infty$ independent of $k_0$. + +Thus, global stability holds. + +## Exercises + +```{exercise} +:label: solow_ex1 + +Plot per capita consumption $c$ at the steady state, as a function of the savings rate $s$, where $0 \leq s \leq 1$. + +Use the Cobb--Douglas specification $f(k) = A k^\alpha$. + +Set $A=2.0, \alpha=0.3,$ and $\delta=0.5$ + +Also, find the approximate value of $s$ that maximizes the $c^*(s)$ and show it in the plot. + +``` + +```{solution-start} solow_ex1 +:class: dropdown +``` + +Steady state consumption at savings rate $s$ is given by + + +$$ + c^*(s) = (1-s)f(k^*) = (1-s)A(k^*)^\alpha +$$ + +```{code-cell} ipython3 +A = 2.0 +alpha = 0.3 +delta = 0.5 +``` + +```{code-cell} ipython3 +s_grid = np.linspace(0, 1, 1000) +k_star = ((s_grid * A) / delta)**(1/(1 - alpha)) +c_star = (1 - s_grid) * A * k_star ** alpha +``` + +Let's find the value of $s$ that maximizes $c^*$ using [scipy.optimize.minimize_scalar](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize_scalar.html#scipy.optimize.minimize_scalar). +We will use $-c^*(s)$ since `minimize_scalar` finds the minimum value. + +```{code-cell} ipython3 +from scipy.optimize import minimize_scalar +``` + +```{code-cell} ipython3 +def calc_c_star(s): + k = ((s * A) / delta)**(1/(1 - alpha)) + return - (1 - s) * A * k ** alpha +``` + +```{code-cell} ipython3 +return_values = minimize_scalar(calc_c_star, bounds=(0, 1)) +s_star_max = return_values.x +c_star_max = -return_values.fun +print(f"Function is maximized at s = {round(s_star_max, 4)}") +``` + +```{code-cell} ipython3 +x_s_max = np.array([s_star_max, s_star_max]) +y_s_max = np.array([0, c_star_max]) + +fig, ax = plt.subplots(figsize=[11, 5]) + +fps = (c_star_max,) + +# Highlight the maximum point with a marker +ax.plot((s_star_max, ), (c_star_max,), 'go', ms=8, alpha=0.6) + +ax.annotate(r'$s^*$', + xy=(s_star_max, c_star_max), + xycoords='data', + xytext=(20, -50), + textcoords='offset points', + fontsize=12, + arrowprops=dict(arrowstyle="->")) +ax.plot(s_grid, c_star, label=r'$c*(s)$') +ax.plot(x_s_max, y_s_max, alpha=0.5, ls='dotted') +ax.set_xlabel(r'$s$') +ax.set_ylabel(r'$c^*(s)$') +ax.legend() + +plt.show() +``` + +One can also try to solve this mathematically by differentiating $c^*(s)$ and solve for $\frac{d}{ds}c^*(s)=0$ using [sympy](https://www.sympy.org/en/index.html). + +```{code-cell} ipython3 +from sympy import solve, Symbol +``` + +```{code-cell} ipython3 +s_symbol = Symbol('s', real=True) +k = ((s_symbol * A) / delta)**(1/(1 - alpha)) +c = (1 - s_symbol) * A * k ** alpha +``` + +Let's differentiate $c$ and solve using [sympy.solve](https://docs.sympy.org/latest/modules/solvers/solvers.html#sympy.solvers.solvers.solve) + +```{code-cell} ipython3 +# Solve using sympy +s_star = solve(c.diff())[0] +print(f"s_star = {s_star}") +``` + +Incidentally, the rate of savings which maximizes steady state level of per capita consumption is called the [Golden Rule savings rate](https://en.wikipedia.org/wiki/Golden_Rule_savings_rate). + +```{solution-end} +``` + +```{exercise-start} +:label: solow_ex2 +``` +**Stochastic Productivity** + +To bring the Solow--Swan model closer to data, we need to think about handling +random fluctuations in aggregate quantities. + +Among other things, this will +eliminate the unrealistic prediction that per-capita output $y_t = A +k^\alpha_t$ converges to a constant $y^* := A (k^*)^\alpha$. + +We shift to discrete time for the following discussion. + +One approach is to replace constant productivity with some +stochastic sequence $(A_t)_{t \geq 1}$. + +Dynamics are now + +```{math} +:label: solowran + k_{t+1} = s A_{t+1} f(k_t) + (1 - \delta) k_t +``` + +We suppose $f$ is Cobb--Douglas and $(A_t)$ is IID and lognormal. + +Now the long run convergence obtained in the deterministic case breaks +down, since the system is hit with new shocks at each point in time. + +Consider $A=2.0, s=0.6, \alpha=0.3,$ and $\delta=0.5$ + +Generate and plot the time series $k_t$. + +```{exercise-end} +``` + +```{solution-start} solow_ex2 +:class: dropdown +``` + +Let's define the constants for lognormal distribution and initial values used for simulation + +```{code-cell} ipython3 +# Define the constants +sig = 0.2 +mu = np.log(2) - sig**2 / 2 +A = 2.0 +s = 0.6 +alpha = 0.3 +delta = 0.5 +x0 = [.25, 3.25] # list of initial values used for simulation +``` + +Let's define the function *k_next* to find the next value of $k$ + +```{code-cell} ipython3 +def lgnorm(): + return np.exp(mu + sig * np.random.randn()) + +def k_next(s, alpha, delta, k): + return lgnorm() * s * k**alpha + (1 - delta) * k +``` + +```{code-cell} ipython3 +def ts_plot(x_values, ts_length): + fig, ax = plt.subplots(figsize=[11, 5]) + ts = np.zeros(ts_length) + + # simulate and plot time series + for x_init in x_values: + ts[0] = x_init + for t in range(1, ts_length): + ts[t] = k_next(s, alpha, delta, ts[t-1]) + ax.plot(np.arange(ts_length), ts, '-o', ms=4, + alpha=0.6, label=r'$k_0=%g$' %x_init) + + ax.legend(loc='best', fontsize=10) + + ax.set_xlabel(r'$t$', fontsize=12) + ax.set_ylabel(r'$k_t$', fontsize=12) + + + plt.show() +``` + +```{code-cell} ipython3 +ts_plot(x0, 50) +``` + + + +```{solution-end} +``` diff --git a/book/_build/html/_sources/status.ipynb b/book/_build/html/_sources/status.ipynb new file mode 100644 index 0000000..7dba38f --- /dev/null +++ b/book/_build/html/_sources/status.ipynb @@ -0,0 +1,76 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "371835c9", + "metadata": {}, + "source": [ + "# Execution Statistics\n", + "\n", + "This table contains the latest execution statistics.\n", + "\n", + "```{nb-exec-table}\n", + "```\n", + "\n", + "(status:machine-details)=\n", + "\n", + "These lectures are built on `linux` instances through `github actions`. \n", + "\n", + "These lectures are using the following python version" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2173ed3e", + "metadata": {}, + "outputs": [], + "source": [ + "!python --version" + ] + }, + { + "cell_type": "markdown", + "id": "b44be3ac", + "metadata": {}, + "source": [ + "and the following package versions" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "db065ee9", + "metadata": { + "tags": [ + "hide-output" + ] + }, + "outputs": [], + "source": [ + "!conda list" + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst" + } + }, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "source_map": [ + 10, + 25, + 27, + 31 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/status.md b/book/_build/html/_sources/status.md new file mode 100644 index 0000000..3ada25f --- /dev/null +++ b/book/_build/html/_sources/status.md @@ -0,0 +1,34 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst +kernelspec: + display_name: Python 3 + language: python + name: python3 +--- + +# Execution Statistics + +This table contains the latest execution statistics. + +```{nb-exec-table} +``` + +(status:machine-details)= + +These lectures are built on `linux` instances through `github actions`. + +These lectures are using the following python version + +```{code-cell} ipython +!python --version +``` + +and the following package versions + +```{code-cell} ipython +:tags: [hide-output] +!conda list +``` \ No newline at end of file diff --git a/book/_build/html/_sources/supply_demand_heterogeneity.ipynb b/book/_build/html/_sources/supply_demand_heterogeneity.ipynb new file mode 100644 index 0000000..f8fb8c7 --- /dev/null +++ b/book/_build/html/_sources/supply_demand_heterogeneity.ipynb @@ -0,0 +1,582 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "0a083fdf", + "metadata": {}, + "source": [ + "(supply_demand_heterogeneity)=\n", + "# Market Equilibrium with Heterogeneity\n", + "\n", + "## Overview\n", + "\n", + "In the {doc}`previous lecture\n", + "`, we studied competitive equilibria in an economy with many goods.\n", + "\n", + "While the results of the study were informative, we used a strong simplifying assumption: all of the agents in the economy are identical.\n", + "\n", + "In the real world, households, firms and other economic agents differ from one another along many dimensions.\n", + "\n", + "In this lecture, we introduce heterogeneity across consumers by allowing their preferences and endowments to differ.\n", + "\n", + "We will examine competitive equilibrium in this setting.\n", + "\n", + "We will also show how a \"representative consumer\" can be constructed.\n", + "\n", + "Here are some imports:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "74d60cdd", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "from scipy.linalg import inv" + ] + }, + { + "cell_type": "markdown", + "id": "7a04536c", + "metadata": {}, + "source": [ + "## An simple example\n", + "\n", + "Let's study a simple example of **pure exchange** economy without production.\n", + "\n", + "There are two consumers who differ in their endowment vectors $e_i$ and their bliss-point vectors $b_i$ for $i=1,2$.\n", + "\n", + "The total endowment is $e_1 + e_2$.\n", + "\n", + "A competitive equilibrium requires that\n", + "\n", + "$$\n", + "c_1 + c_2 = e_1 + e_2\n", + "$$\n", + "\n", + "Assume the demand curves\n", + "\n", + "$$\n", + " c_i = (\\Pi^\\top \\Pi )^{-1}(\\Pi^\\top b_i - \\mu_i p )\n", + "$$\n", + "\n", + "Competitive equilibrium then requires that\n", + "\n", + "$$\n", + "e_1 + e_2 =\n", + " (\\Pi^\\top \\Pi)^{-1}(\\Pi^\\top (b_1 + b_2) - (\\mu_1 + \\mu_2) p )\n", + "$$\n", + "\n", + "which, after a line or two of linear algebra, implies that\n", + "\n", + "$$\n", + "(\\mu_1 + \\mu_2) p = \\Pi^\\top(b_1+ b_2) - \\Pi^\\top \\Pi (e_1 + e_2)\n", + "$$ (eq:old6)\n", + "\n", + "We can normalize prices by setting $\\mu_1 + \\mu_2 =1$ and then solving\n", + "\n", + "$$\n", + "\\mu_i(p,e) = \\frac{p^\\top (\\Pi^{-1} b_i - e_i)}{p^\\top (\\Pi^\\top \\Pi )^{-1} p}\n", + "$$ (eq:old7)\n", + "\n", + "for $\\mu_i, i = 1,2$.\n", + "\n", + "```{exercise-start}\n", + ":label: sdh_ex1\n", + "```\n", + "\n", + "Show that, up to normalization by a positive scalar, the same competitive equilibrium price vector that you computed in the preceding two-consumer economy would prevail in a single-consumer economy in which a single **representative consumer** has utility function\n", + "\n", + "$$\n", + "-.5 (\\Pi c -b) ^\\top (\\Pi c -b )\n", + "$$\n", + "\n", + "and endowment vector $e$, where\n", + "\n", + "$$\n", + "b = b_1 + b_2\n", + "$$\n", + "\n", + "and\n", + "\n", + "$$\n", + "e = e_1 + e_2 .\n", + "$$\n", + "\n", + "```{exercise-end}\n", + "```\n", + "\n", + "## Pure exchange economy\n", + "\n", + "Let's further explore a pure exchange economy with $n$ goods and $m$ people.\n", + "\n", + "### Competitive equilibrium\n", + "\n", + "We'll compute a competitive equilibrium.\n", + "\n", + "To compute a competitive equilibrium of a pure exchange economy, we use the fact that\n", + "\n", + "- Relative prices in a competitive equilibrium are the same as those in a special single person or representative consumer economy with preference $\\Pi$ and $b=\\sum_i b_i$, and endowment $e = \\sum_i e_{i}$.\n", + "\n", + "We can use the following steps to compute a competitive equilibrium:\n", + "\n", + "- First we solve the single representative consumer economy by normalizing $\\mu = 1$. Then, we renormalize the price vector by using the first consumption good as a numeraire.\n", + "\n", + "- Next we use the competitive equilibrium prices to compute each consumer's marginal utility of wealth:\n", + "\n", + "$$\n", + "\\mu_{i}=\\frac{-W_{i}+p^{\\top}\\left(\\Pi^{-1}b_{i}-e_{i}\\right)}{p^{\\top}(\\Pi^{\\top}\\Pi)^{-1}p}$$\n", + "\n", + "- Finally we compute a competitive equilibrium allocation by using the demand curves:\n", + " \n", + "$$\n", + "c_{i}=\\Pi^{-1}b_{i}-(\\Pi^{\\top}\\Pi)^{-1}\\mu_{i}p \n", + "$$\n", + "\n", + "\n", + "### Designing some Python code\n", + "\n", + "\n", + "Below we shall construct a Python class with the following attributes:\n", + "\n", + " * **Preferences** in the form of\n", + "\n", + " * an $n \\times n$ positive definite matrix $\\Pi$\n", + " * an $n \\times 1$ vector of bliss points $b$\n", + "\n", + " * **Endowments** in the form of\n", + "\n", + " * an $n \\times 1$ vector $e$\n", + " * a scalar \"wealth\" $W$ with default value $0$\n", + "\n", + "\n", + "The class will include a test to make sure that $b \\gg \\Pi e $ and raise an exception if it is violated\n", + "(at some threshold level we'd have to specify).\n", + "\n", + " * **A Person** in the form of a pair that consists of\n", + "\n", + " * **Preferences** and **Endowments**\n", + "\n", + " * **A Pure Exchange Economy** will consist of\n", + "\n", + " * a collection of $m$ **persons**\n", + "\n", + " * $m=1$ for our single-agent economy\n", + " * $m=2$ for our illustrations of a pure exchange economy\n", + "\n", + " * an equilibrium price vector $p$ (normalized somehow)\n", + " * an equilibrium allocation $c_1, c_2, \\ldots, c_m$ -- a collection of $m$ vectors of dimension $n \\times 1$\n", + "\n", + "Now let's proceed to code." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a0ffc84b", + "metadata": {}, + "outputs": [], + "source": [ + "class ExchangeEconomy:\n", + " def __init__(self, \n", + " Π, \n", + " bs, \n", + " es, \n", + " Ws=None, \n", + " thres=1.5):\n", + " \"\"\"\n", + " Set up the environment for an exchange economy\n", + "\n", + " Args:\n", + " Π (np.array): shared matrix of substitution\n", + " bs (list): all consumers' bliss points\n", + " es (list): all consumers' endowments\n", + " Ws (list): all consumers' wealth\n", + " thres (float): a threshold set to test b >> Pi e violated\n", + " \"\"\"\n", + " n, m = Π.shape[0], len(bs)\n", + "\n", + " # check non-satiation\n", + " for b, e in zip(bs, es):\n", + " if np.min(b / np.max(Π @ e)) <= thres:\n", + " raise Exception('set bliss points further away')\n", + "\n", + " if Ws == None:\n", + " Ws = np.zeros(m)\n", + " else:\n", + " if sum(Ws) != 0:\n", + " raise Exception('invalid wealth distribution')\n", + "\n", + " self.Π, self.bs, self.es, self.Ws, self.n, self.m = Π, bs, es, Ws, n, m\n", + "\n", + " def competitive_equilibrium(self):\n", + " \"\"\"\n", + " Compute the competitive equilibrium prices and allocation\n", + " \"\"\"\n", + " Π, bs, es, Ws = self.Π, self.bs, self.es, self.Ws\n", + " n, m = self.n, self.m\n", + " slope_dc = inv(Π.T @ Π)\n", + " Π_inv = inv(Π)\n", + "\n", + " # aggregate\n", + " b = sum(bs)\n", + " e = sum(es)\n", + "\n", + " # compute price vector with mu=1 and renormalize\n", + " p = Π.T @ b - Π.T @ Π @ e\n", + " p = p / p[0]\n", + "\n", + " # compute marginal utility of wealth\n", + " μ_s = []\n", + " c_s = []\n", + " A = p.T @ slope_dc @ p\n", + "\n", + " for i in range(m):\n", + " μ_i = (-Ws[i] + p.T @ (Π_inv @ bs[i] - es[i])) / A\n", + " c_i = Π_inv @ bs[i] - μ_i * slope_dc @ p\n", + " μ_s.append(μ_i)\n", + " c_s.append(c_i)\n", + "\n", + " for c_i in c_s:\n", + " if any(c_i < 0):\n", + " print('allocation: ', c_s)\n", + " raise Exception('negative allocation: equilibrium does not exist')\n", + "\n", + " return p, c_s, μ_s" + ] + }, + { + "cell_type": "markdown", + "id": "41870199", + "metadata": {}, + "source": [ + "## Implementation\n", + "\n", + "Next we use the class ``ExchangeEconomy`` defined above to study \n", + "\n", + "* a two-person economy without production,\n", + "* a dynamic economy, and\n", + "* an economy with risk and arrow securities.\n", + "\n", + "### Two-person economy without production\n", + "\n", + "Here we study how competitive equilibrium $p, c_1, c_2$ respond to different $b_i$ and $e_i$, $i \\in \\{1, 2\\}$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ff00f579", + "metadata": {}, + "outputs": [], + "source": [ + "Π = np.array([[1, 0],\n", + " [0, 1]])\n", + "\n", + "bs = [np.array([5, 5]), # first consumer's bliss points\n", + " np.array([5, 5])] # second consumer's bliss points\n", + "\n", + "es = [np.array([0, 2]), # first consumer's endowment\n", + " np.array([2, 0])] # second consumer's endowment\n", + "\n", + "EE = ExchangeEconomy(Π, bs, es)\n", + "p, c_s, μ_s = EE.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price vector:', p)\n", + "print('Competitive equilibrium allocation:', c_s)" + ] + }, + { + "cell_type": "markdown", + "id": "69afb377", + "metadata": {}, + "source": [ + "What happens if the first consumer likes the first good more and the second consumer likes the second good more?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bc104b8a", + "metadata": {}, + "outputs": [], + "source": [ + "EE.bs = [np.array([6, 5]), # first consumer's bliss points\n", + " np.array([5, 6])] # second consumer's bliss points\n", + "\n", + "p, c_s, μ_s = EE.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price vector:', p)\n", + "print('Competitive equilibrium allocation:', c_s)" + ] + }, + { + "cell_type": "markdown", + "id": "0222dec9", + "metadata": {}, + "source": [ + "Let the first consumer be poorer." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3930e0b0", + "metadata": {}, + "outputs": [], + "source": [ + "EE.es = [np.array([0.5, 0.5]), # first consumer's endowment\n", + " np.array([1, 1])] # second consumer's endowment\n", + "\n", + "p, c_s, μ_s = EE.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price vector:', p)\n", + "print('Competitive equilibrium allocation:', c_s)" + ] + }, + { + "cell_type": "markdown", + "id": "58014bf9", + "metadata": {}, + "source": [ + "Now let's construct an autarky (i.e., no-trade) equilibrium." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "28c12cd3", + "metadata": {}, + "outputs": [], + "source": [ + "EE.bs = [np.array([4, 6]), # first consumer's bliss points\n", + " np.array([6, 4])] # second consumer's bliss points\n", + "\n", + "EE.es = [np.array([0, 2]), # first consumer's endowment\n", + " np.array([2, 0])] # second consumer's endowment\n", + "\n", + "p, c_s, μ_s = EE.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price vector:', p)\n", + "print('Competitive equilibrium allocation:', c_s)" + ] + }, + { + "cell_type": "markdown", + "id": "4fdd95ac", + "metadata": {}, + "source": [ + "Now let's redistribute endowments before trade." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8a464d38", + "metadata": {}, + "outputs": [], + "source": [ + "bs = [np.array([5, 5]), # first consumer's bliss points\n", + " np.array([5, 5])] # second consumer's bliss points\n", + "\n", + "es = [np.array([1, 1]), # first consumer's endowment\n", + " np.array([1, 1])] # second consumer's endowment\n", + "\n", + "Ws = [0.5, -0.5]\n", + "EE_new = ExchangeEconomy(Π, bs, es, Ws)\n", + "p, c_s, μ_s = EE_new.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price vector:', p)\n", + "print('Competitive equilibrium allocation:', c_s)" + ] + }, + { + "cell_type": "markdown", + "id": "c6395a26", + "metadata": {}, + "source": [ + "### A dynamic economy\n", + "\n", + "Now let's use the tricks described above to study a dynamic economy, one with two periods." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "11d55efe", + "metadata": {}, + "outputs": [], + "source": [ + "beta = 0.95\n", + "\n", + "Π = np.array([[1, 0],\n", + " [0, np.sqrt(beta)]])\n", + "\n", + "bs = [np.array([5, np.sqrt(beta) * 5])]\n", + "\n", + "es = [np.array([1, 1])]\n", + "\n", + "EE_DE = ExchangeEconomy(Π, bs, es)\n", + "p, c_s, μ_s = EE_DE.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price vector:', p)\n", + "print('Competitive equilibrium allocation:', c_s)" + ] + }, + { + "cell_type": "markdown", + "id": "a3083f52", + "metadata": {}, + "source": [ + "### Risk economy with arrow securities\n", + "\n", + "We use the tricks described above to interpret $c_1, c_2$ as \"Arrow securities\" that are state-contingent claims to consumption goods." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "44b9ec07", + "metadata": {}, + "outputs": [], + "source": [ + "prob = 0.7\n", + "\n", + "Π = np.array([[np.sqrt(prob), 0],\n", + " [0, np.sqrt(1 - prob)]])\n", + "\n", + "bs = [np.array([np.sqrt(prob) * 5, np.sqrt(1 - prob) * 5]),\n", + " np.array([np.sqrt(prob) * 5, np.sqrt(1 - prob) * 5])]\n", + "\n", + "es = [np.array([1, 0]),\n", + " np.array([0, 1])]\n", + "\n", + "EE_AS = ExchangeEconomy(Π, bs, es)\n", + "p, c_s, μ_s = EE_AS.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price vector:', p)\n", + "print('Competitive equilibrium allocation:', c_s)" + ] + }, + { + "cell_type": "markdown", + "id": "eae6a32c", + "metadata": {}, + "source": [ + "## Deducing a representative consumer\n", + "\n", + "In the class of multiple consumer economies that we are studying here, it turns out that there\n", + "exists a single **representative consumer** whose preferences and endowments can be deduced from lists of preferences and endowments for separate individual consumers.\n", + "\n", + "Consider a multiple consumer economy with initial distribution of wealth $W_i$ satisfying $\\sum_i W_{i}=0$\n", + "\n", + "We allow an initial redistribution of wealth.\n", + "\n", + "We have the following objects\n", + "\n", + "\n", + "- The demand curve:\n", + " \n", + "$$ \n", + "c_{i}=\\Pi^{-1}b_{i}-(\\Pi^{\\top}\\Pi)^{-1}\\mu_{i}p \n", + "$$\n", + "\n", + "- The marginal utility of wealth:\n", + " \n", + "$$ \n", + "\\mu_{i}=\\frac{-W_{i}+p^{\\top}\\left(\\Pi^{-1}b_{i}-e_{i}\\right)}{p^{\\top}(\\Pi^{\\top}\\Pi)^{-1}p}\n", + "$$\n", + "\n", + "- Market clearing:\n", + " \n", + "$$ \n", + "\\sum c_{i}=\\sum e_{i}\n", + "$$\n", + "\n", + "Denote aggregate consumption $\\sum_i c_{i}=c$ and $\\sum_i \\mu_i = \\mu$.\n", + "\n", + "Market clearing requires\n", + "\n", + "$$ \n", + "\\Pi^{-1}\\left(\\sum_{i}b_{i}\\right)-(\\Pi^{\\top}\\Pi)^{-1}p\\left(\\sum_{i}\\mu_{i}\\right)=\\sum_{i}e_{i}\n", + "$$\n", + "which, after a few steps, leads to\n", + "\n", + "$$\n", + "p=\\mu^{-1}\\left(\\Pi^{\\top}b-\\Pi^{\\top}\\Pi e\\right)\n", + "$$\n", + "\n", + "where\n", + "\n", + "$$ \n", + "\\mu = \\sum_i\\mu_{i}=\\frac{0 + p^{\\top}\\left(\\Pi^{-1}b-e\\right)}{p^{\\top}(\\Pi^{\\top}\\Pi)^{-1}p}.\n", + "$$\n", + "\n", + "Now consider the representative consumer economy specified above.\n", + "\n", + "Denote the marginal utility of wealth of the representative consumer by $\\tilde{\\mu}$.\n", + "\n", + "The demand function is\n", + "\n", + "$$\n", + "c=\\Pi^{-1}b-(\\Pi^{\\top}\\Pi)^{-1}\\tilde{\\mu} p\n", + "$$\n", + "\n", + "Substituting this into the budget constraint gives\n", + "\n", + "$$\n", + "\\tilde{\\mu}=\\frac{p^{\\top}\\left(\\Pi^{-1}b-e\\right)}{p^{\\top}(\\Pi^{\\top}\\Pi)^{-1}p}\n", + "$$\n", + "\n", + "In an equilibrium $c=e$, so\n", + "\n", + "$$\n", + "p=\\tilde{\\mu}^{-1}(\\Pi^{\\top}b-\\Pi^{\\top}\\Pi e)\n", + "$$\n", + "\n", + "Thus, we have verified that, up to the choice of a numeraire in which to express absolute prices, the price \n", + "vector in our representative consumer economy is the same as that in an underlying economy with multiple consumers." + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.5" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 34, + 37, + 168, + 235, + 249, + 264, + 268, + 276, + 280, + 288, + 292, + 303, + 307, + 320, + 326, + 341, + 347, + 364 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/supply_demand_heterogeneity.md b/book/_build/html/_sources/supply_demand_heterogeneity.md new file mode 100644 index 0000000..347294b --- /dev/null +++ b/book/_build/html/_sources/supply_demand_heterogeneity.md @@ -0,0 +1,438 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.5 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +(supply_demand_heterogeneity)= +# Market Equilibrium with Heterogeneity + +## Overview + +In the {doc}`previous lecture +`, we studied competitive equilibria in an economy with many goods. + +While the results of the study were informative, we used a strong simplifying assumption: all of the agents in the economy are identical. + +In the real world, households, firms and other economic agents differ from one another along many dimensions. + +In this lecture, we introduce heterogeneity across consumers by allowing their preferences and endowments to differ. + +We will examine competitive equilibrium in this setting. + +We will also show how a "representative consumer" can be constructed. + +Here are some imports: + +```{code-cell} ipython3 +import numpy as np +from scipy.linalg import inv +``` + +## An simple example + +Let's study a simple example of **pure exchange** economy without production. + +There are two consumers who differ in their endowment vectors $e_i$ and their bliss-point vectors $b_i$ for $i=1,2$. + +The total endowment is $e_1 + e_2$. + +A competitive equilibrium requires that + +$$ +c_1 + c_2 = e_1 + e_2 +$$ + +Assume the demand curves + +$$ + c_i = (\Pi^\top \Pi )^{-1}(\Pi^\top b_i - \mu_i p ) +$$ + +Competitive equilibrium then requires that + +$$ +e_1 + e_2 = + (\Pi^\top \Pi)^{-1}(\Pi^\top (b_1 + b_2) - (\mu_1 + \mu_2) p ) +$$ + +which, after a line or two of linear algebra, implies that + +$$ +(\mu_1 + \mu_2) p = \Pi^\top(b_1+ b_2) - \Pi^\top \Pi (e_1 + e_2) +$$ (eq:old6) + +We can normalize prices by setting $\mu_1 + \mu_2 =1$ and then solving + +$$ +\mu_i(p,e) = \frac{p^\top (\Pi^{-1} b_i - e_i)}{p^\top (\Pi^\top \Pi )^{-1} p} +$$ (eq:old7) + +for $\mu_i, i = 1,2$. + +```{exercise-start} +:label: sdh_ex1 +``` + +Show that, up to normalization by a positive scalar, the same competitive equilibrium price vector that you computed in the preceding two-consumer economy would prevail in a single-consumer economy in which a single **representative consumer** has utility function + +$$ +-.5 (\Pi c -b) ^\top (\Pi c -b ) +$$ + +and endowment vector $e$, where + +$$ +b = b_1 + b_2 +$$ + +and + +$$ +e = e_1 + e_2 . +$$ + +```{exercise-end} +``` + +## Pure exchange economy + +Let's further explore a pure exchange economy with $n$ goods and $m$ people. + +### Competitive equilibrium + +We'll compute a competitive equilibrium. + +To compute a competitive equilibrium of a pure exchange economy, we use the fact that + +- Relative prices in a competitive equilibrium are the same as those in a special single person or representative consumer economy with preference $\Pi$ and $b=\sum_i b_i$, and endowment $e = \sum_i e_{i}$. + +We can use the following steps to compute a competitive equilibrium: + +- First we solve the single representative consumer economy by normalizing $\mu = 1$. Then, we renormalize the price vector by using the first consumption good as a numeraire. + +- Next we use the competitive equilibrium prices to compute each consumer's marginal utility of wealth: + +$$ +\mu_{i}=\frac{-W_{i}+p^{\top}\left(\Pi^{-1}b_{i}-e_{i}\right)}{p^{\top}(\Pi^{\top}\Pi)^{-1}p}$$ + +- Finally we compute a competitive equilibrium allocation by using the demand curves: + +$$ +c_{i}=\Pi^{-1}b_{i}-(\Pi^{\top}\Pi)^{-1}\mu_{i}p +$$ + + +### Designing some Python code + + +Below we shall construct a Python class with the following attributes: + + * **Preferences** in the form of + + * an $n \times n$ positive definite matrix $\Pi$ + * an $n \times 1$ vector of bliss points $b$ + + * **Endowments** in the form of + + * an $n \times 1$ vector $e$ + * a scalar "wealth" $W$ with default value $0$ + + +The class will include a test to make sure that $b \gg \Pi e $ and raise an exception if it is violated +(at some threshold level we'd have to specify). + + * **A Person** in the form of a pair that consists of + + * **Preferences** and **Endowments** + + * **A Pure Exchange Economy** will consist of + + * a collection of $m$ **persons** + + * $m=1$ for our single-agent economy + * $m=2$ for our illustrations of a pure exchange economy + + * an equilibrium price vector $p$ (normalized somehow) + * an equilibrium allocation $c_1, c_2, \ldots, c_m$ -- a collection of $m$ vectors of dimension $n \times 1$ + +Now let's proceed to code. + +```{code-cell} ipython3 +class ExchangeEconomy: + def __init__(self, + Π, + bs, + es, + Ws=None, + thres=1.5): + """ + Set up the environment for an exchange economy + + Args: + Π (np.array): shared matrix of substitution + bs (list): all consumers' bliss points + es (list): all consumers' endowments + Ws (list): all consumers' wealth + thres (float): a threshold set to test b >> Pi e violated + """ + n, m = Π.shape[0], len(bs) + + # check non-satiation + for b, e in zip(bs, es): + if np.min(b / np.max(Π @ e)) <= thres: + raise Exception('set bliss points further away') + + if Ws == None: + Ws = np.zeros(m) + else: + if sum(Ws) != 0: + raise Exception('invalid wealth distribution') + + self.Π, self.bs, self.es, self.Ws, self.n, self.m = Π, bs, es, Ws, n, m + + def competitive_equilibrium(self): + """ + Compute the competitive equilibrium prices and allocation + """ + Π, bs, es, Ws = self.Π, self.bs, self.es, self.Ws + n, m = self.n, self.m + slope_dc = inv(Π.T @ Π) + Π_inv = inv(Π) + + # aggregate + b = sum(bs) + e = sum(es) + + # compute price vector with mu=1 and renormalize + p = Π.T @ b - Π.T @ Π @ e + p = p / p[0] + + # compute marginal utility of wealth + μ_s = [] + c_s = [] + A = p.T @ slope_dc @ p + + for i in range(m): + μ_i = (-Ws[i] + p.T @ (Π_inv @ bs[i] - es[i])) / A + c_i = Π_inv @ bs[i] - μ_i * slope_dc @ p + μ_s.append(μ_i) + c_s.append(c_i) + + for c_i in c_s: + if any(c_i < 0): + print('allocation: ', c_s) + raise Exception('negative allocation: equilibrium does not exist') + + return p, c_s, μ_s +``` + +## Implementation + +Next we use the class ``ExchangeEconomy`` defined above to study + +* a two-person economy without production, +* a dynamic economy, and +* an economy with risk and arrow securities. + +### Two-person economy without production + +Here we study how competitive equilibrium $p, c_1, c_2$ respond to different $b_i$ and $e_i$, $i \in \{1, 2\}$. + +```{code-cell} ipython3 +Π = np.array([[1, 0], + [0, 1]]) + +bs = [np.array([5, 5]), # first consumer's bliss points + np.array([5, 5])] # second consumer's bliss points + +es = [np.array([0, 2]), # first consumer's endowment + np.array([2, 0])] # second consumer's endowment + +EE = ExchangeEconomy(Π, bs, es) +p, c_s, μ_s = EE.competitive_equilibrium() + +print('Competitive equilibrium price vector:', p) +print('Competitive equilibrium allocation:', c_s) +``` + +What happens if the first consumer likes the first good more and the second consumer likes the second good more? + +```{code-cell} ipython3 +EE.bs = [np.array([6, 5]), # first consumer's bliss points + np.array([5, 6])] # second consumer's bliss points + +p, c_s, μ_s = EE.competitive_equilibrium() + +print('Competitive equilibrium price vector:', p) +print('Competitive equilibrium allocation:', c_s) +``` + +Let the first consumer be poorer. + +```{code-cell} ipython3 +EE.es = [np.array([0.5, 0.5]), # first consumer's endowment + np.array([1, 1])] # second consumer's endowment + +p, c_s, μ_s = EE.competitive_equilibrium() + +print('Competitive equilibrium price vector:', p) +print('Competitive equilibrium allocation:', c_s) +``` + +Now let's construct an autarky (i.e., no-trade) equilibrium. + +```{code-cell} ipython3 +EE.bs = [np.array([4, 6]), # first consumer's bliss points + np.array([6, 4])] # second consumer's bliss points + +EE.es = [np.array([0, 2]), # first consumer's endowment + np.array([2, 0])] # second consumer's endowment + +p, c_s, μ_s = EE.competitive_equilibrium() + +print('Competitive equilibrium price vector:', p) +print('Competitive equilibrium allocation:', c_s) +``` + +Now let's redistribute endowments before trade. + +```{code-cell} ipython3 +bs = [np.array([5, 5]), # first consumer's bliss points + np.array([5, 5])] # second consumer's bliss points + +es = [np.array([1, 1]), # first consumer's endowment + np.array([1, 1])] # second consumer's endowment + +Ws = [0.5, -0.5] +EE_new = ExchangeEconomy(Π, bs, es, Ws) +p, c_s, μ_s = EE_new.competitive_equilibrium() + +print('Competitive equilibrium price vector:', p) +print('Competitive equilibrium allocation:', c_s) +``` + +### A dynamic economy + +Now let's use the tricks described above to study a dynamic economy, one with two periods. + +```{code-cell} ipython3 +beta = 0.95 + +Π = np.array([[1, 0], + [0, np.sqrt(beta)]]) + +bs = [np.array([5, np.sqrt(beta) * 5])] + +es = [np.array([1, 1])] + +EE_DE = ExchangeEconomy(Π, bs, es) +p, c_s, μ_s = EE_DE.competitive_equilibrium() + +print('Competitive equilibrium price vector:', p) +print('Competitive equilibrium allocation:', c_s) +``` + +### Risk economy with arrow securities + +We use the tricks described above to interpret $c_1, c_2$ as "Arrow securities" that are state-contingent claims to consumption goods. + +```{code-cell} ipython3 +prob = 0.7 + +Π = np.array([[np.sqrt(prob), 0], + [0, np.sqrt(1 - prob)]]) + +bs = [np.array([np.sqrt(prob) * 5, np.sqrt(1 - prob) * 5]), + np.array([np.sqrt(prob) * 5, np.sqrt(1 - prob) * 5])] + +es = [np.array([1, 0]), + np.array([0, 1])] + +EE_AS = ExchangeEconomy(Π, bs, es) +p, c_s, μ_s = EE_AS.competitive_equilibrium() + +print('Competitive equilibrium price vector:', p) +print('Competitive equilibrium allocation:', c_s) +``` + +## Deducing a representative consumer + +In the class of multiple consumer economies that we are studying here, it turns out that there +exists a single **representative consumer** whose preferences and endowments can be deduced from lists of preferences and endowments for separate individual consumers. + +Consider a multiple consumer economy with initial distribution of wealth $W_i$ satisfying $\sum_i W_{i}=0$ + +We allow an initial redistribution of wealth. + +We have the following objects + + +- The demand curve: + +$$ +c_{i}=\Pi^{-1}b_{i}-(\Pi^{\top}\Pi)^{-1}\mu_{i}p +$$ + +- The marginal utility of wealth: + +$$ +\mu_{i}=\frac{-W_{i}+p^{\top}\left(\Pi^{-1}b_{i}-e_{i}\right)}{p^{\top}(\Pi^{\top}\Pi)^{-1}p} +$$ + +- Market clearing: + +$$ +\sum c_{i}=\sum e_{i} +$$ + +Denote aggregate consumption $\sum_i c_{i}=c$ and $\sum_i \mu_i = \mu$. + +Market clearing requires + +$$ +\Pi^{-1}\left(\sum_{i}b_{i}\right)-(\Pi^{\top}\Pi)^{-1}p\left(\sum_{i}\mu_{i}\right)=\sum_{i}e_{i} +$$ +which, after a few steps, leads to + +$$ +p=\mu^{-1}\left(\Pi^{\top}b-\Pi^{\top}\Pi e\right) +$$ + +where + +$$ +\mu = \sum_i\mu_{i}=\frac{0 + p^{\top}\left(\Pi^{-1}b-e\right)}{p^{\top}(\Pi^{\top}\Pi)^{-1}p}. +$$ + +Now consider the representative consumer economy specified above. + +Denote the marginal utility of wealth of the representative consumer by $\tilde{\mu}$. + +The demand function is + +$$ +c=\Pi^{-1}b-(\Pi^{\top}\Pi)^{-1}\tilde{\mu} p +$$ + +Substituting this into the budget constraint gives + +$$ +\tilde{\mu}=\frac{p^{\top}\left(\Pi^{-1}b-e\right)}{p^{\top}(\Pi^{\top}\Pi)^{-1}p} +$$ + +In an equilibrium $c=e$, so + +$$ +p=\tilde{\mu}^{-1}(\Pi^{\top}b-\Pi^{\top}\Pi e) +$$ + +Thus, we have verified that, up to the choice of a numeraire in which to express absolute prices, the price +vector in our representative consumer economy is the same as that in an underlying economy with multiple consumers. diff --git a/book/_build/html/_sources/supply_demand_multiple_goods.ipynb b/book/_build/html/_sources/supply_demand_multiple_goods.ipynb new file mode 100644 index 0000000..610a8dd --- /dev/null +++ b/book/_build/html/_sources/supply_demand_multiple_goods.ipynb @@ -0,0 +1,1504 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "15318565", + "metadata": {}, + "source": [ + "(supply_demand_multiple_goods)=\n", + "# Supply and Demand with Many Goods\n", + "\n", + "## Overview\n", + "\n", + "In a {doc}`previous lecture ` we studied supply, demand\n", + "and welfare in a market with a single consumption good.\n", + "\n", + "In this lecture, we study a setting with $n$ goods and $n$ corresponding prices.\n", + "\n", + "Key infrastructure concepts that we'll encounter in this lecture are\n", + "\n", + "* inverse demand curves\n", + "* marginal utilities of wealth\n", + "* inverse supply curves\n", + "* consumer surplus\n", + "* producer surplus\n", + "* social welfare as a sum of consumer and producer surpluses\n", + "* competitive equilibrium\n", + "\n", + "\n", + "We will provide a version of the [first fundamental welfare theorem](https://en.wikipedia.org/wiki/Fundamental_theorems_of_welfare_economics), which was formulated by \n", + "\n", + "* [Leon Walras](https://en.wikipedia.org/wiki/L%C3%A9on_Walras)\n", + "* [Francis Ysidro Edgeworth](https://en.wikipedia.org/wiki/Francis_Ysidro_Edgeworth)\n", + "* [Vilfredo Pareto](https://en.wikipedia.org/wiki/Vilfredo_Pareto)\n", + "\n", + "Important extensions to the key ideas were obtained by\n", + "\n", + "* [Abba Lerner](https://en.wikipedia.org/wiki/Abba_P._Lerner)\n", + "* [Harold Hotelling](https://en.wikipedia.org/wiki/Harold_Hotelling)\n", + "* [Paul Samuelson](https://en.wikipedia.org/wiki/Paul_Samuelson)\n", + "* [Kenneth Arrow](https://en.wikipedia.org/wiki/Kenneth_Arrow) \n", + "* [Gerard Debreu](https://en.wikipedia.org/wiki/G%C3%A9rard_Debreu)\n", + "\n", + "\n", + "We shall describe two classic welfare theorems:\n", + "\n", + "* **first welfare theorem:** for a given distribution of wealth among consumers, a competitive equilibrium allocation of goods solves a social planning problem.\n", + "\n", + "* **second welfare theorem:** An allocation of goods to consumers that solves a social planning problem can be supported by a competitive equilibrium with an appropriate initial distribution of wealth.\n", + "\n", + "As usual, we start by importing some Python modules." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cb1652b5", + "metadata": {}, + "outputs": [], + "source": [ + "# import some packages\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from scipy.linalg import inv" + ] + }, + { + "cell_type": "markdown", + "id": "a4436f92", + "metadata": {}, + "source": [ + "## Formulas from linear algebra\n", + "\n", + "We shall apply formulas from linear algebra that\n", + "\n", + "* differentiate an inner product with respect to each vector\n", + "* differentiate a product of a matrix and a vector with respect to the vector\n", + "* differentiate a quadratic form in a vector with respect to the vector\n", + "\n", + "Where $a$ is an $n \\times 1$ vector, $A$ is an $n \\times n$ matrix, and $x$ is an $n \\times 1$ vector:\n", + "\n", + "$$\n", + "\\frac{\\partial a^\\top x }{\\partial x} = \\frac{\\partial x^\\top a }{\\partial x} = a\n", + "$$\n", + "\n", + "$$\n", + "\\frac{\\partial A x} {\\partial x} = A\n", + "$$\n", + "\n", + "$$\n", + "\\frac{\\partial x^\\top A x}{\\partial x} = (A + A^\\top)x\n", + "$$\n", + "\n", + "## From utility function to demand curve\n", + "\n", + "Our study of consumers will use the following primitives\n", + "\n", + "* $\\Pi$ be an $m \\times n$ matrix,\n", + "* $b$ be an $m \\times 1$ vector of bliss points,\n", + "* $e$ be an $n \\times 1$ vector of endowments, and" + ] + }, + { + "cell_type": "markdown", + "id": "d3130a30", + "metadata": {}, + "source": [ + "We will analyze endogenous objects $c$ and $p$, where\n", + "\n", + "* $c$ is an $n \\times 1$ vector of consumptions of various goods,\n", + "* $p$ is an $n \\times 1$ vector of prices" + ] + }, + { + "cell_type": "markdown", + "id": "3d9f6be3", + "metadata": {}, + "source": [ + "The matrix $\\Pi$ describes a consumer's willingness to substitute one good for every other good.\n", + "\n", + "We assume that $\\Pi$ has linearly independent columns, which implies that $\\Pi^\\top \\Pi$ is a positive definite matrix.\n", + "\n", + "* it follows that $\\Pi^\\top \\Pi$ has an inverse.\n", + "\n", + "We shall see below that $(\\Pi^\\top \\Pi)^{-1}$ is a matrix of slopes of (compensated) demand curves for $c$ with respect to a vector of prices:\n", + "\n", + "$$\n", + " \\frac{\\partial c } {\\partial p} = (\\Pi^\\top \\Pi)^{-1}\n", + "$$\n", + "\n", + "A consumer faces $p$ as a price taker and chooses $c$ to maximize the utility function\n", + "\n", + "$$\n", + " - \\frac{1}{2} (\\Pi c -b) ^\\top (\\Pi c -b )\n", + "$$ (eq:old0)\n", + "\n", + "subject to the budget constraint\n", + "\n", + "$$\n", + " p^\\top (c -e ) = 0\n", + "$$ (eq:old2)\n", + "\n", + "We shall specify examples in which $\\Pi$ and $b$ are such that it typically happens that\n", + "\n", + "$$\n", + " \\Pi c \\ll b\n", + "$$ (eq:bversusc)\n", + "\n", + "This means that the consumer has much less of each good than he wants.\n", + "\n", + "The deviation in {eq}`eq:bversusc` will ultimately assure us that competitive equilibrium prices are positive." + ] + }, + { + "cell_type": "markdown", + "id": "5d9c54dd", + "metadata": {}, + "source": [ + "### Demand curve implied by constrained utility maximization\n", + "\n", + "For now, we assume that the budget constraint is {eq}`eq:old2`.\n", + "\n", + "So we'll be deriving what is known as a **Marshallian** demand curve.\n", + "\n", + "Our aim is to maximize [](eq:old0) subject to [](eq:old2).\n", + "\n", + "Form a Lagrangian\n", + "\n", + "$$ L = - \\frac{1}{2} (\\Pi c -b)^\\top (\\Pi c -b ) + \\mu [p^\\top (e-c)] $$\n", + "\n", + "where $\\mu$ is a Lagrange multiplier that is often called a **marginal utility of wealth**.\n", + "\n", + "The consumer chooses $c$ to maximize $L$ and $\\mu$ to minimize it.\n", + "\n", + "First-order conditions for $c$ are\n", + "\n", + "$$\n", + " \\frac{\\partial L} {\\partial c}\n", + " = - \\Pi^\\top \\Pi c + \\Pi^\\top b - \\mu p = 0\n", + "$$\n", + "\n", + "so that, given $\\mu$, the consumer chooses\n", + "\n", + "$$\n", + " c = (\\Pi^\\top \\Pi )^{-1}(\\Pi^\\top b - \\mu p )\n", + "$$ (eq:old3)\n", + "\n", + "Substituting {eq}`eq:old3` into budget constraint {eq}`eq:old2` and solving for $\\mu$ gives\n", + "\n", + "$$\n", + " \\mu(p,e) = \\frac{p^\\top ( \\Pi^\\top \\Pi )^{-1} \\Pi^\\top b - p^\\top e}{p^\\top (\\Pi^\\top \\Pi )^{-1} p}.\n", + "$$ (eq:old4)\n", + "\n", + "Equation {eq}`eq:old4` tells how marginal utility of wealth depends on the endowment vector $e$ and the price vector $p$.\n", + "\n", + "```{note}\n", + "Equation {eq}`eq:old4` is a consequence of imposing that $p^\\top (c - e) = 0$. \n", + "\n", + "We could instead take $\\mu$ as a parameter and use {eq}`eq:old3` and the budget constraint {eq}`eq:old2p` to solve for wealth. \n", + "\n", + "Which way we proceed determines whether we are constructing a **Marshallian** or **Hicksian** demand curve.\n", + "```\n", + "\n", + "## Endowment economy\n", + "\n", + "We now study a pure-exchange economy, or what is sometimes called an endowment economy.\n", + "\n", + "Consider a single-consumer, multiple-goods economy without production.\n", + "\n", + "The only source of goods is the single consumer's endowment vector $e$.\n", + "\n", + "A competitive equilibrium price vector induces the consumer to choose $c=e$.\n", + "\n", + "This implies that the equilibrium price vector satisfies\n", + "\n", + "$$\n", + "p = \\mu^{-1} (\\Pi^\\top b - \\Pi^\\top \\Pi e)\n", + "$$\n", + "\n", + "In the present case where we have imposed budget constraint in the form {eq}`eq:old2`, we are free to normalize the price vector by setting the marginal utility of wealth $\\mu =1$ (or any other value for that matter).\n", + "\n", + "This amounts to choosing a common unit (or numeraire) in which prices of all goods are expressed.\n", + "\n", + "(Doubling all prices will affect neither quantities nor relative prices.)\n", + "\n", + "We'll set $\\mu=1$.\n", + "\n", + "```{exercise}\n", + ":label: sdm_ex1\n", + "\n", + "Verify that setting $\\mu=1$ in {eq}`eq:old3` implies that formula {eq}`eq:old4` is satisfied.\n", + "\n", + "```\n", + "\n", + "```{exercise}\n", + ":label: sdm_ex2\n", + "\n", + "Verify that setting $\\mu=2$ in {eq}`eq:old3` also implies that formula\n", + "{eq}`eq:old4` is satisfied.\n", + "\n", + "```\n", + "\n", + "Here is a class that computes competitive equilibria for our economy." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1bf35185", + "metadata": {}, + "outputs": [], + "source": [ + "class ExchangeEconomy:\n", + " \n", + " def __init__(self, \n", + " Π, \n", + " b, \n", + " e,\n", + " thres=1.5):\n", + " \"\"\"\n", + " Set up the environment for an exchange economy\n", + "\n", + " Args:\n", + " Π (np.array): shared matrix of substitution\n", + " b (list): the consumer's bliss point\n", + " e (list): the consumer's endowment\n", + " thres (float): a threshold to check p >> Π e condition\n", + " \"\"\"\n", + "\n", + " # check non-satiation\n", + " if np.min(b / np.max(Π @ e)) <= thres:\n", + " raise Exception('set bliss points further away')\n", + "\n", + "\n", + " self.Π, self.b, self.e = Π, b, e\n", + "\n", + " \n", + " def competitive_equilibrium(self):\n", + " \"\"\"\n", + " Compute the competitive equilibrium prices and allocation\n", + " \"\"\"\n", + " Π, b, e = self.Π, self.b, self.e\n", + "\n", + " # compute price vector with μ=1\n", + " p = Π.T @ b - Π.T @ Π @ e\n", + " \n", + " # compute consumption vector\n", + " slope_dc = inv(Π.T @ Π)\n", + " Π_inv = inv(Π)\n", + " c = Π_inv @ b - slope_dc @ p\n", + "\n", + " if any(c < 0):\n", + " print('allocation: ', c)\n", + " raise Exception('negative allocation: equilibrium does not exist')\n", + "\n", + " return p, c" + ] + }, + { + "cell_type": "markdown", + "id": "6f90ba94", + "metadata": {}, + "source": [ + "## Digression: Marshallian and Hicksian demand curves\n", + "\n", + "Sometimes we'll use budget constraint {eq}`eq:old2` in situations in which a consumer's endowment vector $e$ is his **only** source of income.\n", + "\n", + "Other times we'll instead assume that the consumer has another source of income (positive or negative) and write his budget constraint as\n", + "\n", + "$$\n", + "p ^\\top (c -e ) = w\n", + "$$ (eq:old2p)\n", + "\n", + "where $w$ is measured in \"dollars\" (or some other **numeraire**) and component $p_i$ of the price vector is measured in dollars per unit of good $i$.\n", + "\n", + "Whether the consumer's budget constraint is {eq}`eq:old2` or {eq}`eq:old2p` and whether we take $w$ as a free parameter or instead as an endogenous variable will affect the consumer's marginal utility of wealth.\n", + "\n", + "Consequently, how we set $\\mu$ determines whether we are constructing\n", + "\n", + "* a **Marshallian** demand curve, as when we use {eq}`eq:old2` and solve for $\\mu$ using equation {eq}`eq:old4` above, or\n", + "* a **Hicksian** demand curve, as when we treat $\\mu$ as a fixed parameter and solve for $w$ from {eq}`eq:old2p`.\n", + "\n", + "Marshallian and Hicksian demand curves contemplate different mental experiments:\n", + "\n", + "For a Marshallian demand curve, hypothetical changes in a price vector have both **substitution** and **income** effects\n", + "\n", + "* income effects are consequences of changes in $p^\\top e$ associated with the change in the price vector\n", + "\n", + "For a Hicksian demand curve, hypothetical price vector changes have only **substitution** effects\n", + "\n", + "* changes in the price vector leave the $p^\\top e + w$ unaltered because we freeze $\\mu$ and solve for $w$\n", + "\n", + "Sometimes a Hicksian demand curve is called a **compensated** demand curve in order to emphasize that, to disarm the income (or wealth) effect associated with a price change, the consumer's wealth $w$ is adjusted.\n", + "\n", + "We'll discuss these distinct demand curves more below." + ] + }, + { + "cell_type": "markdown", + "id": "a1fc0e9d", + "metadata": {}, + "source": [ + "## Dynamics and risk as special cases\n", + "\n", + "Special cases of our $n$-good pure exchange model can be created to represent\n", + "\n", + "* **dynamics** --- by putting different dates on different commodities\n", + "* **risk** --- by interpreting delivery of goods as being contingent on states of the world whose realizations are described by a *known probability distribution*\n", + "\n", + "Let's illustrate how.\n", + "\n", + "### Dynamics\n", + "\n", + "Suppose that we want to represent a utility function\n", + "\n", + "$$\n", + " - \\frac{1}{2} [(c_1 - b_1)^2 + \\beta (c_2 - b_2)^2]\n", + "$$\n", + "\n", + "where $\\beta \\in (0,1)$ is a discount factor, $c_1$ is consumption at time $1$ and $c_2$ is consumption at time 2.\n", + "\n", + "To capture this with our quadratic utility function {eq}`eq:old0`, set\n", + "\n", + "$$\n", + "\\Pi = \\begin{bmatrix} 1 & 0 \\cr\n", + " 0 & \\sqrt{\\beta} \\end{bmatrix}\n", + "$$\n", + "\n", + "$$\n", + "e = \\begin{bmatrix} e_1 \\cr e_2 \\end{bmatrix}\n", + "$$\n", + "\n", + "and\n", + "\n", + "$$\n", + "b = \\begin{bmatrix} b_1 \\cr \\sqrt{\\beta} b_2\n", + "\\end{bmatrix}\n", + "$$\n", + "\n", + "The budget constraint {eq}`eq:old2` becomes\n", + "\n", + "$$\n", + "p_1 c_1 + p_2 c_2 = p_1 e_1 + p_2 e_2\n", + "$$\n", + "\n", + "The left side is the **discounted present value** of consumption.\n", + "\n", + "The right side is the **discounted present value** of the consumer's endowment.\n", + "\n", + "The relative price $\\frac{p_1}{p_2}$ has units of time $2$ goods per unit of time $1$ goods.\n", + "\n", + "Consequently, \n", + "\n", + "$$\n", + " (1+r) := R := \\frac{p_1}{p_2}\n", + "$$ \n", + "\n", + "is the **gross interest rate** and $r$ is the **net interest rate**.\n", + "\n", + "Here is an example." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fb1040c4", + "metadata": {}, + "outputs": [], + "source": [ + "beta = 0.95\n", + "\n", + "Π = np.array([[1, 0],\n", + " [0, np.sqrt(beta)]])\n", + "\n", + "b = np.array([5, np.sqrt(beta) * 5])\n", + "\n", + "e = np.array([1, 1])\n", + "\n", + "dynamics = ExchangeEconomy(Π, b, e)\n", + "p, c = dynamics.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price vector:', p)\n", + "print('Competitive equilibrium allocation:', c)" + ] + }, + { + "cell_type": "markdown", + "id": "3c5bc5d6", + "metadata": {}, + "source": [ + "### Risk and state-contingent claims\n", + "\n", + "We study risk in the context of a **static** environment, meaning that there is only one period.\n", + "\n", + "By **risk** we mean that an outcome is not known in advance, but that it is governed by a known probability distribution.\n", + "\n", + "As an example, our consumer confronts **risk** means in particular that\n", + "\n", + " * there are two states of nature, $1$ and $2$.\n", + "\n", + " * the consumer knows that the probability that state $1$ occurs is $\\lambda$.\n", + "\n", + " * the consumer knows that the probability that state $2$ occurs is $(1-\\lambda)$.\n", + "\n", + "Before the outcome is realized, the consumer's **expected utility** is\n", + "\n", + "$$\n", + "- \\frac{1}{2} [\\lambda (c_1 - b_1)^2 + (1-\\lambda)(c_2 - b_2)^2]\n", + "$$\n", + "\n", + "where\n", + "\n", + "* $c_1$ is consumption in state $1$\n", + "* $c_2$ is consumption in state $2$\n", + "\n", + "To capture these preferences we set\n", + "\n", + "$$\n", + "\\Pi = \\begin{bmatrix} \\sqrt{\\lambda} & 0 \\cr\n", + " 0 & \\sqrt{1-\\lambda} \\end{bmatrix}\n", + "$$\n", + "\n", + "$$\n", + "e = \\begin{bmatrix} e_1 \\cr e_2 \\end{bmatrix}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "363fb08b", + "metadata": {}, + "source": [ + "$$\n", + "b = \\begin{bmatrix} \\sqrt{\\lambda}b_1 \\cr \\sqrt{1-\\lambda}b_2 \\end{bmatrix}\n", + "$$\n", + "\n", + "A consumer's endowment vector is\n", + "\n", + "$$\n", + "c = \\begin{bmatrix} c_1 \\cr c_2 \\end{bmatrix}\n", + "$$\n", + "\n", + "A price vector is\n", + "\n", + "$$\n", + "p = \\begin{bmatrix} p_1 \\cr p_2 \\end{bmatrix}\n", + "$$\n", + "\n", + "where $p_i$ is the price of one unit of consumption in state $i \\in \\{1, 2\\}$.\n", + "\n", + "The state-contingent goods being traded are often called **Arrow securities**.\n", + "\n", + "Before the random state of the world $i$ is realized, the consumer sells his/her state-contingent endowment bundle and purchases a state-contingent consumption bundle.\n", + "\n", + "Trading such state-contingent goods is one way economists often model **insurance**." + ] + }, + { + "cell_type": "markdown", + "id": "bcb7548b", + "metadata": {}, + "source": [ + "We use the tricks described above to interpret $c_1, c_2$ as \"Arrow securities\" that are state-contingent claims to consumption goods." + ] + }, + { + "cell_type": "markdown", + "id": "f2a5e02b", + "metadata": {}, + "source": [ + "Here is an instance of the risk economy:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "efcc5f01", + "metadata": {}, + "outputs": [], + "source": [ + "prob = 0.2\n", + "\n", + "Π = np.array([[np.sqrt(prob), 0],\n", + " [0, np.sqrt(1 - prob)]])\n", + "\n", + "b = np.array([np.sqrt(prob) * 5, np.sqrt(1 - prob) * 5])\n", + "\n", + "e = np.array([1, 1])\n", + "\n", + "risk = ExchangeEconomy(Π, b, e)\n", + "p, c = risk.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price vector:', p)\n", + "print('Competitive equilibrium allocation:', c)" + ] + }, + { + "cell_type": "markdown", + "id": "cb369781", + "metadata": {}, + "source": [ + "```{exercise}\n", + ":label: sdm_ex3\n", + "\n", + "Consider the instance above.\n", + "\n", + "Please numerically study how each of the following cases affects the equilibrium prices and allocations:\n", + "\n", + "* the consumer gets poorer,\n", + "* they like the first good more, or\n", + "* the probability that state $1$ occurs is higher.\n", + "\n", + "Hints. For each case choose some parameter $e, b, \\text{ or } \\lambda$ different from the instance.\n", + "\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "98db78cb", + "metadata": {}, + "source": [ + "```{solution-start} sdm_ex3\n", + ":class: dropdown\n", + "```\n", + "\n", + "First consider when the consumer is poorer.\n", + "\n", + "Here we just decrease the endowment." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4515c364", + "metadata": {}, + "outputs": [], + "source": [ + "risk.e = np.array([0.5, 0.5])\n", + "\n", + "p, c = risk.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price vector:', p)\n", + "print('Competitive equilibrium allocation:', c)" + ] + }, + { + "cell_type": "markdown", + "id": "2df35f89", + "metadata": {}, + "source": [ + "If the consumer likes the first (or second) good more, then we can set a larger bliss value for good 1." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2533a676", + "metadata": {}, + "outputs": [], + "source": [ + "risk.b = np.array([np.sqrt(prob) * 6, np.sqrt(1 - prob) * 5])\n", + "p, c = risk.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price vector:', p)\n", + "print('Competitive equilibrium allocation:', c)" + ] + }, + { + "cell_type": "markdown", + "id": "b33d54fa", + "metadata": {}, + "source": [ + "Increase the probability that state $1$ occurs." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b0cf972b", + "metadata": {}, + "outputs": [], + "source": [ + "prob = 0.8\n", + "\n", + "Π = np.array([[np.sqrt(prob), 0],\n", + " [0, np.sqrt(1 - prob)]])\n", + "\n", + "b = np.array([np.sqrt(prob) * 5, np.sqrt(1 - prob) * 5])\n", + "\n", + "e = np.array([1, 1])\n", + "\n", + "risk = ExchangeEconomy(Π, b, e)\n", + "p, c = risk.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price vector:', p)\n", + "print('Competitive equilibrium allocation:', c)" + ] + }, + { + "cell_type": "markdown", + "id": "7f154cb2", + "metadata": {}, + "source": [ + "```{solution-end}\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "9fc3a565", + "metadata": {}, + "source": [ + "## Economies with endogenous supplies of goods\n", + "\n", + "Up to now we have described a pure exchange economy in which endowments of goods are exogenous, meaning that they are taken as given from outside the model.\n", + "\n", + "### Supply curve of a competitive firm\n", + "\n", + "A competitive firm that can produce goods takes a price vector $p$ as given and chooses a quantity $q$\n", + "to maximize total revenue minus total costs.\n", + "\n", + "The firm's total revenue equals $p^\\top q$ and its total cost equals $C(q)$ where $C(q)$ is a total cost function\n", + "\n", + "$$\n", + "C(q) = h ^\\top q + \\frac{1}{2} q^\\top J q\n", + "$$\n", + "\n", + "\n", + "and $J$ is a positive definite matrix.\n", + "\n", + "\n", + "So the firm's profits are\n", + "\n", + "$$\n", + "p^\\top q - C(q)\n", + "$$ (eq:compprofits)\n", + "\n", + "\n", + "\n", + "An $n\\times 1$ vector of **marginal costs** is\n", + "\n", + "$$\n", + "\\frac{\\partial C(q)}{\\partial q} = h + H q\n", + "$$\n", + "\n", + "where\n", + "\n", + "$$\n", + "H = \\frac{1}{2} (J + J^\\top)\n", + "$$\n", + "\n", + "The firm maximizes total profits by setting **marginal revenue to marginal costs**.\n", + "\n", + "An $n \\times 1$ vector of marginal revenues for the price-taking firm is $\\frac{\\partial p^\\top q}\n", + "{\\partial q} = p $.\n", + "\n", + "So **price equals marginal revenue** for our price-taking competitive firm.\n", + "\n", + "This leads to the following **inverse supply curve** for the competitive firm:\n", + "\n", + "\n", + "$$\n", + "p = h + H q\n", + "$$\n", + "\n", + "\n", + "\n", + "\n", + "### Competitive equilibrium\n", + "\n", + "\n", + "To compute a competitive equilibrium for a production economy where demand curve is pinned down by the marginal utility of wealth $\\mu$, we first compute an allocation by solving a planning problem.\n", + "\n", + "Then we compute the equilibrium price vector using the inverse demand or supply curve.\n", + "\n", + "#### $\\mu=1$ warmup\n", + "\n", + "As a special case, let's pin down a demand curve by setting the marginal utility of wealth $\\mu =1$.\n", + "\n", + "Equating supply price to demand price and letting $q=c$ we get\n", + "\n", + "$$\n", + "p = h + H c = \\Pi^\\top b - \\Pi^\\top \\Pi c ,\n", + "$$\n", + "\n", + "which implies the equilibrium quantity vector\n", + "\n", + "$$\n", + "c = (\\Pi^\\top \\Pi + H )^{-1} ( \\Pi^\\top b - h)\n", + "$$ (eq:old5)\n", + "\n", + "This equation is the counterpart of equilibrium quantity {eq}`eq:old1` for the scalar $n=1$ model with which we began.\n", + "\n", + "#### General $\\mu\\neq 1$ case\n", + "\n", + "Now let's extend the preceding analysis to a more\n", + "general case by allowing $\\mu \\neq 1$.\n", + "\n", + "Then the inverse demand curve is\n", + "\n", + "$$\n", + "p = \\mu^{-1} [\\Pi^\\top b - \\Pi^\\top \\Pi c]\n", + "$$ (eq:old5pa)\n", + "\n", + "Equating this to the inverse supply curve, letting $q=c$ and solving\n", + "for $c$ gives\n", + "\n", + "$$\n", + "c = [\\Pi^\\top \\Pi + \\mu H]^{-1} [ \\Pi^\\top b - \\mu h]\n", + "$$ (eq:old5p)" + ] + }, + { + "cell_type": "markdown", + "id": "f12b73be", + "metadata": {}, + "source": [ + "### Implementation\n", + "\n", + "A Production Economy will consist of\n", + "\n", + "* a single **person** that we'll interpret as a representative consumer\n", + "* a single set of **production costs**\n", + "* a multiplier $\\mu$ that weights \"consumers\" versus \"producers\" in a planner's welfare function, as described above in the main text\n", + "* an $n \\times 1$ vector $p$ of competitive equilibrium prices\n", + "* an $n \\times 1$ vector $c$ of competitive equilibrium quantities\n", + "* **consumer surplus**\n", + "* **producer surplus**\n", + "\n", + "Here we define a class ``ProductionEconomy``." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5a995758", + "metadata": {}, + "outputs": [], + "source": [ + "class ProductionEconomy:\n", + " \n", + " def __init__(self, \n", + " Π, \n", + " b, \n", + " h, \n", + " J, \n", + " μ):\n", + " \"\"\"\n", + " Set up the environment for a production economy\n", + "\n", + " Args:\n", + " Π (np.ndarray): matrix of substitution\n", + " b (np.array): bliss points\n", + " h (np.array): h in cost func\n", + " J (np.ndarray): J in cost func\n", + " μ (float): welfare weight of the corresponding planning problem\n", + " \"\"\"\n", + " self.n = len(b)\n", + " self.Π, self.b, self.h, self.J, self.μ = Π, b, h, J, μ\n", + " \n", + " def competitive_equilibrium(self):\n", + " \"\"\"\n", + " Compute a competitive equilibrium of the production economy\n", + " \"\"\"\n", + " Π, b, h, μ, J = self.Π, self.b, self.h, self.μ, self.J\n", + " H = .5 * (J + J.T)\n", + "\n", + " # allocation\n", + " c = inv(Π.T @ Π + μ * H) @ (Π.T @ b - μ * h)\n", + "\n", + " # price\n", + " p = 1 / μ * (Π.T @ b - Π.T @ Π @ c)\n", + "\n", + " # check non-satiation\n", + " if any(Π @ c - b >= 0):\n", + " raise Exception('invalid result: set bliss points further away')\n", + "\n", + " return c, p\n", + "\n", + " def compute_surplus(self):\n", + " \"\"\"\n", + " Compute consumer and producer surplus for single good case\n", + " \"\"\"\n", + " if self.n != 1:\n", + " raise Exception('not single good')\n", + " h, J, Π, b, μ = self.h.item(), self.J.item(), self.Π.item(), self.b.item(), self.μ\n", + " H = J\n", + "\n", + " # supply/demand curve coefficients\n", + " s0, s1 = h, H\n", + " d0, d1 = 1 / μ * Π * b, 1 / μ * Π**2\n", + "\n", + " # competitive equilibrium\n", + " c, p = self.competitive_equilibrium()\n", + "\n", + " # calculate surplus\n", + " c_surplus = d0 * c - .5 * d1 * c**2 - p * c\n", + " p_surplus = p * c - s0 * c - .5 * s1 * c**2\n", + "\n", + " return c_surplus, p_surplus" + ] + }, + { + "cell_type": "markdown", + "id": "10fbde83", + "metadata": {}, + "source": [ + "Then define a function that plots demand and supply curves and labels surpluses and equilibrium." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0601aa5b", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "def plot_competitive_equilibrium(PE):\n", + " \"\"\"\n", + " Plot demand and supply curves, producer/consumer surpluses, and equilibrium for\n", + " a single good production economy\n", + "\n", + " Args:\n", + " PE (class): A initialized production economy class\n", + " \"\"\"\n", + " # get singleton value\n", + " J, h, Π, b, μ = PE.J.item(), PE.h.item(), PE.Π.item(), PE.b.item(), PE.μ\n", + " H = J\n", + "\n", + " # compute competitive equilibrium\n", + " c, p = PE.competitive_equilibrium()\n", + " c, p = c.item(), p.item()\n", + "\n", + " # inverse supply/demand curve\n", + " supply_inv = lambda x: h + H * x\n", + " demand_inv = lambda x: 1 / μ * (Π * b - Π * Π * x)\n", + "\n", + " xs = np.linspace(0, 2 * c, 100)\n", + " ps = np.ones(100) * p\n", + " supply_curve = supply_inv(xs)\n", + " demand_curve = demand_inv(xs)\n", + "\n", + " # plot\n", + " plt.figure()\n", + " plt.plot(xs, supply_curve, label='Supply', color='#020060')\n", + " plt.plot(xs, demand_curve, label='Demand', color='#600001')\n", + "\n", + " plt.fill_between(xs[xs <= c], demand_curve[xs <= c], ps[xs <= c], label='Consumer surplus', color='#EED1CF')\n", + " plt.fill_between(xs[xs <= c], supply_curve[xs <= c], ps[xs <= c], label='Producer surplus', color='#E6E6F5')\n", + "\n", + " plt.vlines(c, 0, p, linestyle=\"dashed\", color='black', alpha=0.7)\n", + " plt.hlines(p, 0, c, linestyle=\"dashed\", color='black', alpha=0.7)\n", + " plt.scatter(c, p, zorder=10, label='Competitive equilibrium', color='#600001')\n", + "\n", + " plt.legend(loc='upper right')\n", + " plt.margins(x=0, y=0)\n", + " plt.ylim(0)\n", + " plt.xlabel('Quantity')\n", + " plt.ylabel('Price')\n", + " plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "c58ab1aa", + "metadata": {}, + "source": [ + "#### Example: single agent with one good and production\n", + "\n", + "Now let's construct an example of a production economy with one good.\n", + "\n", + "To do this we\n", + "\n", + " * specify a single **person** and a **cost curve** in a way that let's us replicate the simple single-good supply demand example with which we started\n", + "\n", + " * compute equilibrium $p$ and $c$ and consumer and producer surpluses\n", + "\n", + " * draw graphs of both surpluses\n", + "\n", + " * do experiments in which we shift $b$ and watch what happens to $p, c$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e625a4f4", + "metadata": {}, + "outputs": [], + "source": [ + "Π = np.array([[1]]) # the matrix now is a singleton\n", + "b = np.array([10])\n", + "h = np.array([0.5])\n", + "J = np.array([[1]])\n", + "μ = 1\n", + "\n", + "PE = ProductionEconomy(Π, b, h, J, μ)\n", + "c, p = PE.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price:', p.item())\n", + "print('Competitive equilibrium allocation:', c.item())\n", + "\n", + "# plot\n", + "plot_competitive_equilibrium(PE)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c13f9a16", + "metadata": {}, + "outputs": [], + "source": [ + "c_surplus, p_surplus = PE.compute_surplus()\n", + "\n", + "print('Consumer surplus:', c_surplus.item())\n", + "print('Producer surplus:', p_surplus.item())" + ] + }, + { + "cell_type": "markdown", + "id": "c992857b", + "metadata": {}, + "source": [ + "Let's give the consumer a lower welfare weight by raising $\\mu$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6ee8ee2d", + "metadata": {}, + "outputs": [], + "source": [ + "PE.μ = 2\n", + "c, p = PE.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price:', p.item())\n", + "print('Competitive equilibrium allocation:', c.item())\n", + "\n", + "# plot\n", + "plot_competitive_equilibrium(PE)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "df32f68b", + "metadata": {}, + "outputs": [], + "source": [ + "c_surplus, p_surplus = PE.compute_surplus()\n", + "\n", + "print('Consumer surplus:', c_surplus.item())\n", + "print('Producer surplus:', p_surplus.item())" + ] + }, + { + "cell_type": "markdown", + "id": "0334d0f8", + "metadata": {}, + "source": [ + "Now we change the bliss point so that the consumer derives more utility from consumption." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9ed4ea1a", + "metadata": {}, + "outputs": [], + "source": [ + "PE.μ = 1\n", + "PE.b = PE.b * 1.5\n", + "c, p = PE.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price:', p.item())\n", + "print('Competitive equilibrium allocation:', c.item())\n", + "\n", + "# plot\n", + "plot_competitive_equilibrium(PE)" + ] + }, + { + "cell_type": "markdown", + "id": "5eb74843", + "metadata": {}, + "source": [ + "This raises both the equilibrium price and quantity.\n", + "\n", + "\n", + "#### Example: single agent two-good economy with production\n", + "\n", + " * we'll do some experiments like those above\n", + "\n", + " * we can do experiments with a **diagonal** $\\Pi$ and also with a **non-diagonal** $\\Pi$ matrices to study how cross-slopes affect responses of $p$ and $c$ to various shifts in $b$ (TODO)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a84f106d", + "metadata": {}, + "outputs": [], + "source": [ + "Π = np.array([[1, 0],\n", + " [0, 1]])\n", + "\n", + "b = np.array([10, 10])\n", + "\n", + "h = np.array([0.5, 0.5])\n", + "\n", + "J = np.array([[1, 0.5],\n", + " [0.5, 1]])\n", + "μ = 1\n", + "\n", + "PE = ProductionEconomy(Π, b, h, J, μ)\n", + "c, p = PE.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price:', p)\n", + "print('Competitive equilibrium allocation:', c)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b16d77bf", + "metadata": {}, + "outputs": [], + "source": [ + "PE.b = np.array([12, 10])\n", + "\n", + "c, p = PE.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price:', p)\n", + "print('Competitive equilibrium allocation:', c)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d8b39507", + "metadata": {}, + "outputs": [], + "source": [ + "PE.Π = np.array([[1, 0.5],\n", + " [0.5, 1]])\n", + "\n", + "PE.b = np.array([10, 10])\n", + "\n", + "c, p = PE.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price:', p)\n", + "print('Competitive equilibrium allocation:', c)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7a085c31", + "metadata": {}, + "outputs": [], + "source": [ + "PE.b = np.array([12, 10])\n", + "c, p = PE.competitive_equilibrium()\n", + "\n", + "print('Competitive equilibrium price:', p)\n", + "print('Competitive equilibrium allocation:', c)" + ] + }, + { + "cell_type": "markdown", + "id": "fab7e4d4", + "metadata": {}, + "source": [ + "### Digression: a supplier who is a monopolist\n", + "\n", + "A competitive firm is a **price-taker** who regards the price and therefore its marginal revenue as being beyond its control.\n", + "\n", + "A monopolist knows that it has no competition and can influence the price and its marginal revenue by\n", + "setting quantity.\n", + "\n", + "A monopolist takes a **demand curve** and not the **price** as beyond its control.\n", + "\n", + "Thus, instead of being a price-taker, a monopolist sets prices to maximize profits subject to the inverse demand curve\n", + "{eq}`eq:old5pa`.\n", + "\n", + "So the monopolist's total profits as a function of its output $q$ is\n", + "\n", + "$$\n", + "[\\mu^{-1} \\Pi^\\top (b - \\Pi q)]^\\top q - h^\\top q - \\frac{1}{2} q^\\top J q\n", + "$$ (eq:monopprof)\n", + "\n", + "After finding\n", + "first-order necessary conditions for maximizing monopoly profits with respect to $q$\n", + "and solving them for $q$, we find that the monopolist sets\n", + "\n", + "$$\n", + "q = (H + 2 \\mu^{-1} \\Pi^\\top \\Pi)^{-1} (\\mu^{-1} \\Pi^\\top b - h)\n", + "$$ (eq:qmonop)\n", + "\n", + "We'll soon see that a monopolist sets a **lower output** $q$ than does either a\n", + "\n", + " * planner who chooses $q$ to maximize social welfare\n", + "\n", + " * a competitive equilibrium\n", + "\n", + "\n", + "\n", + "```{exercise}\n", + ":label: sdm_ex4\n", + "\n", + "Please verify the monopolist's supply curve {eq}`eq:qmonop`.\n", + "\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "14df1354", + "metadata": {}, + "source": [ + "### A monopolist\n", + "\n", + "Let's consider a monopolist supplier.\n", + "\n", + "We have included a method in our `ProductionEconomy` class to compute an equilibrium price and allocation when the supplier is a monopolist.\n", + "\n", + "Since the supplier now has the price-setting power\n", + "\n", + "- we first compute the optimal quantity that solves the monopolist's profit maximization problem.\n", + "- Then we back out an equilibrium price from the consumer's inverse demand curve.\n", + "\n", + "Next, we use a graph for the single good case to illustrate the difference between a competitive equilibrium and an equilibrium with a monopolist supplier.\n", + "\n", + "Recall that in a competitive equilibrium, a price-taking supplier equates marginal revenue $p$ to marginal cost $h + Hq$.\n", + "\n", + "This yields a competitive producer's inverse supply curve.\n", + "\n", + "A monopolist's marginal revenue is not constant but instead is a non-trivial function of the quantity it sets.\n", + "\n", + "The monopolist's marginal revenue is\n", + "\n", + "$$\n", + "MR(q) = -2\\mu^{-1}\\Pi^{\\top}\\Pi q+\\mu^{-1}\\Pi^{\\top}b,\n", + "$$\n", + "\n", + "which the monopolist equates to its marginal cost.\n", + "\n", + "The plot indicates that the monopolist's sets output lower than either the competitive equilibrium quantity.\n", + "\n", + "In a single good case, this equilibrium is associated with a higher price of the good." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c2df090e", + "metadata": {}, + "outputs": [], + "source": [ + "class Monopoly(ProductionEconomy):\n", + " \n", + " def __init__(self, \n", + " Π, \n", + " b, \n", + " h, \n", + " J, \n", + " μ):\n", + " \"\"\"\n", + " Inherit all properties and methods from class ProductionEconomy\n", + " \"\"\"\n", + " super().__init__(Π, b, h, J, μ)\n", + " \n", + "\n", + " def equilibrium_with_monopoly(self):\n", + " \"\"\"\n", + " Compute the equilibrium price and allocation when there is a monopolist supplier\n", + " \"\"\"\n", + " Π, b, h, μ, J = self.Π, self.b, self.h, self.μ, self.J\n", + " H = .5 * (J + J.T)\n", + "\n", + " # allocation\n", + " q = inv(μ * H + 2 * Π.T @ Π) @ (Π.T @ b - μ * h)\n", + "\n", + " # price\n", + " p = 1 / μ * (Π.T @ b - Π.T @ Π @ q)\n", + "\n", + " if any(Π @ q - b >= 0):\n", + " raise Exception('invalid result: set bliss points further away')\n", + "\n", + " return q, p" + ] + }, + { + "cell_type": "markdown", + "id": "0bbab98d", + "metadata": {}, + "source": [ + "Define a function that plots the demand, marginal cost and marginal revenue curves with surpluses and equilibrium labelled." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c8ce68e3", + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "def plot_monopoly(M):\n", + " \"\"\"\n", + " Plot demand curve, marginal production cost and revenue, surpluses and the\n", + " equilibrium in a monopolist supplier economy with a single good\n", + "\n", + " Args:\n", + " M (class): A class inherits class ProductionEconomy with monopoly\n", + " \"\"\"\n", + " # get singleton value\n", + " J, h, Π, b, μ = M.J.item(), M.h.item(), M.Π.item(), M.b.item(), M.μ\n", + " H = J\n", + "\n", + " # compute competitive equilibrium\n", + " c, p = M.competitive_equilibrium()\n", + " q, pm = M.equilibrium_with_monopoly()\n", + " c, p, q, pm = c.item(), p.item(), q.item(), pm.item()\n", + "\n", + " # compute\n", + "\n", + " # inverse supply/demand curve\n", + " marg_cost = lambda x: h + H * x\n", + " marg_rev = lambda x: -2 * 1 / μ * Π * Π * x + 1 / μ * Π * b\n", + " demand_inv = lambda x: 1 / μ * (Π * b - Π * Π * x)\n", + "\n", + " xs = np.linspace(0, 2 * c, 100)\n", + " pms = np.ones(100) * pm\n", + " marg_cost_curve = marg_cost(xs)\n", + " marg_rev_curve = marg_rev(xs)\n", + " demand_curve = demand_inv(xs)\n", + "\n", + " # plot\n", + " plt.figure()\n", + " plt.plot(xs, marg_cost_curve, label='Marginal cost', color='#020060')\n", + " plt.plot(xs, marg_rev_curve, label='Marginal revenue', color='#E55B13')\n", + " plt.plot(xs, demand_curve, label='Demand', color='#600001')\n", + "\n", + " plt.fill_between(xs[xs <= q], demand_curve[xs <= q], pms[xs <= q], label='Consumer surplus', color='#EED1CF')\n", + " plt.fill_between(xs[xs <= q], marg_cost_curve[xs <= q], pms[xs <= q], label='Producer surplus', color='#E6E6F5')\n", + "\n", + " plt.vlines(c, 0, p, linestyle=\"dashed\", color='black', alpha=0.7)\n", + " plt.hlines(p, 0, c, linestyle=\"dashed\", color='black', alpha=0.7)\n", + " plt.scatter(c, p, zorder=10, label='Competitive equilibrium', color='#600001')\n", + "\n", + " plt.vlines(q, 0, pm, linestyle=\"dashed\", color='black', alpha=0.7)\n", + " plt.hlines(pm, 0, q, linestyle=\"dashed\", color='black', alpha=0.7)\n", + " plt.scatter(q, pm, zorder=10, label='Equilibrium with monopoly', color='#E55B13')\n", + "\n", + " plt.legend(loc='upper right')\n", + " plt.margins(x=0, y=0)\n", + " plt.ylim(0)\n", + " plt.xlabel('Quantity')\n", + " plt.ylabel('Price')\n", + " plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "dd3f2961", + "metadata": {}, + "source": [ + "#### A multiple good example\n", + "\n", + "Let's compare competitive equilibrium and monopoly outcomes in a multiple goods economy." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "71a2d05a", + "metadata": {}, + "outputs": [], + "source": [ + "Π = np.array([[1, 0],\n", + " [0, 1.2]])\n", + "\n", + "b = np.array([10, 10])\n", + "\n", + "h = np.array([0.5, 0.5])\n", + "\n", + "J = np.array([[1, 0.5],\n", + " [0.5, 1]])\n", + "μ = 1\n", + "\n", + "M = Monopoly(Π, b, h, J, μ)\n", + "c, p = M.competitive_equilibrium()\n", + "q, pm = M.equilibrium_with_monopoly()\n", + "\n", + "print('Competitive equilibrium price:', p)\n", + "print('Competitive equilibrium allocation:', c)\n", + "\n", + "print('Equilibrium with monopolist supplier price:', pm)\n", + "print('Equilibrium with monopolist supplier allocation:', q)" + ] + }, + { + "cell_type": "markdown", + "id": "0c0d5c16", + "metadata": {}, + "source": [ + "#### A single-good example" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0ff3767b", + "metadata": {}, + "outputs": [], + "source": [ + "Π = np.array([[1]]) # the matrix now is a singleton\n", + "b = np.array([10])\n", + "h = np.array([0.5])\n", + "J = np.array([[1]])\n", + "μ = 1\n", + "\n", + "M = Monopoly(Π, b, h, J, μ)\n", + "c, p = M.competitive_equilibrium()\n", + "q, pm = M.equilibrium_with_monopoly()\n", + "\n", + "print('Competitive equilibrium price:', p.item())\n", + "print('Competitive equilibrium allocation:', c.item())\n", + "\n", + "print('Equilibrium with monopolist supplier price:', pm.item())\n", + "print('Equilibrium with monopolist supplier allocation:', q.item())\n", + "\n", + "# plot\n", + "plot_monopoly(M)" + ] + }, + { + "cell_type": "markdown", + "id": "8424a928", + "metadata": {}, + "source": [ + "## Multi-good welfare maximization problem\n", + "\n", + "Our welfare maximization problem -- also sometimes called a social planning problem -- is to choose $c$ to maximize\n", + "\n", + "$$\n", + " - \\frac{1}{2} \\mu^{-1}(\\Pi c -b) ^\\top (\\Pi c -b )\n", + "$$\n", + "\n", + "minus the area under the inverse supply curve, namely,\n", + "\n", + "$$\n", + " h c + \\frac{1}{2} c^\\top J c \n", + "$$\n", + "\n", + "So the welfare criterion is\n", + "\n", + "$$\n", + " - \\frac{1}{2} \\mu^{-1}(\\Pi c -b)^\\top (\\Pi c -b ) -h c \n", + " - \\frac{1}{2} c^\\top J c\n", + "$$\n", + "\n", + "In this formulation, $\\mu$ is a parameter that describes how the planner weighs interests of outside suppliers and our representative consumer.\n", + "\n", + "The first-order condition with respect to $c$ is\n", + "\n", + "$$\n", + "- \\mu^{-1} \\Pi^\\top \\Pi c + \\mu^{-1}\\Pi^\\top b - h - H c = 0\n", + "$$\n", + "\n", + "which implies {eq}`eq:old5p`.\n", + "\n", + "Thus, as for the single-good case, with multiple goods a competitive equilibrium quantity vector solves a planning problem.\n", + "\n", + "(This is another version of the first welfare theorem.)\n", + "\n", + "We can deduce a competitive equilibrium price vector from either\n", + "\n", + " * the inverse demand curve, or\n", + "\n", + " * the inverse supply curve" + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.5" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 58, + 63, + 95, + 102, + 138, + 226, + 271, + 306, + 367, + 382, + 420, + 446, + 450, + 454, + 469, + 486, + 496, + 503, + 507, + 513, + 517, + 532, + 537, + 638, + 654, + 716, + 720, + 766, + 782, + 799, + 804, + 808, + 819, + 824, + 828, + 838, + 849, + 868, + 877, + 889, + 895, + 938, + 971, + 1003, + 1007, + 1063, + 1069, + 1090, + 1094, + 1113 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/supply_demand_multiple_goods.md b/book/_build/html/_sources/supply_demand_multiple_goods.md new file mode 100644 index 0000000..5a010ce --- /dev/null +++ b/book/_build/html/_sources/supply_demand_multiple_goods.md @@ -0,0 +1,1154 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.5 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +(supply_demand_multiple_goods)= +# Supply and Demand with Many Goods + +## Overview + +In a {doc}`previous lecture ` we studied supply, demand +and welfare in a market with a single consumption good. + +In this lecture, we study a setting with $n$ goods and $n$ corresponding prices. + +Key infrastructure concepts that we'll encounter in this lecture are + +* inverse demand curves +* marginal utilities of wealth +* inverse supply curves +* consumer surplus +* producer surplus +* social welfare as a sum of consumer and producer surpluses +* competitive equilibrium + + +We will provide a version of the [first fundamental welfare theorem](https://en.wikipedia.org/wiki/Fundamental_theorems_of_welfare_economics), which was formulated by + +* [Leon Walras](https://en.wikipedia.org/wiki/L%C3%A9on_Walras) +* [Francis Ysidro Edgeworth](https://en.wikipedia.org/wiki/Francis_Ysidro_Edgeworth) +* [Vilfredo Pareto](https://en.wikipedia.org/wiki/Vilfredo_Pareto) + +Important extensions to the key ideas were obtained by + +* [Abba Lerner](https://en.wikipedia.org/wiki/Abba_P._Lerner) +* [Harold Hotelling](https://en.wikipedia.org/wiki/Harold_Hotelling) +* [Paul Samuelson](https://en.wikipedia.org/wiki/Paul_Samuelson) +* [Kenneth Arrow](https://en.wikipedia.org/wiki/Kenneth_Arrow) +* [Gerard Debreu](https://en.wikipedia.org/wiki/G%C3%A9rard_Debreu) + + +We shall describe two classic welfare theorems: + +* **first welfare theorem:** for a given distribution of wealth among consumers, a competitive equilibrium allocation of goods solves a social planning problem. + +* **second welfare theorem:** An allocation of goods to consumers that solves a social planning problem can be supported by a competitive equilibrium with an appropriate initial distribution of wealth. + +As usual, we start by importing some Python modules. + +```{code-cell} ipython3 +# import some packages +import numpy as np +import matplotlib.pyplot as plt +from scipy.linalg import inv +``` + +## Formulas from linear algebra + +We shall apply formulas from linear algebra that + +* differentiate an inner product with respect to each vector +* differentiate a product of a matrix and a vector with respect to the vector +* differentiate a quadratic form in a vector with respect to the vector + +Where $a$ is an $n \times 1$ vector, $A$ is an $n \times n$ matrix, and $x$ is an $n \times 1$ vector: + +$$ +\frac{\partial a^\top x }{\partial x} = \frac{\partial x^\top a }{\partial x} = a +$$ + +$$ +\frac{\partial A x} {\partial x} = A +$$ + +$$ +\frac{\partial x^\top A x}{\partial x} = (A + A^\top)x +$$ + +## From utility function to demand curve + +Our study of consumers will use the following primitives + +* $\Pi$ be an $m \times n$ matrix, +* $b$ be an $m \times 1$ vector of bliss points, +* $e$ be an $n \times 1$ vector of endowments, and + ++++ + +We will analyze endogenous objects $c$ and $p$, where + +* $c$ is an $n \times 1$ vector of consumptions of various goods, +* $p$ is an $n \times 1$ vector of prices + ++++ + +The matrix $\Pi$ describes a consumer's willingness to substitute one good for every other good. + +We assume that $\Pi$ has linearly independent columns, which implies that $\Pi^\top \Pi$ is a positive definite matrix. + +* it follows that $\Pi^\top \Pi$ has an inverse. + +We shall see below that $(\Pi^\top \Pi)^{-1}$ is a matrix of slopes of (compensated) demand curves for $c$ with respect to a vector of prices: + +$$ + \frac{\partial c } {\partial p} = (\Pi^\top \Pi)^{-1} +$$ + +A consumer faces $p$ as a price taker and chooses $c$ to maximize the utility function + +$$ + - \frac{1}{2} (\Pi c -b) ^\top (\Pi c -b ) +$$ (eq:old0) + +subject to the budget constraint + +$$ + p^\top (c -e ) = 0 +$$ (eq:old2) + +We shall specify examples in which $\Pi$ and $b$ are such that it typically happens that + +$$ + \Pi c \ll b +$$ (eq:bversusc) + +This means that the consumer has much less of each good than he wants. + +The deviation in {eq}`eq:bversusc` will ultimately assure us that competitive equilibrium prices are positive. + ++++ + +### Demand curve implied by constrained utility maximization + +For now, we assume that the budget constraint is {eq}`eq:old2`. + +So we'll be deriving what is known as a **Marshallian** demand curve. + +Our aim is to maximize [](eq:old0) subject to [](eq:old2). + +Form a Lagrangian + +$$ L = - \frac{1}{2} (\Pi c -b)^\top (\Pi c -b ) + \mu [p^\top (e-c)] $$ + +where $\mu$ is a Lagrange multiplier that is often called a **marginal utility of wealth**. + +The consumer chooses $c$ to maximize $L$ and $\mu$ to minimize it. + +First-order conditions for $c$ are + +$$ + \frac{\partial L} {\partial c} + = - \Pi^\top \Pi c + \Pi^\top b - \mu p = 0 +$$ + +so that, given $\mu$, the consumer chooses + +$$ + c = (\Pi^\top \Pi )^{-1}(\Pi^\top b - \mu p ) +$$ (eq:old3) + +Substituting {eq}`eq:old3` into budget constraint {eq}`eq:old2` and solving for $\mu$ gives + +$$ + \mu(p,e) = \frac{p^\top ( \Pi^\top \Pi )^{-1} \Pi^\top b - p^\top e}{p^\top (\Pi^\top \Pi )^{-1} p}. +$$ (eq:old4) + +Equation {eq}`eq:old4` tells how marginal utility of wealth depends on the endowment vector $e$ and the price vector $p$. + +```{note} +Equation {eq}`eq:old4` is a consequence of imposing that $p^\top (c - e) = 0$. + +We could instead take $\mu$ as a parameter and use {eq}`eq:old3` and the budget constraint {eq}`eq:old2p` to solve for wealth. + +Which way we proceed determines whether we are constructing a **Marshallian** or **Hicksian** demand curve. +``` + +## Endowment economy + +We now study a pure-exchange economy, or what is sometimes called an endowment economy. + +Consider a single-consumer, multiple-goods economy without production. + +The only source of goods is the single consumer's endowment vector $e$. + +A competitive equilibrium price vector induces the consumer to choose $c=e$. + +This implies that the equilibrium price vector satisfies + +$$ +p = \mu^{-1} (\Pi^\top b - \Pi^\top \Pi e) +$$ + +In the present case where we have imposed budget constraint in the form {eq}`eq:old2`, we are free to normalize the price vector by setting the marginal utility of wealth $\mu =1$ (or any other value for that matter). + +This amounts to choosing a common unit (or numeraire) in which prices of all goods are expressed. + +(Doubling all prices will affect neither quantities nor relative prices.) + +We'll set $\mu=1$. + +```{exercise} +:label: sdm_ex1 + +Verify that setting $\mu=1$ in {eq}`eq:old3` implies that formula {eq}`eq:old4` is satisfied. + +``` + +```{exercise} +:label: sdm_ex2 + +Verify that setting $\mu=2$ in {eq}`eq:old3` also implies that formula +{eq}`eq:old4` is satisfied. + +``` + +Here is a class that computes competitive equilibria for our economy. + +```{code-cell} ipython3 +class ExchangeEconomy: + + def __init__(self, + Π, + b, + e, + thres=1.5): + """ + Set up the environment for an exchange economy + + Args: + Π (np.array): shared matrix of substitution + b (list): the consumer's bliss point + e (list): the consumer's endowment + thres (float): a threshold to check p >> Π e condition + """ + + # check non-satiation + if np.min(b / np.max(Π @ e)) <= thres: + raise Exception('set bliss points further away') + + + self.Π, self.b, self.e = Π, b, e + + + def competitive_equilibrium(self): + """ + Compute the competitive equilibrium prices and allocation + """ + Π, b, e = self.Π, self.b, self.e + + # compute price vector with μ=1 + p = Π.T @ b - Π.T @ Π @ e + + # compute consumption vector + slope_dc = inv(Π.T @ Π) + Π_inv = inv(Π) + c = Π_inv @ b - slope_dc @ p + + if any(c < 0): + print('allocation: ', c) + raise Exception('negative allocation: equilibrium does not exist') + + return p, c +``` + +## Digression: Marshallian and Hicksian demand curves + +Sometimes we'll use budget constraint {eq}`eq:old2` in situations in which a consumer's endowment vector $e$ is his **only** source of income. + +Other times we'll instead assume that the consumer has another source of income (positive or negative) and write his budget constraint as + +$$ +p ^\top (c -e ) = w +$$ (eq:old2p) + +where $w$ is measured in "dollars" (or some other **numeraire**) and component $p_i$ of the price vector is measured in dollars per unit of good $i$. + +Whether the consumer's budget constraint is {eq}`eq:old2` or {eq}`eq:old2p` and whether we take $w$ as a free parameter or instead as an endogenous variable will affect the consumer's marginal utility of wealth. + +Consequently, how we set $\mu$ determines whether we are constructing + +* a **Marshallian** demand curve, as when we use {eq}`eq:old2` and solve for $\mu$ using equation {eq}`eq:old4` above, or +* a **Hicksian** demand curve, as when we treat $\mu$ as a fixed parameter and solve for $w$ from {eq}`eq:old2p`. + +Marshallian and Hicksian demand curves contemplate different mental experiments: + +For a Marshallian demand curve, hypothetical changes in a price vector have both **substitution** and **income** effects + +* income effects are consequences of changes in $p^\top e$ associated with the change in the price vector + +For a Hicksian demand curve, hypothetical price vector changes have only **substitution** effects + +* changes in the price vector leave the $p^\top e + w$ unaltered because we freeze $\mu$ and solve for $w$ + +Sometimes a Hicksian demand curve is called a **compensated** demand curve in order to emphasize that, to disarm the income (or wealth) effect associated with a price change, the consumer's wealth $w$ is adjusted. + +We'll discuss these distinct demand curves more below. + ++++ + +## Dynamics and risk as special cases + +Special cases of our $n$-good pure exchange model can be created to represent + +* **dynamics** --- by putting different dates on different commodities +* **risk** --- by interpreting delivery of goods as being contingent on states of the world whose realizations are described by a *known probability distribution* + +Let's illustrate how. + +### Dynamics + +Suppose that we want to represent a utility function + +$$ + - \frac{1}{2} [(c_1 - b_1)^2 + \beta (c_2 - b_2)^2] +$$ + +where $\beta \in (0,1)$ is a discount factor, $c_1$ is consumption at time $1$ and $c_2$ is consumption at time 2. + +To capture this with our quadratic utility function {eq}`eq:old0`, set + +$$ +\Pi = \begin{bmatrix} 1 & 0 \cr + 0 & \sqrt{\beta} \end{bmatrix} +$$ + +$$ +e = \begin{bmatrix} e_1 \cr e_2 \end{bmatrix} +$$ + +and + +$$ +b = \begin{bmatrix} b_1 \cr \sqrt{\beta} b_2 +\end{bmatrix} +$$ + +The budget constraint {eq}`eq:old2` becomes + +$$ +p_1 c_1 + p_2 c_2 = p_1 e_1 + p_2 e_2 +$$ + +The left side is the **discounted present value** of consumption. + +The right side is the **discounted present value** of the consumer's endowment. + +The relative price $\frac{p_1}{p_2}$ has units of time $2$ goods per unit of time $1$ goods. + +Consequently, + +$$ + (1+r) := R := \frac{p_1}{p_2} +$$ + +is the **gross interest rate** and $r$ is the **net interest rate**. + +Here is an example. + +```{code-cell} ipython3 +beta = 0.95 + +Π = np.array([[1, 0], + [0, np.sqrt(beta)]]) + +b = np.array([5, np.sqrt(beta) * 5]) + +e = np.array([1, 1]) + +dynamics = ExchangeEconomy(Π, b, e) +p, c = dynamics.competitive_equilibrium() + +print('Competitive equilibrium price vector:', p) +print('Competitive equilibrium allocation:', c) +``` + +### Risk and state-contingent claims + +We study risk in the context of a **static** environment, meaning that there is only one period. + +By **risk** we mean that an outcome is not known in advance, but that it is governed by a known probability distribution. + +As an example, our consumer confronts **risk** means in particular that + + * there are two states of nature, $1$ and $2$. + + * the consumer knows that the probability that state $1$ occurs is $\lambda$. + + * the consumer knows that the probability that state $2$ occurs is $(1-\lambda)$. + +Before the outcome is realized, the consumer's **expected utility** is + +$$ +- \frac{1}{2} [\lambda (c_1 - b_1)^2 + (1-\lambda)(c_2 - b_2)^2] +$$ + +where + +* $c_1$ is consumption in state $1$ +* $c_2$ is consumption in state $2$ + +To capture these preferences we set + +$$ +\Pi = \begin{bmatrix} \sqrt{\lambda} & 0 \cr + 0 & \sqrt{1-\lambda} \end{bmatrix} +$$ + +$$ +e = \begin{bmatrix} e_1 \cr e_2 \end{bmatrix} +$$ + ++++ + +$$ +b = \begin{bmatrix} \sqrt{\lambda}b_1 \cr \sqrt{1-\lambda}b_2 \end{bmatrix} +$$ + +A consumer's endowment vector is + +$$ +c = \begin{bmatrix} c_1 \cr c_2 \end{bmatrix} +$$ + +A price vector is + +$$ +p = \begin{bmatrix} p_1 \cr p_2 \end{bmatrix} +$$ + +where $p_i$ is the price of one unit of consumption in state $i \in \{1, 2\}$. + +The state-contingent goods being traded are often called **Arrow securities**. + +Before the random state of the world $i$ is realized, the consumer sells his/her state-contingent endowment bundle and purchases a state-contingent consumption bundle. + +Trading such state-contingent goods is one way economists often model **insurance**. + ++++ + +We use the tricks described above to interpret $c_1, c_2$ as "Arrow securities" that are state-contingent claims to consumption goods. + ++++ + +Here is an instance of the risk economy: + +```{code-cell} ipython3 +prob = 0.2 + +Π = np.array([[np.sqrt(prob), 0], + [0, np.sqrt(1 - prob)]]) + +b = np.array([np.sqrt(prob) * 5, np.sqrt(1 - prob) * 5]) + +e = np.array([1, 1]) + +risk = ExchangeEconomy(Π, b, e) +p, c = risk.competitive_equilibrium() + +print('Competitive equilibrium price vector:', p) +print('Competitive equilibrium allocation:', c) +``` + +```{exercise} +:label: sdm_ex3 + +Consider the instance above. + +Please numerically study how each of the following cases affects the equilibrium prices and allocations: + +* the consumer gets poorer, +* they like the first good more, or +* the probability that state $1$ occurs is higher. + +Hints. For each case choose some parameter $e, b, \text{ or } \lambda$ different from the instance. + +``` + ++++ + +```{solution-start} sdm_ex3 +:class: dropdown +``` + +First consider when the consumer is poorer. + +Here we just decrease the endowment. + +```{code-cell} ipython3 +risk.e = np.array([0.5, 0.5]) + +p, c = risk.competitive_equilibrium() + +print('Competitive equilibrium price vector:', p) +print('Competitive equilibrium allocation:', c) +``` + +If the consumer likes the first (or second) good more, then we can set a larger bliss value for good 1. + +```{code-cell} ipython3 +risk.b = np.array([np.sqrt(prob) * 6, np.sqrt(1 - prob) * 5]) +p, c = risk.competitive_equilibrium() + +print('Competitive equilibrium price vector:', p) +print('Competitive equilibrium allocation:', c) +``` + +Increase the probability that state $1$ occurs. + +```{code-cell} ipython3 +prob = 0.8 + +Π = np.array([[np.sqrt(prob), 0], + [0, np.sqrt(1 - prob)]]) + +b = np.array([np.sqrt(prob) * 5, np.sqrt(1 - prob) * 5]) + +e = np.array([1, 1]) + +risk = ExchangeEconomy(Π, b, e) +p, c = risk.competitive_equilibrium() + +print('Competitive equilibrium price vector:', p) +print('Competitive equilibrium allocation:', c) +``` + +```{solution-end} +``` + ++++ + +## Economies with endogenous supplies of goods + +Up to now we have described a pure exchange economy in which endowments of goods are exogenous, meaning that they are taken as given from outside the model. + +### Supply curve of a competitive firm + +A competitive firm that can produce goods takes a price vector $p$ as given and chooses a quantity $q$ +to maximize total revenue minus total costs. + +The firm's total revenue equals $p^\top q$ and its total cost equals $C(q)$ where $C(q)$ is a total cost function + +$$ +C(q) = h ^\top q + \frac{1}{2} q^\top J q +$$ + + +and $J$ is a positive definite matrix. + + +So the firm's profits are + +$$ +p^\top q - C(q) +$$ (eq:compprofits) + + + +An $n\times 1$ vector of **marginal costs** is + +$$ +\frac{\partial C(q)}{\partial q} = h + H q +$$ + +where + +$$ +H = \frac{1}{2} (J + J^\top) +$$ + +The firm maximizes total profits by setting **marginal revenue to marginal costs**. + +An $n \times 1$ vector of marginal revenues for the price-taking firm is $\frac{\partial p^\top q} +{\partial q} = p $. + +So **price equals marginal revenue** for our price-taking competitive firm. + +This leads to the following **inverse supply curve** for the competitive firm: + + +$$ +p = h + H q +$$ + + + + +### Competitive equilibrium + + +To compute a competitive equilibrium for a production economy where demand curve is pinned down by the marginal utility of wealth $\mu$, we first compute an allocation by solving a planning problem. + +Then we compute the equilibrium price vector using the inverse demand or supply curve. + +#### $\mu=1$ warmup + +As a special case, let's pin down a demand curve by setting the marginal utility of wealth $\mu =1$. + +Equating supply price to demand price and letting $q=c$ we get + +$$ +p = h + H c = \Pi^\top b - \Pi^\top \Pi c , +$$ + +which implies the equilibrium quantity vector + +$$ +c = (\Pi^\top \Pi + H )^{-1} ( \Pi^\top b - h) +$$ (eq:old5) + +This equation is the counterpart of equilibrium quantity {eq}`eq:old1` for the scalar $n=1$ model with which we began. + +#### General $\mu\neq 1$ case + +Now let's extend the preceding analysis to a more +general case by allowing $\mu \neq 1$. + +Then the inverse demand curve is + +$$ +p = \mu^{-1} [\Pi^\top b - \Pi^\top \Pi c] +$$ (eq:old5pa) + +Equating this to the inverse supply curve, letting $q=c$ and solving +for $c$ gives + +$$ +c = [\Pi^\top \Pi + \mu H]^{-1} [ \Pi^\top b - \mu h] +$$ (eq:old5p) + ++++ + +### Implementation + +A Production Economy will consist of + +* a single **person** that we'll interpret as a representative consumer +* a single set of **production costs** +* a multiplier $\mu$ that weights "consumers" versus "producers" in a planner's welfare function, as described above in the main text +* an $n \times 1$ vector $p$ of competitive equilibrium prices +* an $n \times 1$ vector $c$ of competitive equilibrium quantities +* **consumer surplus** +* **producer surplus** + +Here we define a class ``ProductionEconomy``. + +```{code-cell} ipython3 +class ProductionEconomy: + + def __init__(self, + Π, + b, + h, + J, + μ): + """ + Set up the environment for a production economy + + Args: + Π (np.ndarray): matrix of substitution + b (np.array): bliss points + h (np.array): h in cost func + J (np.ndarray): J in cost func + μ (float): welfare weight of the corresponding planning problem + """ + self.n = len(b) + self.Π, self.b, self.h, self.J, self.μ = Π, b, h, J, μ + + def competitive_equilibrium(self): + """ + Compute a competitive equilibrium of the production economy + """ + Π, b, h, μ, J = self.Π, self.b, self.h, self.μ, self.J + H = .5 * (J + J.T) + + # allocation + c = inv(Π.T @ Π + μ * H) @ (Π.T @ b - μ * h) + + # price + p = 1 / μ * (Π.T @ b - Π.T @ Π @ c) + + # check non-satiation + if any(Π @ c - b >= 0): + raise Exception('invalid result: set bliss points further away') + + return c, p + + def compute_surplus(self): + """ + Compute consumer and producer surplus for single good case + """ + if self.n != 1: + raise Exception('not single good') + h, J, Π, b, μ = self.h.item(), self.J.item(), self.Π.item(), self.b.item(), self.μ + H = J + + # supply/demand curve coefficients + s0, s1 = h, H + d0, d1 = 1 / μ * Π * b, 1 / μ * Π**2 + + # competitive equilibrium + c, p = self.competitive_equilibrium() + + # calculate surplus + c_surplus = d0 * c - .5 * d1 * c**2 - p * c + p_surplus = p * c - s0 * c - .5 * s1 * c**2 + + return c_surplus, p_surplus +``` + +Then define a function that plots demand and supply curves and labels surpluses and equilibrium. + +```{code-cell} ipython3 +:tags: [hide-input] + +def plot_competitive_equilibrium(PE): + """ + Plot demand and supply curves, producer/consumer surpluses, and equilibrium for + a single good production economy + + Args: + PE (class): A initialized production economy class + """ + # get singleton value + J, h, Π, b, μ = PE.J.item(), PE.h.item(), PE.Π.item(), PE.b.item(), PE.μ + H = J + + # compute competitive equilibrium + c, p = PE.competitive_equilibrium() + c, p = c.item(), p.item() + + # inverse supply/demand curve + supply_inv = lambda x: h + H * x + demand_inv = lambda x: 1 / μ * (Π * b - Π * Π * x) + + xs = np.linspace(0, 2 * c, 100) + ps = np.ones(100) * p + supply_curve = supply_inv(xs) + demand_curve = demand_inv(xs) + + # plot + plt.figure() + plt.plot(xs, supply_curve, label='Supply', color='#020060') + plt.plot(xs, demand_curve, label='Demand', color='#600001') + + plt.fill_between(xs[xs <= c], demand_curve[xs <= c], ps[xs <= c], label='Consumer surplus', color='#EED1CF') + plt.fill_between(xs[xs <= c], supply_curve[xs <= c], ps[xs <= c], label='Producer surplus', color='#E6E6F5') + + plt.vlines(c, 0, p, linestyle="dashed", color='black', alpha=0.7) + plt.hlines(p, 0, c, linestyle="dashed", color='black', alpha=0.7) + plt.scatter(c, p, zorder=10, label='Competitive equilibrium', color='#600001') + + plt.legend(loc='upper right') + plt.margins(x=0, y=0) + plt.ylim(0) + plt.xlabel('Quantity') + plt.ylabel('Price') + plt.show() +``` + +#### Example: single agent with one good and production + +Now let's construct an example of a production economy with one good. + +To do this we + + * specify a single **person** and a **cost curve** in a way that let's us replicate the simple single-good supply demand example with which we started + + * compute equilibrium $p$ and $c$ and consumer and producer surpluses + + * draw graphs of both surpluses + + * do experiments in which we shift $b$ and watch what happens to $p, c$. + +```{code-cell} ipython3 +Π = np.array([[1]]) # the matrix now is a singleton +b = np.array([10]) +h = np.array([0.5]) +J = np.array([[1]]) +μ = 1 + +PE = ProductionEconomy(Π, b, h, J, μ) +c, p = PE.competitive_equilibrium() + +print('Competitive equilibrium price:', p.item()) +print('Competitive equilibrium allocation:', c.item()) + +# plot +plot_competitive_equilibrium(PE) +``` + +```{code-cell} ipython3 +c_surplus, p_surplus = PE.compute_surplus() + +print('Consumer surplus:', c_surplus.item()) +print('Producer surplus:', p_surplus.item()) +``` + +Let's give the consumer a lower welfare weight by raising $\mu$. + +```{code-cell} ipython3 +PE.μ = 2 +c, p = PE.competitive_equilibrium() + +print('Competitive equilibrium price:', p.item()) +print('Competitive equilibrium allocation:', c.item()) + +# plot +plot_competitive_equilibrium(PE) +``` + +```{code-cell} ipython3 +c_surplus, p_surplus = PE.compute_surplus() + +print('Consumer surplus:', c_surplus.item()) +print('Producer surplus:', p_surplus.item()) +``` + +Now we change the bliss point so that the consumer derives more utility from consumption. + +```{code-cell} ipython3 +PE.μ = 1 +PE.b = PE.b * 1.5 +c, p = PE.competitive_equilibrium() + +print('Competitive equilibrium price:', p.item()) +print('Competitive equilibrium allocation:', c.item()) + +# plot +plot_competitive_equilibrium(PE) +``` + +This raises both the equilibrium price and quantity. + + +#### Example: single agent two-good economy with production + + * we'll do some experiments like those above + + * we can do experiments with a **diagonal** $\Pi$ and also with a **non-diagonal** $\Pi$ matrices to study how cross-slopes affect responses of $p$ and $c$ to various shifts in $b$ (TODO) + +```{code-cell} ipython3 +Π = np.array([[1, 0], + [0, 1]]) + +b = np.array([10, 10]) + +h = np.array([0.5, 0.5]) + +J = np.array([[1, 0.5], + [0.5, 1]]) +μ = 1 + +PE = ProductionEconomy(Π, b, h, J, μ) +c, p = PE.competitive_equilibrium() + +print('Competitive equilibrium price:', p) +print('Competitive equilibrium allocation:', c) +``` + +```{code-cell} ipython3 +PE.b = np.array([12, 10]) + +c, p = PE.competitive_equilibrium() + +print('Competitive equilibrium price:', p) +print('Competitive equilibrium allocation:', c) +``` + +```{code-cell} ipython3 +PE.Π = np.array([[1, 0.5], + [0.5, 1]]) + +PE.b = np.array([10, 10]) + +c, p = PE.competitive_equilibrium() + +print('Competitive equilibrium price:', p) +print('Competitive equilibrium allocation:', c) +``` + +```{code-cell} ipython3 +PE.b = np.array([12, 10]) +c, p = PE.competitive_equilibrium() + +print('Competitive equilibrium price:', p) +print('Competitive equilibrium allocation:', c) +``` + +### Digression: a supplier who is a monopolist + +A competitive firm is a **price-taker** who regards the price and therefore its marginal revenue as being beyond its control. + +A monopolist knows that it has no competition and can influence the price and its marginal revenue by +setting quantity. + +A monopolist takes a **demand curve** and not the **price** as beyond its control. + +Thus, instead of being a price-taker, a monopolist sets prices to maximize profits subject to the inverse demand curve +{eq}`eq:old5pa`. + +So the monopolist's total profits as a function of its output $q$ is + +$$ +[\mu^{-1} \Pi^\top (b - \Pi q)]^\top q - h^\top q - \frac{1}{2} q^\top J q +$$ (eq:monopprof) + +After finding +first-order necessary conditions for maximizing monopoly profits with respect to $q$ +and solving them for $q$, we find that the monopolist sets + +$$ +q = (H + 2 \mu^{-1} \Pi^\top \Pi)^{-1} (\mu^{-1} \Pi^\top b - h) +$$ (eq:qmonop) + +We'll soon see that a monopolist sets a **lower output** $q$ than does either a + + * planner who chooses $q$ to maximize social welfare + + * a competitive equilibrium + + + +```{exercise} +:label: sdm_ex4 + +Please verify the monopolist's supply curve {eq}`eq:qmonop`. + +``` + ++++ + +### A monopolist + +Let's consider a monopolist supplier. + +We have included a method in our `ProductionEconomy` class to compute an equilibrium price and allocation when the supplier is a monopolist. + +Since the supplier now has the price-setting power + +- we first compute the optimal quantity that solves the monopolist's profit maximization problem. +- Then we back out an equilibrium price from the consumer's inverse demand curve. + +Next, we use a graph for the single good case to illustrate the difference between a competitive equilibrium and an equilibrium with a monopolist supplier. + +Recall that in a competitive equilibrium, a price-taking supplier equates marginal revenue $p$ to marginal cost $h + Hq$. + +This yields a competitive producer's inverse supply curve. + +A monopolist's marginal revenue is not constant but instead is a non-trivial function of the quantity it sets. + +The monopolist's marginal revenue is + +$$ +MR(q) = -2\mu^{-1}\Pi^{\top}\Pi q+\mu^{-1}\Pi^{\top}b, +$$ + +which the monopolist equates to its marginal cost. + +The plot indicates that the monopolist's sets output lower than either the competitive equilibrium quantity. + +In a single good case, this equilibrium is associated with a higher price of the good. + +```{code-cell} ipython3 +class Monopoly(ProductionEconomy): + + def __init__(self, + Π, + b, + h, + J, + μ): + """ + Inherit all properties and methods from class ProductionEconomy + """ + super().__init__(Π, b, h, J, μ) + + + def equilibrium_with_monopoly(self): + """ + Compute the equilibrium price and allocation when there is a monopolist supplier + """ + Π, b, h, μ, J = self.Π, self.b, self.h, self.μ, self.J + H = .5 * (J + J.T) + + # allocation + q = inv(μ * H + 2 * Π.T @ Π) @ (Π.T @ b - μ * h) + + # price + p = 1 / μ * (Π.T @ b - Π.T @ Π @ q) + + if any(Π @ q - b >= 0): + raise Exception('invalid result: set bliss points further away') + + return q, p +``` + +Define a function that plots the demand, marginal cost and marginal revenue curves with surpluses and equilibrium labelled. + +```{code-cell} ipython3 +:tags: [hide-input] + +def plot_monopoly(M): + """ + Plot demand curve, marginal production cost and revenue, surpluses and the + equilibrium in a monopolist supplier economy with a single good + + Args: + M (class): A class inherits class ProductionEconomy with monopoly + """ + # get singleton value + J, h, Π, b, μ = M.J.item(), M.h.item(), M.Π.item(), M.b.item(), M.μ + H = J + + # compute competitive equilibrium + c, p = M.competitive_equilibrium() + q, pm = M.equilibrium_with_monopoly() + c, p, q, pm = c.item(), p.item(), q.item(), pm.item() + + # compute + + # inverse supply/demand curve + marg_cost = lambda x: h + H * x + marg_rev = lambda x: -2 * 1 / μ * Π * Π * x + 1 / μ * Π * b + demand_inv = lambda x: 1 / μ * (Π * b - Π * Π * x) + + xs = np.linspace(0, 2 * c, 100) + pms = np.ones(100) * pm + marg_cost_curve = marg_cost(xs) + marg_rev_curve = marg_rev(xs) + demand_curve = demand_inv(xs) + + # plot + plt.figure() + plt.plot(xs, marg_cost_curve, label='Marginal cost', color='#020060') + plt.plot(xs, marg_rev_curve, label='Marginal revenue', color='#E55B13') + plt.plot(xs, demand_curve, label='Demand', color='#600001') + + plt.fill_between(xs[xs <= q], demand_curve[xs <= q], pms[xs <= q], label='Consumer surplus', color='#EED1CF') + plt.fill_between(xs[xs <= q], marg_cost_curve[xs <= q], pms[xs <= q], label='Producer surplus', color='#E6E6F5') + + plt.vlines(c, 0, p, linestyle="dashed", color='black', alpha=0.7) + plt.hlines(p, 0, c, linestyle="dashed", color='black', alpha=0.7) + plt.scatter(c, p, zorder=10, label='Competitive equilibrium', color='#600001') + + plt.vlines(q, 0, pm, linestyle="dashed", color='black', alpha=0.7) + plt.hlines(pm, 0, q, linestyle="dashed", color='black', alpha=0.7) + plt.scatter(q, pm, zorder=10, label='Equilibrium with monopoly', color='#E55B13') + + plt.legend(loc='upper right') + plt.margins(x=0, y=0) + plt.ylim(0) + plt.xlabel('Quantity') + plt.ylabel('Price') + plt.show() +``` + +#### A multiple good example + +Let's compare competitive equilibrium and monopoly outcomes in a multiple goods economy. + +```{code-cell} ipython3 +Π = np.array([[1, 0], + [0, 1.2]]) + +b = np.array([10, 10]) + +h = np.array([0.5, 0.5]) + +J = np.array([[1, 0.5], + [0.5, 1]]) +μ = 1 + +M = Monopoly(Π, b, h, J, μ) +c, p = M.competitive_equilibrium() +q, pm = M.equilibrium_with_monopoly() + +print('Competitive equilibrium price:', p) +print('Competitive equilibrium allocation:', c) + +print('Equilibrium with monopolist supplier price:', pm) +print('Equilibrium with monopolist supplier allocation:', q) +``` + +#### A single-good example + +```{code-cell} ipython3 +Π = np.array([[1]]) # the matrix now is a singleton +b = np.array([10]) +h = np.array([0.5]) +J = np.array([[1]]) +μ = 1 + +M = Monopoly(Π, b, h, J, μ) +c, p = M.competitive_equilibrium() +q, pm = M.equilibrium_with_monopoly() + +print('Competitive equilibrium price:', p.item()) +print('Competitive equilibrium allocation:', c.item()) + +print('Equilibrium with monopolist supplier price:', pm.item()) +print('Equilibrium with monopolist supplier allocation:', q.item()) + +# plot +plot_monopoly(M) +``` + +## Multi-good welfare maximization problem + +Our welfare maximization problem -- also sometimes called a social planning problem -- is to choose $c$ to maximize + +$$ + - \frac{1}{2} \mu^{-1}(\Pi c -b) ^\top (\Pi c -b ) +$$ + +minus the area under the inverse supply curve, namely, + +$$ + h c + \frac{1}{2} c^\top J c +$$ + +So the welfare criterion is + +$$ + - \frac{1}{2} \mu^{-1}(\Pi c -b)^\top (\Pi c -b ) -h c + - \frac{1}{2} c^\top J c +$$ + +In this formulation, $\mu$ is a parameter that describes how the planner weighs interests of outside suppliers and our representative consumer. + +The first-order condition with respect to $c$ is + +$$ +- \mu^{-1} \Pi^\top \Pi c + \mu^{-1}\Pi^\top b - h - H c = 0 +$$ + +which implies {eq}`eq:old5p`. + +Thus, as for the single-good case, with multiple goods a competitive equilibrium quantity vector solves a planning problem. + +(This is another version of the first welfare theorem.) + +We can deduce a competitive equilibrium price vector from either + + * the inverse demand curve, or + + * the inverse supply curve diff --git a/book/_build/html/_sources/time_series_with_matrices.ipynb b/book/_build/html/_sources/time_series_with_matrices.ipynb new file mode 100644 index 0000000..68744a7 --- /dev/null +++ b/book/_build/html/_sources/time_series_with_matrices.ipynb @@ -0,0 +1,1057 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "b878bee3", + "metadata": {}, + "source": [ + "(time_series_with_matrices)=\n", + "```{raw} jupyter\n", + "
\n", + " \n", + " \"QuantEcon\"\n", + " \n", + "
\n", + "```\n", + "\n", + "# Univariate Time Series with Matrix Algebra\n", + "\n", + "## Overview\n", + "\n", + "This lecture uses matrices to solve some linear difference equations.\n", + "\n", + "As a running example, we’ll study a **second-order linear difference\n", + "equation** that was the key technical tool in Paul Samuelson’s 1939\n", + "article {cite}`Samuelson1939` that introduced the *multiplier-accelerator model*.\n", + "\n", + "This model became the workhorse that powered early econometric versions of\n", + "Keynesian macroeconomic models in the United States.\n", + "\n", + "You can read about the details of that model in {doc}`intermediate:samuelson`.\n", + "\n", + "(That lecture also describes some technicalities about second-order linear difference equations.)\n", + "\n", + "In this lecture, we'll also learn about an **autoregressive** representation and a **moving average** representation of a non-stationary\n", + "univariate time series $\\{y_t\\}_{t=0}^T$.\n", + "\n", + "We'll also study a \"perfect foresight\" model of stock prices that involves solving\n", + "a \"forward-looking\" linear difference equation.\n", + "\n", + "We will use the following imports:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f1c8b44e", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from matplotlib import cm\n", + "\n", + "# Custom figsize for this lecture\n", + "plt.rcParams[\"figure.figsize\"] = (11, 5)\n", + "\n", + "# Set decimal printing to 3 decimal places\n", + "np.set_printoptions(precision=3, suppress=True)" + ] + }, + { + "cell_type": "markdown", + "id": "7a5b1a35", + "metadata": {}, + "source": [ + "## Samuelson's model\n", + "\n", + "Let $t = 0, \\pm 1, \\pm 2, \\ldots$ index time.\n", + "\n", + "For $t = 1, 2, 3, \\ldots, T$ suppose that\n", + "\n", + "```{math}\n", + ":label: tswm_1\n", + "\n", + "y_{t} = \\alpha_{0} + \\alpha_{1} y_{t-1} + \\alpha_{2} y_{t-2}\n", + "```\n", + "\n", + "where we assume that $y_0$ and $y_{-1}$ are given numbers\n", + "that we take as *initial conditions*.\n", + "\n", + "In Samuelson's model, $y_t$ stood for **national income** or perhaps a different\n", + "measure of aggregate activity called **gross domestic product** (GDP) at time $t$.\n", + "\n", + "Equation {eq}`tswm_1` is called a *second-order linear difference equation*. It is called second order because it depends on two lags.\n", + "\n", + "But actually, it is a collection of $T$ simultaneous linear\n", + "equations in the $T$ variables $y_1, y_2, \\ldots, y_T$.\n", + "\n", + "```{note}\n", + "To be able to solve a second-order linear difference\n", + "equation, we require two *boundary conditions* that can take the form\n", + "either of two *initial conditions*, two *terminal conditions* or\n", + "possibly one of each.\n", + "```\n", + "\n", + "Let’s write our equations as a stacked system\n", + "\n", + "$$\n", + "\\underset{\\equiv A}{\\underbrace{\\left[\\begin{array}{cccccccc}\n", + "1 & 0 & 0 & 0 & \\cdots & 0 & 0 & 0\\\\\n", + "-\\alpha_{1} & 1 & 0 & 0 & \\cdots & 0 & 0 & 0\\\\\n", + "-\\alpha_{2} & -\\alpha_{1} & 1 & 0 & \\cdots & 0 & 0 & 0\\\\\n", + "0 & -\\alpha_{2} & -\\alpha_{1} & 1 & \\cdots & 0 & 0 & 0\\\\\n", + "\\vdots & \\vdots & \\vdots & \\vdots & \\cdots & \\vdots & \\vdots & \\vdots\\\\\n", + "0 & 0 & 0 & 0 & \\cdots & -\\alpha_{2} & -\\alpha_{1} & 1\n", + "\\end{array}\\right]}}\\left[\\begin{array}{c}\n", + "y_{1}\\\\\n", + "y_{2}\\\\\n", + "y_{3}\\\\\n", + "y_{4}\\\\\n", + "\\vdots\\\\\n", + "y_{T}\n", + "\\end{array}\\right]=\\underset{\\equiv b}{\\underbrace{\\left[\\begin{array}{c}\n", + "\\alpha_{0}+\\alpha_{1}y_{0}+\\alpha_{2}y_{-1}\\\\\n", + "\\alpha_{0}+\\alpha_{2}y_{0}\\\\\n", + "\\alpha_{0}\\\\\n", + "\\alpha_{0}\\\\\n", + "\\vdots\\\\\n", + "\\alpha_{0}\n", + "\\end{array}\\right]}}\n", + "$$\n", + "\n", + "or\n", + "\n", + "$$\n", + "A y = b\n", + "$$\n", + "\n", + "where\n", + "\n", + "$$\n", + "y = \\begin{bmatrix} y_1 \\cr y_2 \\cr \\vdots \\cr y_T \\end{bmatrix}\n", + "$$\n", + "\n", + "Evidently $y$ can be computed from\n", + "\n", + "$$\n", + "y = A^{-1} b\n", + "$$\n", + "\n", + "The vector $y$ is a complete time path $\\{y_t\\}_{t=1}^T$.\n", + "\n", + "Let’s put Python to work on an example that captures the flavor of\n", + "Samuelson’s multiplier-accelerator model.\n", + "\n", + "We'll set parameters equal to the same values we used in {doc}`intermediate:samuelson`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4b008ea3", + "metadata": {}, + "outputs": [], + "source": [ + "T = 80\n", + "\n", + "# parameters\n", + "α_0 = 10.0\n", + "α_1 = 1.53\n", + "α_2 = -.9\n", + "\n", + "y_neg1 = 28.0 # y_{-1}\n", + "y_0 = 24.0" + ] + }, + { + "cell_type": "markdown", + "id": "ac737ee0", + "metadata": {}, + "source": [ + "Now we construct $A$ and $b$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6b7a82d4", + "metadata": {}, + "outputs": [], + "source": [ + "A = np.identity(T) # The T x T identity matrix\n", + "\n", + "for i in range(T):\n", + "\n", + " if i-1 >= 0:\n", + " A[i, i-1] = -α_1\n", + "\n", + " if i-2 >= 0:\n", + " A[i, i-2] = -α_2\n", + "\n", + "b = np.full(T, α_0)\n", + "b[0] = α_0 + α_1 * y_0 + α_2 * y_neg1\n", + "b[1] = α_0 + α_2 * y_0" + ] + }, + { + "cell_type": "markdown", + "id": "4d0ccb9a", + "metadata": {}, + "source": [ + "Let’s look at the matrix $A$ and the vector $b$ for our\n", + "example." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9b3e612a", + "metadata": {}, + "outputs": [], + "source": [ + "A, b" + ] + }, + { + "cell_type": "markdown", + "id": "dd180745", + "metadata": {}, + "source": [ + "Now let’s solve for the path of $y$.\n", + "\n", + "If $y_t$ is GNP at time $t$, then we have a version of\n", + "Samuelson’s model of the dynamics for GNP.\n", + "\n", + "To solve $y = A^{-1} b$ we can either invert $A$ directly, as in" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7adaee8e", + "metadata": {}, + "outputs": [], + "source": [ + "A_inv = np.linalg.inv(A)\n", + "\n", + "y = A_inv @ b" + ] + }, + { + "cell_type": "markdown", + "id": "b59d6b3c", + "metadata": {}, + "source": [ + "or we can use `np.linalg.solve`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3d33f1b5", + "metadata": {}, + "outputs": [], + "source": [ + "y_second_method = np.linalg.solve(A, b)" + ] + }, + { + "cell_type": "markdown", + "id": "f7c44b68", + "metadata": {}, + "source": [ + "Here make sure the two methods give the same result, at least up to floating\n", + "point precision:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9edb5d47", + "metadata": {}, + "outputs": [], + "source": [ + "np.allclose(y, y_second_method)" + ] + }, + { + "cell_type": "markdown", + "id": "6b9b9b66", + "metadata": {}, + "source": [ + "$A$ is invertible as it is lower triangular and [its diagonal entries are non-zero](https://www.statlect.com/matrix-algebra/triangular-matrix)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b978f29f", + "metadata": {}, + "outputs": [], + "source": [ + "# Check if A is lower triangular\n", + "np.allclose(A, np.tril(A))" + ] + }, + { + "cell_type": "markdown", + "id": "0277a4d4", + "metadata": {}, + "source": [ + "```{note}\n", + "In general, `np.linalg.solve` is more numerically stable than using\n", + "`np.linalg.inv` directly. \n", + "However, stability is not an issue for this small example. Moreover, we will\n", + "repeatedly use `A_inv` in what follows, so there is added value in computing\n", + "it directly.\n", + "```\n", + "\n", + "Now we can plot." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4b467a4a", + "metadata": {}, + "outputs": [], + "source": [ + "plt.plot(np.arange(T)+1, y)\n", + "plt.xlabel('t')\n", + "plt.ylabel('y')\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "69011996", + "metadata": {}, + "source": [ + "The {ref}`*steady state*` value $y^*$ of $y_t$ is obtained by setting $y_t = y_{t-1} =\n", + "y_{t-2} = y^*$ in {eq}`tswm_1`, which yields\n", + "\n", + "$$\n", + "y^* = \\frac{\\alpha_{0}}{1 - \\alpha_{1} - \\alpha_{2}}\n", + "$$\n", + "\n", + "If we set the initial values to $y_{0} = y_{-1} = y^*$, then $y_{t}$ will be\n", + "constant:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e2646e84", + "metadata": {}, + "outputs": [], + "source": [ + "y_star = α_0 / (1 - α_1 - α_2)\n", + "y_neg1_steady = y_star # y_{-1}\n", + "y_0_steady = y_star\n", + "\n", + "b_steady = np.full(T, α_0)\n", + "b_steady[0] = α_0 + α_1 * y_0_steady + α_2 * y_neg1_steady\n", + "b_steady[1] = α_0 + α_2 * y_0_steady" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e9e52d5d", + "metadata": {}, + "outputs": [], + "source": [ + "y_steady = A_inv @ b_steady" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e036b4b1", + "metadata": {}, + "outputs": [], + "source": [ + "plt.plot(np.arange(T)+1, y_steady)\n", + "plt.xlabel('t')\n", + "plt.ylabel('y')\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "6c82d911", + "metadata": {}, + "source": [ + "## Adding a random term\n", + "\n", + "To generate some excitement, we'll follow in the spirit of the great economists\n", + "[Eugen Slutsky](https://en.wikipedia.org/wiki/Eugen_Slutsky) and [Ragnar Frisch](https://en.wikipedia.org/wiki/Ragnar_Frisch) and replace our original second-order difference\n", + "equation with the following **second-order stochastic linear difference\n", + "equation**:\n", + "\n", + "```{math}\n", + ":label: tswm_2\n", + "\n", + "y_{t} = \\alpha_{0} + \\alpha_{1} y_{t-1} + \\alpha_{2} y_{t-2} + u_t\n", + "```\n", + "\n", + "where $u_{t} \\sim N\\left(0, \\sigma_{u}^{2}\\right)$ and is {ref}`IID `,\n", + "meaning independent and identically distributed.\n", + "\n", + "We’ll stack these $T$ equations into a system cast in terms of\n", + "matrix algebra.\n", + "\n", + "Let’s define the random vector\n", + "\n", + "$$\n", + "u=\\left[\\begin{array}{c}\n", + "u_{1}\\\\\n", + "u_{2}\\\\\n", + "\\vdots\\\\\n", + "u_{T}\n", + "\\end{array}\\right]\n", + "$$\n", + "\n", + "Where $A, b, y$ are defined as above, now assume that $y$ is\n", + "governed by the system\n", + "\n", + "$$\n", + "A y = b + u\n", + "$$ (eq:eqar)\n", + "\n", + "The solution for $y$ becomes\n", + "\n", + "$$\n", + "y = A^{-1} \\left(b + u\\right)\n", + "$$ (eq:eqma)\n", + "\n", + "Let’s try it out in Python." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "aa43dfed", + "metadata": {}, + "outputs": [], + "source": [ + "σ_u = 2.\n", + "u = np.random.normal(0, σ_u, size=T)\n", + "y = A_inv @ (b + u)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "91004441", + "metadata": {}, + "outputs": [], + "source": [ + "plt.plot(np.arange(T)+1, y)\n", + "plt.xlabel('t')\n", + "plt.ylabel('y')\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "2e31824b", + "metadata": {}, + "source": [ + "The above time series looks a lot like (detrended) GDP series for a\n", + "number of advanced countries in recent decades.\n", + "\n", + "We can simulate $N$ paths." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b67e9a23", + "metadata": {}, + "outputs": [], + "source": [ + "N = 100\n", + "\n", + "for i in range(N):\n", + " col = cm.viridis(np.random.rand()) # Choose a random color from viridis\n", + " u = np.random.normal(0, σ_u, size=T)\n", + " y = A_inv @ (b + u)\n", + " plt.plot(np.arange(T)+1, y, lw=0.5, color=col)\n", + "\n", + "plt.xlabel('t')\n", + "plt.ylabel('y')\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "c68b5439", + "metadata": {}, + "source": [ + "Also consider the case when $y_{0}$ and $y_{-1}$ are at\n", + "steady state." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2cb0f7fe", + "metadata": {}, + "outputs": [], + "source": [ + "N = 100\n", + "\n", + "for i in range(N):\n", + " col = cm.viridis(np.random.rand()) # Choose a random color from viridis\n", + " u = np.random.normal(0, σ_u, size=T)\n", + " y_steady = A_inv @ (b_steady + u)\n", + " plt.plot(np.arange(T)+1, y_steady, lw=0.5, color=col)\n", + "\n", + "plt.xlabel('t')\n", + "plt.ylabel('y')\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "7143140f", + "metadata": {}, + "source": [ + "## Computing population moments\n", + "\n", + "\n", + "We can apply standard formulas for multivariate normal distributions to compute the mean vector and covariance matrix\n", + "for our time series model\n", + "\n", + "$$\n", + "y = A^{-1} (b + u) .\n", + "$$\n", + "\n", + "You can read about multivariate normal distributions in this lecture [Multivariate Normal Distribution](https://python.quantecon.org/multivariate_normal.html).\n", + "\n", + "Let's write our model as \n", + "\n", + "$$ \n", + "y = \\tilde A (b + u)\n", + "$$\n", + "\n", + "where $\\tilde A = A^{-1}$.\n", + "\n", + "Because linear combinations of normal random variables are normal, we know that\n", + "\n", + "$$\n", + "y \\sim {\\mathcal N}(\\mu_y, \\Sigma_y)\n", + "$$\n", + "\n", + "where\n", + "\n", + "$$ \n", + "\\mu_y = \\tilde A b\n", + "$$\n", + "\n", + "and \n", + "\n", + "$$\n", + "\\Sigma_y = \\tilde A (\\sigma_u^2 I_{T \\times T} ) \\tilde A^T\n", + "$$\n", + "\n", + "Let's write a Python class that computes the mean vector $\\mu_y$ and covariance matrix $\\Sigma_y$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c8eb7726", + "metadata": {}, + "outputs": [], + "source": [ + "class population_moments:\n", + " \"\"\"\n", + " Compute population moments μ_y, Σ_y.\n", + " ---------\n", + " Parameters:\n", + " α_0, α_1, α_2, T, y_neg1, y_0\n", + " \"\"\"\n", + " def __init__(self, α_0=10.0, \n", + " α_1=1.53, \n", + " α_2=-.9, \n", + " T=80, \n", + " y_neg1=28.0, \n", + " y_0=24.0, \n", + " σ_u=1):\n", + "\n", + " # compute A\n", + " A = np.identity(T)\n", + "\n", + " for i in range(T):\n", + " if i-1 >= 0:\n", + " A[i, i-1] = -α_1\n", + "\n", + " if i-2 >= 0:\n", + " A[i, i-2] = -α_2\n", + "\n", + " # compute b\n", + " b = np.full(T, α_0)\n", + " b[0] = α_0 + α_1 * y_0 + α_2 * y_neg1\n", + " b[1] = α_0 + α_2 * y_0\n", + "\n", + " # compute A inverse\n", + " A_inv = np.linalg.inv(A)\n", + "\n", + " self.A, self.b, self.A_inv, self.σ_u, self.T = A, b, A_inv, σ_u, T\n", + " \n", + " def sample_y(self, n):\n", + " \"\"\"\n", + " Give a sample of size n of y.\n", + " \"\"\"\n", + " A_inv, σ_u, b, T = self.A_inv, self.σ_u, self.b, self.T\n", + " us = np.random.normal(0, σ_u, size=[n, T])\n", + " ys = np.vstack([A_inv @ (b + u) for u in us])\n", + "\n", + " return ys\n", + "\n", + " def get_moments(self):\n", + " \"\"\"\n", + " Compute the population moments of y.\n", + " \"\"\"\n", + " A_inv, σ_u, b = self.A_inv, self.σ_u, self.b\n", + "\n", + " # compute μ_y\n", + " self.μ_y = A_inv @ b\n", + " self.Σ_y = σ_u**2 * (A_inv @ A_inv.T)\n", + " \n", + " return self.μ_y, self.Σ_y\n", + "\n", + "\n", + "series_process = population_moments()\n", + " \n", + "μ_y, Σ_y = series_process.get_moments()\n", + "A_inv = series_process.A_inv" + ] + }, + { + "cell_type": "markdown", + "id": "9ec7defd", + "metadata": {}, + "source": [ + "It is enlightening to study the $\\mu_y, \\Sigma_y$'s implied by various parameter values.\n", + "\n", + "Among other things, we can use the class to exhibit how **statistical stationarity** of $y$ prevails only for very special initial conditions. \n", + "\n", + "Let's begin by generating $N$ time realizations of $y$ plotting them together with population mean $\\mu_y$ ." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d08f93fe", + "metadata": {}, + "outputs": [], + "source": [ + "# Plot mean\n", + "N = 100\n", + "\n", + "for i in range(N):\n", + " col = cm.viridis(np.random.rand()) # Choose a random color from viridis\n", + " ys = series_process.sample_y(N)\n", + " plt.plot(ys[i,:], lw=0.5, color=col)\n", + " plt.plot(μ_y, color='red')\n", + "\n", + "plt.xlabel('t')\n", + "plt.ylabel('y')\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "772dc503", + "metadata": {}, + "source": [ + "Visually, notice how the variance across realizations of $y_t$ decreases as $t$ increases.\n", + "\n", + "Let's plot the population variance of $y_t$ against $t$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "aa37a4da", + "metadata": {}, + "outputs": [], + "source": [ + "# Plot variance\n", + "plt.plot(Σ_y.diagonal())\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "d7926562", + "metadata": {}, + "source": [ + "Notice how the population variance increases and asymptotes." + ] + }, + { + "cell_type": "markdown", + "id": "93498a14", + "metadata": {}, + "source": [ + "Let's print out the covariance matrix $\\Sigma_y$ for a time series $y$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5865fc35", + "metadata": {}, + "outputs": [], + "source": [ + "series_process = population_moments(α_0=0, \n", + " α_1=.8, \n", + " α_2=0, \n", + " T=6,\n", + " y_neg1=0., \n", + " y_0=0., \n", + " σ_u=1)\n", + "\n", + "μ_y, Σ_y = series_process.get_moments()\n", + "print(\"μ_y = \", μ_y)\n", + "print(\"Σ_y = \\n\", Σ_y)" + ] + }, + { + "cell_type": "markdown", + "id": "f7b4a562", + "metadata": {}, + "source": [ + "Notice that the covariance between $y_t$ and $y_{t-1}$ -- the elements on the superdiagonal -- are *not* identical.\n", + "\n", + "This is an indication that the time series represented by our $y$ vector is not **stationary**. \n", + "\n", + "To make it stationary, we'd have to alter our system so that our *initial conditions* $(y_0, y_{-1})$ are not fixed numbers but instead a jointly normally distributed random vector with a particular mean and covariance matrix.\n", + "\n", + "We describe how to do that in [Linear State Space Models](https://python.quantecon.org/linear_models.html).\n", + "\n", + "But just to set the stage for that analysis, let's print out the bottom right corner of $\\Sigma_y$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8349c6af", + "metadata": {}, + "outputs": [], + "source": [ + "series_process = population_moments()\n", + "μ_y, Σ_y = series_process.get_moments()\n", + "\n", + "print(\"bottom right corner of Σ_y = \\n\", Σ_y[72:,72:])" + ] + }, + { + "cell_type": "markdown", + "id": "f8618ba8", + "metadata": {}, + "source": [ + "Please notice how the subdiagonal and superdiagonal elements seem to have converged.\n", + "\n", + "This is an indication that our process is asymptotically stationary.\n", + "\n", + "You can read about stationarity of more general linear time series models in this lecture [Linear State Space Models](https://python.quantecon.org/linear_models.html).\n", + "\n", + "There is a lot to be learned about the process by staring at the off diagonal elements of $\\Sigma_y$ corresponding to different time periods $t$, but we resist the temptation to do so here." + ] + }, + { + "cell_type": "markdown", + "id": "2afae198", + "metadata": {}, + "source": [ + "## Moving average representation\n", + "\n", + "Let's print out $A^{-1}$ and stare at its structure \n", + "\n", + " * is it triangular or almost triangular or $\\ldots$ ?\n", + "\n", + "To study the structure of $A^{-1}$, we shall print just up to $3$ decimals.\n", + "\n", + "Let's begin by printing out just the upper left hand corner of $A^{-1}$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ef8fb28a", + "metadata": {}, + "outputs": [], + "source": [ + "print(A_inv[0:7,0:7])" + ] + }, + { + "cell_type": "markdown", + "id": "afa30a0a", + "metadata": {}, + "source": [ + "Evidently, $A^{-1}$ is a lower triangular matrix. \n", + "\n", + "Notice how every row ends with the previous row's pre-diagonal entries.\n", + "\n", + "Since $A^{-1}$ is lower triangular, each row represents $ y_t$ for a particular $t$ as the sum of \n", + "- a time-dependent function $A^{-1} b$ of the initial conditions incorporated in $b$, and \n", + "- a weighted sum of current and past values of the IID shocks $\\{u_t\\}$.\n", + "\n", + "Thus, let $\\tilde{A}=A^{-1}$. \n", + "\n", + "Evidently, for $t\\geq0$,\n", + "\n", + "$$\n", + "y_{t+1}=\\sum_{i=1}^{t+1}\\tilde{A}_{t+1,i}b_{i}+\\sum_{i=1}^{t}\\tilde{A}_{t+1,i}u_{i}+u_{t+1}\n", + "$$\n", + "\n", + "This is a **moving average** representation with time-varying coefficients.\n", + "\n", + "Just as system {eq}`eq:eqma` constitutes a \n", + "**moving average** representation for $y$, system {eq}`eq:eqar` constitutes an **autoregressive** representation for $y$.\n", + "\n", + "## A forward looking model\n", + "\n", + "Samuelson’s model is *backward looking* in the sense that we give it *initial conditions* and let it\n", + "run.\n", + "\n", + "Let’s now turn to model that is *forward looking*.\n", + "\n", + "We apply similar linear algebra machinery to study a *perfect\n", + "foresight* model widely used as a benchmark in macroeconomics and\n", + "finance.\n", + "\n", + "As an example, we suppose that $p_t$ is the price of a stock and\n", + "that $y_t$ is its dividend.\n", + "\n", + "We assume that $y_t$ is determined by second-order difference\n", + "equation that we analyzed just above, so that\n", + "\n", + "$$\n", + "y = A^{-1} \\left(b + u\\right)\n", + "$$\n", + "\n", + "Our *perfect foresight* model of stock prices is\n", + "\n", + "$$\n", + "p_{t} = \\sum_{j=0}^{T-t} \\beta^{j} y_{t+j}, \\quad \\beta \\in (0,1)\n", + "$$\n", + "\n", + "where $\\beta$ is a discount factor.\n", + "\n", + "The model asserts that the price of the stock at $t$ equals the\n", + "discounted present values of the (perfectly foreseen) future dividends.\n", + "\n", + "Form\n", + "\n", + "$$\n", + "\\underset{\\equiv p}{\\underbrace{\\left[\\begin{array}{c}\n", + "p_{1}\\\\\n", + "p_{2}\\\\\n", + "p_{3}\\\\\n", + "\\vdots\\\\\n", + "p_{T}\n", + "\\end{array}\\right]}}=\\underset{\\equiv B}{\\underbrace{\\left[\\begin{array}{ccccc}\n", + "1 & \\beta & \\beta^{2} & \\cdots & \\beta^{T-1}\\\\\n", + "0 & 1 & \\beta & \\cdots & \\beta^{T-2}\\\\\n", + "0 & 0 & 1 & \\cdots & \\beta^{T-3}\\\\\n", + "\\vdots & \\vdots & \\vdots & \\vdots & \\vdots\\\\\n", + "0 & 0 & 0 & \\cdots & 1\n", + "\\end{array}\\right]}}\\left[\\begin{array}{c}\n", + "y_{1}\\\\\n", + "y_{2}\\\\\n", + "y_{3}\\\\\n", + "\\vdots\\\\\n", + "y_{T}\n", + "\\end{array}\\right]\n", + "$$" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0a6bda0f", + "metadata": {}, + "outputs": [], + "source": [ + "β = .96" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dc364592", + "metadata": {}, + "outputs": [], + "source": [ + "# construct B\n", + "B = np.zeros((T, T))\n", + "\n", + "for i in range(T):\n", + " B[i, i:] = β ** np.arange(0, T-i)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "51b51578", + "metadata": {}, + "outputs": [], + "source": [ + "print(B)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e55ef156", + "metadata": {}, + "outputs": [], + "source": [ + "σ_u = 0.\n", + "u = np.random.normal(0, σ_u, size=T)\n", + "y = A_inv @ (b + u)\n", + "y_steady = A_inv @ (b_steady + u)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9eba6d30", + "metadata": {}, + "outputs": [], + "source": [ + "p = B @ y" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6e504cc4", + "metadata": {}, + "outputs": [], + "source": [ + "plt.plot(np.arange(0, T)+1, y, label='y')\n", + "plt.plot(np.arange(0, T)+1, p, label='p')\n", + "plt.xlabel('t')\n", + "plt.ylabel('y/p')\n", + "plt.legend()\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "1de84b0a", + "metadata": {}, + "source": [ + "Can you explain why the trend of the price is downward over time?\n", + "\n", + "Also consider the case when $y_{0}$ and $y_{-1}$ are at the\n", + "steady state." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6574e326", + "metadata": {}, + "outputs": [], + "source": [ + "p_steady = B @ y_steady\n", + "\n", + "plt.plot(np.arange(0, T)+1, y_steady, label='y')\n", + "plt.plot(np.arange(0, T)+1, p_steady, label='p')\n", + "plt.xlabel('t')\n", + "plt.ylabel('y/p')\n", + "plt.legend()\n", + "\n", + "plt.show()" + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.16.1" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 48, + 58, + 142, + 152, + 156, + 170, + 175, + 177, + 186, + 190, + 194, + 196, + 201, + 203, + 207, + 210, + 222, + 228, + 240, + 250, + 254, + 260, + 307, + 313, + 319, + 326, + 339, + 344, + 357, + 399, + 462, + 470, + 484, + 490, + 494, + 498, + 502, + 514, + 526, + 531, + 541, + 553, + 555, + 634, + 638, + 646, + 650, + 657, + 661, + 669, + 676 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/time_series_with_matrices.md b/book/_build/html/_sources/time_series_with_matrices.md new file mode 100644 index 0000000..e73566c --- /dev/null +++ b/book/_build/html/_sources/time_series_with_matrices.md @@ -0,0 +1,686 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.16.1 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +(time_series_with_matrices)= +```{raw} jupyter + +``` + +# Univariate Time Series with Matrix Algebra + +## Overview + +This lecture uses matrices to solve some linear difference equations. + +As a running example, we’ll study a **second-order linear difference +equation** that was the key technical tool in Paul Samuelson’s 1939 +article {cite}`Samuelson1939` that introduced the *multiplier-accelerator model*. + +This model became the workhorse that powered early econometric versions of +Keynesian macroeconomic models in the United States. + +You can read about the details of that model in {doc}`intermediate:samuelson`. + +(That lecture also describes some technicalities about second-order linear difference equations.) + +In this lecture, we'll also learn about an **autoregressive** representation and a **moving average** representation of a non-stationary +univariate time series $\{y_t\}_{t=0}^T$. + +We'll also study a "perfect foresight" model of stock prices that involves solving +a "forward-looking" linear difference equation. + +We will use the following imports: + +```{code-cell} ipython3 +import numpy as np +import matplotlib.pyplot as plt +from matplotlib import cm + +# Custom figsize for this lecture +plt.rcParams["figure.figsize"] = (11, 5) + +# Set decimal printing to 3 decimal places +np.set_printoptions(precision=3, suppress=True) +``` + +## Samuelson's model + +Let $t = 0, \pm 1, \pm 2, \ldots$ index time. + +For $t = 1, 2, 3, \ldots, T$ suppose that + +```{math} +:label: tswm_1 + +y_{t} = \alpha_{0} + \alpha_{1} y_{t-1} + \alpha_{2} y_{t-2} +``` + +where we assume that $y_0$ and $y_{-1}$ are given numbers +that we take as *initial conditions*. + +In Samuelson's model, $y_t$ stood for **national income** or perhaps a different +measure of aggregate activity called **gross domestic product** (GDP) at time $t$. + +Equation {eq}`tswm_1` is called a *second-order linear difference equation*. It is called second order because it depends on two lags. + +But actually, it is a collection of $T$ simultaneous linear +equations in the $T$ variables $y_1, y_2, \ldots, y_T$. + +```{note} +To be able to solve a second-order linear difference +equation, we require two *boundary conditions* that can take the form +either of two *initial conditions*, two *terminal conditions* or +possibly one of each. +``` + +Let’s write our equations as a stacked system + +$$ +\underset{\equiv A}{\underbrace{\left[\begin{array}{cccccccc} +1 & 0 & 0 & 0 & \cdots & 0 & 0 & 0\\ +-\alpha_{1} & 1 & 0 & 0 & \cdots & 0 & 0 & 0\\ +-\alpha_{2} & -\alpha_{1} & 1 & 0 & \cdots & 0 & 0 & 0\\ +0 & -\alpha_{2} & -\alpha_{1} & 1 & \cdots & 0 & 0 & 0\\ +\vdots & \vdots & \vdots & \vdots & \cdots & \vdots & \vdots & \vdots\\ +0 & 0 & 0 & 0 & \cdots & -\alpha_{2} & -\alpha_{1} & 1 +\end{array}\right]}}\left[\begin{array}{c} +y_{1}\\ +y_{2}\\ +y_{3}\\ +y_{4}\\ +\vdots\\ +y_{T} +\end{array}\right]=\underset{\equiv b}{\underbrace{\left[\begin{array}{c} +\alpha_{0}+\alpha_{1}y_{0}+\alpha_{2}y_{-1}\\ +\alpha_{0}+\alpha_{2}y_{0}\\ +\alpha_{0}\\ +\alpha_{0}\\ +\vdots\\ +\alpha_{0} +\end{array}\right]}} +$$ + +or + +$$ +A y = b +$$ + +where + +$$ +y = \begin{bmatrix} y_1 \cr y_2 \cr \vdots \cr y_T \end{bmatrix} +$$ + +Evidently $y$ can be computed from + +$$ +y = A^{-1} b +$$ + +The vector $y$ is a complete time path $\{y_t\}_{t=1}^T$. + +Let’s put Python to work on an example that captures the flavor of +Samuelson’s multiplier-accelerator model. + +We'll set parameters equal to the same values we used in {doc}`intermediate:samuelson`. + +```{code-cell} ipython3 +T = 80 + +# parameters +α_0 = 10.0 +α_1 = 1.53 +α_2 = -.9 + +y_neg1 = 28.0 # y_{-1} +y_0 = 24.0 +``` + +Now we construct $A$ and $b$. + +```{code-cell} ipython3 +A = np.identity(T) # The T x T identity matrix + +for i in range(T): + + if i-1 >= 0: + A[i, i-1] = -α_1 + + if i-2 >= 0: + A[i, i-2] = -α_2 + +b = np.full(T, α_0) +b[0] = α_0 + α_1 * y_0 + α_2 * y_neg1 +b[1] = α_0 + α_2 * y_0 +``` + +Let’s look at the matrix $A$ and the vector $b$ for our +example. + +```{code-cell} ipython3 +A, b +``` + +Now let’s solve for the path of $y$. + +If $y_t$ is GNP at time $t$, then we have a version of +Samuelson’s model of the dynamics for GNP. + +To solve $y = A^{-1} b$ we can either invert $A$ directly, as in + +```{code-cell} ipython3 +A_inv = np.linalg.inv(A) + +y = A_inv @ b +``` + +or we can use `np.linalg.solve`: + +```{code-cell} ipython3 +y_second_method = np.linalg.solve(A, b) +``` + +Here make sure the two methods give the same result, at least up to floating +point precision: + +```{code-cell} ipython3 +np.allclose(y, y_second_method) +``` + +$A$ is invertible as it is lower triangular and [its diagonal entries are non-zero](https://www.statlect.com/matrix-algebra/triangular-matrix) + +```{code-cell} ipython3 +# Check if A is lower triangular +np.allclose(A, np.tril(A)) +``` + +```{note} +In general, `np.linalg.solve` is more numerically stable than using +`np.linalg.inv` directly. +However, stability is not an issue for this small example. Moreover, we will +repeatedly use `A_inv` in what follows, so there is added value in computing +it directly. +``` + +Now we can plot. + +```{code-cell} ipython3 +plt.plot(np.arange(T)+1, y) +plt.xlabel('t') +plt.ylabel('y') + +plt.show() +``` + +The {ref}`*steady state*` value $y^*$ of $y_t$ is obtained by setting $y_t = y_{t-1} = +y_{t-2} = y^*$ in {eq}`tswm_1`, which yields + +$$ +y^* = \frac{\alpha_{0}}{1 - \alpha_{1} - \alpha_{2}} +$$ + +If we set the initial values to $y_{0} = y_{-1} = y^*$, then $y_{t}$ will be +constant: + +```{code-cell} ipython3 +y_star = α_0 / (1 - α_1 - α_2) +y_neg1_steady = y_star # y_{-1} +y_0_steady = y_star + +b_steady = np.full(T, α_0) +b_steady[0] = α_0 + α_1 * y_0_steady + α_2 * y_neg1_steady +b_steady[1] = α_0 + α_2 * y_0_steady +``` + +```{code-cell} ipython3 +y_steady = A_inv @ b_steady +``` + +```{code-cell} ipython3 +plt.plot(np.arange(T)+1, y_steady) +plt.xlabel('t') +plt.ylabel('y') + +plt.show() +``` + +## Adding a random term + +To generate some excitement, we'll follow in the spirit of the great economists +[Eugen Slutsky](https://en.wikipedia.org/wiki/Eugen_Slutsky) and [Ragnar Frisch](https://en.wikipedia.org/wiki/Ragnar_Frisch) and replace our original second-order difference +equation with the following **second-order stochastic linear difference +equation**: + +```{math} +:label: tswm_2 + +y_{t} = \alpha_{0} + \alpha_{1} y_{t-1} + \alpha_{2} y_{t-2} + u_t +``` + +where $u_{t} \sim N\left(0, \sigma_{u}^{2}\right)$ and is {ref}`IID `, +meaning independent and identically distributed. + +We’ll stack these $T$ equations into a system cast in terms of +matrix algebra. + +Let’s define the random vector + +$$ +u=\left[\begin{array}{c} +u_{1}\\ +u_{2}\\ +\vdots\\ +u_{T} +\end{array}\right] +$$ + +Where $A, b, y$ are defined as above, now assume that $y$ is +governed by the system + +$$ +A y = b + u +$$ (eq:eqar) + +The solution for $y$ becomes + +$$ +y = A^{-1} \left(b + u\right) +$$ (eq:eqma) + +Let’s try it out in Python. + +```{code-cell} ipython3 +σ_u = 2. +u = np.random.normal(0, σ_u, size=T) +y = A_inv @ (b + u) +``` + +```{code-cell} ipython3 +plt.plot(np.arange(T)+1, y) +plt.xlabel('t') +plt.ylabel('y') + +plt.show() +``` + +The above time series looks a lot like (detrended) GDP series for a +number of advanced countries in recent decades. + +We can simulate $N$ paths. + +```{code-cell} ipython3 +N = 100 + +for i in range(N): + col = cm.viridis(np.random.rand()) # Choose a random color from viridis + u = np.random.normal(0, σ_u, size=T) + y = A_inv @ (b + u) + plt.plot(np.arange(T)+1, y, lw=0.5, color=col) + +plt.xlabel('t') +plt.ylabel('y') + +plt.show() +``` + +Also consider the case when $y_{0}$ and $y_{-1}$ are at +steady state. + +```{code-cell} ipython3 +N = 100 + +for i in range(N): + col = cm.viridis(np.random.rand()) # Choose a random color from viridis + u = np.random.normal(0, σ_u, size=T) + y_steady = A_inv @ (b_steady + u) + plt.plot(np.arange(T)+1, y_steady, lw=0.5, color=col) + +plt.xlabel('t') +plt.ylabel('y') + +plt.show() +``` + +## Computing population moments + + +We can apply standard formulas for multivariate normal distributions to compute the mean vector and covariance matrix +for our time series model + +$$ +y = A^{-1} (b + u) . +$$ + +You can read about multivariate normal distributions in this lecture [Multivariate Normal Distribution](https://python.quantecon.org/multivariate_normal.html). + +Let's write our model as + +$$ +y = \tilde A (b + u) +$$ + +where $\tilde A = A^{-1}$. + +Because linear combinations of normal random variables are normal, we know that + +$$ +y \sim {\mathcal N}(\mu_y, \Sigma_y) +$$ + +where + +$$ +\mu_y = \tilde A b +$$ + +and + +$$ +\Sigma_y = \tilde A (\sigma_u^2 I_{T \times T} ) \tilde A^T +$$ + +Let's write a Python class that computes the mean vector $\mu_y$ and covariance matrix $\Sigma_y$. + +```{code-cell} ipython3 +class population_moments: + """ + Compute population moments μ_y, Σ_y. + --------- + Parameters: + α_0, α_1, α_2, T, y_neg1, y_0 + """ + def __init__(self, α_0=10.0, + α_1=1.53, + α_2=-.9, + T=80, + y_neg1=28.0, + y_0=24.0, + σ_u=1): + + # compute A + A = np.identity(T) + + for i in range(T): + if i-1 >= 0: + A[i, i-1] = -α_1 + + if i-2 >= 0: + A[i, i-2] = -α_2 + + # compute b + b = np.full(T, α_0) + b[0] = α_0 + α_1 * y_0 + α_2 * y_neg1 + b[1] = α_0 + α_2 * y_0 + + # compute A inverse + A_inv = np.linalg.inv(A) + + self.A, self.b, self.A_inv, self.σ_u, self.T = A, b, A_inv, σ_u, T + + def sample_y(self, n): + """ + Give a sample of size n of y. + """ + A_inv, σ_u, b, T = self.A_inv, self.σ_u, self.b, self.T + us = np.random.normal(0, σ_u, size=[n, T]) + ys = np.vstack([A_inv @ (b + u) for u in us]) + + return ys + + def get_moments(self): + """ + Compute the population moments of y. + """ + A_inv, σ_u, b = self.A_inv, self.σ_u, self.b + + # compute μ_y + self.μ_y = A_inv @ b + self.Σ_y = σ_u**2 * (A_inv @ A_inv.T) + + return self.μ_y, self.Σ_y + + +series_process = population_moments() + +μ_y, Σ_y = series_process.get_moments() +A_inv = series_process.A_inv +``` + +It is enlightening to study the $\mu_y, \Sigma_y$'s implied by various parameter values. + +Among other things, we can use the class to exhibit how **statistical stationarity** of $y$ prevails only for very special initial conditions. + +Let's begin by generating $N$ time realizations of $y$ plotting them together with population mean $\mu_y$ . + +```{code-cell} ipython3 +# Plot mean +N = 100 + +for i in range(N): + col = cm.viridis(np.random.rand()) # Choose a random color from viridis + ys = series_process.sample_y(N) + plt.plot(ys[i,:], lw=0.5, color=col) + plt.plot(μ_y, color='red') + +plt.xlabel('t') +plt.ylabel('y') + +plt.show() +``` + +Visually, notice how the variance across realizations of $y_t$ decreases as $t$ increases. + +Let's plot the population variance of $y_t$ against $t$. + +```{code-cell} ipython3 +# Plot variance +plt.plot(Σ_y.diagonal()) +plt.show() +``` + +Notice how the population variance increases and asymptotes. + ++++ + +Let's print out the covariance matrix $\Sigma_y$ for a time series $y$. + +```{code-cell} ipython3 +series_process = population_moments(α_0=0, + α_1=.8, + α_2=0, + T=6, + y_neg1=0., + y_0=0., + σ_u=1) + +μ_y, Σ_y = series_process.get_moments() +print("μ_y = ", μ_y) +print("Σ_y = \n", Σ_y) +``` + +Notice that the covariance between $y_t$ and $y_{t-1}$ -- the elements on the superdiagonal -- are *not* identical. + +This is an indication that the time series represented by our $y$ vector is not **stationary**. + +To make it stationary, we'd have to alter our system so that our *initial conditions* $(y_0, y_{-1})$ are not fixed numbers but instead a jointly normally distributed random vector with a particular mean and covariance matrix. + +We describe how to do that in [Linear State Space Models](https://python.quantecon.org/linear_models.html). + +But just to set the stage for that analysis, let's print out the bottom right corner of $\Sigma_y$. + +```{code-cell} ipython3 +series_process = population_moments() +μ_y, Σ_y = series_process.get_moments() + +print("bottom right corner of Σ_y = \n", Σ_y[72:,72:]) +``` + +Please notice how the subdiagonal and superdiagonal elements seem to have converged. + +This is an indication that our process is asymptotically stationary. + +You can read about stationarity of more general linear time series models in this lecture [Linear State Space Models](https://python.quantecon.org/linear_models.html). + +There is a lot to be learned about the process by staring at the off diagonal elements of $\Sigma_y$ corresponding to different time periods $t$, but we resist the temptation to do so here. + ++++ + +## Moving average representation + +Let's print out $A^{-1}$ and stare at its structure + + * is it triangular or almost triangular or $\ldots$ ? + +To study the structure of $A^{-1}$, we shall print just up to $3$ decimals. + +Let's begin by printing out just the upper left hand corner of $A^{-1}$. + +```{code-cell} ipython3 +print(A_inv[0:7,0:7]) +``` + +Evidently, $A^{-1}$ is a lower triangular matrix. + +Notice how every row ends with the previous row's pre-diagonal entries. + +Since $A^{-1}$ is lower triangular, each row represents $ y_t$ for a particular $t$ as the sum of +- a time-dependent function $A^{-1} b$ of the initial conditions incorporated in $b$, and +- a weighted sum of current and past values of the IID shocks $\{u_t\}$. + +Thus, let $\tilde{A}=A^{-1}$. + +Evidently, for $t\geq0$, + +$$ +y_{t+1}=\sum_{i=1}^{t+1}\tilde{A}_{t+1,i}b_{i}+\sum_{i=1}^{t}\tilde{A}_{t+1,i}u_{i}+u_{t+1} +$$ + +This is a **moving average** representation with time-varying coefficients. + +Just as system {eq}`eq:eqma` constitutes a +**moving average** representation for $y$, system {eq}`eq:eqar` constitutes an **autoregressive** representation for $y$. + +## A forward looking model + +Samuelson’s model is *backward looking* in the sense that we give it *initial conditions* and let it +run. + +Let’s now turn to model that is *forward looking*. + +We apply similar linear algebra machinery to study a *perfect +foresight* model widely used as a benchmark in macroeconomics and +finance. + +As an example, we suppose that $p_t$ is the price of a stock and +that $y_t$ is its dividend. + +We assume that $y_t$ is determined by second-order difference +equation that we analyzed just above, so that + +$$ +y = A^{-1} \left(b + u\right) +$$ + +Our *perfect foresight* model of stock prices is + +$$ +p_{t} = \sum_{j=0}^{T-t} \beta^{j} y_{t+j}, \quad \beta \in (0,1) +$$ + +where $\beta$ is a discount factor. + +The model asserts that the price of the stock at $t$ equals the +discounted present values of the (perfectly foreseen) future dividends. + +Form + +$$ +\underset{\equiv p}{\underbrace{\left[\begin{array}{c} +p_{1}\\ +p_{2}\\ +p_{3}\\ +\vdots\\ +p_{T} +\end{array}\right]}}=\underset{\equiv B}{\underbrace{\left[\begin{array}{ccccc} +1 & \beta & \beta^{2} & \cdots & \beta^{T-1}\\ +0 & 1 & \beta & \cdots & \beta^{T-2}\\ +0 & 0 & 1 & \cdots & \beta^{T-3}\\ +\vdots & \vdots & \vdots & \vdots & \vdots\\ +0 & 0 & 0 & \cdots & 1 +\end{array}\right]}}\left[\begin{array}{c} +y_{1}\\ +y_{2}\\ +y_{3}\\ +\vdots\\ +y_{T} +\end{array}\right] +$$ + +```{code-cell} ipython3 +β = .96 +``` + +```{code-cell} ipython3 +# construct B +B = np.zeros((T, T)) + +for i in range(T): + B[i, i:] = β ** np.arange(0, T-i) +``` + +```{code-cell} ipython3 +print(B) +``` + +```{code-cell} ipython3 +σ_u = 0. +u = np.random.normal(0, σ_u, size=T) +y = A_inv @ (b + u) +y_steady = A_inv @ (b_steady + u) +``` + +```{code-cell} ipython3 +p = B @ y +``` + +```{code-cell} ipython3 +plt.plot(np.arange(0, T)+1, y, label='y') +plt.plot(np.arange(0, T)+1, p, label='p') +plt.xlabel('t') +plt.ylabel('y/p') +plt.legend() + +plt.show() +``` + +Can you explain why the trend of the price is downward over time? + +Also consider the case when $y_{0}$ and $y_{-1}$ are at the +steady state. + +```{code-cell} ipython3 +p_steady = B @ y_steady + +plt.plot(np.arange(0, T)+1, y_steady, label='y') +plt.plot(np.arange(0, T)+1, p_steady, label='p') +plt.xlabel('t') +plt.ylabel('y/p') +plt.legend() + +plt.show() +``` diff --git a/content/lectures/troubleshooting.ipynb b/book/_build/html/_sources/troubleshooting.ipynb similarity index 92% rename from content/lectures/troubleshooting.ipynb rename to book/_build/html/_sources/troubleshooting.ipynb index 1e10fc7..17a53ec 100644 --- a/content/lectures/troubleshooting.ipynb +++ b/book/_build/html/_sources/troubleshooting.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "f553b263", + "id": "a318fb62", "metadata": {}, "source": [ "(troubleshooting)=\n", @@ -16,13 +16,9 @@ "\n", "# Troubleshooting\n", "\n", - "```{contents} Contents\n", - ":depth: 2\n", - "```\n", - "\n", "This page is for readers experiencing errors when running the code from the lectures.\n", "\n", - "## Fixing Your Local Environment\n", + "## Fixing your local environment\n", "\n", "The basic assumption of the lectures is that code in a lecture should execute whenever\n", "\n", @@ -58,7 +54,7 @@ "We like getting feedback on the lectures so please don't hesitate to get in\n", "touch.\n", "\n", - "## Reporting an Issue\n", + "## Reporting an issue\n", "\n", "One way to give feedback is to raise an issue through our [issue tracker](https://github.com/QuantEcon/lecture-python/issues).\n", "\n", @@ -72,12 +68,21 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst" + } + }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" - } + }, + "source_map": [ + 10 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/troubleshooting.md b/book/_build/html/_sources/troubleshooting.md new file mode 100644 index 0000000..7bc907a --- /dev/null +++ b/book/_build/html/_sources/troubleshooting.md @@ -0,0 +1,71 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst +kernelspec: + display_name: Python 3 + language: python + name: python3 +--- + +(troubleshooting)= +```{raw} html + +``` + +# Troubleshooting + +This page is for readers experiencing errors when running the code from the lectures. + +## Fixing your local environment + +The basic assumption of the lectures is that code in a lecture should execute whenever + +1. it is executed in a Jupyter notebook and +1. the notebook is running on a machine with the latest version of Anaconda Python. + +You have installed Anaconda, haven't you, following the instructions in [this lecture](https://python-programming.quantecon.org/getting_started.html)? + +Assuming that you have, the most common source of problems for our readers is that their Anaconda distribution is not up to date. + +[Here's a useful article](https://www.anaconda.com/blog/keeping-anaconda-date) +on how to update Anaconda. + +Another option is to simply remove Anaconda and reinstall. + +You also need to keep the external code libraries, such as [QuantEcon.py](https://quantecon.org/quantecon-py) up to date. + +For this task you can either + +* use conda install -y quantecon on the command line, or +* execute !conda install -y quantecon within a Jupyter notebook. + +If your local environment is still not working you can do two things. + +First, you can use a remote machine instead, by clicking on the Launch Notebook icon available for each lecture + +```{image} _static/lecture_specific/troubleshooting/launch.png + +``` + +Second, you can report an issue, so we can try to fix your local set up. + +We like getting feedback on the lectures so please don't hesitate to get in +touch. + +## Reporting an issue + +One way to give feedback is to raise an issue through our [issue tracker](https://github.com/QuantEcon/lecture-python/issues). + +Please be as specific as possible. Tell us where the problem is and as much +detail about your local set up as you can provide. + +Another feedback option is to use our [discourse forum](https://discourse.quantecon.org/). + +Finally, you can provide direct feedback to [contact@quantecon.org](mailto:contact@quantecon.org) + diff --git a/book/_build/html/_sources/unpleasant.ipynb b/book/_build/html/_sources/unpleasant.ipynb new file mode 100644 index 0000000..171d5ba --- /dev/null +++ b/book/_build/html/_sources/unpleasant.ipynb @@ -0,0 +1,622 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "ba348dcc", + "metadata": {}, + "source": [ + "# Some Unpleasant Monetarist Arithmetic \n", + "\n", + "## Overview\n", + "\n", + "\n", + "This lecture builds on concepts and issues introduced in {doc}`money_inflation`.\n", + "\n", + "That lecture describes stationary equilibria that reveal a [*Laffer curve*](https://en.wikipedia.org/wiki/Laffer_curve) in the inflation tax rate and the associated stationary rate of return \n", + "on currency. \n", + "\n", + "In this lecture we study a situation in which a stationary equilibrium prevails after date $T > 0$, but not before then. \n", + "\n", + "For $t=0, \\ldots, T-1$, the money supply, price level, and interest-bearing government debt vary along a transition path that ends at $t=T$.\n", + "\n", + "During this transition, the ratio of the real balances $\\frac{m_{t+1}}{{p_t}}$ to indexed one-period government bonds $\\tilde R B_{t-1}$ maturing at time $t$ decreases each period. \n", + "\n", + "This has consequences for the **gross-of-interest** government deficit that must be financed by printing money for times $t \\geq T$. \n", + "\n", + "The critical **money-to-bonds** ratio stabilizes only at time $T$ and afterwards.\n", + "\n", + "And the larger is $T$, the higher is the gross-of-interest government deficit that must be financed\n", + "by printing money at times $t \\geq T$. \n", + "\n", + "These outcomes are the essential finding of Sargent and Wallace's \"unpleasant monetarist arithmetic\" {cite}`sargent1981`.\n", + "\n", + "That lecture described supplies and demands for money that appear in lecture.\n", + "\n", + "It also characterized the steady state equilibrium from which we work backwards in this lecture. \n", + "\n", + "In addition to learning about \"unpleasant monetarist arithmetic\", in this lecture we'll learn how to implement a [*fixed point*](https://en.wikipedia.org/wiki/Fixed_point_(mathematics)) algorithm for computing an initial price level.\n", + "\n", + "\n", + "## Setup\n", + "\n", + "Let's start with quick reminders of the model's components set out in {doc}`money_inflation`.\n", + "\n", + "Please consult that lecture for more details and Python code that we'll also use in this lecture.\n", + "\n", + "For $t \\geq 1$, **real balances** evolve according to\n", + "\n", + "\n", + "$$\n", + "\\frac{m_{t+1}}{p_t} - \\frac{m_{t}}{p_{t-1}} \\frac{p_{t-1}}{p_t} = g\n", + "$$\n", + "\n", + "or\n", + "\n", + "$$\n", + "b_t - b_{t-1} R_{t-1} = g\n", + "$$ (eq:up_bmotion)\n", + "\n", + "where\n", + "\n", + "* $b_t = \\frac{m_{t+1}}{p_t}$ is real balances at the end of period $t$\n", + "* $R_{t-1} = \\frac{p_{t-1}}{p_t}$ is the gross rate of return on real balances held from $t-1$ to $t$\n", + "\n", + "The demand for real balances is \n", + "\n", + "$$\n", + "b_t = \\gamma_1 - \\gamma_2 R_t^{-1} . \n", + "$$ (eq:up_bdemand)\n", + "\n", + "where $\\gamma_1 > \\gamma_2 > 0$.\n", + "\n", + "## Monetary-Fiscal Policy\n", + "\n", + "To the basic model of {doc}`money_inflation`, we add inflation-indexed one-period government bonds as an additional way for the government to finance government expenditures. \n", + "\n", + "Let $\\widetilde R > 1$ be a time-invariant gross real rate of return on government one-period inflation-indexed bonds.\n", + "\n", + "With this additional source of funds, the government's budget constraint at time $t \\geq 0$ is now\n", + "\n", + "$$\n", + "B_t + \\frac{m_{t+1}}{p_t} = \\widetilde R B_{t-1} + \\frac{m_t}{p_t} + g\n", + "$$ \n", + "\n", + "\n", + "Just before the beginning of time $0$, the public owns $\\check m_0$ units of currency (measured in dollars)\n", + "and $\\widetilde R \\check B_{-1}$ units of one-period indexed bonds (measured in time $0$ goods); these two quantities are initial conditions set outside the model.\n", + "\n", + "Notice that $\\check m_0$ is a *nominal* quantity, being measured in dollars, while\n", + "$\\widetilde R \\check B_{-1}$ is a *real* quantity, being measured in time $0$ goods.\n", + "\n", + "\n", + "### Open market operations\n", + "\n", + "At time $0$, government can rearrange its portfolio of debts subject to the following constraint (on open-market operations):\n", + "\n", + "$$\n", + "\\widetilde R B_{-1} + \\frac{m_0}{p_0} = \\widetilde R \\check B_{-1} + \\frac{\\check m_0}{p_0}\n", + "$$\n", + "\n", + "or\n", + "\n", + "$$\n", + "B_{-1} - \\check B_{-1} = \\frac{1}{p_0 \\widetilde R} \\left( \\check m_0 - m_0 \\right) \n", + "$$ (eq:openmarketconstraint)\n", + "\n", + "This equation says that the government (e.g., the central bank) can *decrease* $m_0$ relative to \n", + "$\\check m_0$ by *increasing* $B_{-1}$ relative to $\\check B_{-1}$. \n", + "\n", + "This is a version of a standard constraint on a central bank's [**open market operations**](https://www.federalreserve.gov/monetarypolicy/openmarket.htm) in which it expands the stock of money by buying government bonds from the public. \n", + "\n", + "## An open market operation at $t=0$\n", + "\n", + "Following Sargent and Wallace {cite}`sargent1981`, we analyze consequences of a central bank policy that \n", + "uses an open market operation to lower the price level in the face of a persistent fiscal\n", + "deficit that takes the form of a positive $g$.\n", + "\n", + "Just before time $0$, the government chooses $(m_0, B_{-1})$ subject to constraint\n", + "{eq}`eq:openmarketconstraint`.\n", + "\n", + "For $t =0, 1, \\ldots, T-1$,\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "B_t & = \\widetilde R B_{t-1} + g \\cr\n", + "m_{t+1} & = m_0 \n", + "\\end{aligned}\n", + "$$\n", + "\n", + "while for $t \\geq T$,\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "B_t & = B_{T-1} \\cr\n", + "m_{t+1} & = m_t + p_t \\overline g\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "where \n", + "\n", + "$$\n", + "\\overline g = \\left[(\\tilde R -1) B_{T-1} + g \\right]\n", + "$$ (eq:overlineg)\n", + "\n", + "We want to compute an equilibrium $\\{p_t,m_t,b_t, R_t\\}_{t=0}$ sequence under this scheme for\n", + "running monetary and fiscal policies.\n", + "\n", + "Here, by **fiscal policy** we mean the collection of actions that determine a sequence of net-of-interest government deficits $\\{g_t\\}_{t=0}^\\infty$ that must be financed by issuing to the public either money or interest bearing bonds.\n", + "\n", + "By **monetary policy** or **debt-management policy**, we mean the collection of actions that determine how the government divides its portfolio of debts to the public between interest-bearing parts (government bonds) and non-interest-bearing parts (money).\n", + "\n", + "By an **open market operation**, we mean a government monetary policy action in which the government\n", + "(or its delegate, say, a central bank) either buys government bonds from the public for newly issued money, or sells bonds to the public and withdraws the money it receives from public circulation. \n", + "\n", + "## Algorithm (basic idea)\n", + "\n", + "\n", + "We work backwards from $t=T$ and first compute $p_T, R_u$ associated with the low-inflation, low-inflation-tax-rate stationary equilibrium in {doc}`money_inflation_nonlinear`.\n", + "\n", + "To start our description of our algorithm, it is useful to recall that a stationary rate of return\n", + "on currency $\\bar R$ solves the quadratic equation\n", + "\n", + "$$\n", + "-\\gamma_2 + (\\gamma_1 + \\gamma_2 - \\overline g) \\bar R - \\gamma_1 \\bar R^2 = 0\n", + "$$ (eq:up_steadyquadratic)\n", + "\n", + "Quadratic equation {eq}`eq:up_steadyquadratic` has two roots, $R_l < R_u < 1$.\n", + "\n", + "For reasons described at the end of {doc}`money_inflation`, we select the larger root $R_u$. \n", + "\n", + "\n", + "Next, we compute\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "R_T & = R_u \\cr\n", + "b_T & = \\gamma_1 - \\gamma_2 R_u^{-1} \\cr\n", + "p_T & = \\frac{m_0}{\\gamma_1 - \\overline g - \\gamma_2 R_u^{-1}}\n", + "\\end{aligned}\n", + "$$ (eq:LafferTstationary)\n", + "\n", + "\n", + "We can compute continuation sequences $\\{R_t, b_t\\}_{t=T+1}^\\infty$ of rates of return and real balances that are associated with an equilibrium by solving equation {eq}`eq:up_bmotion` and {eq}`eq:up_bdemand` sequentially for $t \\geq 1$:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "b_t & = b_{t-1} R_{t-1} + \\overline g \\cr\n", + "R_t^{-1} & = \\frac{\\gamma_1}{\\gamma_2} - \\gamma_2^{-1} b_t \\cr\n", + "p_t & = R_t p_{t-1} \\cr\n", + " m_t & = b_{t-1} p_t \n", + "\\end{aligned}\n", + "$$\n", + " \n", + "\n", + "## Before time $T$ \n", + "\n", + "Define \n", + "\n", + "$$\n", + "\\lambda \\equiv \\frac{\\gamma_2}{\\gamma_1}.\n", + "$$\n", + "\n", + "Our restrictions that $\\gamma_1 > \\gamma_2 > 0$ imply that $\\lambda \\in [0,1)$.\n", + "\n", + "We want to compute\n", + "\n", + "$$ \n", + "\\begin{aligned}\n", + "p_0 & = \\gamma_1^{-1} \\left[ \\sum_{j=0}^\\infty \\lambda^j m_{j} \\right] \\cr\n", + "& = \\gamma_1^{-1} \\left[ \\sum_{j=0}^{T-1} \\lambda^j m_{0} + \\sum_{j=T}^\\infty \\lambda^j m_{1+j} \\right]\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "Thus,\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "p_0 & = \\gamma_1^{-1} m_0 \\left\\{ \\frac{1 - \\lambda^T}{1-\\lambda} + \\frac{\\lambda^T}{R_u-\\lambda} \\right\\} \\cr\n", + "p_1 & = \\gamma_1^{-1} m_0 \\left\\{ \\frac{1 - \\lambda^{T-1}}{1-\\lambda} + \\frac{\\lambda^{T-1}}{R_u-\\lambda} \\right\\} \\cr\n", + "\\quad \\vdots & \\quad \\quad \\vdots \\cr\n", + "p_{T-1} & = \\gamma_1^{-1} m_0 \\left\\{ \\frac{1 - \\lambda}{1-\\lambda} + \\frac{\\lambda}{R_u-\\lambda} \\right\\} \\cr\n", + "p_T & = \\gamma_1^{-1} m_0 \\left\\{\\frac{1}{R_u-\\lambda} \\right\\}\n", + "\\end{aligned}\n", + "$$ (eq:allts)\n", + "\n", + "We can implement the preceding formulas by iterating on\n", + "\n", + "$$\n", + "p_t = \\gamma_1^{-1} m_0 + \\lambda p_{t+1}, \\quad t = T-1, T-2, \\ldots, 0\n", + "$$\n", + "\n", + "starting from \n", + "\n", + "$$\n", + "p_T = \\frac{m_0}{\\gamma_1 - \\overline g - \\gamma_2 R_u^{-1}} = \\gamma_1^{-1} m_0 \\left\\{\\frac{1}{R_u-\\lambda} \\right\\}\n", + "$$ (eq:pTformula)\n", + "\n", + "```{prf:remark}\n", + ":label: equivalence\n", + "We can verify the equivalence of the two formulas on the right sides of {eq}`eq:pTformula` by recalling that \n", + "$R_u$ is a root of the quadratic equation {eq}`eq:up_steadyquadratic` that determines steady state rates of return on currency.\n", + "```\n", + " \n", + "## Algorithm (pseudo code)\n", + "\n", + "Now let's describe a computational algorithm in more detail in the form of a description\n", + "that constitutes pseudo code because it approaches a set of instructions we could provide to a \n", + "Python coder.\n", + "\n", + "To compute an equilibrium, we deploy the following algorithm.\n", + "\n", + "```{prf:algorithm}\n", + "Given *parameters* include $g, \\check m_0, \\check B_{-1}, \\widetilde R >1, T $.\n", + "\n", + "We define a mapping from $p_0$ to $\\widehat p_0$ as follows.\n", + "\n", + "* Set $m_0$ and then compute $B_{-1}$ to satisfy the constraint on time $0$ **open market operations**\n", + "\n", + "$$\n", + "B_{-1}- \\check B_{-1} = \\frac{\\widetilde R}{p_0} \\left( \\check m_0 - m_0 \\right)\n", + "$$\n", + "\n", + "* Compute $B_{T-1}$ from\n", + "\n", + "$$\n", + "B_{T-1} = \\widetilde R^T B_{-1} + \\left( \\frac{1 - \\widetilde R^T}{1-\\widetilde R} \\right) g\n", + "$$\n", + "\n", + "* Compute \n", + "\n", + "$$\n", + "\\overline g = g + \\left[ \\tilde R - 1\\right] B_{T-1}\n", + "$$\n", + "\n", + "\n", + "\n", + "* Compute $R_u, p_T$ from formulas {eq}`eq:up_steadyquadratic` and {eq}`eq:LafferTstationary` above\n", + "\n", + "* Compute a new estimate of $p_0$, call it $\\widehat p_0$, from equation {eq}`eq:allts` above\n", + "\n", + "* Note that the preceding steps define a mapping\n", + "\n", + "$$\n", + "\\widehat p_0 = {\\mathcal S}(p_0)\n", + "$$\n", + "\n", + "* We seek a fixed point of ${\\mathcal S}$, i.e., a solution of $p_0 = {\\mathcal S}(p_0)$.\n", + "\n", + "* Compute a fixed point by iterating to convergence on the relaxation algorithm\n", + "\n", + "$$\n", + "p_{0,j+1} = (1-\\theta) {\\mathcal S}(p_{0,j}) + \\theta p_{0,j}, \n", + "$$\n", + "\n", + "where $\\theta \\in [0,1)$ is a relaxation parameter.\n", + "```\n", + "\n", + "## Example Calculations\n", + "\n", + "We'll set parameters of the model so that the steady state after time $T$ is initially the same\n", + "as in {doc}`money_inflation_nonlinear`\n", + "\n", + "In particular, we set $\\gamma_1=100, \\gamma_2 =50, g=3.0$. We set $m_0 = 100$ in that lecture,\n", + "but now the counterpart will be $M_T$, which is endogenous. \n", + "\n", + "As for new parameters, we'll set $\\tilde R = 1.01, \\check B_{-1} = 0, \\check m_0 = 105, T = 5$.\n", + "\n", + "We'll study a \"small\" open market operation by setting $m_0 = 100$.\n", + "\n", + "These parameter settings mean that just before time $0$, the \"central bank\" sells the public bonds in exchange for $\\check m_0 - m_0 = 5$ units of currency. \n", + "\n", + "That leaves the public with less currency but more government interest-bearing bonds.\n", + "\n", + "Since the public has less currency (its supply has diminished) it is plausible to anticipate that the price level at time $0$ will be driven downward.\n", + "\n", + "But that is not the end of the story, because this **open market operation** at time $0$ has consequences for future settings of $m_{t+1}$ and the gross-of-interest government deficit $\\bar g_t$. \n", + "\n", + "\n", + "Let's start with some imports:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "df278809", + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from collections import namedtuple" + ] + }, + { + "cell_type": "markdown", + "id": "67241fc1", + "metadata": {}, + "source": [ + "Now let's dive in and implement our pseudo code in Python." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3850e676", + "metadata": {}, + "outputs": [], + "source": [ + "# Create a namedtuple that contains parameters\n", + "MoneySupplyModel = namedtuple(\"MoneySupplyModel\", \n", + " [\"γ1\", \"γ2\", \"g\",\n", + " \"R_tilde\", \"m0_check\", \"Bm1_check\",\n", + " \"T\"])\n", + "\n", + "def create_model(γ1=100, γ2=50, g=3.0,\n", + " R_tilde=1.01,\n", + " Bm1_check=0, m0_check=105,\n", + " T=5):\n", + " \n", + " return MoneySupplyModel(γ1=γ1, γ2=γ2, g=g,\n", + " R_tilde=R_tilde,\n", + " m0_check=m0_check, Bm1_check=Bm1_check,\n", + " T=T)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "721a42c6", + "metadata": {}, + "outputs": [], + "source": [ + "msm = create_model()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "44e63921", + "metadata": {}, + "outputs": [], + "source": [ + "def S(p0, m0, model):\n", + "\n", + " # unpack parameters\n", + " γ1, γ2, g = model.γ1, model.γ2, model.g\n", + " R_tilde = model.R_tilde\n", + " m0_check, Bm1_check = model.m0_check, model.Bm1_check\n", + " T = model.T\n", + "\n", + " # open market operation\n", + " Bm1 = 1 / (p0 * R_tilde) * (m0_check - m0) + Bm1_check\n", + "\n", + " # compute B_{T-1}\n", + " BTm1 = R_tilde ** T * Bm1 + ((1 - R_tilde ** T) / (1 - R_tilde)) * g\n", + "\n", + " # compute g bar\n", + " g_bar = g + (R_tilde - 1) * BTm1\n", + "\n", + " # solve the quadratic equation\n", + " Ru = np.roots((-γ1, γ1 + γ2 - g_bar, -γ2)).max()\n", + "\n", + " # compute p0\n", + " λ = γ2 / γ1\n", + " p0_new = (1 / γ1) * m0 * ((1 - λ ** T) / (1 - λ) + λ ** T / (Ru - λ))\n", + "\n", + " return p0_new" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dec0b1ae", + "metadata": {}, + "outputs": [], + "source": [ + "def compute_fixed_point(m0, p0_guess, model, θ=0.5, tol=1e-6):\n", + "\n", + " p0 = p0_guess\n", + " error = tol + 1\n", + "\n", + " while error > tol:\n", + " p0_next = (1 - θ) * S(p0, m0, model) + θ * p0\n", + "\n", + " error = np.abs(p0_next - p0)\n", + " p0 = p0_next\n", + "\n", + " return p0" + ] + }, + { + "cell_type": "markdown", + "id": "db24e5df", + "metadata": {}, + "source": [ + "Let's look at how price level $p_0$ in the stationary $R_u$ equilibrium depends on the initial\n", + "money supply $m_0$. \n", + "\n", + "Notice that the slope of $p_0$ as a function of $m_0$ is constant.\n", + "\n", + "This outcome indicates that our model verifies a quantity theory of money outcome,\n", + "something that Sargent and Wallace {cite}`sargent1981` purposefully built into their model to justify\n", + "the adjective *monetarist* in their title." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "734dca86", + "metadata": {}, + "outputs": [], + "source": [ + "m0_arr = np.arange(10, 110, 10)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4c7bbeb3", + "metadata": {}, + "outputs": [], + "source": [ + "plt.plot(m0_arr, [compute_fixed_point(m0, 1, msm) for m0 in m0_arr])\n", + "\n", + "plt.ylabel('$p_0$')\n", + "plt.xlabel('$m_0$')\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "a7d85ec0", + "metadata": {}, + "source": [ + "Now let's write and implement code that lets us experiment with the time $0$ open market operation described earlier." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7005ee74", + "metadata": {}, + "outputs": [], + "source": [ + "def simulate(m0, model, length=15, p0_guess=1):\n", + "\n", + " # unpack parameters\n", + " γ1, γ2, g = model.γ1, model.γ2, model.g\n", + " R_tilde = model.R_tilde\n", + " m0_check, Bm1_check = model.m0_check, model.Bm1_check\n", + " T = model.T\n", + "\n", + " # (pt, mt, bt, Rt)\n", + " paths = np.empty((4, length))\n", + "\n", + " # open market operation\n", + " p0 = compute_fixed_point(m0, 1, model)\n", + " Bm1 = 1 / (p0 * R_tilde) * (m0_check - m0) + Bm1_check\n", + " BTm1 = R_tilde ** T * Bm1 + ((1 - R_tilde ** T) / (1 - R_tilde)) * g\n", + " g_bar = g + (R_tilde - 1) * BTm1\n", + " Ru = np.roots((-γ1, γ1 + γ2 - g_bar, -γ2)).max()\n", + "\n", + " λ = γ2 / γ1\n", + "\n", + " # t = 0\n", + " paths[0, 0] = p0\n", + " paths[1, 0] = m0\n", + "\n", + " # 1 <= t <= T\n", + " for t in range(1, T+1, 1):\n", + " paths[0, t] = (1 / γ1) * m0 * \\\n", + " ((1 - λ ** (T - t)) / (1 - λ)\n", + " + (λ ** (T - t) / (Ru - λ)))\n", + " paths[1, t] = m0\n", + "\n", + " # t > T\n", + " for t in range(T+1, length):\n", + " paths[0, t] = paths[0, t-1] / Ru\n", + " paths[1, t] = paths[1, t-1] + paths[0, t] * g_bar\n", + "\n", + " # Rt = pt / pt+1\n", + " paths[3, :T] = paths[0, :T] / paths[0, 1:T+1]\n", + " paths[3, T:] = Ru\n", + "\n", + " # bt = γ1 - γ2 / Rt\n", + " paths[2, :] = γ1 - γ2 / paths[3, :]\n", + "\n", + " return paths" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "03ea0768", + "metadata": {}, + "outputs": [], + "source": [ + "def plot_path(m0_arr, model, length=15):\n", + "\n", + " fig, axs = plt.subplots(2, 2, figsize=(8, 5))\n", + " titles = ['$p_t$', '$m_t$', '$b_t$', '$R_t$']\n", + " \n", + " for m0 in m0_arr:\n", + " paths = simulate(m0, model, length=length)\n", + " for i, ax in enumerate(axs.flat):\n", + " ax.plot(paths[i])\n", + " ax.set_title(titles[i])\n", + " \n", + " axs[0, 1].hlines(model.m0_check, 0, length, color='r', linestyle='--')\n", + " axs[0, 1].text(length * 0.8, model.m0_check * 0.9, '$\\check{m}_0$')\n", + " plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2a52439d", + "metadata": { + "mystnb": { + "figure": { + "caption": "Unpleasant Arithmetic", + "name": "fig:unpl1" + } + } + }, + "outputs": [], + "source": [ + "plot_path([80, 100], msm)" + ] + }, + { + "cell_type": "markdown", + "id": "22ee3006", + "metadata": {}, + "source": [ + "{numref}`fig:unpl1` summarizes outcomes of two experiments that convey messages of Sargent and Wallace {cite}`sargent1981`.\n", + "\n", + "* An open market operation that reduces the supply of money at time $t=0$ reduces the price level at time $t=0$\n", + "\n", + "* The lower is the post-open-market-operation money supply at time $0$, lower is the price level at time $0$.\n", + "\n", + "* An open market operation that reduces the post open market operation money supply at time $0$ also *lowers* the rate of return on money $R_u$ at times $t \\geq T$ because it brings a higher gross of interest government deficit that must be financed by printing money (i.e., levying an inflation tax) at time $t \\geq T$.\n", + "\n", + "* $R$ is important in the context of maintaining monetary stability and addressing the consequences of increased inflation due to government deficits. Thus, a larger $R$ might be chosen to mitigate the negative impacts on the real rate of return caused by inflation." + ] + } + ], + "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst", + "format_version": 0.13, + "jupytext_version": "1.14.1" + } + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "source_map": [ + 12, + 326, + 330, + 334, + 352, + 356, + 384, + 397, + 409, + 413, + 420, + 424, + 471, + 488, + 496 + ] + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/book/_build/html/_sources/unpleasant.md b/book/_build/html/_sources/unpleasant.md new file mode 100644 index 0000000..5eb80e3 --- /dev/null +++ b/book/_build/html/_sources/unpleasant.md @@ -0,0 +1,506 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.14.1 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Some Unpleasant Monetarist Arithmetic + +## Overview + + +This lecture builds on concepts and issues introduced in {doc}`money_inflation`. + +That lecture describes stationary equilibria that reveal a [*Laffer curve*](https://en.wikipedia.org/wiki/Laffer_curve) in the inflation tax rate and the associated stationary rate of return +on currency. + +In this lecture we study a situation in which a stationary equilibrium prevails after date $T > 0$, but not before then. + +For $t=0, \ldots, T-1$, the money supply, price level, and interest-bearing government debt vary along a transition path that ends at $t=T$. + +During this transition, the ratio of the real balances $\frac{m_{t+1}}{{p_t}}$ to indexed one-period government bonds $\tilde R B_{t-1}$ maturing at time $t$ decreases each period. + +This has consequences for the **gross-of-interest** government deficit that must be financed by printing money for times $t \geq T$. + +The critical **money-to-bonds** ratio stabilizes only at time $T$ and afterwards. + +And the larger is $T$, the higher is the gross-of-interest government deficit that must be financed +by printing money at times $t \geq T$. + +These outcomes are the essential finding of Sargent and Wallace's "unpleasant monetarist arithmetic" {cite}`sargent1981`. + +That lecture described supplies and demands for money that appear in lecture. + +It also characterized the steady state equilibrium from which we work backwards in this lecture. + +In addition to learning about "unpleasant monetarist arithmetic", in this lecture we'll learn how to implement a [*fixed point*](https://en.wikipedia.org/wiki/Fixed_point_(mathematics)) algorithm for computing an initial price level. + + +## Setup + +Let's start with quick reminders of the model's components set out in {doc}`money_inflation`. + +Please consult that lecture for more details and Python code that we'll also use in this lecture. + +For $t \geq 1$, **real balances** evolve according to + + +$$ +\frac{m_{t+1}}{p_t} - \frac{m_{t}}{p_{t-1}} \frac{p_{t-1}}{p_t} = g +$$ + +or + +$$ +b_t - b_{t-1} R_{t-1} = g +$$ (eq:up_bmotion) + +where + +* $b_t = \frac{m_{t+1}}{p_t}$ is real balances at the end of period $t$ +* $R_{t-1} = \frac{p_{t-1}}{p_t}$ is the gross rate of return on real balances held from $t-1$ to $t$ + +The demand for real balances is + +$$ +b_t = \gamma_1 - \gamma_2 R_t^{-1} . +$$ (eq:up_bdemand) + +where $\gamma_1 > \gamma_2 > 0$. + +## Monetary-Fiscal Policy + +To the basic model of {doc}`money_inflation`, we add inflation-indexed one-period government bonds as an additional way for the government to finance government expenditures. + +Let $\widetilde R > 1$ be a time-invariant gross real rate of return on government one-period inflation-indexed bonds. + +With this additional source of funds, the government's budget constraint at time $t \geq 0$ is now + +$$ +B_t + \frac{m_{t+1}}{p_t} = \widetilde R B_{t-1} + \frac{m_t}{p_t} + g +$$ + + +Just before the beginning of time $0$, the public owns $\check m_0$ units of currency (measured in dollars) +and $\widetilde R \check B_{-1}$ units of one-period indexed bonds (measured in time $0$ goods); these two quantities are initial conditions set outside the model. + +Notice that $\check m_0$ is a *nominal* quantity, being measured in dollars, while +$\widetilde R \check B_{-1}$ is a *real* quantity, being measured in time $0$ goods. + + +### Open market operations + +At time $0$, government can rearrange its portfolio of debts subject to the following constraint (on open-market operations): + +$$ +\widetilde R B_{-1} + \frac{m_0}{p_0} = \widetilde R \check B_{-1} + \frac{\check m_0}{p_0} +$$ + +or + +$$ +B_{-1} - \check B_{-1} = \frac{1}{p_0 \widetilde R} \left( \check m_0 - m_0 \right) +$$ (eq:openmarketconstraint) + +This equation says that the government (e.g., the central bank) can *decrease* $m_0$ relative to +$\check m_0$ by *increasing* $B_{-1}$ relative to $\check B_{-1}$. + +This is a version of a standard constraint on a central bank's [**open market operations**](https://www.federalreserve.gov/monetarypolicy/openmarket.htm) in which it expands the stock of money by buying government bonds from the public. + +## An open market operation at $t=0$ + +Following Sargent and Wallace {cite}`sargent1981`, we analyze consequences of a central bank policy that +uses an open market operation to lower the price level in the face of a persistent fiscal +deficit that takes the form of a positive $g$. + +Just before time $0$, the government chooses $(m_0, B_{-1})$ subject to constraint +{eq}`eq:openmarketconstraint`. + +For $t =0, 1, \ldots, T-1$, + +$$ +\begin{aligned} +B_t & = \widetilde R B_{t-1} + g \cr +m_{t+1} & = m_0 +\end{aligned} +$$ + +while for $t \geq T$, + +$$ +\begin{aligned} +B_t & = B_{T-1} \cr +m_{t+1} & = m_t + p_t \overline g +\end{aligned} +$$ + +where + +$$ +\overline g = \left[(\tilde R -1) B_{T-1} + g \right] +$$ (eq:overlineg) + +We want to compute an equilibrium $\{p_t,m_t,b_t, R_t\}_{t=0}$ sequence under this scheme for +running monetary and fiscal policies. + +Here, by **fiscal policy** we mean the collection of actions that determine a sequence of net-of-interest government deficits $\{g_t\}_{t=0}^\infty$ that must be financed by issuing to the public either money or interest bearing bonds. + +By **monetary policy** or **debt-management policy**, we mean the collection of actions that determine how the government divides its portfolio of debts to the public between interest-bearing parts (government bonds) and non-interest-bearing parts (money). + +By an **open market operation**, we mean a government monetary policy action in which the government +(or its delegate, say, a central bank) either buys government bonds from the public for newly issued money, or sells bonds to the public and withdraws the money it receives from public circulation. + +## Algorithm (basic idea) + + +We work backwards from $t=T$ and first compute $p_T, R_u$ associated with the low-inflation, low-inflation-tax-rate stationary equilibrium in {doc}`money_inflation_nonlinear`. + +To start our description of our algorithm, it is useful to recall that a stationary rate of return +on currency $\bar R$ solves the quadratic equation + +$$ +-\gamma_2 + (\gamma_1 + \gamma_2 - \overline g) \bar R - \gamma_1 \bar R^2 = 0 +$$ (eq:up_steadyquadratic) + +Quadratic equation {eq}`eq:up_steadyquadratic` has two roots, $R_l < R_u < 1$. + +For reasons described at the end of {doc}`money_inflation`, we select the larger root $R_u$. + + +Next, we compute + +$$ +\begin{aligned} +R_T & = R_u \cr +b_T & = \gamma_1 - \gamma_2 R_u^{-1} \cr +p_T & = \frac{m_0}{\gamma_1 - \overline g - \gamma_2 R_u^{-1}} +\end{aligned} +$$ (eq:LafferTstationary) + + +We can compute continuation sequences $\{R_t, b_t\}_{t=T+1}^\infty$ of rates of return and real balances that are associated with an equilibrium by solving equation {eq}`eq:up_bmotion` and {eq}`eq:up_bdemand` sequentially for $t \geq 1$: + +$$ +\begin{aligned} +b_t & = b_{t-1} R_{t-1} + \overline g \cr +R_t^{-1} & = \frac{\gamma_1}{\gamma_2} - \gamma_2^{-1} b_t \cr +p_t & = R_t p_{t-1} \cr + m_t & = b_{t-1} p_t +\end{aligned} +$$ + + +## Before time $T$ + +Define + +$$ +\lambda \equiv \frac{\gamma_2}{\gamma_1}. +$$ + +Our restrictions that $\gamma_1 > \gamma_2 > 0$ imply that $\lambda \in [0,1)$. + +We want to compute + +$$ +\begin{aligned} +p_0 & = \gamma_1^{-1} \left[ \sum_{j=0}^\infty \lambda^j m_{j} \right] \cr +& = \gamma_1^{-1} \left[ \sum_{j=0}^{T-1} \lambda^j m_{0} + \sum_{j=T}^\infty \lambda^j m_{1+j} \right] +\end{aligned} +$$ + +Thus, + +$$ +\begin{aligned} +p_0 & = \gamma_1^{-1} m_0 \left\{ \frac{1 - \lambda^T}{1-\lambda} + \frac{\lambda^T}{R_u-\lambda} \right\} \cr +p_1 & = \gamma_1^{-1} m_0 \left\{ \frac{1 - \lambda^{T-1}}{1-\lambda} + \frac{\lambda^{T-1}}{R_u-\lambda} \right\} \cr +\quad \vdots & \quad \quad \vdots \cr +p_{T-1} & = \gamma_1^{-1} m_0 \left\{ \frac{1 - \lambda}{1-\lambda} + \frac{\lambda}{R_u-\lambda} \right\} \cr +p_T & = \gamma_1^{-1} m_0 \left\{\frac{1}{R_u-\lambda} \right\} +\end{aligned} +$$ (eq:allts) + +We can implement the preceding formulas by iterating on + +$$ +p_t = \gamma_1^{-1} m_0 + \lambda p_{t+1}, \quad t = T-1, T-2, \ldots, 0 +$$ + +starting from + +$$ +p_T = \frac{m_0}{\gamma_1 - \overline g - \gamma_2 R_u^{-1}} = \gamma_1^{-1} m_0 \left\{\frac{1}{R_u-\lambda} \right\} +$$ (eq:pTformula) + +```{prf:remark} +:label: equivalence +We can verify the equivalence of the two formulas on the right sides of {eq}`eq:pTformula` by recalling that +$R_u$ is a root of the quadratic equation {eq}`eq:up_steadyquadratic` that determines steady state rates of return on currency. +``` + +## Algorithm (pseudo code) + +Now let's describe a computational algorithm in more detail in the form of a description +that constitutes pseudo code because it approaches a set of instructions we could provide to a +Python coder. + +To compute an equilibrium, we deploy the following algorithm. + +```{prf:algorithm} +Given *parameters* include $g, \check m_0, \check B_{-1}, \widetilde R >1, T $. + +We define a mapping from $p_0$ to $\widehat p_0$ as follows. + +* Set $m_0$ and then compute $B_{-1}$ to satisfy the constraint on time $0$ **open market operations** + +$$ +B_{-1}- \check B_{-1} = \frac{\widetilde R}{p_0} \left( \check m_0 - m_0 \right) +$$ + +* Compute $B_{T-1}$ from + +$$ +B_{T-1} = \widetilde R^T B_{-1} + \left( \frac{1 - \widetilde R^T}{1-\widetilde R} \right) g +$$ + +* Compute + +$$ +\overline g = g + \left[ \tilde R - 1\right] B_{T-1} +$$ + + + +* Compute $R_u, p_T$ from formulas {eq}`eq:up_steadyquadratic` and {eq}`eq:LafferTstationary` above + +* Compute a new estimate of $p_0$, call it $\widehat p_0$, from equation {eq}`eq:allts` above + +* Note that the preceding steps define a mapping + +$$ +\widehat p_0 = {\mathcal S}(p_0) +$$ + +* We seek a fixed point of ${\mathcal S}$, i.e., a solution of $p_0 = {\mathcal S}(p_0)$. + +* Compute a fixed point by iterating to convergence on the relaxation algorithm + +$$ +p_{0,j+1} = (1-\theta) {\mathcal S}(p_{0,j}) + \theta p_{0,j}, +$$ + +where $\theta \in [0,1)$ is a relaxation parameter. +``` + +## Example Calculations + +We'll set parameters of the model so that the steady state after time $T$ is initially the same +as in {doc}`money_inflation_nonlinear` + +In particular, we set $\gamma_1=100, \gamma_2 =50, g=3.0$. We set $m_0 = 100$ in that lecture, +but now the counterpart will be $M_T$, which is endogenous. + +As for new parameters, we'll set $\tilde R = 1.01, \check B_{-1} = 0, \check m_0 = 105, T = 5$. + +We'll study a "small" open market operation by setting $m_0 = 100$. + +These parameter settings mean that just before time $0$, the "central bank" sells the public bonds in exchange for $\check m_0 - m_0 = 5$ units of currency. + +That leaves the public with less currency but more government interest-bearing bonds. + +Since the public has less currency (its supply has diminished) it is plausible to anticipate that the price level at time $0$ will be driven downward. + +But that is not the end of the story, because this **open market operation** at time $0$ has consequences for future settings of $m_{t+1}$ and the gross-of-interest government deficit $\bar g_t$. + + +Let's start with some imports: + +```{code-cell} ipython3 +import numpy as np +import matplotlib.pyplot as plt +from collections import namedtuple +``` + +Now let's dive in and implement our pseudo code in Python. + +```{code-cell} ipython3 +# Create a namedtuple that contains parameters +MoneySupplyModel = namedtuple("MoneySupplyModel", + ["γ1", "γ2", "g", + "R_tilde", "m0_check", "Bm1_check", + "T"]) + +def create_model(γ1=100, γ2=50, g=3.0, + R_tilde=1.01, + Bm1_check=0, m0_check=105, + T=5): + + return MoneySupplyModel(γ1=γ1, γ2=γ2, g=g, + R_tilde=R_tilde, + m0_check=m0_check, Bm1_check=Bm1_check, + T=T) +``` + +```{code-cell} ipython3 +msm = create_model() +``` + +```{code-cell} ipython3 +def S(p0, m0, model): + + # unpack parameters + γ1, γ2, g = model.γ1, model.γ2, model.g + R_tilde = model.R_tilde + m0_check, Bm1_check = model.m0_check, model.Bm1_check + T = model.T + + # open market operation + Bm1 = 1 / (p0 * R_tilde) * (m0_check - m0) + Bm1_check + + # compute B_{T-1} + BTm1 = R_tilde ** T * Bm1 + ((1 - R_tilde ** T) / (1 - R_tilde)) * g + + # compute g bar + g_bar = g + (R_tilde - 1) * BTm1 + + # solve the quadratic equation + Ru = np.roots((-γ1, γ1 + γ2 - g_bar, -γ2)).max() + + # compute p0 + λ = γ2 / γ1 + p0_new = (1 / γ1) * m0 * ((1 - λ ** T) / (1 - λ) + λ ** T / (Ru - λ)) + + return p0_new +``` + +```{code-cell} ipython3 +def compute_fixed_point(m0, p0_guess, model, θ=0.5, tol=1e-6): + + p0 = p0_guess + error = tol + 1 + + while error > tol: + p0_next = (1 - θ) * S(p0, m0, model) + θ * p0 + + error = np.abs(p0_next - p0) + p0 = p0_next + + return p0 +``` + +Let's look at how price level $p_0$ in the stationary $R_u$ equilibrium depends on the initial +money supply $m_0$. + +Notice that the slope of $p_0$ as a function of $m_0$ is constant. + +This outcome indicates that our model verifies a quantity theory of money outcome, +something that Sargent and Wallace {cite}`sargent1981` purposefully built into their model to justify +the adjective *monetarist* in their title. + + +```{code-cell} ipython3 +m0_arr = np.arange(10, 110, 10) +``` + +```{code-cell} ipython3 +plt.plot(m0_arr, [compute_fixed_point(m0, 1, msm) for m0 in m0_arr]) + +plt.ylabel('$p_0$') +plt.xlabel('$m_0$') + +plt.show() +``` + +Now let's write and implement code that lets us experiment with the time $0$ open market operation described earlier. + +```{code-cell} ipython3 +def simulate(m0, model, length=15, p0_guess=1): + + # unpack parameters + γ1, γ2, g = model.γ1, model.γ2, model.g + R_tilde = model.R_tilde + m0_check, Bm1_check = model.m0_check, model.Bm1_check + T = model.T + + # (pt, mt, bt, Rt) + paths = np.empty((4, length)) + + # open market operation + p0 = compute_fixed_point(m0, 1, model) + Bm1 = 1 / (p0 * R_tilde) * (m0_check - m0) + Bm1_check + BTm1 = R_tilde ** T * Bm1 + ((1 - R_tilde ** T) / (1 - R_tilde)) * g + g_bar = g + (R_tilde - 1) * BTm1 + Ru = np.roots((-γ1, γ1 + γ2 - g_bar, -γ2)).max() + + λ = γ2 / γ1 + + # t = 0 + paths[0, 0] = p0 + paths[1, 0] = m0 + + # 1 <= t <= T + for t in range(1, T+1, 1): + paths[0, t] = (1 / γ1) * m0 * \ + ((1 - λ ** (T - t)) / (1 - λ) + + (λ ** (T - t) / (Ru - λ))) + paths[1, t] = m0 + + # t > T + for t in range(T+1, length): + paths[0, t] = paths[0, t-1] / Ru + paths[1, t] = paths[1, t-1] + paths[0, t] * g_bar + + # Rt = pt / pt+1 + paths[3, :T] = paths[0, :T] / paths[0, 1:T+1] + paths[3, T:] = Ru + + # bt = γ1 - γ2 / Rt + paths[2, :] = γ1 - γ2 / paths[3, :] + + return paths +``` + +```{code-cell} ipython3 +def plot_path(m0_arr, model, length=15): + + fig, axs = plt.subplots(2, 2, figsize=(8, 5)) + titles = ['$p_t$', '$m_t$', '$b_t$', '$R_t$'] + + for m0 in m0_arr: + paths = simulate(m0, model, length=length) + for i, ax in enumerate(axs.flat): + ax.plot(paths[i]) + ax.set_title(titles[i]) + + axs[0, 1].hlines(model.m0_check, 0, length, color='r', linestyle='--') + axs[0, 1].text(length * 0.8, model.m0_check * 0.9, '$\check{m}_0$') + plt.show() +``` + +```{code-cell} ipython3 +--- +mystnb: + figure: + caption: "Unpleasant Arithmetic" + name: fig:unpl1 +--- +plot_path([80, 100], msm) +``` + +{numref}`fig:unpl1` summarizes outcomes of two experiments that convey messages of Sargent and Wallace {cite}`sargent1981`. + +* An open market operation that reduces the supply of money at time $t=0$ reduces the price level at time $t=0$ + +* The lower is the post-open-market-operation money supply at time $0$, lower is the price level at time $0$. + +* An open market operation that reduces the post open market operation money supply at time $0$ also *lowers* the rate of return on money $R_u$ at times $t \geq T$ because it brings a higher gross of interest government deficit that must be financed by printing money (i.e., levying an inflation tax) at time $t \geq T$. + +* $R$ is important in the context of maintaining monetary stability and addressing the consequences of increased inflation due to government deficits. Thus, a larger $R$ might be chosen to mitigate the negative impacts on the real rate of return caused by inflation. diff --git a/content/lectures/zreferences.ipynb b/book/_build/html/_sources/zreferences.ipynb similarity index 69% rename from content/lectures/zreferences.ipynb rename to book/_build/html/_sources/zreferences.ipynb index 477fa94..c6210a9 100644 --- a/content/lectures/zreferences.ipynb +++ b/book/_build/html/_sources/zreferences.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "d191fa4c", + "id": "f1cfe933", "metadata": {}, "source": [ "(references)=\n", @@ -14,12 +14,21 @@ } ], "metadata": { + "jupytext": { + "text_representation": { + "extension": ".md", + "format_name": "myst" + } + }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" - } + }, + "source_map": [ + 10 + ] }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/book/_build/html/_sources/zreferences.md b/book/_build/html/_sources/zreferences.md new file mode 100644 index 0000000..5f17e89 --- /dev/null +++ b/book/_build/html/_sources/zreferences.md @@ -0,0 +1,17 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst +kernelspec: + display_name: Python 3 + language: python + name: python3 +--- + +(references)= +# References + +```{bibliography} _static/quant-econ.bib +``` + diff --git a/book/_build/html/_sphinx_design_static/design-tabs.js b/book/_build/html/_sphinx_design_static/design-tabs.js new file mode 100644 index 0000000..b25bd6a --- /dev/null +++ b/book/_build/html/_sphinx_design_static/design-tabs.js @@ -0,0 +1,101 @@ +// @ts-check + +// Extra JS capability for selected tabs to be synced +// The selection is stored in local storage so that it persists across page loads. + +/** + * @type {Record} + */ +let sd_id_to_elements = {}; +const storageKeyPrefix = "sphinx-design-tab-id-"; + +/** + * Create a key for a tab element. + * @param {HTMLElement} el - The tab element. + * @returns {[string, string, string] | null} - The key. + * + */ +function create_key(el) { + let syncId = el.getAttribute("data-sync-id"); + let syncGroup = el.getAttribute("data-sync-group"); + if (!syncId || !syncGroup) return null; + return [syncGroup, syncId, syncGroup + "--" + syncId]; +} + +/** + * Initialize the tab selection. + * + */ +function ready() { + // Find all tabs with sync data + + /** @type {string[]} */ + let groups = []; + + document.querySelectorAll(".sd-tab-label").forEach((label) => { + if (label instanceof HTMLElement) { + let data = create_key(label); + if (data) { + let [group, id, key] = data; + + // add click event listener + // @ts-ignore + label.onclick = onSDLabelClick; + + // store map of key to elements + if (!sd_id_to_elements[key]) { + sd_id_to_elements[key] = []; + } + sd_id_to_elements[key].push(label); + + if (groups.indexOf(group) === -1) { + groups.push(group); + // Check if a specific tab has been selected via URL parameter + const tabParam = new URLSearchParams(window.location.search).get( + group + ); + if (tabParam) { + console.log( + "sphinx-design: Selecting tab id for group '" + + group + + "' from URL parameter: " + + tabParam + ); + window.sessionStorage.setItem(storageKeyPrefix + group, tabParam); + } + } + + // Check is a specific tab has been selected previously + let previousId = window.sessionStorage.getItem( + storageKeyPrefix + group + ); + if (previousId === id) { + // console.log( + // "sphinx-design: Selecting tab from session storage: " + id + // ); + // @ts-ignore + label.previousElementSibling.checked = true; + } + } + } + }); +} + +/** + * Activate other tabs with the same sync id. + * + * @this {HTMLElement} - The element that was clicked. + */ +function onSDLabelClick() { + let data = create_key(this); + if (!data) return; + let [group, id, key] = data; + for (const label of sd_id_to_elements[key]) { + if (label === this) continue; + // @ts-ignore + label.previousElementSibling.checked = true; + } + window.sessionStorage.setItem(storageKeyPrefix + group, id); +} + +document.addEventListener("DOMContentLoaded", ready, false); diff --git a/book/_build/html/_sphinx_design_static/sphinx-design.5ea377869091fd0449014c60fc090103.min.css b/book/_build/html/_sphinx_design_static/sphinx-design.5ea377869091fd0449014c60fc090103.min.css new file mode 100644 index 0000000..a325746 --- /dev/null +++ b/book/_build/html/_sphinx_design_static/sphinx-design.5ea377869091fd0449014c60fc090103.min.css @@ -0,0 +1 @@ +.sd-bg-primary{background-color:var(--sd-color-primary) !important}.sd-bg-text-primary{color:var(--sd-color-primary-text) !important}button.sd-bg-primary:focus,button.sd-bg-primary:hover{background-color:var(--sd-color-primary-highlight) !important}a.sd-bg-primary:focus,a.sd-bg-primary:hover{background-color:var(--sd-color-primary-highlight) !important}.sd-bg-secondary{background-color:var(--sd-color-secondary) !important}.sd-bg-text-secondary{color:var(--sd-color-secondary-text) !important}button.sd-bg-secondary:focus,button.sd-bg-secondary:hover{background-color:var(--sd-color-secondary-highlight) !important}a.sd-bg-secondary:focus,a.sd-bg-secondary:hover{background-color:var(--sd-color-secondary-highlight) !important}.sd-bg-success{background-color:var(--sd-color-success) !important}.sd-bg-text-success{color:var(--sd-color-success-text) !important}button.sd-bg-success:focus,button.sd-bg-success:hover{background-color:var(--sd-color-success-highlight) !important}a.sd-bg-success:focus,a.sd-bg-success:hover{background-color:var(--sd-color-success-highlight) !important}.sd-bg-info{background-color:var(--sd-color-info) !important}.sd-bg-text-info{color:var(--sd-color-info-text) !important}button.sd-bg-info:focus,button.sd-bg-info:hover{background-color:var(--sd-color-info-highlight) !important}a.sd-bg-info:focus,a.sd-bg-info:hover{background-color:var(--sd-color-info-highlight) !important}.sd-bg-warning{background-color:var(--sd-color-warning) !important}.sd-bg-text-warning{color:var(--sd-color-warning-text) !important}button.sd-bg-warning:focus,button.sd-bg-warning:hover{background-color:var(--sd-color-warning-highlight) !important}a.sd-bg-warning:focus,a.sd-bg-warning:hover{background-color:var(--sd-color-warning-highlight) !important}.sd-bg-danger{background-color:var(--sd-color-danger) !important}.sd-bg-text-danger{color:var(--sd-color-danger-text) !important}button.sd-bg-danger:focus,button.sd-bg-danger:hover{background-color:var(--sd-color-danger-highlight) !important}a.sd-bg-danger:focus,a.sd-bg-danger:hover{background-color:var(--sd-color-danger-highlight) !important}.sd-bg-light{background-color:var(--sd-color-light) !important}.sd-bg-text-light{color:var(--sd-color-light-text) !important}button.sd-bg-light:focus,button.sd-bg-light:hover{background-color:var(--sd-color-light-highlight) !important}a.sd-bg-light:focus,a.sd-bg-light:hover{background-color:var(--sd-color-light-highlight) !important}.sd-bg-muted{background-color:var(--sd-color-muted) !important}.sd-bg-text-muted{color:var(--sd-color-muted-text) !important}button.sd-bg-muted:focus,button.sd-bg-muted:hover{background-color:var(--sd-color-muted-highlight) !important}a.sd-bg-muted:focus,a.sd-bg-muted:hover{background-color:var(--sd-color-muted-highlight) !important}.sd-bg-dark{background-color:var(--sd-color-dark) !important}.sd-bg-text-dark{color:var(--sd-color-dark-text) !important}button.sd-bg-dark:focus,button.sd-bg-dark:hover{background-color:var(--sd-color-dark-highlight) !important}a.sd-bg-dark:focus,a.sd-bg-dark:hover{background-color:var(--sd-color-dark-highlight) !important}.sd-bg-black{background-color:var(--sd-color-black) !important}.sd-bg-text-black{color:var(--sd-color-black-text) !important}button.sd-bg-black:focus,button.sd-bg-black:hover{background-color:var(--sd-color-black-highlight) !important}a.sd-bg-black:focus,a.sd-bg-black:hover{background-color:var(--sd-color-black-highlight) !important}.sd-bg-white{background-color:var(--sd-color-white) !important}.sd-bg-text-white{color:var(--sd-color-white-text) !important}button.sd-bg-white:focus,button.sd-bg-white:hover{background-color:var(--sd-color-white-highlight) !important}a.sd-bg-white:focus,a.sd-bg-white:hover{background-color:var(--sd-color-white-highlight) !important}.sd-text-primary,.sd-text-primary>p{color:var(--sd-color-primary) !important}a.sd-text-primary:focus,a.sd-text-primary:hover{color:var(--sd-color-primary-highlight) !important}.sd-text-secondary,.sd-text-secondary>p{color:var(--sd-color-secondary) !important}a.sd-text-secondary:focus,a.sd-text-secondary:hover{color:var(--sd-color-secondary-highlight) !important}.sd-text-success,.sd-text-success>p{color:var(--sd-color-success) !important}a.sd-text-success:focus,a.sd-text-success:hover{color:var(--sd-color-success-highlight) !important}.sd-text-info,.sd-text-info>p{color:var(--sd-color-info) !important}a.sd-text-info:focus,a.sd-text-info:hover{color:var(--sd-color-info-highlight) !important}.sd-text-warning,.sd-text-warning>p{color:var(--sd-color-warning) !important}a.sd-text-warning:focus,a.sd-text-warning:hover{color:var(--sd-color-warning-highlight) !important}.sd-text-danger,.sd-text-danger>p{color:var(--sd-color-danger) !important}a.sd-text-danger:focus,a.sd-text-danger:hover{color:var(--sd-color-danger-highlight) !important}.sd-text-light,.sd-text-light>p{color:var(--sd-color-light) !important}a.sd-text-light:focus,a.sd-text-light:hover{color:var(--sd-color-light-highlight) !important}.sd-text-muted,.sd-text-muted>p{color:var(--sd-color-muted) !important}a.sd-text-muted:focus,a.sd-text-muted:hover{color:var(--sd-color-muted-highlight) !important}.sd-text-dark,.sd-text-dark>p{color:var(--sd-color-dark) !important}a.sd-text-dark:focus,a.sd-text-dark:hover{color:var(--sd-color-dark-highlight) !important}.sd-text-black,.sd-text-black>p{color:var(--sd-color-black) !important}a.sd-text-black:focus,a.sd-text-black:hover{color:var(--sd-color-black-highlight) !important}.sd-text-white,.sd-text-white>p{color:var(--sd-color-white) !important}a.sd-text-white:focus,a.sd-text-white:hover{color:var(--sd-color-white-highlight) !important}.sd-outline-primary{border-color:var(--sd-color-primary) !important;border-style:solid !important;border-width:1px !important}a.sd-outline-primary:focus,a.sd-outline-primary:hover{border-color:var(--sd-color-primary-highlight) !important}.sd-outline-secondary{border-color:var(--sd-color-secondary) !important;border-style:solid !important;border-width:1px !important}a.sd-outline-secondary:focus,a.sd-outline-secondary:hover{border-color:var(--sd-color-secondary-highlight) !important}.sd-outline-success{border-color:var(--sd-color-success) !important;border-style:solid !important;border-width:1px !important}a.sd-outline-success:focus,a.sd-outline-success:hover{border-color:var(--sd-color-success-highlight) !important}.sd-outline-info{border-color:var(--sd-color-info) !important;border-style:solid !important;border-width:1px !important}a.sd-outline-info:focus,a.sd-outline-info:hover{border-color:var(--sd-color-info-highlight) !important}.sd-outline-warning{border-color:var(--sd-color-warning) !important;border-style:solid !important;border-width:1px !important}a.sd-outline-warning:focus,a.sd-outline-warning:hover{border-color:var(--sd-color-warning-highlight) !important}.sd-outline-danger{border-color:var(--sd-color-danger) !important;border-style:solid !important;border-width:1px !important}a.sd-outline-danger:focus,a.sd-outline-danger:hover{border-color:var(--sd-color-danger-highlight) !important}.sd-outline-light{border-color:var(--sd-color-light) !important;border-style:solid !important;border-width:1px !important}a.sd-outline-light:focus,a.sd-outline-light:hover{border-color:var(--sd-color-light-highlight) !important}.sd-outline-muted{border-color:var(--sd-color-muted) !important;border-style:solid !important;border-width:1px !important}a.sd-outline-muted:focus,a.sd-outline-muted:hover{border-color:var(--sd-color-muted-highlight) !important}.sd-outline-dark{border-color:var(--sd-color-dark) !important;border-style:solid !important;border-width:1px !important}a.sd-outline-dark:focus,a.sd-outline-dark:hover{border-color:var(--sd-color-dark-highlight) !important}.sd-outline-black{border-color:var(--sd-color-black) !important;border-style:solid !important;border-width:1px !important}a.sd-outline-black:focus,a.sd-outline-black:hover{border-color:var(--sd-color-black-highlight) !important}.sd-outline-white{border-color:var(--sd-color-white) !important;border-style:solid !important;border-width:1px !important}a.sd-outline-white:focus,a.sd-outline-white:hover{border-color:var(--sd-color-white-highlight) !important}.sd-bg-transparent{background-color:transparent !important}.sd-outline-transparent{border-color:transparent !important}.sd-text-transparent{color:transparent !important}.sd-p-0{padding:0 !important}.sd-pt-0,.sd-py-0{padding-top:0 !important}.sd-pr-0,.sd-px-0{padding-right:0 !important}.sd-pb-0,.sd-py-0{padding-bottom:0 !important}.sd-pl-0,.sd-px-0{padding-left:0 !important}.sd-p-1{padding:.25rem !important}.sd-pt-1,.sd-py-1{padding-top:.25rem !important}.sd-pr-1,.sd-px-1{padding-right:.25rem !important}.sd-pb-1,.sd-py-1{padding-bottom:.25rem !important}.sd-pl-1,.sd-px-1{padding-left:.25rem !important}.sd-p-2{padding:.5rem !important}.sd-pt-2,.sd-py-2{padding-top:.5rem !important}.sd-pr-2,.sd-px-2{padding-right:.5rem !important}.sd-pb-2,.sd-py-2{padding-bottom:.5rem !important}.sd-pl-2,.sd-px-2{padding-left:.5rem !important}.sd-p-3{padding:1rem !important}.sd-pt-3,.sd-py-3{padding-top:1rem !important}.sd-pr-3,.sd-px-3{padding-right:1rem !important}.sd-pb-3,.sd-py-3{padding-bottom:1rem !important}.sd-pl-3,.sd-px-3{padding-left:1rem !important}.sd-p-4{padding:1.5rem !important}.sd-pt-4,.sd-py-4{padding-top:1.5rem !important}.sd-pr-4,.sd-px-4{padding-right:1.5rem !important}.sd-pb-4,.sd-py-4{padding-bottom:1.5rem !important}.sd-pl-4,.sd-px-4{padding-left:1.5rem !important}.sd-p-5{padding:3rem !important}.sd-pt-5,.sd-py-5{padding-top:3rem !important}.sd-pr-5,.sd-px-5{padding-right:3rem !important}.sd-pb-5,.sd-py-5{padding-bottom:3rem !important}.sd-pl-5,.sd-px-5{padding-left:3rem !important}.sd-m-auto{margin:auto !important}.sd-mt-auto,.sd-my-auto{margin-top:auto !important}.sd-mr-auto,.sd-mx-auto{margin-right:auto !important}.sd-mb-auto,.sd-my-auto{margin-bottom:auto !important}.sd-ml-auto,.sd-mx-auto{margin-left:auto !important}.sd-m-0{margin:0 !important}.sd-mt-0,.sd-my-0{margin-top:0 !important}.sd-mr-0,.sd-mx-0{margin-right:0 !important}.sd-mb-0,.sd-my-0{margin-bottom:0 !important}.sd-ml-0,.sd-mx-0{margin-left:0 !important}.sd-m-1{margin:.25rem !important}.sd-mt-1,.sd-my-1{margin-top:.25rem !important}.sd-mr-1,.sd-mx-1{margin-right:.25rem !important}.sd-mb-1,.sd-my-1{margin-bottom:.25rem !important}.sd-ml-1,.sd-mx-1{margin-left:.25rem !important}.sd-m-2{margin:.5rem !important}.sd-mt-2,.sd-my-2{margin-top:.5rem !important}.sd-mr-2,.sd-mx-2{margin-right:.5rem !important}.sd-mb-2,.sd-my-2{margin-bottom:.5rem !important}.sd-ml-2,.sd-mx-2{margin-left:.5rem !important}.sd-m-3{margin:1rem !important}.sd-mt-3,.sd-my-3{margin-top:1rem !important}.sd-mr-3,.sd-mx-3{margin-right:1rem !important}.sd-mb-3,.sd-my-3{margin-bottom:1rem !important}.sd-ml-3,.sd-mx-3{margin-left:1rem !important}.sd-m-4{margin:1.5rem !important}.sd-mt-4,.sd-my-4{margin-top:1.5rem !important}.sd-mr-4,.sd-mx-4{margin-right:1.5rem !important}.sd-mb-4,.sd-my-4{margin-bottom:1.5rem !important}.sd-ml-4,.sd-mx-4{margin-left:1.5rem !important}.sd-m-5{margin:3rem !important}.sd-mt-5,.sd-my-5{margin-top:3rem !important}.sd-mr-5,.sd-mx-5{margin-right:3rem !important}.sd-mb-5,.sd-my-5{margin-bottom:3rem !important}.sd-ml-5,.sd-mx-5{margin-left:3rem !important}.sd-w-25{width:25% !important}.sd-w-50{width:50% !important}.sd-w-75{width:75% !important}.sd-w-100{width:100% !important}.sd-w-auto{width:auto !important}.sd-h-25{height:25% !important}.sd-h-50{height:50% !important}.sd-h-75{height:75% !important}.sd-h-100{height:100% !important}.sd-h-auto{height:auto !important}.sd-d-none{display:none !important}.sd-d-inline{display:inline !important}.sd-d-inline-block{display:inline-block !important}.sd-d-block{display:block !important}.sd-d-grid{display:grid !important}.sd-d-flex-row{display:-ms-flexbox !important;display:flex !important;flex-direction:row !important}.sd-d-flex-column{display:-ms-flexbox !important;display:flex !important;flex-direction:column !important}.sd-d-inline-flex{display:-ms-inline-flexbox !important;display:inline-flex !important}@media(min-width: 576px){.sd-d-sm-none{display:none !important}.sd-d-sm-inline{display:inline !important}.sd-d-sm-inline-block{display:inline-block !important}.sd-d-sm-block{display:block !important}.sd-d-sm-grid{display:grid !important}.sd-d-sm-flex{display:-ms-flexbox !important;display:flex !important}.sd-d-sm-inline-flex{display:-ms-inline-flexbox !important;display:inline-flex !important}}@media(min-width: 768px){.sd-d-md-none{display:none !important}.sd-d-md-inline{display:inline !important}.sd-d-md-inline-block{display:inline-block !important}.sd-d-md-block{display:block !important}.sd-d-md-grid{display:grid !important}.sd-d-md-flex{display:-ms-flexbox !important;display:flex !important}.sd-d-md-inline-flex{display:-ms-inline-flexbox !important;display:inline-flex !important}}@media(min-width: 992px){.sd-d-lg-none{display:none !important}.sd-d-lg-inline{display:inline !important}.sd-d-lg-inline-block{display:inline-block !important}.sd-d-lg-block{display:block !important}.sd-d-lg-grid{display:grid !important}.sd-d-lg-flex{display:-ms-flexbox !important;display:flex !important}.sd-d-lg-inline-flex{display:-ms-inline-flexbox !important;display:inline-flex !important}}@media(min-width: 1200px){.sd-d-xl-none{display:none !important}.sd-d-xl-inline{display:inline !important}.sd-d-xl-inline-block{display:inline-block !important}.sd-d-xl-block{display:block !important}.sd-d-xl-grid{display:grid !important}.sd-d-xl-flex{display:-ms-flexbox !important;display:flex !important}.sd-d-xl-inline-flex{display:-ms-inline-flexbox !important;display:inline-flex !important}}.sd-align-major-start{justify-content:flex-start !important}.sd-align-major-end{justify-content:flex-end !important}.sd-align-major-center{justify-content:center !important}.sd-align-major-justify{justify-content:space-between !important}.sd-align-major-spaced{justify-content:space-evenly !important}.sd-align-minor-start{align-items:flex-start !important}.sd-align-minor-end{align-items:flex-end !important}.sd-align-minor-center{align-items:center !important}.sd-align-minor-stretch{align-items:stretch !important}.sd-text-justify{text-align:justify !important}.sd-text-left{text-align:left !important}.sd-text-right{text-align:right !important}.sd-text-center{text-align:center !important}.sd-font-weight-light{font-weight:300 !important}.sd-font-weight-lighter{font-weight:lighter !important}.sd-font-weight-normal{font-weight:400 !important}.sd-font-weight-bold{font-weight:700 !important}.sd-font-weight-bolder{font-weight:bolder !important}.sd-font-italic{font-style:italic !important}.sd-text-decoration-none{text-decoration:none !important}.sd-text-lowercase{text-transform:lowercase !important}.sd-text-uppercase{text-transform:uppercase !important}.sd-text-capitalize{text-transform:capitalize !important}.sd-text-wrap{white-space:normal !important}.sd-text-nowrap{white-space:nowrap !important}.sd-text-truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sd-fs-1,.sd-fs-1>p{font-size:calc(1.375rem + 1.5vw) !important;line-height:unset !important}.sd-fs-2,.sd-fs-2>p{font-size:calc(1.325rem + 0.9vw) !important;line-height:unset !important}.sd-fs-3,.sd-fs-3>p{font-size:calc(1.3rem + 0.6vw) !important;line-height:unset !important}.sd-fs-4,.sd-fs-4>p{font-size:calc(1.275rem + 0.3vw) !important;line-height:unset !important}.sd-fs-5,.sd-fs-5>p{font-size:1.25rem !important;line-height:unset !important}.sd-fs-6,.sd-fs-6>p{font-size:1rem !important;line-height:unset !important}.sd-border-0{border:0 solid !important}.sd-border-top-0{border-top:0 solid !important}.sd-border-bottom-0{border-bottom:0 solid !important}.sd-border-right-0{border-right:0 solid !important}.sd-border-left-0{border-left:0 solid !important}.sd-border-1{border:1px solid !important}.sd-border-top-1{border-top:1px solid !important}.sd-border-bottom-1{border-bottom:1px solid !important}.sd-border-right-1{border-right:1px solid !important}.sd-border-left-1{border-left:1px solid !important}.sd-border-2{border:2px solid !important}.sd-border-top-2{border-top:2px solid !important}.sd-border-bottom-2{border-bottom:2px solid !important}.sd-border-right-2{border-right:2px solid !important}.sd-border-left-2{border-left:2px solid !important}.sd-border-3{border:3px solid !important}.sd-border-top-3{border-top:3px solid !important}.sd-border-bottom-3{border-bottom:3px solid !important}.sd-border-right-3{border-right:3px solid !important}.sd-border-left-3{border-left:3px solid !important}.sd-border-4{border:4px solid !important}.sd-border-top-4{border-top:4px solid !important}.sd-border-bottom-4{border-bottom:4px solid !important}.sd-border-right-4{border-right:4px solid !important}.sd-border-left-4{border-left:4px solid !important}.sd-border-5{border:5px solid !important}.sd-border-top-5{border-top:5px solid !important}.sd-border-bottom-5{border-bottom:5px solid !important}.sd-border-right-5{border-right:5px solid !important}.sd-border-left-5{border-left:5px solid !important}.sd-rounded-0{border-radius:0 !important}.sd-rounded-1{border-radius:.2rem !important}.sd-rounded-2{border-radius:.3rem !important}.sd-rounded-3{border-radius:.5rem !important}.sd-rounded-pill{border-radius:50rem !important}.sd-rounded-circle{border-radius:50% !important}.shadow-none{box-shadow:none !important}.sd-shadow-sm{box-shadow:0 .125rem .25rem var(--sd-color-shadow) !important}.sd-shadow-md{box-shadow:0 .5rem 1rem var(--sd-color-shadow) !important}.sd-shadow-lg{box-shadow:0 1rem 3rem var(--sd-color-shadow) !important}@keyframes sd-slide-from-left{0%{transform:translateX(-100%)}100%{transform:translateX(0)}}@keyframes sd-slide-from-right{0%{transform:translateX(200%)}100%{transform:translateX(0)}}@keyframes sd-grow100{0%{transform:scale(0);opacity:.5}100%{transform:scale(1);opacity:1}}@keyframes sd-grow50{0%{transform:scale(0.5);opacity:.5}100%{transform:scale(1);opacity:1}}@keyframes sd-grow50-rot20{0%{transform:scale(0.5) rotateZ(-20deg);opacity:.5}75%{transform:scale(1) rotateZ(5deg);opacity:1}95%{transform:scale(1) rotateZ(-1deg);opacity:1}100%{transform:scale(1) rotateZ(0);opacity:1}}.sd-animate-slide-from-left{animation:1s ease-out 0s 1 normal none running sd-slide-from-left}.sd-animate-slide-from-right{animation:1s ease-out 0s 1 normal none running sd-slide-from-right}.sd-animate-grow100{animation:1s ease-out 0s 1 normal none running sd-grow100}.sd-animate-grow50{animation:1s ease-out 0s 1 normal none running sd-grow50}.sd-animate-grow50-rot20{animation:1s ease-out 0s 1 normal none running sd-grow50-rot20}.sd-badge{display:inline-block;padding:.35em .65em;font-size:.75em;font-weight:700;line-height:1;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25rem}.sd-badge:empty{display:none}a.sd-badge{text-decoration:none}.sd-btn .sd-badge{position:relative;top:-1px}.sd-btn{background-color:transparent;border:1px solid transparent;border-radius:.25rem;cursor:pointer;display:inline-block;font-weight:400;font-size:1rem;line-height:1.5;padding:.375rem .75rem;text-align:center;text-decoration:none;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;vertical-align:middle;user-select:none;-moz-user-select:none;-ms-user-select:none;-webkit-user-select:none}.sd-btn:hover{text-decoration:none}@media(prefers-reduced-motion: reduce){.sd-btn{transition:none}}.sd-btn-primary,.sd-btn-outline-primary:hover,.sd-btn-outline-primary:focus{color:var(--sd-color-primary-text) !important;background-color:var(--sd-color-primary) !important;border-color:var(--sd-color-primary) !important;border-width:1px !important;border-style:solid !important}.sd-btn-primary:hover,.sd-btn-primary:focus{color:var(--sd-color-primary-text) !important;background-color:var(--sd-color-primary-highlight) !important;border-color:var(--sd-color-primary-highlight) !important;border-width:1px !important;border-style:solid !important}.sd-btn-outline-primary{color:var(--sd-color-primary) !important;border-color:var(--sd-color-primary) !important;border-width:1px !important;border-style:solid !important}.sd-btn-secondary,.sd-btn-outline-secondary:hover,.sd-btn-outline-secondary:focus{color:var(--sd-color-secondary-text) !important;background-color:var(--sd-color-secondary) !important;border-color:var(--sd-color-secondary) !important;border-width:1px !important;border-style:solid !important}.sd-btn-secondary:hover,.sd-btn-secondary:focus{color:var(--sd-color-secondary-text) !important;background-color:var(--sd-color-secondary-highlight) !important;border-color:var(--sd-color-secondary-highlight) !important;border-width:1px !important;border-style:solid !important}.sd-btn-outline-secondary{color:var(--sd-color-secondary) !important;border-color:var(--sd-color-secondary) !important;border-width:1px !important;border-style:solid !important}.sd-btn-success,.sd-btn-outline-success:hover,.sd-btn-outline-success:focus{color:var(--sd-color-success-text) !important;background-color:var(--sd-color-success) !important;border-color:var(--sd-color-success) !important;border-width:1px !important;border-style:solid !important}.sd-btn-success:hover,.sd-btn-success:focus{color:var(--sd-color-success-text) !important;background-color:var(--sd-color-success-highlight) !important;border-color:var(--sd-color-success-highlight) !important;border-width:1px !important;border-style:solid !important}.sd-btn-outline-success{color:var(--sd-color-success) !important;border-color:var(--sd-color-success) !important;border-width:1px !important;border-style:solid !important}.sd-btn-info,.sd-btn-outline-info:hover,.sd-btn-outline-info:focus{color:var(--sd-color-info-text) !important;background-color:var(--sd-color-info) !important;border-color:var(--sd-color-info) !important;border-width:1px !important;border-style:solid !important}.sd-btn-info:hover,.sd-btn-info:focus{color:var(--sd-color-info-text) !important;background-color:var(--sd-color-info-highlight) !important;border-color:var(--sd-color-info-highlight) !important;border-width:1px !important;border-style:solid !important}.sd-btn-outline-info{color:var(--sd-color-info) !important;border-color:var(--sd-color-info) !important;border-width:1px !important;border-style:solid !important}.sd-btn-warning,.sd-btn-outline-warning:hover,.sd-btn-outline-warning:focus{color:var(--sd-color-warning-text) !important;background-color:var(--sd-color-warning) !important;border-color:var(--sd-color-warning) !important;border-width:1px !important;border-style:solid !important}.sd-btn-warning:hover,.sd-btn-warning:focus{color:var(--sd-color-warning-text) !important;background-color:var(--sd-color-warning-highlight) !important;border-color:var(--sd-color-warning-highlight) !important;border-width:1px !important;border-style:solid !important}.sd-btn-outline-warning{color:var(--sd-color-warning) !important;border-color:var(--sd-color-warning) !important;border-width:1px !important;border-style:solid !important}.sd-btn-danger,.sd-btn-outline-danger:hover,.sd-btn-outline-danger:focus{color:var(--sd-color-danger-text) !important;background-color:var(--sd-color-danger) !important;border-color:var(--sd-color-danger) !important;border-width:1px !important;border-style:solid !important}.sd-btn-danger:hover,.sd-btn-danger:focus{color:var(--sd-color-danger-text) !important;background-color:var(--sd-color-danger-highlight) !important;border-color:var(--sd-color-danger-highlight) !important;border-width:1px !important;border-style:solid !important}.sd-btn-outline-danger{color:var(--sd-color-danger) !important;border-color:var(--sd-color-danger) !important;border-width:1px !important;border-style:solid !important}.sd-btn-light,.sd-btn-outline-light:hover,.sd-btn-outline-light:focus{color:var(--sd-color-light-text) !important;background-color:var(--sd-color-light) !important;border-color:var(--sd-color-light) !important;border-width:1px !important;border-style:solid !important}.sd-btn-light:hover,.sd-btn-light:focus{color:var(--sd-color-light-text) !important;background-color:var(--sd-color-light-highlight) !important;border-color:var(--sd-color-light-highlight) !important;border-width:1px !important;border-style:solid !important}.sd-btn-outline-light{color:var(--sd-color-light) !important;border-color:var(--sd-color-light) !important;border-width:1px !important;border-style:solid !important}.sd-btn-muted,.sd-btn-outline-muted:hover,.sd-btn-outline-muted:focus{color:var(--sd-color-muted-text) !important;background-color:var(--sd-color-muted) !important;border-color:var(--sd-color-muted) !important;border-width:1px !important;border-style:solid !important}.sd-btn-muted:hover,.sd-btn-muted:focus{color:var(--sd-color-muted-text) !important;background-color:var(--sd-color-muted-highlight) !important;border-color:var(--sd-color-muted-highlight) !important;border-width:1px !important;border-style:solid !important}.sd-btn-outline-muted{color:var(--sd-color-muted) !important;border-color:var(--sd-color-muted) !important;border-width:1px !important;border-style:solid !important}.sd-btn-dark,.sd-btn-outline-dark:hover,.sd-btn-outline-dark:focus{color:var(--sd-color-dark-text) !important;background-color:var(--sd-color-dark) !important;border-color:var(--sd-color-dark) !important;border-width:1px !important;border-style:solid !important}.sd-btn-dark:hover,.sd-btn-dark:focus{color:var(--sd-color-dark-text) !important;background-color:var(--sd-color-dark-highlight) !important;border-color:var(--sd-color-dark-highlight) !important;border-width:1px !important;border-style:solid !important}.sd-btn-outline-dark{color:var(--sd-color-dark) !important;border-color:var(--sd-color-dark) !important;border-width:1px !important;border-style:solid !important}.sd-btn-black,.sd-btn-outline-black:hover,.sd-btn-outline-black:focus{color:var(--sd-color-black-text) !important;background-color:var(--sd-color-black) !important;border-color:var(--sd-color-black) !important;border-width:1px !important;border-style:solid !important}.sd-btn-black:hover,.sd-btn-black:focus{color:var(--sd-color-black-text) !important;background-color:var(--sd-color-black-highlight) !important;border-color:var(--sd-color-black-highlight) !important;border-width:1px !important;border-style:solid !important}.sd-btn-outline-black{color:var(--sd-color-black) !important;border-color:var(--sd-color-black) !important;border-width:1px !important;border-style:solid !important}.sd-btn-white,.sd-btn-outline-white:hover,.sd-btn-outline-white:focus{color:var(--sd-color-white-text) !important;background-color:var(--sd-color-white) !important;border-color:var(--sd-color-white) !important;border-width:1px !important;border-style:solid !important}.sd-btn-white:hover,.sd-btn-white:focus{color:var(--sd-color-white-text) !important;background-color:var(--sd-color-white-highlight) !important;border-color:var(--sd-color-white-highlight) !important;border-width:1px !important;border-style:solid !important}.sd-btn-outline-white{color:var(--sd-color-white) !important;border-color:var(--sd-color-white) !important;border-width:1px !important;border-style:solid !important}.sd-stretched-link::after{position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;content:""}.sd-hide-link-text{font-size:0}.sd-octicon,.sd-material-icon{display:inline-block;fill:currentColor;vertical-align:middle}.sd-avatar-xs{border-radius:50%;object-fit:cover;object-position:center;width:1rem;height:1rem}.sd-avatar-sm{border-radius:50%;object-fit:cover;object-position:center;width:3rem;height:3rem}.sd-avatar-md{border-radius:50%;object-fit:cover;object-position:center;width:5rem;height:5rem}.sd-avatar-lg{border-radius:50%;object-fit:cover;object-position:center;width:7rem;height:7rem}.sd-avatar-xl{border-radius:50%;object-fit:cover;object-position:center;width:10rem;height:10rem}.sd-avatar-inherit{border-radius:50%;object-fit:cover;object-position:center;width:inherit;height:inherit}.sd-avatar-initial{border-radius:50%;object-fit:cover;object-position:center;width:initial;height:initial}.sd-card{background-clip:border-box;background-color:var(--sd-color-card-background);border:1px solid var(--sd-color-card-border);border-radius:.25rem;color:var(--sd-color-card-text);display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;min-width:0;position:relative;word-wrap:break-word}.sd-card>hr{margin-left:0;margin-right:0}.sd-card-hover:hover{border-color:var(--sd-color-card-border-hover);transform:scale(1.01)}.sd-card-body{-ms-flex:1 1 auto;flex:1 1 auto;padding:1rem 1rem}.sd-card-title{margin-bottom:.5rem}.sd-card-subtitle{margin-top:-0.25rem;margin-bottom:0}.sd-card-text:last-child{margin-bottom:0}.sd-card-link:hover{text-decoration:none}.sd-card-link+.card-link{margin-left:1rem}.sd-card-header{padding:.5rem 1rem;margin-bottom:0;background-color:var(--sd-color-card-header);border-bottom:1px solid var(--sd-color-card-border)}.sd-card-header:first-child{border-radius:calc(0.25rem - 1px) calc(0.25rem - 1px) 0 0}.sd-card-footer{padding:.5rem 1rem;background-color:var(--sd-color-card-footer);border-top:1px solid var(--sd-color-card-border)}.sd-card-footer:last-child{border-radius:0 0 calc(0.25rem - 1px) calc(0.25rem - 1px)}.sd-card-header-tabs{margin-right:-0.5rem;margin-bottom:-0.5rem;margin-left:-0.5rem;border-bottom:0}.sd-card-header-pills{margin-right:-0.5rem;margin-left:-0.5rem}.sd-card-img-overlay{position:absolute;top:0;right:0;bottom:0;left:0;padding:1rem;border-radius:calc(0.25rem - 1px)}.sd-card-img,.sd-card-img-bottom,.sd-card-img-top{width:100%}.sd-card-img,.sd-card-img-top{border-top-left-radius:calc(0.25rem - 1px);border-top-right-radius:calc(0.25rem - 1px)}.sd-card-img,.sd-card-img-bottom{border-bottom-left-radius:calc(0.25rem - 1px);border-bottom-right-radius:calc(0.25rem - 1px)}.sd-cards-carousel{width:100%;display:flex;flex-wrap:nowrap;-ms-flex-direction:row;flex-direction:row;overflow-x:hidden;scroll-snap-type:x mandatory}.sd-cards-carousel.sd-show-scrollbar{overflow-x:auto}.sd-cards-carousel:hover,.sd-cards-carousel:focus{overflow-x:auto}.sd-cards-carousel>.sd-card{flex-shrink:0;scroll-snap-align:start}.sd-cards-carousel>.sd-card:not(:last-child){margin-right:3px}.sd-card-cols-1>.sd-card{width:90%}.sd-card-cols-2>.sd-card{width:45%}.sd-card-cols-3>.sd-card{width:30%}.sd-card-cols-4>.sd-card{width:22.5%}.sd-card-cols-5>.sd-card{width:18%}.sd-card-cols-6>.sd-card{width:15%}.sd-card-cols-7>.sd-card{width:12.8571428571%}.sd-card-cols-8>.sd-card{width:11.25%}.sd-card-cols-9>.sd-card{width:10%}.sd-card-cols-10>.sd-card{width:9%}.sd-card-cols-11>.sd-card{width:8.1818181818%}.sd-card-cols-12>.sd-card{width:7.5%}.sd-container,.sd-container-fluid,.sd-container-lg,.sd-container-md,.sd-container-sm,.sd-container-xl{margin-left:auto;margin-right:auto;padding-left:var(--sd-gutter-x, 0.75rem);padding-right:var(--sd-gutter-x, 0.75rem);width:100%}@media(min-width: 576px){.sd-container-sm,.sd-container{max-width:540px}}@media(min-width: 768px){.sd-container-md,.sd-container-sm,.sd-container{max-width:720px}}@media(min-width: 992px){.sd-container-lg,.sd-container-md,.sd-container-sm,.sd-container{max-width:960px}}@media(min-width: 1200px){.sd-container-xl,.sd-container-lg,.sd-container-md,.sd-container-sm,.sd-container{max-width:1140px}}.sd-row{--sd-gutter-x: 1.5rem;--sd-gutter-y: 0;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;margin-top:calc(var(--sd-gutter-y) * -1);margin-right:calc(var(--sd-gutter-x) * -0.5);margin-left:calc(var(--sd-gutter-x) * -0.5)}.sd-row>*{box-sizing:border-box;flex-shrink:0;width:100%;max-width:100%;padding-right:calc(var(--sd-gutter-x) * 0.5);padding-left:calc(var(--sd-gutter-x) * 0.5);margin-top:var(--sd-gutter-y)}.sd-col{flex:1 0 0%;-ms-flex:1 0 0%}.sd-row-cols-auto>*{flex:0 0 auto;width:auto}.sd-row-cols-1>*{flex:0 0 auto;-ms-flex:0 0 auto;width:100%}.sd-row-cols-2>*{flex:0 0 auto;-ms-flex:0 0 auto;width:50%}.sd-row-cols-3>*{flex:0 0 auto;-ms-flex:0 0 auto;width:33.3333333333%}.sd-row-cols-4>*{flex:0 0 auto;-ms-flex:0 0 auto;width:25%}.sd-row-cols-5>*{flex:0 0 auto;-ms-flex:0 0 auto;width:20%}.sd-row-cols-6>*{flex:0 0 auto;-ms-flex:0 0 auto;width:16.6666666667%}.sd-row-cols-7>*{flex:0 0 auto;-ms-flex:0 0 auto;width:14.2857142857%}.sd-row-cols-8>*{flex:0 0 auto;-ms-flex:0 0 auto;width:12.5%}.sd-row-cols-9>*{flex:0 0 auto;-ms-flex:0 0 auto;width:11.1111111111%}.sd-row-cols-10>*{flex:0 0 auto;-ms-flex:0 0 auto;width:10%}.sd-row-cols-11>*{flex:0 0 auto;-ms-flex:0 0 auto;width:9.0909090909%}.sd-row-cols-12>*{flex:0 0 auto;-ms-flex:0 0 auto;width:8.3333333333%}@media(min-width: 576px){.sd-col-sm{flex:1 0 0%;-ms-flex:1 0 0%}.sd-row-cols-sm-auto{flex:1 0 auto;-ms-flex:1 0 auto;width:100%}.sd-row-cols-sm-1>*{flex:0 0 auto;-ms-flex:0 0 auto;width:100%}.sd-row-cols-sm-2>*{flex:0 0 auto;-ms-flex:0 0 auto;width:50%}.sd-row-cols-sm-3>*{flex:0 0 auto;-ms-flex:0 0 auto;width:33.3333333333%}.sd-row-cols-sm-4>*{flex:0 0 auto;-ms-flex:0 0 auto;width:25%}.sd-row-cols-sm-5>*{flex:0 0 auto;-ms-flex:0 0 auto;width:20%}.sd-row-cols-sm-6>*{flex:0 0 auto;-ms-flex:0 0 auto;width:16.6666666667%}.sd-row-cols-sm-7>*{flex:0 0 auto;-ms-flex:0 0 auto;width:14.2857142857%}.sd-row-cols-sm-8>*{flex:0 0 auto;-ms-flex:0 0 auto;width:12.5%}.sd-row-cols-sm-9>*{flex:0 0 auto;-ms-flex:0 0 auto;width:11.1111111111%}.sd-row-cols-sm-10>*{flex:0 0 auto;-ms-flex:0 0 auto;width:10%}.sd-row-cols-sm-11>*{flex:0 0 auto;-ms-flex:0 0 auto;width:9.0909090909%}.sd-row-cols-sm-12>*{flex:0 0 auto;-ms-flex:0 0 auto;width:8.3333333333%}}@media(min-width: 768px){.sd-col-md{flex:1 0 0%;-ms-flex:1 0 0%}.sd-row-cols-md-auto{flex:1 0 auto;-ms-flex:1 0 auto;width:100%}.sd-row-cols-md-1>*{flex:0 0 auto;-ms-flex:0 0 auto;width:100%}.sd-row-cols-md-2>*{flex:0 0 auto;-ms-flex:0 0 auto;width:50%}.sd-row-cols-md-3>*{flex:0 0 auto;-ms-flex:0 0 auto;width:33.3333333333%}.sd-row-cols-md-4>*{flex:0 0 auto;-ms-flex:0 0 auto;width:25%}.sd-row-cols-md-5>*{flex:0 0 auto;-ms-flex:0 0 auto;width:20%}.sd-row-cols-md-6>*{flex:0 0 auto;-ms-flex:0 0 auto;width:16.6666666667%}.sd-row-cols-md-7>*{flex:0 0 auto;-ms-flex:0 0 auto;width:14.2857142857%}.sd-row-cols-md-8>*{flex:0 0 auto;-ms-flex:0 0 auto;width:12.5%}.sd-row-cols-md-9>*{flex:0 0 auto;-ms-flex:0 0 auto;width:11.1111111111%}.sd-row-cols-md-10>*{flex:0 0 auto;-ms-flex:0 0 auto;width:10%}.sd-row-cols-md-11>*{flex:0 0 auto;-ms-flex:0 0 auto;width:9.0909090909%}.sd-row-cols-md-12>*{flex:0 0 auto;-ms-flex:0 0 auto;width:8.3333333333%}}@media(min-width: 992px){.sd-col-lg{flex:1 0 0%;-ms-flex:1 0 0%}.sd-row-cols-lg-auto{flex:1 0 auto;-ms-flex:1 0 auto;width:100%}.sd-row-cols-lg-1>*{flex:0 0 auto;-ms-flex:0 0 auto;width:100%}.sd-row-cols-lg-2>*{flex:0 0 auto;-ms-flex:0 0 auto;width:50%}.sd-row-cols-lg-3>*{flex:0 0 auto;-ms-flex:0 0 auto;width:33.3333333333%}.sd-row-cols-lg-4>*{flex:0 0 auto;-ms-flex:0 0 auto;width:25%}.sd-row-cols-lg-5>*{flex:0 0 auto;-ms-flex:0 0 auto;width:20%}.sd-row-cols-lg-6>*{flex:0 0 auto;-ms-flex:0 0 auto;width:16.6666666667%}.sd-row-cols-lg-7>*{flex:0 0 auto;-ms-flex:0 0 auto;width:14.2857142857%}.sd-row-cols-lg-8>*{flex:0 0 auto;-ms-flex:0 0 auto;width:12.5%}.sd-row-cols-lg-9>*{flex:0 0 auto;-ms-flex:0 0 auto;width:11.1111111111%}.sd-row-cols-lg-10>*{flex:0 0 auto;-ms-flex:0 0 auto;width:10%}.sd-row-cols-lg-11>*{flex:0 0 auto;-ms-flex:0 0 auto;width:9.0909090909%}.sd-row-cols-lg-12>*{flex:0 0 auto;-ms-flex:0 0 auto;width:8.3333333333%}}@media(min-width: 1200px){.sd-col-xl{flex:1 0 0%;-ms-flex:1 0 0%}.sd-row-cols-xl-auto{flex:1 0 auto;-ms-flex:1 0 auto;width:100%}.sd-row-cols-xl-1>*{flex:0 0 auto;-ms-flex:0 0 auto;width:100%}.sd-row-cols-xl-2>*{flex:0 0 auto;-ms-flex:0 0 auto;width:50%}.sd-row-cols-xl-3>*{flex:0 0 auto;-ms-flex:0 0 auto;width:33.3333333333%}.sd-row-cols-xl-4>*{flex:0 0 auto;-ms-flex:0 0 auto;width:25%}.sd-row-cols-xl-5>*{flex:0 0 auto;-ms-flex:0 0 auto;width:20%}.sd-row-cols-xl-6>*{flex:0 0 auto;-ms-flex:0 0 auto;width:16.6666666667%}.sd-row-cols-xl-7>*{flex:0 0 auto;-ms-flex:0 0 auto;width:14.2857142857%}.sd-row-cols-xl-8>*{flex:0 0 auto;-ms-flex:0 0 auto;width:12.5%}.sd-row-cols-xl-9>*{flex:0 0 auto;-ms-flex:0 0 auto;width:11.1111111111%}.sd-row-cols-xl-10>*{flex:0 0 auto;-ms-flex:0 0 auto;width:10%}.sd-row-cols-xl-11>*{flex:0 0 auto;-ms-flex:0 0 auto;width:9.0909090909%}.sd-row-cols-xl-12>*{flex:0 0 auto;-ms-flex:0 0 auto;width:8.3333333333%}}.sd-col-auto{flex:0 0 auto;-ms-flex:0 0 auto;width:auto}.sd-col-1{flex:0 0 auto;-ms-flex:0 0 auto;width:8.3333333333%}.sd-col-2{flex:0 0 auto;-ms-flex:0 0 auto;width:16.6666666667%}.sd-col-3{flex:0 0 auto;-ms-flex:0 0 auto;width:25%}.sd-col-4{flex:0 0 auto;-ms-flex:0 0 auto;width:33.3333333333%}.sd-col-5{flex:0 0 auto;-ms-flex:0 0 auto;width:41.6666666667%}.sd-col-6{flex:0 0 auto;-ms-flex:0 0 auto;width:50%}.sd-col-7{flex:0 0 auto;-ms-flex:0 0 auto;width:58.3333333333%}.sd-col-8{flex:0 0 auto;-ms-flex:0 0 auto;width:66.6666666667%}.sd-col-9{flex:0 0 auto;-ms-flex:0 0 auto;width:75%}.sd-col-10{flex:0 0 auto;-ms-flex:0 0 auto;width:83.3333333333%}.sd-col-11{flex:0 0 auto;-ms-flex:0 0 auto;width:91.6666666667%}.sd-col-12{flex:0 0 auto;-ms-flex:0 0 auto;width:100%}.sd-g-0,.sd-gy-0{--sd-gutter-y: 0}.sd-g-0,.sd-gx-0{--sd-gutter-x: 0}.sd-g-1,.sd-gy-1{--sd-gutter-y: 0.25rem}.sd-g-1,.sd-gx-1{--sd-gutter-x: 0.25rem}.sd-g-2,.sd-gy-2{--sd-gutter-y: 0.5rem}.sd-g-2,.sd-gx-2{--sd-gutter-x: 0.5rem}.sd-g-3,.sd-gy-3{--sd-gutter-y: 1rem}.sd-g-3,.sd-gx-3{--sd-gutter-x: 1rem}.sd-g-4,.sd-gy-4{--sd-gutter-y: 1.5rem}.sd-g-4,.sd-gx-4{--sd-gutter-x: 1.5rem}.sd-g-5,.sd-gy-5{--sd-gutter-y: 3rem}.sd-g-5,.sd-gx-5{--sd-gutter-x: 3rem}@media(min-width: 576px){.sd-col-sm-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto}.sd-col-sm-1{-ms-flex:0 0 auto;flex:0 0 auto;width:8.3333333333%}.sd-col-sm-2{-ms-flex:0 0 auto;flex:0 0 auto;width:16.6666666667%}.sd-col-sm-3{-ms-flex:0 0 auto;flex:0 0 auto;width:25%}.sd-col-sm-4{-ms-flex:0 0 auto;flex:0 0 auto;width:33.3333333333%}.sd-col-sm-5{-ms-flex:0 0 auto;flex:0 0 auto;width:41.6666666667%}.sd-col-sm-6{-ms-flex:0 0 auto;flex:0 0 auto;width:50%}.sd-col-sm-7{-ms-flex:0 0 auto;flex:0 0 auto;width:58.3333333333%}.sd-col-sm-8{-ms-flex:0 0 auto;flex:0 0 auto;width:66.6666666667%}.sd-col-sm-9{-ms-flex:0 0 auto;flex:0 0 auto;width:75%}.sd-col-sm-10{-ms-flex:0 0 auto;flex:0 0 auto;width:83.3333333333%}.sd-col-sm-11{-ms-flex:0 0 auto;flex:0 0 auto;width:91.6666666667%}.sd-col-sm-12{-ms-flex:0 0 auto;flex:0 0 auto;width:100%}.sd-g-sm-0,.sd-gy-sm-0{--sd-gutter-y: 0}.sd-g-sm-0,.sd-gx-sm-0{--sd-gutter-x: 0}.sd-g-sm-1,.sd-gy-sm-1{--sd-gutter-y: 0.25rem}.sd-g-sm-1,.sd-gx-sm-1{--sd-gutter-x: 0.25rem}.sd-g-sm-2,.sd-gy-sm-2{--sd-gutter-y: 0.5rem}.sd-g-sm-2,.sd-gx-sm-2{--sd-gutter-x: 0.5rem}.sd-g-sm-3,.sd-gy-sm-3{--sd-gutter-y: 1rem}.sd-g-sm-3,.sd-gx-sm-3{--sd-gutter-x: 1rem}.sd-g-sm-4,.sd-gy-sm-4{--sd-gutter-y: 1.5rem}.sd-g-sm-4,.sd-gx-sm-4{--sd-gutter-x: 1.5rem}.sd-g-sm-5,.sd-gy-sm-5{--sd-gutter-y: 3rem}.sd-g-sm-5,.sd-gx-sm-5{--sd-gutter-x: 3rem}}@media(min-width: 768px){.sd-col-md-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto}.sd-col-md-1{-ms-flex:0 0 auto;flex:0 0 auto;width:8.3333333333%}.sd-col-md-2{-ms-flex:0 0 auto;flex:0 0 auto;width:16.6666666667%}.sd-col-md-3{-ms-flex:0 0 auto;flex:0 0 auto;width:25%}.sd-col-md-4{-ms-flex:0 0 auto;flex:0 0 auto;width:33.3333333333%}.sd-col-md-5{-ms-flex:0 0 auto;flex:0 0 auto;width:41.6666666667%}.sd-col-md-6{-ms-flex:0 0 auto;flex:0 0 auto;width:50%}.sd-col-md-7{-ms-flex:0 0 auto;flex:0 0 auto;width:58.3333333333%}.sd-col-md-8{-ms-flex:0 0 auto;flex:0 0 auto;width:66.6666666667%}.sd-col-md-9{-ms-flex:0 0 auto;flex:0 0 auto;width:75%}.sd-col-md-10{-ms-flex:0 0 auto;flex:0 0 auto;width:83.3333333333%}.sd-col-md-11{-ms-flex:0 0 auto;flex:0 0 auto;width:91.6666666667%}.sd-col-md-12{-ms-flex:0 0 auto;flex:0 0 auto;width:100%}.sd-g-md-0,.sd-gy-md-0{--sd-gutter-y: 0}.sd-g-md-0,.sd-gx-md-0{--sd-gutter-x: 0}.sd-g-md-1,.sd-gy-md-1{--sd-gutter-y: 0.25rem}.sd-g-md-1,.sd-gx-md-1{--sd-gutter-x: 0.25rem}.sd-g-md-2,.sd-gy-md-2{--sd-gutter-y: 0.5rem}.sd-g-md-2,.sd-gx-md-2{--sd-gutter-x: 0.5rem}.sd-g-md-3,.sd-gy-md-3{--sd-gutter-y: 1rem}.sd-g-md-3,.sd-gx-md-3{--sd-gutter-x: 1rem}.sd-g-md-4,.sd-gy-md-4{--sd-gutter-y: 1.5rem}.sd-g-md-4,.sd-gx-md-4{--sd-gutter-x: 1.5rem}.sd-g-md-5,.sd-gy-md-5{--sd-gutter-y: 3rem}.sd-g-md-5,.sd-gx-md-5{--sd-gutter-x: 3rem}}@media(min-width: 992px){.sd-col-lg-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto}.sd-col-lg-1{-ms-flex:0 0 auto;flex:0 0 auto;width:8.3333333333%}.sd-col-lg-2{-ms-flex:0 0 auto;flex:0 0 auto;width:16.6666666667%}.sd-col-lg-3{-ms-flex:0 0 auto;flex:0 0 auto;width:25%}.sd-col-lg-4{-ms-flex:0 0 auto;flex:0 0 auto;width:33.3333333333%}.sd-col-lg-5{-ms-flex:0 0 auto;flex:0 0 auto;width:41.6666666667%}.sd-col-lg-6{-ms-flex:0 0 auto;flex:0 0 auto;width:50%}.sd-col-lg-7{-ms-flex:0 0 auto;flex:0 0 auto;width:58.3333333333%}.sd-col-lg-8{-ms-flex:0 0 auto;flex:0 0 auto;width:66.6666666667%}.sd-col-lg-9{-ms-flex:0 0 auto;flex:0 0 auto;width:75%}.sd-col-lg-10{-ms-flex:0 0 auto;flex:0 0 auto;width:83.3333333333%}.sd-col-lg-11{-ms-flex:0 0 auto;flex:0 0 auto;width:91.6666666667%}.sd-col-lg-12{-ms-flex:0 0 auto;flex:0 0 auto;width:100%}.sd-g-lg-0,.sd-gy-lg-0{--sd-gutter-y: 0}.sd-g-lg-0,.sd-gx-lg-0{--sd-gutter-x: 0}.sd-g-lg-1,.sd-gy-lg-1{--sd-gutter-y: 0.25rem}.sd-g-lg-1,.sd-gx-lg-1{--sd-gutter-x: 0.25rem}.sd-g-lg-2,.sd-gy-lg-2{--sd-gutter-y: 0.5rem}.sd-g-lg-2,.sd-gx-lg-2{--sd-gutter-x: 0.5rem}.sd-g-lg-3,.sd-gy-lg-3{--sd-gutter-y: 1rem}.sd-g-lg-3,.sd-gx-lg-3{--sd-gutter-x: 1rem}.sd-g-lg-4,.sd-gy-lg-4{--sd-gutter-y: 1.5rem}.sd-g-lg-4,.sd-gx-lg-4{--sd-gutter-x: 1.5rem}.sd-g-lg-5,.sd-gy-lg-5{--sd-gutter-y: 3rem}.sd-g-lg-5,.sd-gx-lg-5{--sd-gutter-x: 3rem}}@media(min-width: 1200px){.sd-col-xl-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto}.sd-col-xl-1{-ms-flex:0 0 auto;flex:0 0 auto;width:8.3333333333%}.sd-col-xl-2{-ms-flex:0 0 auto;flex:0 0 auto;width:16.6666666667%}.sd-col-xl-3{-ms-flex:0 0 auto;flex:0 0 auto;width:25%}.sd-col-xl-4{-ms-flex:0 0 auto;flex:0 0 auto;width:33.3333333333%}.sd-col-xl-5{-ms-flex:0 0 auto;flex:0 0 auto;width:41.6666666667%}.sd-col-xl-6{-ms-flex:0 0 auto;flex:0 0 auto;width:50%}.sd-col-xl-7{-ms-flex:0 0 auto;flex:0 0 auto;width:58.3333333333%}.sd-col-xl-8{-ms-flex:0 0 auto;flex:0 0 auto;width:66.6666666667%}.sd-col-xl-9{-ms-flex:0 0 auto;flex:0 0 auto;width:75%}.sd-col-xl-10{-ms-flex:0 0 auto;flex:0 0 auto;width:83.3333333333%}.sd-col-xl-11{-ms-flex:0 0 auto;flex:0 0 auto;width:91.6666666667%}.sd-col-xl-12{-ms-flex:0 0 auto;flex:0 0 auto;width:100%}.sd-g-xl-0,.sd-gy-xl-0{--sd-gutter-y: 0}.sd-g-xl-0,.sd-gx-xl-0{--sd-gutter-x: 0}.sd-g-xl-1,.sd-gy-xl-1{--sd-gutter-y: 0.25rem}.sd-g-xl-1,.sd-gx-xl-1{--sd-gutter-x: 0.25rem}.sd-g-xl-2,.sd-gy-xl-2{--sd-gutter-y: 0.5rem}.sd-g-xl-2,.sd-gx-xl-2{--sd-gutter-x: 0.5rem}.sd-g-xl-3,.sd-gy-xl-3{--sd-gutter-y: 1rem}.sd-g-xl-3,.sd-gx-xl-3{--sd-gutter-x: 1rem}.sd-g-xl-4,.sd-gy-xl-4{--sd-gutter-y: 1.5rem}.sd-g-xl-4,.sd-gx-xl-4{--sd-gutter-x: 1.5rem}.sd-g-xl-5,.sd-gy-xl-5{--sd-gutter-y: 3rem}.sd-g-xl-5,.sd-gx-xl-5{--sd-gutter-x: 3rem}}.sd-flex-row-reverse{flex-direction:row-reverse !important}details.sd-dropdown{position:relative;font-size:var(--sd-fontsize-dropdown)}details.sd-dropdown:hover{cursor:pointer}details.sd-dropdown .sd-summary-content{cursor:default}details.sd-dropdown summary.sd-summary-title{padding:.5em 1em;font-size:var(--sd-fontsize-dropdown-title);font-weight:var(--sd-fontweight-dropdown-title);user-select:none;-moz-user-select:none;-ms-user-select:none;-webkit-user-select:none;list-style:none;display:inline-flex;justify-content:space-between}details.sd-dropdown summary.sd-summary-title::-webkit-details-marker{display:none}details.sd-dropdown summary.sd-summary-title:focus{outline:none}details.sd-dropdown summary.sd-summary-title .sd-summary-icon{margin-right:.6em;display:inline-flex;align-items:center}details.sd-dropdown summary.sd-summary-title .sd-summary-icon svg{opacity:.8}details.sd-dropdown summary.sd-summary-title .sd-summary-text{flex-grow:1;line-height:1.5;padding-right:.5rem}details.sd-dropdown summary.sd-summary-title .sd-summary-state-marker{pointer-events:none;display:inline-flex;align-items:center}details.sd-dropdown summary.sd-summary-title .sd-summary-state-marker svg{opacity:.6}details.sd-dropdown summary.sd-summary-title:hover .sd-summary-state-marker svg{opacity:1;transform:scale(1.1)}details.sd-dropdown[open] summary .sd-octicon.no-title{visibility:hidden}details.sd-dropdown .sd-summary-chevron-right{transition:.25s}details.sd-dropdown[open]>.sd-summary-title .sd-summary-chevron-right{transform:rotate(90deg)}details.sd-dropdown[open]>.sd-summary-title .sd-summary-chevron-down{transform:rotate(180deg)}details.sd-dropdown:not([open]).sd-card{border:none}details.sd-dropdown:not([open])>.sd-card-header{border:1px solid var(--sd-color-card-border);border-radius:.25rem}details.sd-dropdown.sd-fade-in[open] summary~*{-moz-animation:sd-fade-in .5s ease-in-out;-webkit-animation:sd-fade-in .5s ease-in-out;animation:sd-fade-in .5s ease-in-out}details.sd-dropdown.sd-fade-in-slide-down[open] summary~*{-moz-animation:sd-fade-in .5s ease-in-out,sd-slide-down .5s ease-in-out;-webkit-animation:sd-fade-in .5s ease-in-out,sd-slide-down .5s ease-in-out;animation:sd-fade-in .5s ease-in-out,sd-slide-down .5s ease-in-out}.sd-col>.sd-dropdown{width:100%}.sd-summary-content>.sd-tab-set:first-child{margin-top:0}@keyframes sd-fade-in{0%{opacity:0}100%{opacity:1}}@keyframes sd-slide-down{0%{transform:translate(0, -10px)}100%{transform:translate(0, 0)}}.sd-tab-set{border-radius:.125rem;display:flex;flex-wrap:wrap;margin:1em 0;position:relative}.sd-tab-set>input{opacity:0;position:absolute}.sd-tab-set>input:checked+label{border-color:var(--sd-color-tabs-underline-active);color:var(--sd-color-tabs-label-active)}.sd-tab-set>input:checked+label+.sd-tab-content{display:block}.sd-tab-set>input:not(:checked)+label:hover{color:var(--sd-color-tabs-label-hover);border-color:var(--sd-color-tabs-underline-hover)}.sd-tab-set>input:focus+label{outline-style:auto}.sd-tab-set>input:not(.focus-visible)+label{outline:none;-webkit-tap-highlight-color:transparent}.sd-tab-set>label{border-bottom:.125rem solid transparent;margin-bottom:0;color:var(--sd-color-tabs-label-inactive);border-color:var(--sd-color-tabs-underline-inactive);cursor:pointer;font-size:var(--sd-fontsize-tabs-label);font-weight:700;padding:1em 1.25em .5em;transition:color 250ms;width:auto;z-index:1}html .sd-tab-set>label:hover{color:var(--sd-color-tabs-label-active)}.sd-col>.sd-tab-set{width:100%}.sd-tab-content{box-shadow:0 -0.0625rem var(--sd-color-tabs-overline),0 .0625rem var(--sd-color-tabs-underline);display:none;order:99;padding-bottom:.75rem;padding-top:.75rem;width:100%}.sd-tab-content>:first-child{margin-top:0 !important}.sd-tab-content>:last-child{margin-bottom:0 !important}.sd-tab-content>.sd-tab-set{margin:0}.sd-sphinx-override,.sd-sphinx-override *{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}.sd-sphinx-override p{margin-top:0}:root{--sd-color-primary: #0071bc;--sd-color-secondary: #6c757d;--sd-color-success: #28a745;--sd-color-info: #17a2b8;--sd-color-warning: #f0b37e;--sd-color-danger: #dc3545;--sd-color-light: #f8f9fa;--sd-color-muted: #6c757d;--sd-color-dark: #212529;--sd-color-black: black;--sd-color-white: white;--sd-color-primary-highlight: #0060a0;--sd-color-secondary-highlight: #5c636a;--sd-color-success-highlight: #228e3b;--sd-color-info-highlight: #148a9c;--sd-color-warning-highlight: #cc986b;--sd-color-danger-highlight: #bb2d3b;--sd-color-light-highlight: #d3d4d5;--sd-color-muted-highlight: #5c636a;--sd-color-dark-highlight: #1c1f23;--sd-color-black-highlight: black;--sd-color-white-highlight: #d9d9d9;--sd-color-primary-bg: rgba(0, 113, 188, 0.2);--sd-color-secondary-bg: rgba(108, 117, 125, 0.2);--sd-color-success-bg: rgba(40, 167, 69, 0.2);--sd-color-info-bg: rgba(23, 162, 184, 0.2);--sd-color-warning-bg: rgba(240, 179, 126, 0.2);--sd-color-danger-bg: rgba(220, 53, 69, 0.2);--sd-color-light-bg: rgba(248, 249, 250, 0.2);--sd-color-muted-bg: rgba(108, 117, 125, 0.2);--sd-color-dark-bg: rgba(33, 37, 41, 0.2);--sd-color-black-bg: rgba(0, 0, 0, 0.2);--sd-color-white-bg: rgba(255, 255, 255, 0.2);--sd-color-primary-text: #fff;--sd-color-secondary-text: #fff;--sd-color-success-text: #fff;--sd-color-info-text: #fff;--sd-color-warning-text: #212529;--sd-color-danger-text: #fff;--sd-color-light-text: #212529;--sd-color-muted-text: #fff;--sd-color-dark-text: #fff;--sd-color-black-text: #fff;--sd-color-white-text: #212529;--sd-color-shadow: rgba(0, 0, 0, 0.15);--sd-color-card-border: rgba(0, 0, 0, 0.125);--sd-color-card-border-hover: hsla(231, 99%, 66%, 1);--sd-color-card-background: transparent;--sd-color-card-text: inherit;--sd-color-card-header: transparent;--sd-color-card-footer: transparent;--sd-color-tabs-label-active: hsla(231, 99%, 66%, 1);--sd-color-tabs-label-hover: hsla(231, 99%, 66%, 1);--sd-color-tabs-label-inactive: hsl(0, 0%, 66%);--sd-color-tabs-underline-active: hsla(231, 99%, 66%, 1);--sd-color-tabs-underline-hover: rgba(178, 206, 245, 0.62);--sd-color-tabs-underline-inactive: transparent;--sd-color-tabs-overline: rgb(222, 222, 222);--sd-color-tabs-underline: rgb(222, 222, 222);--sd-fontsize-tabs-label: 1rem;--sd-fontsize-dropdown: inherit;--sd-fontsize-dropdown-title: 1rem;--sd-fontweight-dropdown-title: 700} diff --git a/book/_build/html/_static/1078.index.js b/book/_build/html/_static/1078.index.js new file mode 100644 index 0000000..c33dfba --- /dev/null +++ b/book/_build/html/_static/1078.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[1078],{41078:(e,t,n)=>{function r(e,t,n){return void 0===n&&(n=""),void 0===t&&(t="\\b"),new RegExp("^"+n+"(("+e.join(")|(")+"))"+t)}n.r(t),n.d(t,{julia:()=>_});var a=["[<>]:","[<>=]=","<<=?",">>>?=?","=>","--?>","<--[->]?","\\/\\/","\\.{2,3}","[\\.\\\\%*+\\-<>!\\/^|&]=?","\\?","\\$","~",":"],i=r(["[<>]:","[<>=]=","[!=]==","<<=?",">>>?=?","=>?","--?>","<--[->]?","\\/\\/","[\\\\%*+\\-<>!\\/^|&\\u00F7\\u22BB]=?","\\?","\\$","~",":","\\u00D7","\\u2208","\\u2209","\\u220B","\\u220C","\\u2218","\\u221A","\\u221B","\\u2229","\\u222A","\\u2260","\\u2264","\\u2265","\\u2286","\\u2288","\\u228A","\\u22C5","\\b(in|isa)\\b(?!.?\\()"],""),s=/^[;,()[\]{}]/,u=/^[_A-Za-z\u00A1-\u2217\u2219-\uFFFF][\w\u00A1-\u2217\u2219-\uFFFF]*!*/,o=r(["\\\\[0-7]{1,3}","\\\\x[A-Fa-f0-9]{1,2}","\\\\[abefnrtv0%?'\"\\\\]","([^\\u0027\\u005C\\uD800-\\uDFFF]|[\\uD800-\\uDFFF][\\uDC00-\\uDFFF])"],"'"),c=["if","else","elseif","while","for","begin","let","end","do","try","catch","finally","return","break","continue","global","local","const","export","import","importall","using","function","where","macro","module","baremodule","struct","type","mutable","immutable","quote","typealias","abstract","primitive","bitstype"],l=["true","false","nothing","NaN","Inf"],m=r(["begin","function","type","struct","immutable","let","macro","for","while","quote","if","else","elseif","try","finally","catch","do"]),f=r(["end","else","elseif","catch","finally"]),p=r(c),h=r(l),d=/^@[_A-Za-z\u00A1-\uFFFF][\w\u00A1-\uFFFF]*!*/,F=/^:[_A-Za-z\u00A1-\uFFFF][\w\u00A1-\uFFFF]*!*/,k=/^(`|([_A-Za-z\u00A1-\uFFFF]*"("")?))/,b=r(a,"","@"),g=r(a,"",":");function v(e){return e.nestedArrays>0}function x(e,t){return void 0===t&&(t=0),e.scopes.length<=t?null:e.scopes[e.scopes.length-(t+1)]}function A(e,t){if(e.match("#=",!1))return t.tokenize=y,t.tokenize(e,t);var n=t.leavingExpr;if(e.sol()&&(n=!1),t.leavingExpr=!1,n&&e.match(/^'+/))return"operator";if(e.match(/\.{4,}/))return"error";if(e.match(/\.{1,3}/))return"operator";if(e.eatSpace())return null;var r,a,o=e.peek();if("#"===o)return e.skipToEnd(),"comment";if("["===o&&(t.scopes.push("["),t.nestedArrays++),"("===o&&(t.scopes.push("("),t.nestedGenerators++),v(t)&&"]"===o){for(;t.scopes.length&&"["!==x(t);)t.scopes.pop();t.scopes.pop(),t.nestedArrays--,t.leavingExpr=!0}if(function(e){return e.nestedGenerators>0}(t)&&")"===o){for(;t.scopes.length&&"("!==x(t);)t.scopes.pop();t.scopes.pop(),t.nestedGenerators--,t.leavingExpr=!0}if(v(t)){if("end"==t.lastToken&&e.match(":"))return"operator";if(e.match("end"))return"number"}if((r=e.match(m,!1))&&t.scopes.push(r[0]),e.match(f,!1)&&t.scopes.pop(),e.match(/^::(?![:\$])/))return t.tokenize=z,t.tokenize(e,t);if(!n&&(e.match(F)||e.match(g)))return"builtin";if(e.match(i))return"operator";if(e.match(/^\.?\d/,!1)){var c=RegExp(/^im\b/),l=!1;if(e.match(/^0x\.[0-9a-f_]+p[\+\-]?[_\d]+/i)&&(l=!0),e.match(/^0x[0-9a-f_]+/i)&&(l=!0),e.match(/^0b[01_]+/i)&&(l=!0),e.match(/^0o[0-7_]+/i)&&(l=!0),e.match(/^(?:(?:\d[_\d]*)?\.(?!\.)(?:\d[_\d]*)?|\d[_\d]*\.(?!\.)(?:\d[_\d]*))?([Eef][\+\-]?[_\d]+)?/i)&&(l=!0),e.match(/^\d[_\d]*(e[\+\-]?\d+)?/i)&&(l=!0),l)return e.match(c),t.leavingExpr=!0,"number"}if(e.match("'"))return t.tokenize=E,t.tokenize(e,t);if(e.match(k))return t.tokenize=('"""'===(a=e.current()).substr(-3)?a='"""':'"'===a.substr(-1)&&(a='"'),function(e,t){if(e.eat("\\"))e.next();else{if(e.match(a))return t.tokenize=A,t.leavingExpr=!0,"string";e.eat(/[`"]/)}return e.eatWhile(/[^\\`"]/),"string"}),t.tokenize(e,t);if(e.match(d)||e.match(b))return"meta";if(e.match(s))return null;if(e.match(p))return"keyword";if(e.match(h))return"builtin";var _=t.isDefinition||"function"==t.lastToken||"macro"==t.lastToken||"type"==t.lastToken||"struct"==t.lastToken||"immutable"==t.lastToken;return e.match(u)?_?"."===e.peek()?(t.isDefinition=!0,"variable"):(t.isDefinition=!1,"def"):(t.leavingExpr=!0,"variable"):(e.next(),"error")}function z(e,t){return e.match(/.*?(?=[,;{}()=\s]|$)/),e.match("{")?t.nestedParameters++:e.match("}")&&t.nestedParameters>0&&t.nestedParameters--,t.nestedParameters>0?e.match(/.*?(?={|})/)||e.next():0==t.nestedParameters&&(t.tokenize=A),"builtin"}function y(e,t){return e.match("#=")&&t.nestedComments++,e.match(/.*?(?=(#=|=#))/)||e.skipToEnd(),e.match("=#")&&(t.nestedComments--,0==t.nestedComments&&(t.tokenize=A)),"comment"}function E(e,t){var n,r=!1;if(e.match(o))r=!0;else if(n=e.match(/\\u([a-f0-9]{1,4})(?=')/i))((a=parseInt(n[1],16))<=55295||a>=57344)&&(r=!0,e.next());else if(n=e.match(/\\U([A-Fa-f0-9]{5,8})(?=')/)){var a;(a=parseInt(n[1],16))<=1114111&&(r=!0,e.next())}return r?(t.leavingExpr=!0,t.tokenize=A,"string"):(e.match(/^[^']+(?=')/)||e.skipToEnd(),e.match("'")&&(t.tokenize=A),"error")}const _={name:"julia",startState:function(){return{tokenize:A,scopes:[],lastToken:null,leavingExpr:!1,isDefinition:!1,nestedArrays:0,nestedComments:0,nestedGenerators:0,nestedParameters:0,firstParenPos:-1}},token:function(e,t){var n=t.tokenize(e,t),r=e.current();return r&&n&&(t.lastToken=r),n},indent:function(e,t,n){var r=0;return("]"===t||")"===t||/^end\b/.test(t)||/^else/.test(t)||/^catch\b/.test(t)||/^elseif\b/.test(t)||/^finally/.test(t))&&(r=-1),(e.scopes.length+r)*n.unit},languageData:{indentOnInput:/^\s*(end|else|catch|finally)\b$/,commentTokens:{line:"#",block:{open:"#=",close:"=#"}},closeBrackets:{brackets:["(","[","{",'"']},autocomplete:c.concat(l)}}}}]); +//# sourceMappingURL=1078.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/1078.index.js.map b/book/_build/html/_static/1078.index.js.map new file mode 100644 index 0000000..1adf466 --- /dev/null +++ b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,GAAI,MAClB,OAAS4B,GAAS,SAC7BD,GAAS,EACT5B,EAAOuB,aAEJ,GAAItB,EAAQD,EAAOC,MAAM,8BAA+B,CAC7D,IAAI4B,KAAQC,SAAS7B,EAAM,GAAI,MAClB,UACX2B,GAAS,EACT5B,EAAOuB,OAEX,CACA,OAAIK,GACFnC,EAAMW,aAAc,EACpBX,EAAMS,SAAWH,EACV,WAEJC,EAAOC,MAAM,gBAAkBD,EAAOU,YACvCV,EAAOC,MAAM,OAAQR,EAAMS,SAAWH,GACnC,QACT,CAwBO,MAAMgC,EAAQ,CACnBC,KAAM,QACNC,WAAY,WACV,MAAO,CACL/B,SAAUH,EACVF,OAAQ,GACRkB,UAAW,KACXX,aAAa,EACbqB,cAAc,EACd/B,aAAc,EACdiC,eAAgB,EAChBf,iBAAkB,EAClBc,iBAAkB,EAClBQ,eAAgB,EAEpB,EAEAC,MAAO,SAASnC,EAAQP,GACtB,IAAI2C,EAAQ3C,EAAMS,SAASF,EAAQP,GAC/B2B,EAAUpB,EAAOoB,UAMrB,OAJIA,GAAWgB,IACb3C,EAAMsB,UAAYK,GAGbgB,CACT,EAEAC,OAAQ,SAAS5C,EAAO6C,EAAWC,GACjC,IAAIC,EAAQ,EAMZ,OALmB,MAAdF,GAAmC,MAAdA,GAAqB,SAASG,KAAKH,IACxD,QAAQG,KAAKH,IAAc,WAAWG,KAAKH,IAAc,YAAYG,KAAKH,IAC1E,WAAWG,KAAKH,MACnBE,GAAS,IAEH/C,EAAMI,OAAOC,OAAS0C,GAASD,EAAGG,IAC5C,EAEAC,aAAc,CACZC,cAAe,kCACfC,cAAe,CAACC,KAAM,IAAKC,MAAO,CAACC,KAAM,KAAMC,MAAO,OACtDC,cAAe,CAACC,SAAU,CAAC,IAAK,IAAK,IAAK,MAC1CC,aAAcvE,EAAawE,OAAOvE,I","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/julia.js"],"sourcesContent":["function wordRegexp(words, end, pre) {\n if (typeof pre === \"undefined\") pre = \"\";\n if (typeof end === \"undefined\") { end = \"\\\\b\"; }\n return new RegExp(\"^\" + pre + \"((\" + words.join(\")|(\") + \"))\" + end);\n}\n\nvar octChar = \"\\\\\\\\[0-7]{1,3}\";\nvar hexChar = \"\\\\\\\\x[A-Fa-f0-9]{1,2}\";\nvar sChar = \"\\\\\\\\[abefnrtv0%?'\\\"\\\\\\\\]\";\nvar uChar = \"([^\\\\u0027\\\\u005C\\\\uD800-\\\\uDFFF]|[\\\\uD800-\\\\uDFFF][\\\\uDC00-\\\\uDFFF])\";\n\nvar asciiOperatorsList = [\n \"[<>]:\", \"[<>=]=\", \"<<=?\", \">>>?=?\", \"=>\", \"--?>\", \"<--[->]?\", \"\\\\/\\\\/\",\n \"\\\\.{2,3}\", \"[\\\\.\\\\\\\\%*+\\\\-<>!\\\\/^|&]=?\", \"\\\\?\", \"\\\\$\", \"~\", \":\"\n];\nvar operators = wordRegexp([\n \"[<>]:\", \"[<>=]=\", \"[!=]==\", \"<<=?\", \">>>?=?\", \"=>?\", \"--?>\", \"<--[->]?\", \"\\\\/\\\\/\",\n \"[\\\\\\\\%*+\\\\-<>!\\\\/^|&\\\\u00F7\\\\u22BB]=?\", \"\\\\?\", \"\\\\$\", \"~\", \":\",\n \"\\\\u00D7\", \"\\\\u2208\", \"\\\\u2209\", \"\\\\u220B\", \"\\\\u220C\", \"\\\\u2218\",\n \"\\\\u221A\", \"\\\\u221B\", \"\\\\u2229\", \"\\\\u222A\", \"\\\\u2260\", \"\\\\u2264\",\n \"\\\\u2265\", \"\\\\u2286\", \"\\\\u2288\", \"\\\\u228A\", \"\\\\u22C5\",\n \"\\\\b(in|isa)\\\\b(?!\\.?\\\\()\"\n], \"\");\nvar delimiters = /^[;,()[\\]{}]/;\nvar identifiers = /^[_A-Za-z\\u00A1-\\u2217\\u2219-\\uFFFF][\\w\\u00A1-\\u2217\\u2219-\\uFFFF]*!*/;\n\nvar chars = wordRegexp([octChar, hexChar, sChar, uChar], \"'\");\n\nvar openersList = [\"begin\", \"function\", \"type\", \"struct\", \"immutable\", \"let\",\n \"macro\", \"for\", \"while\", \"quote\", \"if\", \"else\", \"elseif\", \"try\",\n \"finally\", \"catch\", \"do\"];\n\nvar closersList = [\"end\", \"else\", \"elseif\", \"catch\", \"finally\"];\n\nvar keywordsList = [\"if\", \"else\", \"elseif\", \"while\", \"for\", \"begin\", \"let\",\n \"end\", \"do\", \"try\", \"catch\", \"finally\", \"return\", \"break\", \"continue\",\n \"global\", \"local\", \"const\", \"export\", \"import\", \"importall\", \"using\",\n \"function\", \"where\", \"macro\", \"module\", \"baremodule\", \"struct\", \"type\",\n \"mutable\", \"immutable\", \"quote\", \"typealias\", \"abstract\", \"primitive\",\n \"bitstype\"];\n\nvar builtinsList = [\"true\", \"false\", \"nothing\", \"NaN\", \"Inf\"];\n\nvar openers = wordRegexp(openersList);\nvar closers = wordRegexp(closersList);\nvar keywords = wordRegexp(keywordsList);\nvar builtins = wordRegexp(builtinsList);\n\nvar macro = /^@[_A-Za-z\\u00A1-\\uFFFF][\\w\\u00A1-\\uFFFF]*!*/;\nvar symbol = /^:[_A-Za-z\\u00A1-\\uFFFF][\\w\\u00A1-\\uFFFF]*!*/;\nvar stringPrefixes = /^(`|([_A-Za-z\\u00A1-\\uFFFF]*\"(\"\")?))/;\n\nvar macroOperators = wordRegexp(asciiOperatorsList, \"\", \"@\");\nvar symbolOperators = wordRegexp(asciiOperatorsList, \"\", \":\");\n\nfunction inArray(state) {\n return (state.nestedArrays > 0);\n}\n\nfunction inGenerator(state) {\n return (state.nestedGenerators > 0);\n}\n\nfunction currentScope(state, n) {\n if (typeof(n) === \"undefined\") { n = 0; }\n if (state.scopes.length <= n) {\n return null;\n }\n return state.scopes[state.scopes.length - (n + 1)];\n}\n\n// tokenizers\nfunction tokenBase(stream, state) {\n // Handle multiline comments\n if (stream.match('#=', false)) {\n state.tokenize = tokenComment;\n return state.tokenize(stream, state);\n }\n\n // Handle scope changes\n var leavingExpr = state.leavingExpr;\n if (stream.sol()) {\n leavingExpr = false;\n }\n state.leavingExpr = false;\n\n if (leavingExpr) {\n if (stream.match(/^'+/)) {\n return \"operator\";\n }\n }\n\n if (stream.match(/\\.{4,}/)) {\n return \"error\";\n } else if (stream.match(/\\.{1,3}/)) {\n return \"operator\";\n }\n\n if (stream.eatSpace()) {\n return null;\n }\n\n var ch = stream.peek();\n\n // Handle single line comments\n if (ch === '#') {\n stream.skipToEnd();\n return \"comment\";\n }\n\n if (ch === '[') {\n state.scopes.push('[');\n state.nestedArrays++;\n }\n\n if (ch === '(') {\n state.scopes.push('(');\n state.nestedGenerators++;\n }\n\n if (inArray(state) && ch === ']') {\n while (state.scopes.length && currentScope(state) !== \"[\") { state.scopes.pop(); }\n state.scopes.pop();\n state.nestedArrays--;\n state.leavingExpr = true;\n }\n\n if (inGenerator(state) && ch === ')') {\n while (state.scopes.length && currentScope(state) !== \"(\") { state.scopes.pop(); }\n state.scopes.pop();\n state.nestedGenerators--;\n state.leavingExpr = true;\n }\n\n if (inArray(state)) {\n if (state.lastToken == \"end\" && stream.match(':')) {\n return \"operator\";\n }\n if (stream.match('end')) {\n return \"number\";\n }\n }\n\n var match;\n if (match = stream.match(openers, false)) {\n state.scopes.push(match[0]);\n }\n\n if (stream.match(closers, false)) {\n state.scopes.pop();\n }\n\n // Handle type annotations\n if (stream.match(/^::(?![:\\$])/)) {\n state.tokenize = tokenAnnotation;\n return state.tokenize(stream, state);\n }\n\n // Handle symbols\n if (!leavingExpr && (stream.match(symbol) || stream.match(symbolOperators))) {\n return \"builtin\";\n }\n\n // Handle parametric types\n //if (stream.match(/^{[^}]*}(?=\\()/)) {\n // return \"builtin\";\n //}\n\n // Handle operators and Delimiters\n if (stream.match(operators)) {\n return \"operator\";\n }\n\n // Handle Number Literals\n if (stream.match(/^\\.?\\d/, false)) {\n var imMatcher = RegExp(/^im\\b/);\n var numberLiteral = false;\n if (stream.match(/^0x\\.[0-9a-f_]+p[\\+\\-]?[_\\d]+/i)) { numberLiteral = true; }\n // Integers\n if (stream.match(/^0x[0-9a-f_]+/i)) { numberLiteral = true; } // Hex\n if (stream.match(/^0b[01_]+/i)) { numberLiteral = true; } // Binary\n if (stream.match(/^0o[0-7_]+/i)) { numberLiteral = true; } // Octal\n // Floats\n if (stream.match(/^(?:(?:\\d[_\\d]*)?\\.(?!\\.)(?:\\d[_\\d]*)?|\\d[_\\d]*\\.(?!\\.)(?:\\d[_\\d]*))?([Eef][\\+\\-]?[_\\d]+)?/i)) { numberLiteral = true; }\n if (stream.match(/^\\d[_\\d]*(e[\\+\\-]?\\d+)?/i)) { numberLiteral = true; } // Decimal\n if (numberLiteral) {\n // Integer literals may be \"long\"\n stream.match(imMatcher);\n state.leavingExpr = true;\n return \"number\";\n }\n }\n\n // Handle Chars\n if (stream.match(\"'\")) {\n state.tokenize = tokenChar;\n return state.tokenize(stream, state);\n }\n\n // Handle Strings\n if (stream.match(stringPrefixes)) {\n state.tokenize = tokenStringFactory(stream.current());\n return state.tokenize(stream, state);\n }\n\n if (stream.match(macro) || stream.match(macroOperators)) {\n return \"meta\";\n }\n\n if (stream.match(delimiters)) {\n return null;\n }\n\n if (stream.match(keywords)) {\n return \"keyword\";\n }\n\n if (stream.match(builtins)) {\n return \"builtin\";\n }\n\n var isDefinition = state.isDefinition || state.lastToken == \"function\" ||\n state.lastToken == \"macro\" || state.lastToken == \"type\" ||\n state.lastToken == \"struct\" || state.lastToken == \"immutable\";\n\n if (stream.match(identifiers)) {\n if (isDefinition) {\n if (stream.peek() === '.') {\n state.isDefinition = true;\n return \"variable\";\n }\n state.isDefinition = false;\n return \"def\";\n }\n state.leavingExpr = true;\n return \"variable\";\n }\n\n // Handle non-detected items\n stream.next();\n return \"error\";\n}\n\nfunction tokenAnnotation(stream, state) {\n stream.match(/.*?(?=[,;{}()=\\s]|$)/);\n if (stream.match('{')) {\n state.nestedParameters++;\n } else if (stream.match('}') && state.nestedParameters > 0) {\n state.nestedParameters--;\n }\n if (state.nestedParameters > 0) {\n stream.match(/.*?(?={|})/) || stream.next();\n } else if (state.nestedParameters == 0) {\n state.tokenize = tokenBase;\n }\n return \"builtin\";\n}\n\nfunction tokenComment(stream, state) {\n if (stream.match('#=')) {\n state.nestedComments++;\n }\n if (!stream.match(/.*?(?=(#=|=#))/)) {\n stream.skipToEnd();\n }\n if (stream.match('=#')) {\n state.nestedComments--;\n if (state.nestedComments == 0)\n state.tokenize = tokenBase;\n }\n return \"comment\";\n}\n\nfunction tokenChar(stream, state) {\n var isChar = false, match;\n if (stream.match(chars)) {\n isChar = true;\n } else if (match = stream.match(/\\\\u([a-f0-9]{1,4})(?=')/i)) {\n var value = parseInt(match[1], 16);\n if (value <= 55295 || value >= 57344) { // (U+0,U+D7FF), (U+E000,U+FFFF)\n isChar = true;\n stream.next();\n }\n } else if (match = stream.match(/\\\\U([A-Fa-f0-9]{5,8})(?=')/)) {\n var value = parseInt(match[1], 16);\n if (value <= 1114111) { // U+10FFFF\n isChar = true;\n stream.next();\n }\n }\n if (isChar) {\n state.leavingExpr = true;\n state.tokenize = tokenBase;\n return \"string\";\n }\n if (!stream.match(/^[^']+(?=')/)) { stream.skipToEnd(); }\n if (stream.match(\"'\")) { state.tokenize = tokenBase; }\n return \"error\";\n}\n\nfunction tokenStringFactory(delimiter) {\n if (delimiter.substr(-3) === '\"\"\"') {\n delimiter = '\"\"\"';\n } else if (delimiter.substr(-1) === '\"') {\n delimiter = '\"';\n }\n function tokenString(stream, state) {\n if (stream.eat('\\\\')) {\n stream.next();\n } else if (stream.match(delimiter)) {\n state.tokenize = tokenBase;\n state.leavingExpr = true;\n return \"string\";\n } else {\n stream.eat(/[`\"]/);\n }\n stream.eatWhile(/[^\\\\`\"]/);\n return \"string\";\n }\n return tokenString;\n}\n\nexport const julia = {\n name: \"julia\",\n startState: function() {\n return {\n tokenize: tokenBase,\n scopes: [],\n lastToken: null,\n leavingExpr: false,\n isDefinition: false,\n nestedArrays: 0,\n nestedComments: 0,\n nestedGenerators: 0,\n nestedParameters: 0,\n firstParenPos: -1\n };\n },\n\n token: function(stream, state) {\n var style = state.tokenize(stream, state);\n var current = stream.current();\n\n if (current && style) {\n state.lastToken = current;\n }\n\n return style;\n },\n\n indent: function(state, textAfter, cx) {\n var delta = 0;\n if ( textAfter === ']' || textAfter === ')' || /^end\\b/.test(textAfter) ||\n /^else/.test(textAfter) || /^catch\\b/.test(textAfter) || /^elseif\\b/.test(textAfter) ||\n /^finally/.test(textAfter) ) {\n delta = -1;\n }\n return (state.scopes.length + delta) * cx.unit;\n },\n\n languageData: {\n indentOnInput: /^\\s*(end|else|catch|finally)\\b$/,\n commentTokens: {line: \"#\", block: {open: \"#=\", close: \"=#\"}},\n closeBrackets: {brackets: [\"(\", \"[\", \"{\", '\"']},\n autocomplete: keywordsList.concat(builtinsList)\n }\n};\n"],"names":["wordRegexp","words","end","pre","RegExp","join","asciiOperatorsList","operators","delimiters","identifiers","chars","keywordsList","builtinsList","openers","closers","keywords","builtins","macro","symbol","stringPrefixes","macroOperators","symbolOperators","inArray","state","nestedArrays","currentScope","n","scopes","length","tokenBase","stream","match","tokenize","tokenComment","leavingExpr","sol","eatSpace","delimiter","ch","peek","skipToEnd","push","nestedGenerators","pop","inGenerator","lastToken","tokenAnnotation","imMatcher","numberLiteral","tokenChar","current","substr","eat","next","eatWhile","isDefinition","nestedParameters","nestedComments","isChar","value","parseInt","julia","name","startState","firstParenPos","token","style","indent","textAfter","cx","delta","test","unit","languageData","indentOnInput","commentTokens","line","block","open","close","closeBrackets","brackets","autocomplete","concat"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/1118.index.js b/book/_build/html/_static/1118.index.js new file mode 100644 index 0000000..87e3520 --- /dev/null +++ b/book/_build/html/_static/1118.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[1118],{1118:(e,t,a)=>{a.r(t),a.d(t,{ebnf:()=>c});const c={name:"ebnf",startState:function(){return{stringType:null,commentType:null,braced:0,lhs:!0,localState:null,stack:[],inDefinition:!1}},token:function(e,t){if(e){switch(0===t.stack.length&&('"'==e.peek()||"'"==e.peek()?(t.stringType=e.peek(),e.next(),t.stack.unshift(1)):e.match("/*")?(t.stack.unshift(0),t.commentType=0):e.match("(*")&&(t.stack.unshift(0),t.commentType=1)),t.stack[0]){case 1:for(;1===t.stack[0]&&!e.eol();)e.peek()===t.stringType?(e.next(),t.stack.shift()):"\\"===e.peek()?(e.next(),e.next()):e.match(/^.[^\\\"\']*/);return t.lhs?"property":"string";case 0:for(;0===t.stack[0]&&!e.eol();)0===t.commentType&&e.match("*/")||1===t.commentType&&e.match("*)")?(t.stack.shift(),t.commentType=null):e.match(/^.[^\*]*/);return"comment";case 2:for(;2===t.stack[0]&&!e.eol();)e.match(/^[^\]\\]+/)||e.match(".")||t.stack.shift();return"operator"}var a=e.peek();switch(a){case"[":return e.next(),t.stack.unshift(2),"bracket";case":":case"|":case";":return e.next(),"operator";case"%":if(e.match("%%"))return"header";if(e.match(/[%][A-Za-z]+/))return"keyword";if(e.match(/[%][}]/))return"bracket";break;case"/":if(e.match(/[\/][A-Za-z]+/))return"keyword";case"\\":if(e.match(/[\][a-z]+/))return"string.special";case".":if(e.match("."))return"atom";case"*":case"-":case"+":case"^":if(e.match(a))return"atom";case"$":if(e.match("$$"))return"builtin";if(e.match(/[$][0-9]+/))return"variableName.special";case"<":if(e.match(/<<[a-zA-Z_]+>>/))return"builtin"}return e.match("//")?(e.skipToEnd(),"comment"):e.match("return")?"operator":e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/)?e.match(/(?=[\(.])/)?"variable":e.match(/(?=[\s\n]*[:=])/)?"def":"variableName.special":-1!=["[","]","(",")"].indexOf(e.peek())?(e.next(),"bracket"):(e.eatSpace()||e.next(),null)}}}}}]); +//# sourceMappingURL=1118.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/1118.index.js.map b/book/_build/html/_static/1118.index.js.map new file mode 100644 index 0000000..b794a82 --- /dev/null +++ b/book/_build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AGT,IAAIL,EAAOH,EAAOG,OAGlB,OAAQA,GACR,IAAK,IAGH,OAFAH,EAAOI,OACPH,EAAMJ,MAAMQ,QAhFuC,GAiF5C,UACT,IAAK,IACL,IAAK,IACL,IAAK,IAEH,OADAL,EAAOI,OACA,WACT,IAAK,IACH,GAAIJ,EAAOM,MAAM,MACf,MAAO,SACF,GAAIN,EAAOM,MAAM,gBACtB,MAAO,UACF,GAAIN,EAAOM,MAAM,UACtB,MAAO,UAET,MACF,IAAK,IACH,GAAIN,EAAOM,MAAM,iBACf,MAAO,UAEX,IAAK,KACH,GAAIN,EAAOM,MAAM,aACf,MAAO,iBAEX,IAAK,IACH,GAAIN,EAAOM,MAAM,KACf,MAAO,OAEX,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACH,GAAIN,EAAOM,MAAMH,GACf,MAAO,OAEX,IAAK,IACH,GAAIH,EAAOM,MAAM,MACf,MAAO,UACF,GAAIN,EAAOM,MAAM,aACtB,MAAO,uBAEX,IAAK,IACH,GAAIN,EAAOM,MAAM,kBACf,MAAO,UAIX,OAAIN,EAAOM,MAAM,OACfN,EAAOS,YACA,WACET,EAAOM,MAAM,UACf,WACEN,EAAOM,MAAM,2BAClBN,EAAOM,MAAM,aACR,WACEN,EAAOM,MAAM,mBACf,MAEF,wBACkD,GAAhD,CAAC,IAAK,IAAK,IAAK,KAAKI,QAAQV,EAAOG,SAC7CH,EAAOI,OACA,YACGJ,EAAOW,YACjBX,EAAOI,OAEF,KAjIY,CAkIrB,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/ebnf.js"],"sourcesContent":["var commentType = {slash: 0, parenthesis: 1};\nvar stateType = {comment: 0, _string: 1, characterClass: 2};\n\nexport const ebnf = {\n name: \"ebnf\",\n startState: function () {\n return {\n stringType: null,\n commentType: null,\n braced: 0,\n lhs: true,\n localState: null,\n stack: [],\n inDefinition: false\n };\n },\n token: function (stream, state) {\n if (!stream) return;\n\n //check for state changes\n if (state.stack.length === 0) {\n //strings\n if ((stream.peek() == '\"') || (stream.peek() == \"'\")) {\n state.stringType = stream.peek();\n stream.next(); // Skip quote\n state.stack.unshift(stateType._string);\n } else if (stream.match('/*')) { //comments starting with /*\n state.stack.unshift(stateType.comment);\n state.commentType = commentType.slash;\n } else if (stream.match('(*')) { //comments starting with (*\n state.stack.unshift(stateType.comment);\n state.commentType = commentType.parenthesis;\n }\n }\n\n //return state\n //stack has\n switch (state.stack[0]) {\n case stateType._string:\n while (state.stack[0] === stateType._string && !stream.eol()) {\n if (stream.peek() === state.stringType) {\n stream.next(); // Skip quote\n state.stack.shift(); // Clear flag\n } else if (stream.peek() === \"\\\\\") {\n stream.next();\n stream.next();\n } else {\n stream.match(/^.[^\\\\\\\"\\']*/);\n }\n }\n return state.lhs ? \"property\" : \"string\"; // Token style\n\n case stateType.comment:\n while (state.stack[0] === stateType.comment && !stream.eol()) {\n if (state.commentType === commentType.slash && stream.match('*/')) {\n state.stack.shift(); // Clear flag\n state.commentType = null;\n } else if (state.commentType === commentType.parenthesis && stream.match('*)')) {\n state.stack.shift(); // Clear flag\n state.commentType = null;\n } else {\n stream.match(/^.[^\\*]*/);\n }\n }\n return \"comment\";\n\n case stateType.characterClass:\n while (state.stack[0] === stateType.characterClass && !stream.eol()) {\n if (!(stream.match(/^[^\\]\\\\]+/) || stream.match('.'))) {\n state.stack.shift();\n }\n }\n return \"operator\";\n }\n\n var peek = stream.peek();\n\n //no stack\n switch (peek) {\n case \"[\":\n stream.next();\n state.stack.unshift(stateType.characterClass);\n return \"bracket\";\n case \":\":\n case \"|\":\n case \";\":\n stream.next();\n return \"operator\";\n case \"%\":\n if (stream.match(\"%%\")) {\n return \"header\";\n } else if (stream.match(/[%][A-Za-z]+/)) {\n return \"keyword\";\n } else if (stream.match(/[%][}]/)) {\n return \"bracket\";\n }\n break;\n case \"/\":\n if (stream.match(/[\\/][A-Za-z]+/)) {\n return \"keyword\";\n }\n case \"\\\\\":\n if (stream.match(/[\\][a-z]+/)) {\n return \"string.special\";\n }\n case \".\":\n if (stream.match(\".\")) {\n return \"atom\";\n }\n case \"*\":\n case \"-\":\n case \"+\":\n case \"^\":\n if (stream.match(peek)) {\n return \"atom\";\n }\n case \"$\":\n if (stream.match(\"$$\")) {\n return \"builtin\";\n } else if (stream.match(/[$][0-9]+/)) {\n return \"variableName.special\";\n }\n case \"<\":\n if (stream.match(/<<[a-zA-Z_]+>>/)) {\n return \"builtin\";\n }\n }\n\n if (stream.match('//')) {\n stream.skipToEnd();\n return \"comment\";\n } else if (stream.match('return')) {\n return \"operator\";\n } else if (stream.match(/^[a-zA-Z_][a-zA-Z0-9_]*/)) {\n if (stream.match(/(?=[\\(.])/)) {\n return \"variable\";\n } else if (stream.match(/(?=[\\s\\n]*[:=])/)) {\n return \"def\";\n }\n return \"variableName.special\";\n } else if ([\"[\", \"]\", \"(\", \")\"].indexOf(stream.peek()) != -1) {\n stream.next();\n return \"bracket\";\n } else if (!stream.eatSpace()) {\n stream.next();\n }\n return null;\n }\n};\n"],"names":["ebnf","name","startState","stringType","commentType","braced","lhs","localState","stack","inDefinition","token","stream","state","length","peek","next","unshift","match","eol","shift","skipToEnd","indexOf","eatSpace"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/1327.index.js b/book/_build/html/_static/1327.index.js new file mode 100644 index 0000000..d2bc912 --- /dev/null +++ b/book/_build/html/_static/1327.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[1327],{1327:(e,t,r)=>{function i(e){var t,r;e?(t=/^(exx?|(ld|cp)([di]r?)?|[lp]ea|pop|push|ad[cd]|cpl|daa|dec|inc|neg|sbc|sub|and|bit|[cs]cf|x?or|res|set|r[lr]c?a?|r[lr]d|s[lr]a|srl|djnz|nop|[de]i|halt|im|in([di]mr?|ir?|irx|2r?)|ot(dmr?|[id]rx|imr?)|out(0?|[di]r?|[di]2r?)|tst(io)?|slp)(\.([sl]?i)?[sl])?\b/i,r=/^(((call|j[pr]|rst|ret[in]?)(\.([sl]?i)?[sl])?)|(rs|st)mix)\b/i):(t=/^(exx?|(ld|cp|in)([di]r?)?|pop|push|ad[cd]|cpl|daa|dec|inc|neg|sbc|sub|and|bit|[cs]cf|x?or|res|set|r[lr]c?a?|r[lr]d|s[lr]a|srl|djnz|nop|rst|[de]i|halt|im|ot[di]r|out[di]?)\b/i,r=/^(call|j[pr]|ret[in]?|b_?(call|jump))\b/i);var i=/^(af?|bc?|c|de?|e|hl?|l|i[xy]?|r|sp)\b/i,n=/^(n?[zc]|p[oe]?|m)\b/i,l=/^([hl][xy]|i[xy][hl]|slia|sll)\b/i,a=/^([\da-f]+h|[0-7]+o|[01]+b|\d+d?)\b/i;return{name:"z80",startState:function(){return{context:0}},token:function(s,c){if(s.column()||(c.context=0),s.eatSpace())return null;var u;if(s.eatWhile(/\w/)){if(e&&s.eat(".")&&s.eatWhile(/\w/),u=s.current(),!s.indentation())return s.match(a)?"number":null;if((1==c.context||4==c.context)&&i.test(u))return c.context=4,"variable";if(2==c.context&&n.test(u))return c.context=4,"variableName.special";if(t.test(u))return c.context=1,"keyword";if(r.test(u))return c.context=2,"keyword";if(4==c.context&&a.test(u))return"number";if(l.test(u))return"error"}else{if(s.eat(";"))return s.skipToEnd(),"comment";if(s.eat('"')){for(;(u=s.next())&&'"'!=u;)"\\"==u&&s.next();return"string"}if(s.eat("'")){if(s.match(/\\?.'/))return"number"}else if(s.eat(".")||s.sol()&&s.eat("#")){if(c.context=5,s.eatWhile(/\w/))return"def"}else if(s.eat("$")){if(s.eatWhile(/[\da-f]/i))return"number"}else if(s.eat("%")){if(s.eatWhile(/[01]/))return"number"}else s.next()}return null}}}r.r(t),r.d(t,{ez80:()=>l,z80:()=>n});const n=i(!1),l=i(!0)}}]); +//# sourceMappingURL=1327.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/1327.index.js.map b/book/_build/html/_static/1327.index.js.map new file mode 100644 index 0000000..a97b89e --- /dev/null +++ b/book/_build/html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AI,MAAQN,EAAOa,OAASb,EAAOM,IAAI,MAGvD,GAFAL,EAAMH,QAAU,EAEZE,EAAOK,SAAS,MAClB,MAAO,WACJ,GAAIL,EAAOM,IAAI,MACpB,GAAIN,EAAOK,SAAS,YAClB,MAAO,cACJ,GAAIL,EAAOM,IAAI,MACpB,GAAIN,EAAOK,SAAS,QAClB,MAAO,cAETL,EAAOY,MACT,CACA,OAAO,IACT,EAEJ,C,qCAEO,MAAME,EAAM1B,GAAM,GACZC,EAAOD,GAAM,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/z80.js"],"sourcesContent":["function mkZ80(ez80) {\n var keywords1, keywords2;\n if (ez80) {\n keywords1 = /^(exx?|(ld|cp)([di]r?)?|[lp]ea|pop|push|ad[cd]|cpl|daa|dec|inc|neg|sbc|sub|and|bit|[cs]cf|x?or|res|set|r[lr]c?a?|r[lr]d|s[lr]a|srl|djnz|nop|[de]i|halt|im|in([di]mr?|ir?|irx|2r?)|ot(dmr?|[id]rx|imr?)|out(0?|[di]r?|[di]2r?)|tst(io)?|slp)(\\.([sl]?i)?[sl])?\\b/i;\n keywords2 = /^(((call|j[pr]|rst|ret[in]?)(\\.([sl]?i)?[sl])?)|(rs|st)mix)\\b/i;\n } else {\n keywords1 = /^(exx?|(ld|cp|in)([di]r?)?|pop|push|ad[cd]|cpl|daa|dec|inc|neg|sbc|sub|and|bit|[cs]cf|x?or|res|set|r[lr]c?a?|r[lr]d|s[lr]a|srl|djnz|nop|rst|[de]i|halt|im|ot[di]r|out[di]?)\\b/i;\n keywords2 = /^(call|j[pr]|ret[in]?|b_?(call|jump))\\b/i;\n }\n\n var variables1 = /^(af?|bc?|c|de?|e|hl?|l|i[xy]?|r|sp)\\b/i;\n var variables2 = /^(n?[zc]|p[oe]?|m)\\b/i;\n var errors = /^([hl][xy]|i[xy][hl]|slia|sll)\\b/i;\n var numbers = /^([\\da-f]+h|[0-7]+o|[01]+b|\\d+d?)\\b/i;\n\n return {\n name: \"z80\",\n startState: function() {\n return {\n context: 0\n };\n },\n token: function(stream, state) {\n if (!stream.column())\n state.context = 0;\n\n if (stream.eatSpace())\n return null;\n\n var w;\n\n if (stream.eatWhile(/\\w/)) {\n if (ez80 && stream.eat('.')) {\n stream.eatWhile(/\\w/);\n }\n w = stream.current();\n\n if (stream.indentation()) {\n if ((state.context == 1 || state.context == 4) && variables1.test(w)) {\n state.context = 4;\n return 'variable';\n }\n\n if (state.context == 2 && variables2.test(w)) {\n state.context = 4;\n return 'variableName.special';\n }\n\n if (keywords1.test(w)) {\n state.context = 1;\n return 'keyword';\n } else if (keywords2.test(w)) {\n state.context = 2;\n return 'keyword';\n } else if (state.context == 4 && numbers.test(w)) {\n return 'number';\n }\n\n if (errors.test(w))\n return 'error';\n } else if (stream.match(numbers)) {\n return 'number';\n } else {\n return null;\n }\n } else if (stream.eat(';')) {\n stream.skipToEnd();\n return 'comment';\n } else if (stream.eat('\"')) {\n while (w = stream.next()) {\n if (w == '\"')\n break;\n\n if (w == '\\\\')\n stream.next();\n }\n return 'string';\n } else if (stream.eat('\\'')) {\n if (stream.match(/\\\\?.'/))\n return 'number';\n } else if (stream.eat('.') || stream.sol() && stream.eat('#')) {\n state.context = 5;\n\n if (stream.eatWhile(/\\w/))\n return 'def';\n } else if (stream.eat('$')) {\n if (stream.eatWhile(/[\\da-f]/i))\n return 'number';\n } else if (stream.eat('%')) {\n if (stream.eatWhile(/[01]/))\n return 'number';\n } else {\n stream.next();\n }\n return null;\n }\n };\n};\n\nexport const z80 = mkZ80(false)\nexport const ez80 = mkZ80(true)\n"],"names":["mkZ80","ez80","keywords1","keywords2","variables1","variables2","errors","numbers","name","startState","context","token","stream","state","column","eatSpace","w","eatWhile","eat","current","indentation","match","test","skipToEnd","next","sol","z80"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/1363.index.js b/book/_build/html/_static/1363.index.js new file mode 100644 index 0000000..58321eb --- /dev/null +++ b/book/_build/html/_static/1363.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[1363],{71363:(e,t,T)=>{function n(e){for(var t={},T=e.split(" "),n=0;nR});const E={name:"ttcn-cfg",keywords:n("Yes No LogFile FileMask ConsoleMask AppendFile TimeStampFormat LogEventTypes SourceInfoFormat LogEntityName LogSourceInfo DiskFullAction LogFileNumber LogFileSize MatchingHints Detailed Compact SubCategories Stack Single None Seconds DateTime Time Stop Error Retry Delete TCPPort KillTimer NumHCs UnixSocketsEnabled LocalAddress"),fileNCtrlMaskOptions:n("TTCN_EXECUTOR TTCN_ERROR TTCN_WARNING TTCN_PORTEVENT TTCN_TIMEROP TTCN_VERDICTOP TTCN_DEFAULTOP TTCN_TESTCASE TTCN_ACTION TTCN_USER TTCN_FUNCTION TTCN_STATISTICS TTCN_PARALLEL TTCN_MATCHING TTCN_DEBUG EXECUTOR ERROR WARNING PORTEVENT TIMEROP VERDICTOP DEFAULTOP TESTCASE ACTION USER FUNCTION STATISTICS PARALLEL MATCHING DEBUG LOG_ALL LOG_NOTHING ACTION_UNQUALIFIED DEBUG_ENCDEC DEBUG_TESTPORT DEBUG_UNQUALIFIED DEFAULTOP_ACTIVATE DEFAULTOP_DEACTIVATE DEFAULTOP_EXIT DEFAULTOP_UNQUALIFIED ERROR_UNQUALIFIED EXECUTOR_COMPONENT EXECUTOR_CONFIGDATA EXECUTOR_EXTCOMMAND EXECUTOR_LOGOPTIONS EXECUTOR_RUNTIME EXECUTOR_UNQUALIFIED FUNCTION_RND FUNCTION_UNQUALIFIED MATCHING_DONE MATCHING_MCSUCCESS MATCHING_MCUNSUCC MATCHING_MMSUCCESS MATCHING_MMUNSUCC MATCHING_PCSUCCESS MATCHING_PCUNSUCC MATCHING_PMSUCCESS MATCHING_PMUNSUCC MATCHING_PROBLEM MATCHING_TIMEOUT MATCHING_UNQUALIFIED PARALLEL_PORTCONN PARALLEL_PORTMAP PARALLEL_PTC PARALLEL_UNQUALIFIED PORTEVENT_DUALRECV PORTEVENT_DUALSEND PORTEVENT_MCRECV PORTEVENT_MCSEND PORTEVENT_MMRECV PORTEVENT_MMSEND PORTEVENT_MQUEUE PORTEVENT_PCIN PORTEVENT_PCOUT PORTEVENT_PMIN PORTEVENT_PMOUT PORTEVENT_PQUEUE PORTEVENT_STATE PORTEVENT_UNQUALIFIED STATISTICS_UNQUALIFIED STATISTICS_VERDICT TESTCASE_FINISH TESTCASE_START TESTCASE_UNQUALIFIED TIMEROP_GUARD TIMEROP_READ TIMEROP_START TIMEROP_STOP TIMEROP_TIMEOUT TIMEROP_UNQUALIFIED USER_UNQUALIFIED VERDICTOP_FINAL VERDICTOP_GETVERDICT VERDICTOP_SETVERDICT VERDICTOP_UNQUALIFIED WARNING_UNQUALIFIED"),externalCommands:n("BeginControlPart EndControlPart BeginTestCase EndTestCase"),multiLineStrings:!0};var C,N=E.keywords,I=E.fileNCtrlMaskOptions,r=E.externalCommands,i=E.multiLineStrings,o=!1!==E.indentStatements,_=/[\|]/;function A(e,t){var T,n=e.next();if('"'==n||"'"==n)return t.tokenize=(T=n,function(e,t){for(var n,E=!1,C=!1;null!=(n=e.next());){if(n==T&&!E){var N=e.peek();N&&("b"!=(N=N.toLowerCase())&&"h"!=N&&"o"!=N||e.next()),C=!0;break}E=!E&&"\\"==n}return(C||!E&&!i)&&(t.tokenize=null),"string"}),t.tokenize(e,t);if(/[:=]/.test(n))return C=n,"punctuation";if("#"==n)return e.skipToEnd(),"comment";if(/\d/.test(n))return e.eatWhile(/[\w\.]/),"number";if(_.test(n))return e.eatWhile(_),"operator";if("["==n)return e.eatWhile(/[\w_\]]/),"number";e.eatWhile(/[\w\$_]/);var E=e.current();return N.propertyIsEnumerable(E)?"keyword":I.propertyIsEnumerable(E)?"atom":r.propertyIsEnumerable(E)?"deleted":"variable"}function O(e,t,T,n,E){this.indented=e,this.column=t,this.type=T,this.align=n,this.prev=E}function U(e,t,T){var n=e.indented;return e.context&&"statement"==e.context.type&&(n=e.context.indented),e.context=new O(n,t,T,null,e.context)}function a(e){var t=e.context.type;return")"!=t&&"]"!=t&&"}"!=t||(e.indented=e.context.indented),e.context=e.context.prev}const R={name:"ttcn",startState:function(){return{tokenize:null,context:new O(0,0,"top",!1),indented:0,startOfLine:!0}},token:function(e,t){var T=t.context;if(e.sol()&&(null==T.align&&(T.align=!1),t.indented=e.indentation(),t.startOfLine=!0),e.eatSpace())return null;C=null;var n=(t.tokenize||A)(e,t);if("comment"==n)return n;if(null==T.align&&(T.align=!0),";"!=C&&":"!=C&&","!=C||"statement"!=T.type)if("{"==C)U(t,e.column(),"}");else if("["==C)U(t,e.column(),"]");else if("("==C)U(t,e.column(),")");else if("}"==C){for(;"statement"==T.type;)T=a(t);for("}"==T.type&&(T=a(t));"statement"==T.type;)T=a(t)}else C==T.type?a(t):o&&(("}"==T.type||"top"==T.type)&&";"!=C||"statement"==T.type&&"newstatement"==C)&&U(t,e.column(),"statement");else a(t);return t.startOfLine=!1,n},languageData:{indentOnInput:/^\s*[{}]$/,commentTokens:{line:"#"}}}}}]); +//# sourceMappingURL=1363.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/1363.index.js.map b/book/_build/html/_static/1363.index.js.map new file mode 100644 index 0000000..143db22 --- /dev/null +++ b/book/_build/html/_static/1363.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"1363.index.js","mappings":"+FAAA,SAASA,EAAMC,GAEb,IADA,IAAIC,EAAM,CAAC,EAAGF,EAAQC,EAAIE,MAAM,KACvBC,EAAI,EAAGA,EAAIJ,EAAMK,SAAUD,EAClCF,EAAIF,EAAMI,KAAM,EAClB,OAAOF,CACT,C,8BAEA,MAAMI,EAAe,CACnBC,KAAM,WACNC,SAAUR,EAAM,4UAOhBS,qBAAsBT,EAAM,g9CAwC5BU,iBAAkBV,EAAM,6DAExBW,kBAAkB,GAGpB,IAMIC,EANAJ,EAAWF,EAAaE,SACxBC,EAAuBH,EAAaG,qBACpCC,EAAmBJ,EAAaI,iBAChCC,EAAmBL,EAAaK,iB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iC,EAAId,MAAqBc,EAAMN,EAAW3B,EACnD,MACSL,GAAWsC,EAAId,KAAMQ,EAAW3B,GAChCJ,KAAmC,KAAZqC,EAAId,MAA2B,OAAZc,EAAId,OACV,KAAXxB,GAAgC,aAAZsC,EAAId,MACU,gBAAXxB,IACvD4B,EAAYvB,EAAOD,EAAOmB,SAAU,kBAdpCS,EAAW3B,GAgBb,OADAA,EAAM+B,aAAc,EACbM,CACT,EAEAC,aAAc,CACZC,cAAe,YACfC,cAAe,CAACC,KAAM,M","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/ttcn-cfg.js"],"sourcesContent":["function words(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i)\n obj[words[i]] = true;\n return obj;\n}\n\nconst parserConfig = {\n name: \"ttcn-cfg\",\n keywords: words(\"Yes No LogFile FileMask ConsoleMask AppendFile\" +\n \" TimeStampFormat LogEventTypes SourceInfoFormat\" +\n \" LogEntityName LogSourceInfo DiskFullAction\" +\n \" LogFileNumber LogFileSize MatchingHints Detailed\" +\n \" Compact SubCategories Stack Single None Seconds\" +\n \" DateTime Time Stop Error Retry Delete TCPPort KillTimer\" +\n \" NumHCs UnixSocketsEnabled LocalAddress\"),\n fileNCtrlMaskOptions: words(\"TTCN_EXECUTOR TTCN_ERROR TTCN_WARNING\" +\n \" TTCN_PORTEVENT TTCN_TIMEROP TTCN_VERDICTOP\" +\n \" TTCN_DEFAULTOP TTCN_TESTCASE TTCN_ACTION\" +\n \" TTCN_USER TTCN_FUNCTION TTCN_STATISTICS\" +\n \" TTCN_PARALLEL TTCN_MATCHING TTCN_DEBUG\" +\n \" EXECUTOR ERROR WARNING PORTEVENT TIMEROP\" +\n \" VERDICTOP DEFAULTOP TESTCASE ACTION USER\" +\n \" FUNCTION STATISTICS PARALLEL MATCHING DEBUG\" +\n \" LOG_ALL LOG_NOTHING ACTION_UNQUALIFIED\" +\n \" DEBUG_ENCDEC DEBUG_TESTPORT\" +\n \" DEBUG_UNQUALIFIED DEFAULTOP_ACTIVATE\" +\n \" DEFAULTOP_DEACTIVATE DEFAULTOP_EXIT\" +\n \" DEFAULTOP_UNQUALIFIED ERROR_UNQUALIFIED\" +\n \" EXECUTOR_COMPONENT EXECUTOR_CONFIGDATA\" +\n \" EXECUTOR_EXTCOMMAND EXECUTOR_LOGOPTIONS\" +\n \" EXECUTOR_RUNTIME EXECUTOR_UNQUALIFIED\" +\n \" FUNCTION_RND FUNCTION_UNQUALIFIED\" +\n \" MATCHING_DONE MATCHING_MCSUCCESS\" +\n \" MATCHING_MCUNSUCC MATCHING_MMSUCCESS\" +\n \" MATCHING_MMUNSUCC MATCHING_PCSUCCESS\" +\n \" MATCHING_PCUNSUCC MATCHING_PMSUCCESS\" +\n \" MATCHING_PMUNSUCC MATCHING_PROBLEM\" +\n \" MATCHING_TIMEOUT MATCHING_UNQUALIFIED\" +\n \" PARALLEL_PORTCONN PARALLEL_PORTMAP\" +\n \" PARALLEL_PTC PARALLEL_UNQUALIFIED\" +\n \" PORTEVENT_DUALRECV PORTEVENT_DUALSEND\" +\n \" PORTEVENT_MCRECV PORTEVENT_MCSEND\" +\n \" PORTEVENT_MMRECV PORTEVENT_MMSEND\" +\n \" PORTEVENT_MQUEUE PORTEVENT_PCIN\" +\n \" PORTEVENT_PCOUT PORTEVENT_PMIN\" +\n \" PORTEVENT_PMOUT PORTEVENT_PQUEUE\" +\n \" PORTEVENT_STATE PORTEVENT_UNQUALIFIED\" +\n \" STATISTICS_UNQUALIFIED STATISTICS_VERDICT\" +\n \" TESTCASE_FINISH TESTCASE_START\" +\n \" TESTCASE_UNQUALIFIED TIMEROP_GUARD\" +\n \" TIMEROP_READ TIMEROP_START TIMEROP_STOP\" +\n \" TIMEROP_TIMEOUT TIMEROP_UNQUALIFIED\" +\n \" USER_UNQUALIFIED VERDICTOP_FINAL\" +\n \" VERDICTOP_GETVERDICT VERDICTOP_SETVERDICT\" +\n \" VERDICTOP_UNQUALIFIED WARNING_UNQUALIFIED\"),\n externalCommands: words(\"BeginControlPart EndControlPart BeginTestCase\" +\n \" EndTestCase\"),\n multiLineStrings: true\n}\n\nvar keywords = parserConfig.keywords,\n fileNCtrlMaskOptions = parserConfig.fileNCtrlMaskOptions,\n externalCommands = parserConfig.externalCommands,\n multiLineStrings = parserConfig.multiLineStrings,\n indentStatements = parserConfig.indentStatements !== false;\nvar isOperatorChar = /[\\|]/;\nvar curPunc;\n\nfunction tokenBase(stream, state) {\n var ch = stream.next();\n if (ch == '\"' || ch == \"'\") {\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n }\n if (/[:=]/.test(ch)) {\n curPunc = ch;\n return \"punctuation\";\n }\n if (ch == \"#\"){\n stream.skipToEnd();\n return \"comment\";\n }\n if (/\\d/.test(ch)) {\n stream.eatWhile(/[\\w\\.]/);\n return \"number\";\n }\n if (isOperatorChar.test(ch)) {\n stream.eatWhile(isOperatorChar);\n return \"operator\";\n }\n if (ch == \"[\"){\n stream.eatWhile(/[\\w_\\]]/);\n return \"number\";\n }\n\n stream.eatWhile(/[\\w\\$_]/);\n var cur = stream.current();\n if (keywords.propertyIsEnumerable(cur)) return \"keyword\";\n if (fileNCtrlMaskOptions.propertyIsEnumerable(cur))\n return \"atom\";\n if (externalCommands.propertyIsEnumerable(cur)) return \"deleted\";\n\n return \"variable\";\n}\n\nfunction tokenString(quote) {\n return function(stream, state) {\n var escaped = false, next, end = false;\n while ((next = stream.next()) != null) {\n if (next == quote && !escaped){\n var afterNext = stream.peek();\n //look if the character if the quote is like the B in '10100010'B\n if (afterNext){\n afterNext = afterNext.toLowerCase();\n if(afterNext == \"b\" || afterNext == \"h\" || afterNext == \"o\")\n stream.next();\n }\n end = true; break;\n }\n escaped = !escaped && next == \"\\\\\";\n }\n if (end || !(escaped || multiLineStrings))\n state.tokenize = null;\n return \"string\";\n };\n}\n\nfunction Context(indented, column, type, align, prev) {\n this.indented = indented;\n this.column = column;\n this.type = type;\n this.align = align;\n this.prev = prev;\n}\nfunction pushContext(state, col, type) {\n var indent = state.indented;\n if (state.context && state.context.type == \"statement\")\n indent = state.context.indented;\n return state.context = new Context(indent, col, type, null, state.context);\n}\nfunction popContext(state) {\n var t = state.context.type;\n if (t == \")\" || t == \"]\" || t == \"}\")\n state.indented = state.context.indented;\n return state.context = state.context.prev;\n}\n\n//Interface\nexport const ttcnCfg = {\n name: \"ttcn\",\n startState: function() {\n return {\n tokenize: null,\n context: new Context(0, 0, \"top\", false),\n indented: 0,\n startOfLine: true\n };\n },\n\n token: function(stream, state) {\n var ctx = state.context;\n if (stream.sol()) {\n if (ctx.align == null) ctx.align = false;\n state.indented = stream.indentation();\n state.startOfLine = true;\n }\n if (stream.eatSpace()) return null;\n curPunc = null;\n var style = (state.tokenize || tokenBase)(stream, state);\n if (style == \"comment\") return style;\n if (ctx.align == null) ctx.align = true;\n\n if ((curPunc == \";\" || curPunc == \":\" || curPunc == \",\")\n && ctx.type == \"statement\"){\n popContext(state);\n }\n else if (curPunc == \"{\") pushContext(state, stream.column(), \"}\");\n else if (curPunc == \"[\") pushContext(state, stream.column(), \"]\");\n else if (curPunc == \"(\") pushContext(state, stream.column(), \")\");\n else if (curPunc == \"}\") {\n while (ctx.type == \"statement\") ctx = popContext(state);\n if (ctx.type == \"}\") ctx = popContext(state);\n while (ctx.type == \"statement\") ctx = popContext(state);\n }\n else if (curPunc == ctx.type) popContext(state);\n else if (indentStatements && (((ctx.type == \"}\" || ctx.type == \"top\")\n && curPunc != ';') || (ctx.type == \"statement\"\n && curPunc == \"newstatement\")))\n pushContext(state, stream.column(), \"statement\");\n state.startOfLine = false;\n return style;\n },\n\n languageData: {\n indentOnInput: /^\\s*[{}]$/,\n commentTokens: {line: \"#\"}\n }\n};\n"],"names":["words","str","obj","split","i","length","parserConfig","name","keywords","fileNCtrlMaskOptions","externalCommands","multiLineStrings","curPunc","indentStatements","isOperatorChar","tokenBase","stream","state","quote","ch","next","tokenize","escaped","end","afterNext","peek","toLowerCase","test","skipToEnd","eatWhile","cur","current","propertyIsEnumerable","Context","indented","column","type","align","prev","this","pushContext","col","indent","context","popContext","t","ttcnCfg","startState","startOfLine","token","ctx","sol","indentation","eatSpace","style","languageData","indentOnInput","commentTokens","line"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/1620.index.js b/book/_build/html/_static/1620.index.js new file mode 100644 index 0000000..b471bf9 --- /dev/null +++ b/book/_build/html/_static/1620.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[1620],{21620:(e,n,t)=>{function i(e,n){for(var t=0;tk});var a={unnamedDefinition:["interface"],namedDefinition:["module","library","macro","C-struct","C-union","C-function","C-callable-wrapper"],typeParameterizedDefinition:["class","C-subtype","C-mapped-subtype"],otherParameterizedDefinition:["method","function","C-variable","C-address"],constantSimpleDefinition:["constant"],variableSimpleDefinition:["variable"],otherSimpleDefinition:["generic","domain","C-pointer-type","table"],statement:["if","block","begin","method","case","for","select","when","unless","until","while","iterate","profiling","dynamic-bind"],separator:["finally","exception","cleanup","else","elseif","afterwards"],other:["above","below","by","from","handler","in","instance","let","local","otherwise","slot","subclass","then","to","keyed-by","virtual"],signalingCalls:["signal","error","cerror","break","check-type","abort"]};a.otherDefinition=a.unnamedDefinition.concat(a.namedDefinition).concat(a.otherParameterizedDefinition),a.definition=a.typeParameterizedDefinition.concat(a.otherDefinition),a.parameterizedDefinition=a.typeParameterizedDefinition.concat(a.otherParameterizedDefinition),a.simpleDefinition=a.constantSimpleDefinition.concat(a.variableSimpleDefinition).concat(a.otherSimpleDefinition),a.keyword=a.statement.concat(a.separator).concat(a.other);var o="[-_a-zA-Z?!*@<>$%]+",l=new RegExp("^"+o),f={symbolKeyword:o+":",symbolClass:"<"+o+">",symbolGlobal:"\\*"+o+"\\*",symbolConstant:"\\$"+o},c={symbolKeyword:"atom",symbolClass:"tag",symbolGlobal:"variableName.standard",symbolConstant:"variableName.constant"};for(var s in f)f.hasOwnProperty(s)&&(f[s]=new RegExp("^"+f[s]));f.keyword=[/^with(?:out)?-[-_a-zA-Z?!*@<>$%]+/];var u={keyword:"keyword",definition:"def",simpleDefinition:"def",signalingCalls:"builtin"},m={},d={};function p(e,n,t){return n.tokenize=t,t(e,n)}function b(e,n){var t=e.peek();if("'"==t||'"'==t)return e.next(),p(e,n,y(t,"string"));if("/"==t){if(e.next(),e.eat("*"))return p(e,n,h);if(e.eat("/"))return e.skipToEnd(),"comment";e.backUp(1)}else if(/[+\-\d\.]/.test(t)){if(e.match(/^[+-]?[0-9]*\.[0-9]*([esdx][+-]?[0-9]+)?/i)||e.match(/^[+-]?[0-9]+([esdx][+-]?[0-9]+)/i)||e.match(/^[+-]?\d+/))return"number"}else{if("#"==t)return e.next(),'"'==(t=e.peek())?(e.next(),p(e,n,y('"',"string"))):"b"==t?(e.next(),e.eatWhile(/[01]/),"number"):"x"==t?(e.next(),e.eatWhile(/[\da-f]/i),"number"):"o"==t?(e.next(),e.eatWhile(/[0-7]/),"number"):"#"==t?(e.next(),"punctuation"):"["==t||"("==t?(e.next(),"bracket"):e.match(/f|t|all-keys|include|key|next|rest/i)?"atom":(e.eatWhile(/[-a-zA-Z]/),"error");if("~"==t)return e.next(),"="==(t=e.peek())?(e.next(),"="==(t=e.peek())?(e.next(),"operator"):"operator"):"operator";if(":"==t){if(e.next(),"="==(t=e.peek()))return e.next(),"operator";if(":"==t)return e.next(),"punctuation"}else{if(-1!="[](){}".indexOf(t))return e.next(),"bracket";if(-1!=".,".indexOf(t))return e.next(),"punctuation";if(e.match("end"))return"keyword"}}for(var i in f)if(f.hasOwnProperty(i)){var a=f[i];if(a instanceof Array&&r(a,(function(n){return e.match(n)}))||e.match(a))return c[i]}return/[+\-*\/^=<>&|]/.test(t)?(e.next(),"operator"):e.match("define")?"def":(e.eatWhile(/[\w\-]/),m.hasOwnProperty(e.current())?d[e.current()]:e.current().match(l)?"variable":(e.next(),"variableName.standard"))}function h(e,n){for(var t,i=!1,r=!1,a=0;t=e.next();){if("/"==t&&i){if(!(a>0)){n.tokenize=b;break}a--}else"*"==t&&r&&a++;i="*"==t,r="/"==t}return"comment"}function y(e,n){return function(t,i){for(var r,a=!1,o=!1;null!=(r=t.next());){if(r==e&&!a){o=!0;break}a=!a&&"\\"==r}return!o&&a||(i.tokenize=b),n}}i(["keyword","definition","simpleDefinition","signalingCalls"],(function(e){i(a[e],(function(n){m[n]=e,d[n]=u[e]}))}));const k={name:"dylan",startState:function(){return{tokenize:b,currentIndent:0}},token:function(e,n){return e.eatSpace()?null:n.tokenize(e,n)},languageData:{commentTokens:{block:{open:"/*",close:"*/"}}}}}}]); +//# sourceMappingURL=1620.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/1620.index.js.map b/book/_build/html/_static/1620.index.js.map new file mode 100644 index 0000000..6c0176f --- /dev/null +++ b/book/_build/html/_static/1620.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"1620.index.js","mappings":"+FAAA,SAASA,EAAQC,EAAKC,GACpB,IAAK,IAAIC,EAAI,EAAGA,EAAIF,EAAIG,OAAQD,IAAKD,EAAED,EAAIE,GAAIA,EACjD,CACA,SAASE,EAAKJ,EAAKC,GACjB,IAAK,IAAIC,EAAI,EAAGA,EAAIF,EAAIG,OAAQD,IAAK,GAAID,EAAED,EAAIE,GAAIA,GAAI,OAAO,EAC9D,OAAO,CACT,C,4BAGA,IAAIG,EAAQ,CAEVC,kBAAmB,CAAC,aAGpBC,gBAAiB,CAAC,SAAU,UAAW,QACrB,WAAY,UACZ,aAAc,sBAMhCC,4BAA6B,CAAC,QAAS,YAAa,oBAIpDC,6BAA8B,CAAC,SAAU,WACV,aAAc,aAM7CC,yBAA0B,CAAC,YAK3BC,yBAA0B,CAAC,YAI3BC,sBAAuB,CAAC,UAAW,SACX,iBACA,SAIxBC,UAAW,CAAC,KAAM,QAAS,QAAS,SAAU,OAClC,MAAO,SAAU,OAAQ,SAAU,QACnC,QAAS,UAAW,YAAa,gBAM7CC,UAAW,CAAC,UAAW,YAAa,UAAW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EACAC,MAAO,SAASjC,EAAQC,GACtB,OAAID,EAAOkC,WACF,KACGjC,EAAMC,SAASF,EAAQC,EAErC,EACAkC,aAAc,CACZC,cAAe,CAACC,MAAO,CAACC,KAAM,KAAMC,MAAO,Q","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/dylan.js"],"sourcesContent":["function forEach(arr, f) {\n for (var i = 0; i < arr.length; i++) f(arr[i], i)\n}\nfunction some(arr, f) {\n for (var i = 0; i < arr.length; i++) if (f(arr[i], i)) return true\n return false\n}\n\n// Words\nvar words = {\n // Words that introduce unnamed definitions like \"define interface\"\n unnamedDefinition: [\"interface\"],\n\n // Words that introduce simple named definitions like \"define library\"\n namedDefinition: [\"module\", \"library\", \"macro\",\n \"C-struct\", \"C-union\",\n \"C-function\", \"C-callable-wrapper\"\n ],\n\n // Words that introduce type definitions like \"define class\".\n // These are also parameterized like \"define method\" and are\n // appended to otherParameterizedDefinitionWords\n typeParameterizedDefinition: [\"class\", \"C-subtype\", \"C-mapped-subtype\"],\n\n // Words that introduce trickier definitions like \"define method\".\n // These require special definitions to be added to startExpressions\n otherParameterizedDefinition: [\"method\", \"function\",\n \"C-variable\", \"C-address\"\n ],\n\n // Words that introduce module constant definitions.\n // These must also be simple definitions and are\n // appended to otherSimpleDefinitionWords\n constantSimpleDefinition: [\"constant\"],\n\n // Words that introduce module variable definitions.\n // These must also be simple definitions and are\n // appended to otherSimpleDefinitionWords\n variableSimpleDefinition: [\"variable\"],\n\n // Other words that introduce simple definitions\n // (without implicit bodies).\n otherSimpleDefinition: [\"generic\", \"domain\",\n \"C-pointer-type\",\n \"table\"\n ],\n\n // Words that begin statements with implicit bodies.\n statement: [\"if\", \"block\", \"begin\", \"method\", \"case\",\n \"for\", \"select\", \"when\", \"unless\", \"until\",\n \"while\", \"iterate\", \"profiling\", \"dynamic-bind\"\n ],\n\n // Patterns that act as separators in compound statements.\n // This may include any general pattern that must be indented\n // specially.\n separator: [\"finally\", \"exception\", \"cleanup\", \"else\",\n \"elseif\", \"afterwards\"\n ],\n\n // Keywords that do not require special indentation handling,\n // but which should be highlighted\n other: [\"above\", \"below\", \"by\", \"from\", \"handler\", \"in\",\n \"instance\", \"let\", \"local\", \"otherwise\", \"slot\",\n \"subclass\", \"then\", \"to\", \"keyed-by\", \"virtual\"\n ],\n\n // Condition signaling function calls\n signalingCalls: [\"signal\", \"error\", \"cerror\",\n \"break\", \"check-type\", \"abort\"\n ]\n};\n\nwords[\"otherDefinition\"] =\n words[\"unnamedDefinition\"]\n .concat(words[\"namedDefinition\"])\n .concat(words[\"otherParameterizedDefinition\"]);\n\nwords[\"definition\"] =\n words[\"typeParameterizedDefinition\"]\n .concat(words[\"otherDefinition\"]);\n\nwords[\"parameterizedDefinition\"] =\n words[\"typeParameterizedDefinition\"]\n .concat(words[\"otherParameterizedDefinition\"]);\n\nwords[\"simpleDefinition\"] =\n words[\"constantSimpleDefinition\"]\n .concat(words[\"variableSimpleDefinition\"])\n .concat(words[\"otherSimpleDefinition\"]);\n\nwords[\"keyword\"] =\n words[\"statement\"]\n .concat(words[\"separator\"])\n .concat(words[\"other\"]);\n\n// Patterns\nvar symbolPattern = \"[-_a-zA-Z?!*@<>$%]+\";\nvar symbol = new RegExp(\"^\" + symbolPattern);\nvar patterns = {\n // Symbols with special syntax\n symbolKeyword: symbolPattern + \":\",\n symbolClass: \"<\" + symbolPattern + \">\",\n symbolGlobal: \"\\\\*\" + symbolPattern + \"\\\\*\",\n symbolConstant: \"\\\\$\" + symbolPattern\n};\nvar patternStyles = {\n symbolKeyword: \"atom\",\n symbolClass: \"tag\",\n symbolGlobal: \"variableName.standard\",\n symbolConstant: \"variableName.constant\"\n};\n\n// Compile all patterns to regular expressions\nfor (var patternName in patterns)\n if (patterns.hasOwnProperty(patternName))\n patterns[patternName] = new RegExp(\"^\" + patterns[patternName]);\n\n// Names beginning \"with-\" and \"without-\" are commonly\n// used as statement macro\npatterns[\"keyword\"] = [/^with(?:out)?-[-_a-zA-Z?!*@<>$%]+/];\n\nvar styles = {};\nstyles[\"keyword\"] = \"keyword\";\nstyles[\"definition\"] = \"def\";\nstyles[\"simpleDefinition\"] = \"def\";\nstyles[\"signalingCalls\"] = \"builtin\";\n\n// protected words lookup table\nvar wordLookup = {};\nvar styleLookup = {};\n\nforEach([\n \"keyword\",\n \"definition\",\n \"simpleDefinition\",\n \"signalingCalls\"\n], function(type) {\n forEach(words[type], function(word) {\n wordLookup[word] = type;\n styleLookup[word] = styles[type];\n });\n});\n\n\nfunction chain(stream, state, f) {\n state.tokenize = f;\n return f(stream, state);\n}\n\nfunction tokenBase(stream, state) {\n // String\n var ch = stream.peek();\n if (ch == \"'\" || ch == '\"') {\n stream.next();\n return chain(stream, state, tokenString(ch, \"string\"));\n }\n // Comment\n else if (ch == \"/\") {\n stream.next();\n if (stream.eat(\"*\")) {\n return chain(stream, state, tokenComment);\n } else if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return \"comment\";\n }\n stream.backUp(1);\n }\n // Decimal\n else if (/[+\\-\\d\\.]/.test(ch)) {\n if (stream.match(/^[+-]?[0-9]*\\.[0-9]*([esdx][+-]?[0-9]+)?/i) ||\n stream.match(/^[+-]?[0-9]+([esdx][+-]?[0-9]+)/i) ||\n stream.match(/^[+-]?\\d+/)) {\n return \"number\";\n }\n }\n // Hash\n else if (ch == \"#\") {\n stream.next();\n // Symbol with string syntax\n ch = stream.peek();\n if (ch == '\"') {\n stream.next();\n return chain(stream, state, tokenString('\"', \"string\"));\n }\n // Binary number\n else if (ch == \"b\") {\n stream.next();\n stream.eatWhile(/[01]/);\n return \"number\";\n }\n // Hex number\n else if (ch == \"x\") {\n stream.next();\n stream.eatWhile(/[\\da-f]/i);\n return \"number\";\n }\n // Octal number\n else if (ch == \"o\") {\n stream.next();\n stream.eatWhile(/[0-7]/);\n return \"number\";\n }\n // Token concatenation in macros\n else if (ch == '#') {\n stream.next();\n return \"punctuation\";\n }\n // Sequence literals\n else if ((ch == '[') || (ch == '(')) {\n stream.next();\n return \"bracket\";\n // Hash symbol\n } else if (stream.match(/f|t|all-keys|include|key|next|rest/i)) {\n return \"atom\";\n } else {\n stream.eatWhile(/[-a-zA-Z]/);\n return \"error\";\n }\n } else if (ch == \"~\") {\n stream.next();\n ch = stream.peek();\n if (ch == \"=\") {\n stream.next();\n ch = stream.peek();\n if (ch == \"=\") {\n stream.next();\n return \"operator\";\n }\n return \"operator\";\n }\n return \"operator\";\n } else if (ch == \":\") {\n stream.next();\n ch = stream.peek();\n if (ch == \"=\") {\n stream.next();\n return \"operator\";\n } else if (ch == \":\") {\n stream.next();\n return \"punctuation\";\n }\n } else if (\"[](){}\".indexOf(ch) != -1) {\n stream.next();\n return \"bracket\";\n } else if (\".,\".indexOf(ch) != -1) {\n stream.next();\n return \"punctuation\";\n } else if (stream.match(\"end\")) {\n return \"keyword\";\n }\n for (var name in patterns) {\n if (patterns.hasOwnProperty(name)) {\n var pattern = patterns[name];\n if ((pattern instanceof Array && some(pattern, function(p) {\n return stream.match(p);\n })) || stream.match(pattern))\n return patternStyles[name];\n }\n }\n if (/[+\\-*\\/^=<>&|]/.test(ch)) {\n stream.next();\n return \"operator\";\n }\n if (stream.match(\"define\")) {\n return \"def\";\n } else {\n stream.eatWhile(/[\\w\\-]/);\n // Keyword\n if (wordLookup.hasOwnProperty(stream.current())) {\n return styleLookup[stream.current()];\n } else if (stream.current().match(symbol)) {\n return \"variable\";\n } else {\n stream.next();\n return \"variableName.standard\";\n }\n }\n}\n\nfunction tokenComment(stream, state) {\n var maybeEnd = false, maybeNested = false, nestedCount = 0, ch;\n while ((ch = stream.next())) {\n if (ch == \"/\" && maybeEnd) {\n if (nestedCount > 0) {\n nestedCount--;\n } else {\n state.tokenize = tokenBase;\n break;\n }\n } else if (ch == \"*\" && maybeNested) {\n nestedCount++;\n }\n maybeEnd = (ch == \"*\");\n maybeNested = (ch == \"/\");\n }\n return \"comment\";\n}\n\nfunction tokenString(quote, style) {\n return function(stream, state) {\n var escaped = false, next, end = false;\n while ((next = stream.next()) != null) {\n if (next == quote && !escaped) {\n end = true;\n break;\n }\n escaped = !escaped && next == \"\\\\\";\n }\n if (end || !escaped) {\n state.tokenize = tokenBase;\n }\n return style;\n };\n}\n\n// Interface\nexport const dylan = {\n name: \"dylan\",\n startState: function() {\n return {\n tokenize: tokenBase,\n currentIndent: 0\n };\n },\n token: function(stream, state) {\n if (stream.eatSpace())\n return null;\n var style = state.tokenize(stream, state);\n return style;\n },\n languageData: {\n commentTokens: {block: {open: \"/*\", close: \"*/\"}}\n }\n};\n\n"],"names":["forEach","arr","f","i","length","some","words","unnamedDefinition","namedDefinition","typeParameterizedDefinition","otherParameterizedDefinition","constantSimpleDefinition","variableSimpleDefinition","otherSimpleDefinition","statement","separator","other","signalingCalls","concat","symbolPattern","symbol","RegExp","patterns","symbolKeyword","symbolClass","symbolGlobal","symbolConstant","patternStyles","patternName","hasOwnProperty","styles","wordLookup","styleLookup","chain","stream","state","tokenize","tokenBase","ch","peek","next","tokenString","eat","tokenComment","skipToEnd","backUp","test","match","eatWhile","indexOf","name","pattern","Array","p","current","maybeEnd","maybeNested","nestedCount","quote","style","escaped","end","type","word","dylan","startState","currentIndent","token","eatSpace","languageData","commentTokens","block","open","close"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/1643.index.js b/book/_build/html/_static/1643.index.js new file mode 100644 index 0000000..7d22e97 --- /dev/null +++ b/book/_build/html/_static/1643.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[1643],{31643:(a,e,n)=>{n.r(e),n.d(e,{gherkin:()=>i});const i={name:"gherkin",startState:function(){return{lineNumber:0,tableHeaderLine:!1,allowFeature:!0,allowBackground:!1,allowScenario:!1,allowSteps:!1,allowPlaceholders:!1,allowMultilineArgument:!1,inMultilineString:!1,inMultilineTable:!1,inKeywordLine:!1}},token:function(a,e){if(a.sol()&&(e.lineNumber++,e.inKeywordLine=!1,e.inMultilineTable&&(e.tableHeaderLine=!1,a.match(/\s*\|/,!1)||(e.allowMultilineArgument=!1,e.inMultilineTable=!1))),a.eatSpace(),e.allowMultilineArgument){if(e.inMultilineString)return a.match('"""')?(e.inMultilineString=!1,e.allowMultilineArgument=!1):a.match(/.*/),"string";if(e.inMultilineTable)return a.match(/\|\s*/)?"bracket":(a.match(/[^\|]*/),e.tableHeaderLine?"header":"string");if(a.match('"""'))return e.inMultilineString=!0,"string";if(a.match("|"))return e.inMultilineTable=!0,e.tableHeaderLine=!0,"bracket"}return a.match(/#.*/)?"comment":!e.inKeywordLine&&a.match(/@\S+/)?"tag":!e.inKeywordLine&&e.allowFeature&&a.match(/(機能|功能|フィーチャ|기능|โครงหลัก|ความสามารถ|ความต้องการทางธุรกิจ|ಹೆಚ್ಚಳ|గుణము|ਮੁਹਾਂਦਰਾ|ਨਕਸ਼ ਨੁਹਾਰ|ਖਾਸੀਅਤ|रूप लेख|وِیژگی|خاصية|תכונה|Функціонал|Функция|Функционалност|Функционал|Үзенчәлеклелек|Свойство|Особина|Мөмкинлек|Могућност|Λειτουργία|Δυνατότητα|Właściwość|Vlastnosť|Trajto|Tính năng|Savybė|Pretty much|Požiadavka|Požadavek|Potrzeba biznesowa|Özellik|Osobina|Ominaisuus|Omadus|OH HAI|Mogućnost|Mogucnost|Jellemző|Hwæt|Hwaet|Funzionalità|Funktionalitéit|Funktionalität|Funkcja|Funkcionalnost|Funkcionalitāte|Funkcia|Fungsi|Functionaliteit|Funcționalitate|Funcţionalitate|Functionalitate|Funcionalitat|Funcionalidade|Fonctionnalité|Fitur|Fīča|Feature|Eiginleiki|Egenskap|Egenskab|Característica|Caracteristica|Business Need|Aspekt|Arwedd|Ahoy matey!|Ability):/)?(e.allowScenario=!0,e.allowBackground=!0,e.allowPlaceholders=!1,e.allowSteps=!1,e.allowMultilineArgument=!1,e.inKeywordLine=!0,"keyword"):!e.inKeywordLine&&e.allowBackground&&a.match(/(背景|배경|แนวคิด|ಹಿನ್ನೆಲೆ|నేపథ్యం|ਪਿਛੋਕੜ|पृष्ठभूमि|زمینه|الخلفية|רקע|Тарих|Предыстория|Предистория|Позадина|Передумова|Основа|Контекст|Кереш|Υπόβαθρο|Założenia|Yo\-ho\-ho|Tausta|Taust|Situācija|Rerefons|Pozadina|Pozadie|Pozadí|Osnova|Latar Belakang|Kontext|Konteksts|Kontekstas|Kontekst|Háttér|Hannergrond|Grundlage|Geçmiş|Fundo|Fono|First off|Dis is what went down|Dasar|Contexto|Contexte|Context|Contesto|Cenário de Fundo|Cenario de Fundo|Cefndir|Bối cảnh|Bakgrunnur|Bakgrunn|Bakgrund|Baggrund|Background|B4|Antecedents|Antecedentes|Ær|Aer|Achtergrond):/)?(e.allowPlaceholders=!1,e.allowSteps=!0,e.allowBackground=!1,e.allowMultilineArgument=!1,e.inKeywordLine=!0,"keyword"):!e.inKeywordLine&&e.allowScenario&&a.match(/(場景大綱|场景大纲|劇本大綱|剧本大纲|テンプレ|シナリオテンプレート|シナリオテンプレ|シナリオアウトライン|시나리오 개요|สรุปเหตุการณ์|โครงสร้างของเหตุการณ์|ವಿವರಣೆ|కథనం|ਪਟਕਥਾ ਰੂਪ ਰੇਖਾ|ਪਟਕਥਾ ਢਾਂਚਾ|परिदृश्य रूपरेखा|سيناريو مخطط|الگوی سناریو|תבנית תרחיש|Сценарийның төзелеше|Сценарий структураси|Структура сценарію|Структура сценария|Структура сценарија|Скица|Рамка на сценарий|Концепт|Περιγραφή Σεναρίου|Wharrimean is|Template Situai|Template Senario|Template Keadaan|Tapausaihio|Szenariogrundriss|Szablon scenariusza|Swa hwær swa|Swa hwaer swa|Struktura scenarija|Structură scenariu|Structura scenariu|Skica|Skenario konsep|Shiver me timbers|Senaryo taslağı|Schema dello scenario|Scenariomall|Scenariomal|Scenario Template|Scenario Outline|Scenario Amlinellol|Scenārijs pēc parauga|Scenarijaus šablonas|Reckon it's like|Raamstsenaarium|Plang vum Szenario|Plan du Scénario|Plan du scénario|Osnova scénáře|Osnova Scenára|Náčrt Scenáru|Náčrt Scénáře|Náčrt Scenára|MISHUN SRSLY|Menggariskan Senario|Lýsing Dæma|Lýsing Atburðarásar|Konturo de la scenaro|Koncept|Khung tình huống|Khung kịch bản|Forgatókönyv vázlat|Esquema do Cenário|Esquema do Cenario|Esquema del escenario|Esquema de l'escenari|Esbozo do escenario|Delineação do Cenário|Delineacao do Cenario|All y'all|Abstrakt Scenario|Abstract Scenario):/)?(e.allowPlaceholders=!0,e.allowSteps=!0,e.allowMultilineArgument=!1,e.inKeywordLine=!0,"keyword"):e.allowScenario&&a.match(/(例子|例|サンプル|예|ชุดของเหตุการณ์|ชุดของตัวอย่าง|ಉದಾಹರಣೆಗಳು|ఉదాహరణలు|ਉਦਾਹਰਨਾਂ|उदाहरण|نمونه ها|امثلة|דוגמאות|Үрнәкләр|Сценарији|Примеры|Примери|Приклади|Мисоллар|Мисаллар|Σενάρια|Παραδείγματα|You'll wanna|Voorbeelden|Variantai|Tapaukset|Se þe|Se the|Se ðe|Scenarios|Scenariji|Scenarijai|Przykłady|Primjeri|Primeri|Příklady|Príklady|Piemēri|Példák|Pavyzdžiai|Paraugs|Örnekler|Juhtumid|Exemplos|Exemples|Exemple|Exempel|EXAMPLZ|Examples|Esempi|Enghreifftiau|Ekzemploj|Eksempler|Ejemplos|Dữ liệu|Dead men tell no tales|Dæmi|Contoh|Cenários|Cenarios|Beispiller|Beispiele|Atburðarásir):/)?(e.allowPlaceholders=!1,e.allowSteps=!0,e.allowBackground=!1,e.allowMultilineArgument=!0,"keyword"):!e.inKeywordLine&&e.allowScenario&&a.match(/(場景|场景|劇本|剧本|シナリオ|시나리오|เหตุการณ์|ಕಥಾಸಾರಾಂಶ|సన్నివేశం|ਪਟਕਥਾ|परिदृश्य|سيناريو|سناریو|תרחיש|Сценарій|Сценарио|Сценарий|Пример|Σενάριο|Tình huống|The thing of it is|Tapaus|Szenario|Swa|Stsenaarium|Skenario|Situai|Senaryo|Senario|Scenaro|Scenariusz|Scenariu|Scénario|Scenario|Scenarijus|Scenārijs|Scenarij|Scenarie|Scénář|Scenár|Primer|MISHUN|Kịch bản|Keadaan|Heave to|Forgatókönyv|Escenario|Escenari|Cenário|Cenario|Awww, look mate|Atburðarás):/)?(e.allowPlaceholders=!1,e.allowSteps=!0,e.allowBackground=!1,e.allowMultilineArgument=!1,e.inKeywordLine=!0,"keyword"):!e.inKeywordLine&&e.allowSteps&&a.match(/(那麼|那么|而且|當|当|并且|同時|同时|前提|假设|假設|假定|假如|但是|但し|並且|もし|ならば|ただし|しかし|かつ|하지만|조건|먼저|만일|만약|단|그리고|그러면|และ |เมื่อ |แต่ |ดังนั้น |กำหนดให้ |ಸ್ಥಿತಿಯನ್ನು |ಮತ್ತು |ನೀಡಿದ |ನಂತರ |ಆದರೆ |మరియు |చెప్పబడినది |కాని |ఈ పరిస్థితిలో |అప్పుడు |ਪਰ |ਤਦ |ਜੇਕਰ |ਜਿਵੇਂ ਕਿ |ਜਦੋਂ |ਅਤੇ |यदि |परन्तु |पर |तब |तदा |तथा |जब |चूंकि |किन्तु |कदा |और |अगर |و |هنگامی |متى |لكن |عندما |ثم |بفرض |با فرض |اما |اذاً |آنگاه |כאשר |וגם |בהינתן |אזי |אז |אבל |Якщо |Һәм |Унда |Тоді |Тогда |То |Также |Та |Пусть |Припустимо, що |Припустимо |Онда |Но |Нехай |Нәтиҗәдә |Лекин |Ләкин |Коли |Когда |Когато |Када |Кад |К тому же |І |И |Задато |Задати |Задате |Если |Допустим |Дано |Дадено |Вә |Ва |Бирок |Әмма |Әйтик |Әгәр |Аммо |Али |Але |Агар |А також |А |Τότε |Όταν |Και |Δεδομένου |Αλλά |Þurh |Þegar |Þa þe |Þá |Þa |Zatati |Zakładając |Zadato |Zadate |Zadano |Zadani |Zadan |Za předpokladu |Za predpokladu |Youse know when youse got |Youse know like when |Yna |Yeah nah |Y'know |Y |Wun |Wtedy |When y'all |When |Wenn |WEN |wann |Ve |Và |Und |Un |ugeholl |Too right |Thurh |Thì |Then y'all |Then |Tha the |Tha |Tetapi |Tapi |Tak |Tada |Tad |Stel |Soit |Siis |Și |Şi |Si |Sed |Se |Så |Quando |Quand |Quan |Pryd |Potom |Pokud |Pokiaľ |Però |Pero |Pak |Oraz |Onda |Ond |Oletetaan |Og |Och |O zaman |Niin |Nhưng |När |Når |Mutta |Men |Mas |Maka |Majd |Mając |Mais |Maar |mä |Ma |Lorsque |Lorsqu'|Logo |Let go and haul |Kun |Kuid |Kui |Kiedy |Khi |Ketika |Kemudian |Keď |Když |Kaj |Kai |Kada |Kad |Jeżeli |Jeśli |Ja |It's just unbelievable |Ir |I CAN HAZ |I |Ha |Givun |Givet |Given y'all |Given |Gitt |Gegeven |Gegeben seien |Gegeben sei |Gdy |Gangway! |Fakat |Étant donnés |Etant donnés |Étant données |Etant données |Étant donnée |Etant donnée |Étant donné |Etant donné |Et |És |Entonces |Entón |Então |Entao |En |Eğer ki |Ef |Eeldades |E |Ðurh |Duota |Dun |Donitaĵo |Donat |Donada |Do |Diyelim ki |Diberi |Dengan |Den youse gotta |DEN |De |Dato |Dați fiind |Daţi fiind |Dati fiind |Dati |Date fiind |Date |Data |Dat fiind |Dar |Dann |dann |Dan |Dados |Dado |Dadas |Dada |Ða ðe |Ða |Cuando |Cho |Cando |Când |Cand |Cal |But y'all |But at the end of the day I reckon |BUT |But |Buh |Blimey! |Biết |Bet |Bagi |Aye |awer |Avast! |Atunci |Atesa |Atès |Apabila |Anrhegedig a |Angenommen |And y'all |And |AN |An |an |Amikor |Amennyiben |Ama |Als |Alors |Allora |Ali |Aleshores |Ale |Akkor |Ak |Adott |Ac |Aber |A zároveň |A tiež |A taktiež |A také |A |a |7 |\* )/)?(e.inStep=!0,e.allowPlaceholders=!0,e.allowMultilineArgument=!0,e.inKeywordLine=!0,"keyword"):a.match(/"[^"]*"?/)?"string":e.allowPlaceholders&&a.match(/<[^>]*>?/)?"variable":(a.next(),a.eatWhile(/[^@"<#]/),null)}}}}]); +//# sourceMappingURL=1643.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/1643.index.js.map b/book/_build/html/_static/1643.index.js.map new file mode 100644 index 0000000..d6c0afc --- /dev/null +++ b/book/_build/html/_static/1643.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"1643.index.js","mappings":"6HAAO,MAAMA,EAAU,CACrBC,KAAM,UACNC,WAAY,WACV,MAAO,CACLC,WAAY,EACZC,iBAAiB,EACjBC,cAAc,EACdC,iBAAiB,EACjBC,eAAe,EACfC,YAAY,EACZC,mBAAmB,EACnBC,wBAAwB,EACxBC,mBAAmB,EACnBC,kBAAkB,EAClBC,eAAe,EAEnB,EACAC,MAAO,SAAUC,EAAQC,GAevB,GAdID,EAAOE,QACTD,EAAMb,aACNa,EAAMH,eAAgB,EAClBG,EAAMJ,mBACRI,EAAMZ,iBAAkB,EACnBW,EAAOG,MAAM,SAAS,KACzBF,EAAMN,wBAAyB,EAC/BM,EAAMJ,kBAAmB,KAK/BG,EAAOI,WAEHH,EAAMN,uBAAwB,CAGhC,GAAIM,EAAML,kBAOR,OANII,EAAOG,MAAM,QACfF,EAAML,mBAAoB,EAC1BK,EAAMN,wBAAyB,GAE/BK,EAAOG,MAAM,MAER,SAIT,GAAIF,EAAMJ,iBACR,OAAIG,EAAOG,MAAM,SACR,WAEPH,EAAOG,MAAM,UACNF,EAAMZ,gBAAkB,SAAW,UAK9C,GAAIW,EAAOG,MAAM,OAGf,OADAF,EAAML,mBAAoB,EACnB,SACF,GAAII,EAAOG,MAAM,KAItB,OAFAF,EAAMJ,kBAAmB,EACzBI,EAAMZ,iBAAkB,EACjB,SAGX,CAGA,OAAIW,EAAOG,MAAM,OACR,WAGGF,EAAMH,eAAiBE,EAAOG,MAAM,QACvC,OAGGF,EAAMH,eAAiBG,EAAMX,cAAgBU,EAAOG,MAAM,svBACpEF,EAAMT,eAAgB,EACtBS,EAAMV,iBAAkB,EACxBU,EAAMP,mBAAoB,EAC1BO,EAAMR,YAAa,EACnBQ,EAAMN,wBAAyB,EAC/BM,EAAMH,eAAgB,EACf,YAGGG,EAAMH,eAAiBG,EAAMV,iBAAmBS,EAAOG,MAAM,6iBACvEF,EAAMP,mBAAoB,EAC1BO,EAAMR,YAAa,EACnBQ,EAAMV,iBAAkB,EACxBU,EAAMN,wBAAyB,EAC/BM,EAAMH,eAAgB,EACf,YAGGG,EAAMH,eAAiBG,EAAMT,eAAiBQ,EAAOG,MAAM,kuCACrEF,EAAMP,mBAAoB,EAC1BO,EAAMR,YAAa,EACnBQ,EAAMN,wBAAyB,EAC/BM,EAAMH,eAAgB,EACf,WAGEG,EAAMT,eAAiBQ,EAAOG,MAAM,okBAC7CF,EAAMP,mBAAoB,EAC1BO,EAAMR,YAAa,EACnBQ,EAAMV,iBAAkB,EACxBU,EAAMN,wBAAyB,EACxB,YAGGM,EAAMH,eAAiBG,EAAMT,eAAiBQ,EAAOG,MAAM,6bACrEF,EAAMP,mBAAoB,EAC1BO,EAAMR,YAAa,EACnBQ,EAAMV,iBAAkB,EACxBU,EAAMN,wBAAyB,EAC/BM,EAAMH,eAAgB,EACf,YAGGG,EAAMH,eAAiBG,EAAMR,YAAcO,EAAOG,MAAM,y2EAClEF,EAAMI,QAAS,EACfJ,EAAMP,mBAAoB,EAC1BO,EAAMN,wBAAyB,EAC/BM,EAAMH,eAAgB,EACf,WAGEE,EAAOG,MAAM,YACf,SAGEF,EAAMP,mBAAqBM,EAAOG,MAAM,YAC1C,YAIPH,EAAOM,OACPN,EAAOO,SAAS,WACT,KAEX,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/gherkin.js"],"sourcesContent":["export const gherkin = {\n name: \"gherkin\",\n startState: function () {\n return {\n lineNumber: 0,\n tableHeaderLine: false,\n allowFeature: true,\n allowBackground: false,\n allowScenario: false,\n allowSteps: false,\n allowPlaceholders: false,\n allowMultilineArgument: false,\n inMultilineString: false,\n inMultilineTable: false,\n inKeywordLine: false\n };\n },\n token: function (stream, state) {\n if (stream.sol()) {\n state.lineNumber++;\n state.inKeywordLine = false;\n if (state.inMultilineTable) {\n state.tableHeaderLine = false;\n if (!stream.match(/\\s*\\|/, false)) {\n state.allowMultilineArgument = false;\n state.inMultilineTable = false;\n }\n }\n }\n\n stream.eatSpace();\n\n if (state.allowMultilineArgument) {\n\n // STRING\n if (state.inMultilineString) {\n if (stream.match('\"\"\"')) {\n state.inMultilineString = false;\n state.allowMultilineArgument = false;\n } else {\n stream.match(/.*/);\n }\n return \"string\";\n }\n\n // TABLE\n if (state.inMultilineTable) {\n if (stream.match(/\\|\\s*/)) {\n return \"bracket\";\n } else {\n stream.match(/[^\\|]*/);\n return state.tableHeaderLine ? \"header\" : \"string\";\n }\n }\n\n // DETECT START\n if (stream.match('\"\"\"')) {\n // String\n state.inMultilineString = true;\n return \"string\";\n } else if (stream.match(\"|\")) {\n // Table\n state.inMultilineTable = true;\n state.tableHeaderLine = true;\n return \"bracket\";\n }\n\n }\n\n // LINE COMMENT\n if (stream.match(/#.*/)) {\n return \"comment\";\n\n // TAG\n } else if (!state.inKeywordLine && stream.match(/@\\S+/)) {\n return \"tag\";\n\n // FEATURE\n } else if (!state.inKeywordLine && state.allowFeature && stream.match(/(機能|功能|フィーチャ|기능|โครงหลัก|ความสามารถ|ความต้องการทางธุรกิจ|ಹೆಚ್ಚಳ|గుణము|ਮੁਹਾਂਦਰਾ|ਨਕਸ਼ ਨੁਹਾਰ|ਖਾਸੀਅਤ|रूप लेख|وِیژگی|خاصية|תכונה|Функціонал|Функция|Функционалност|Функционал|Үзенчәлеклелек|Свойство|Особина|Мөмкинлек|Могућност|Λειτουργία|Δυνατότητα|Właściwość|Vlastnosť|Trajto|Tính năng|Savybė|Pretty much|Požiadavka|Požadavek|Potrzeba biznesowa|Özellik|Osobina|Ominaisuus|Omadus|OH HAI|Mogućnost|Mogucnost|Jellemző|Hwæt|Hwaet|Funzionalità|Funktionalitéit|Funktionalität|Funkcja|Funkcionalnost|Funkcionalitāte|Funkcia|Fungsi|Functionaliteit|Funcționalitate|Funcţionalitate|Functionalitate|Funcionalitat|Funcionalidade|Fonctionnalité|Fitur|Fīča|Feature|Eiginleiki|Egenskap|Egenskab|Característica|Caracteristica|Business Need|Aspekt|Arwedd|Ahoy matey!|Ability):/)) {\n state.allowScenario = true;\n state.allowBackground = true;\n state.allowPlaceholders = false;\n state.allowSteps = false;\n state.allowMultilineArgument = false;\n state.inKeywordLine = true;\n return \"keyword\";\n\n // BACKGROUND\n } else if (!state.inKeywordLine && state.allowBackground && stream.match(/(背景|배경|แนวคิด|ಹಿನ್ನೆಲೆ|నేపథ్యం|ਪਿਛੋਕੜ|पृष्ठभूमि|زمینه|الخلفية|רקע|Тарих|Предыстория|Предистория|Позадина|Передумова|Основа|Контекст|Кереш|Υπόβαθρο|Założenia|Yo\\-ho\\-ho|Tausta|Taust|Situācija|Rerefons|Pozadina|Pozadie|Pozadí|Osnova|Latar Belakang|Kontext|Konteksts|Kontekstas|Kontekst|Háttér|Hannergrond|Grundlage|Geçmiş|Fundo|Fono|First off|Dis is what went down|Dasar|Contexto|Contexte|Context|Contesto|Cenário de Fundo|Cenario de Fundo|Cefndir|Bối cảnh|Bakgrunnur|Bakgrunn|Bakgrund|Baggrund|Background|B4|Antecedents|Antecedentes|Ær|Aer|Achtergrond):/)) {\n state.allowPlaceholders = false;\n state.allowSteps = true;\n state.allowBackground = false;\n state.allowMultilineArgument = false;\n state.inKeywordLine = true;\n return \"keyword\";\n\n // SCENARIO OUTLINE\n } else if (!state.inKeywordLine && state.allowScenario && stream.match(/(場景大綱|场景大纲|劇本大綱|剧本大纲|テンプレ|シナリオテンプレート|シナリオテンプレ|シナリオアウトライン|시나리오 개요|สรุปเหตุการณ์|โครงสร้างของเหตุการณ์|ವಿವರಣೆ|కథనం|ਪਟਕਥਾ ਰੂਪ ਰੇਖਾ|ਪਟਕਥਾ ਢਾਂਚਾ|परिदृश्य रूपरेखा|سيناريو مخطط|الگوی سناریو|תבנית תרחיש|Сценарийның төзелеше|Сценарий структураси|Структура сценарію|Структура сценария|Структура сценарија|Скица|Рамка на сценарий|Концепт|Περιγραφή Σεναρίου|Wharrimean is|Template Situai|Template Senario|Template Keadaan|Tapausaihio|Szenariogrundriss|Szablon scenariusza|Swa hwær swa|Swa hwaer swa|Struktura scenarija|Structură scenariu|Structura scenariu|Skica|Skenario konsep|Shiver me timbers|Senaryo taslağı|Schema dello scenario|Scenariomall|Scenariomal|Scenario Template|Scenario Outline|Scenario Amlinellol|Scenārijs pēc parauga|Scenarijaus šablonas|Reckon it's like|Raamstsenaarium|Plang vum Szenario|Plan du Scénario|Plan du scénario|Osnova scénáře|Osnova Scenára|Náčrt Scenáru|Náčrt Scénáře|Náčrt Scenára|MISHUN SRSLY|Menggariskan Senario|Lýsing Dæma|Lýsing Atburðarásar|Konturo de la scenaro|Koncept|Khung tình huống|Khung kịch bản|Forgatókönyv vázlat|Esquema do Cenário|Esquema do Cenario|Esquema del escenario|Esquema de l'escenari|Esbozo do escenario|Delineação do Cenário|Delineacao do Cenario|All y'all|Abstrakt Scenario|Abstract Scenario):/)) {\n state.allowPlaceholders = true;\n state.allowSteps = true;\n state.allowMultilineArgument = false;\n state.inKeywordLine = true;\n return \"keyword\";\n\n // EXAMPLES\n } else if (state.allowScenario && stream.match(/(例子|例|サンプル|예|ชุดของเหตุการณ์|ชุดของตัวอย่าง|ಉದಾಹರಣೆಗಳು|ఉదాహరణలు|ਉਦਾਹਰਨਾਂ|उदाहरण|نمونه ها|امثلة|דוגמאות|Үрнәкләр|Сценарији|Примеры|Примери|Приклади|Мисоллар|Мисаллар|Σενάρια|Παραδείγματα|You'll wanna|Voorbeelden|Variantai|Tapaukset|Se þe|Se the|Se ðe|Scenarios|Scenariji|Scenarijai|Przykłady|Primjeri|Primeri|Příklady|Príklady|Piemēri|Példák|Pavyzdžiai|Paraugs|Örnekler|Juhtumid|Exemplos|Exemples|Exemple|Exempel|EXAMPLZ|Examples|Esempi|Enghreifftiau|Ekzemploj|Eksempler|Ejemplos|Dữ liệu|Dead men tell no tales|Dæmi|Contoh|Cenários|Cenarios|Beispiller|Beispiele|Atburðarásir):/)) {\n state.allowPlaceholders = false;\n state.allowSteps = true;\n state.allowBackground = false;\n state.allowMultilineArgument = true;\n return \"keyword\";\n\n // SCENARIO\n } else if (!state.inKeywordLine && state.allowScenario && stream.match(/(場景|场景|劇本|剧本|シナリオ|시나리오|เหตุการณ์|ಕಥಾಸಾರಾಂಶ|సన్నివేశం|ਪਟਕਥਾ|परिदृश्य|سيناريو|سناریو|תרחיש|Сценарій|Сценарио|Сценарий|Пример|Σενάριο|Tình huống|The thing of it is|Tapaus|Szenario|Swa|Stsenaarium|Skenario|Situai|Senaryo|Senario|Scenaro|Scenariusz|Scenariu|Scénario|Scenario|Scenarijus|Scenārijs|Scenarij|Scenarie|Scénář|Scenár|Primer|MISHUN|Kịch bản|Keadaan|Heave to|Forgatókönyv|Escenario|Escenari|Cenário|Cenario|Awww, look mate|Atburðarás):/)) {\n state.allowPlaceholders = false;\n state.allowSteps = true;\n state.allowBackground = false;\n state.allowMultilineArgument = false;\n state.inKeywordLine = true;\n return \"keyword\";\n\n // STEPS\n } else if (!state.inKeywordLine && state.allowSteps && stream.match(/(那麼|那么|而且|當|当|并且|同時|同时|前提|假设|假設|假定|假如|但是|但し|並且|もし|ならば|ただし|しかし|かつ|하지만|조건|먼저|만일|만약|단|그리고|그러면|และ |เมื่อ |แต่ |ดังนั้น |กำหนดให้ |ಸ್ಥಿತಿಯನ್ನು |ಮತ್ತು |ನೀಡಿದ |ನಂತರ |ಆದರೆ |మరియు |చెప్పబడినది |కాని |ఈ పరిస్థితిలో |అప్పుడు |ਪਰ |ਤਦ |ਜੇਕਰ |ਜਿਵੇਂ ਕਿ |ਜਦੋਂ |ਅਤੇ |यदि |परन्तु |पर |तब |तदा |तथा |जब |चूंकि |किन्तु |कदा |और |अगर |و |هنگامی |متى |لكن |عندما |ثم |بفرض |با فرض |اما |اذاً |آنگاه |כאשר |וגם |בהינתן |אזי |אז |אבל |Якщо |Һәм |Унда |Тоді |Тогда |То |Также |Та |Пусть |Припустимо, що |Припустимо |Онда |Но |Нехай |Нәтиҗәдә |Лекин |Ләкин |Коли |Когда |Когато |Када |Кад |К тому же |І |И |Задато |Задати |Задате |Если |Допустим |Дано |Дадено |Вә |Ва |Бирок |Әмма |Әйтик |Әгәр |Аммо |Али |Але |Агар |А також |А |Τότε |Όταν |Και |Δεδομένου |Αλλά |Þurh |Þegar |Þa þe |Þá |Þa |Zatati |Zakładając |Zadato |Zadate |Zadano |Zadani |Zadan |Za předpokladu |Za predpokladu |Youse know when youse got |Youse know like when |Yna |Yeah nah |Y'know |Y |Wun |Wtedy |When y'all |When |Wenn |WEN |wann |Ve |Và |Und |Un |ugeholl |Too right |Thurh |Thì |Then y'all |Then |Tha the |Tha |Tetapi |Tapi |Tak |Tada |Tad |Stel |Soit |Siis |Și |Şi |Si |Sed |Se |Så |Quando |Quand |Quan |Pryd |Potom |Pokud |Pokiaľ |Però |Pero |Pak |Oraz |Onda |Ond |Oletetaan |Og |Och |O zaman |Niin |Nhưng |När |Når |Mutta |Men |Mas |Maka |Majd |Mając |Mais |Maar |mä |Ma |Lorsque |Lorsqu'|Logo |Let go and haul |Kun |Kuid |Kui |Kiedy |Khi |Ketika |Kemudian |Keď |Když |Kaj |Kai |Kada |Kad |Jeżeli |Jeśli |Ja |It's just unbelievable |Ir |I CAN HAZ |I |Ha |Givun |Givet |Given y'all |Given |Gitt |Gegeven |Gegeben seien |Gegeben sei |Gdy |Gangway! |Fakat |Étant donnés |Etant donnés |Étant données |Etant données |Étant donnée |Etant donnée |Étant donné |Etant donné |Et |És |Entonces |Entón |Então |Entao |En |Eğer ki |Ef |Eeldades |E |Ðurh |Duota |Dun |Donitaĵo |Donat |Donada |Do |Diyelim ki |Diberi |Dengan |Den youse gotta |DEN |De |Dato |Dați fiind |Daţi fiind |Dati fiind |Dati |Date fiind |Date |Data |Dat fiind |Dar |Dann |dann |Dan |Dados |Dado |Dadas |Dada |Ða ðe |Ða |Cuando |Cho |Cando |Când |Cand |Cal |But y'all |But at the end of the day I reckon |BUT |But |Buh |Blimey! |Biết |Bet |Bagi |Aye |awer |Avast! |Atunci |Atesa |Atès |Apabila |Anrhegedig a |Angenommen |And y'all |And |AN |An |an |Amikor |Amennyiben |Ama |Als |Alors |Allora |Ali |Aleshores |Ale |Akkor |Ak |Adott |Ac |Aber |A zároveň |A tiež |A taktiež |A také |A |a |7 |\\* )/)) {\n state.inStep = true;\n state.allowPlaceholders = true;\n state.allowMultilineArgument = true;\n state.inKeywordLine = true;\n return \"keyword\";\n\n // INLINE STRING\n } else if (stream.match(/\"[^\"]*\"?/)) {\n return \"string\";\n\n // PLACEHOLDER\n } else if (state.allowPlaceholders && stream.match(/<[^>]*>?/)) {\n return \"variable\";\n\n // Fall through\n } else {\n stream.next();\n stream.eatWhile(/[^@\"<#]/);\n return null;\n }\n }\n};\n\n"],"names":["gherkin","name","startState","lineNumber","tableHeaderLine","allowFeature","allowBackground","allowScenario","allowSteps","allowPlaceholders","allowMultilineArgument","inMultilineString","inMultilineTable","inKeywordLine","token","stream","state","sol","match","eatSpace","inStep","next","eatWhile"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/1649.index.js b/book/_build/html/_static/1649.index.js new file mode 100644 index 0000000..6b0fa4e --- /dev/null +++ b/book/_build/html/_static/1649.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[1649],{1649:(O,T,E)=>{function e(O){for(var T={},E=O.split(" "),e=0;eC});var I="ABS ACOS ARITY ASIN ATAN AVG BAGSIZE BINSTORAGE BLOOM BUILDBLOOM CBRT CEIL CONCAT COR COS COSH COUNT COUNT_STAR COV CONSTANTSIZE CUBEDIMENSIONS DIFF DISTINCT DOUBLEABS DOUBLEAVG DOUBLEBASE DOUBLEMAX DOUBLEMIN DOUBLEROUND DOUBLESUM EXP FLOOR FLOATABS FLOATAVG FLOATMAX FLOATMIN FLOATROUND FLOATSUM GENERICINVOKER INDEXOF INTABS INTAVG INTMAX INTMIN INTSUM INVOKEFORDOUBLE INVOKEFORFLOAT INVOKEFORINT INVOKEFORLONG INVOKEFORSTRING INVOKER ISEMPTY JSONLOADER JSONMETADATA JSONSTORAGE LAST_INDEX_OF LCFIRST LOG LOG10 LOWER LONGABS LONGAVG LONGMAX LONGMIN LONGSUM MAX MIN MAPSIZE MONITOREDUDF NONDETERMINISTIC OUTPUTSCHEMA PIGSTORAGE PIGSTREAMING RANDOM REGEX_EXTRACT REGEX_EXTRACT_ALL REPLACE ROUND SIN SINH SIZE SQRT STRSPLIT SUBSTRING SUM STRINGCONCAT STRINGMAX STRINGMIN STRINGSIZE TAN TANH TOBAG TOKENIZE TOMAP TOP TOTUPLE TRIM TEXTLOADER TUPLESIZE UCFIRST UPPER UTF8STORAGECONVERTER ",N="VOID IMPORT RETURNS DEFINE LOAD FILTER FOREACH ORDER CUBE DISTINCT COGROUP JOIN CROSS UNION SPLIT INTO IF OTHERWISE ALL AS BY USING INNER OUTER ONSCHEMA PARALLEL PARTITION GROUP AND OR NOT GENERATE FLATTEN ASC DESC IS STREAM THROUGH STORE MAPREDUCE SHIP CACHE INPUT OUTPUT STDERROR STDIN STDOUT LIMIT SAMPLE LEFT RIGHT FULL EQ GT LT GTE LTE NEQ MATCHES TRUE FALSE DUMP",A="BOOLEAN INT LONG FLOAT DOUBLE CHARARRAY BYTEARRAY BAG TUPLE MAP ",R=e(I),S=e(N),t=e(A),L=/[*+\-%<>=&?:\/!|]/;function r(O,T,E){return T.tokenize=E,E(O,T)}function n(O,T){for(var E,e=!1;E=O.next();){if("/"==E&&e){T.tokenize=U;break}e="*"==E}return"comment"}function U(O,T){var E,e=O.next();return'"'==e||"'"==e?r(O,T,(E=e,function(O,T){for(var e,I=!1,N=!1;null!=(e=O.next());){if(e==E&&!I){N=!0;break}I=!I&&"\\"==e}return!N&&I||(T.tokenize=U),"error"})):/[\[\]{}\(\),;\.]/.test(e)?null:/\d/.test(e)?(O.eatWhile(/[\w\.]/),"number"):"/"==e?O.eat("*")?r(O,T,n):(O.eatWhile(L),"operator"):"-"==e?O.eat("-")?(O.skipToEnd(),"comment"):(O.eatWhile(L),"operator"):L.test(e)?(O.eatWhile(L),"operator"):(O.eatWhile(/[\w\$_]/),S&&S.propertyIsEnumerable(O.current().toUpperCase())&&!O.eat(")")&&!O.eat(".")?"keyword":R&&R.propertyIsEnumerable(O.current().toUpperCase())?"builtin":t&&t.propertyIsEnumerable(O.current().toUpperCase())?"type":"variable")}const C={name:"pig",startState:function(){return{tokenize:U,startOfLine:!0}},token:function(O,T){return O.eatSpace()?null:T.tokenize(O,T)},languageData:{autocomplete:(I+A+N).split(" ")}}}}]); +//# sourceMappingURL=1649.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/1649.index.js.map b/book/_build/html/_static/1649.index.js.map new file mode 100644 index 0000000..28fbf5f --- /dev/null +++ b/book/_build/html/_static/1649.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"1649.index.js","mappings":"8FAAA,SAASA,EAAMC,GAEb,IADA,IAAIC,EAAM,CAAC,EAAGF,EAAQC,EAAIE,MAAM,KACvBC,EAAI,EAAGA,EAAIJ,EAAMK,SAAUD,EAAGF,EAAIF,EAAMI,KAAM,EACvD,OAAOF,CACT,C,0BAGA,IAAII,EAAY,w3BAYZC,EAAY,mXAOZC,EAAS,mEAETC,EAAWT,EAAMM,GAAYI,EAAWV,EAAMO,GAAYI,EAAQX,EAAMQ,GAExEI,EAAiB,oBAErB,SAASC,EAAMC,EAAQC,EAAOC,GAE5B,OADAD,EAAME,SAAWD,EACVA,EAAEF,EAAQC,EACnB,CAEA,SAASG,EAAaJ,EAAQC,GAG5B,IAFA,IACII,EADAC,GAAQ,EAEND,EAAKL,EAAOO,QAAQ,CACxB,GAAS,KAANF,GAAaC,EAAO,CACrBL,EAAME,SAAWK,EACjB,KACF,CACAF,EAAe,KAAND,CACX,CACA,MAAO,SACT,CAkBA,SAASG,EAAUR,EAAQC,GACzB,IAjBmBQ,EAiBfJ,EAAKL,EAAOO,OAGhB,MAAU,KAANF,GAAmB,KAANA,EACRN,EAAMC,EAAQC,GArBJQ,EAqBuBJ,EApBnC,SAASL,EAAQC,GAEtB,IADA,IAAqBM,EAAjBG,GAAU,EAAaC,GAAM,EACD,OAAzBJ,EAAOP,EAAOO,SAAiB,CACpC,GAAIA,GAAQE,IAAUC,EAAS,CAC7BC,GAAM,EAAM,KACd,CACAD,GAAWA,GAAmB,MAARH,CACxB,CAGA,OAFII,GAAQD,IACVT,EAAME,SAAWK,GACZ,OACT,IAWQ,mBAAmBI,KAAKP,GACvB,KAED,KAAKO,KAAKP,IAChBL,EAAOa,SAAS,UACT,UAGM,KAANR,EACHL,EAAOc,IAAI,KACNf,EAAMC,EAAQC,EAAOG,IAG5BJ,EAAOa,SAASf,GACT,YAIE,KAAJO,EACJL,EAAOc,IAAI,MACZd,EAAOe,YACA,YAGPf,EAAOa,SAASf,GACT,YAIFA,EAAec,KAAKP,IAC3BL,EAAOa,SAASf,GACT,aAIPE,EAAOa,SAAS,WAEZjB,GAAYA,EAASoB,qBAAqBhB,EAAOiB,UAAUC,iBAExDlB,EAAOc,IAAI,OAASd,EAAOc,IAAI,KAC3B,UAGPnB,GAAYA,EAASqB,qBAAqBhB,EAAOiB,UAAUC,eACtD,UAELrB,GAASA,EAAMmB,qBAAqBhB,EAAOiB,UAAUC,eAChD,OAEF,WAEX,CAGO,MAAMC,EAAM,CACjBC,KAAM,MAENC,WAAY,WACV,MAAO,CACLlB,SAAUK,EACVc,aAAa,EAEjB,EAEAC,MAAO,SAASvB,EAAQC,GACtB,OAAGD,EAAOwB,WAAmB,KACjBvB,EAAME,SAASH,EAAQC,EAErC,EAEAwB,aAAc,CACZC,cAAelC,EAAYE,EAASD,GAAWJ,MAAM,M","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/pig.js"],"sourcesContent":["function words(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n}\n\n// builtin funcs taken from trunk revision 1303237\nvar pBuiltins = \"ABS ACOS ARITY ASIN ATAN AVG BAGSIZE BINSTORAGE BLOOM BUILDBLOOM CBRT CEIL \"\n + \"CONCAT COR COS COSH COUNT COUNT_STAR COV CONSTANTSIZE CUBEDIMENSIONS DIFF DISTINCT DOUBLEABS \"\n + \"DOUBLEAVG DOUBLEBASE DOUBLEMAX DOUBLEMIN DOUBLEROUND DOUBLESUM EXP FLOOR FLOATABS FLOATAVG \"\n + \"FLOATMAX FLOATMIN FLOATROUND FLOATSUM GENERICINVOKER INDEXOF INTABS INTAVG INTMAX INTMIN \"\n + \"INTSUM INVOKEFORDOUBLE INVOKEFORFLOAT INVOKEFORINT INVOKEFORLONG INVOKEFORSTRING INVOKER \"\n + \"ISEMPTY JSONLOADER JSONMETADATA JSONSTORAGE LAST_INDEX_OF LCFIRST LOG LOG10 LOWER LONGABS \"\n + \"LONGAVG LONGMAX LONGMIN LONGSUM MAX MIN MAPSIZE MONITOREDUDF NONDETERMINISTIC OUTPUTSCHEMA \"\n + \"PIGSTORAGE PIGSTREAMING RANDOM REGEX_EXTRACT REGEX_EXTRACT_ALL REPLACE ROUND SIN SINH SIZE \"\n + \"SQRT STRSPLIT SUBSTRING SUM STRINGCONCAT STRINGMAX STRINGMIN STRINGSIZE TAN TANH TOBAG \"\n + \"TOKENIZE TOMAP TOP TOTUPLE TRIM TEXTLOADER TUPLESIZE UCFIRST UPPER UTF8STORAGECONVERTER \";\n\n// taken from QueryLexer.g\nvar pKeywords = \"VOID IMPORT RETURNS DEFINE LOAD FILTER FOREACH ORDER CUBE DISTINCT COGROUP \"\n + \"JOIN CROSS UNION SPLIT INTO IF OTHERWISE ALL AS BY USING INNER OUTER ONSCHEMA PARALLEL \"\n + \"PARTITION GROUP AND OR NOT GENERATE FLATTEN ASC DESC IS STREAM THROUGH STORE MAPREDUCE \"\n + \"SHIP CACHE INPUT OUTPUT STDERROR STDIN STDOUT LIMIT SAMPLE LEFT RIGHT FULL EQ GT LT GTE LTE \"\n + \"NEQ MATCHES TRUE FALSE DUMP\";\n\n// data types\nvar pTypes = \"BOOLEAN INT LONG FLOAT DOUBLE CHARARRAY BYTEARRAY BAG TUPLE MAP \";\n\nvar builtins = words(pBuiltins), keywords = words(pKeywords), types = words(pTypes)\n\nvar isOperatorChar = /[*+\\-%<>=&?:\\/!|]/;\n\nfunction chain(stream, state, f) {\n state.tokenize = f;\n return f(stream, state);\n}\n\nfunction tokenComment(stream, state) {\n var isEnd = false;\n var ch;\n while(ch = stream.next()) {\n if(ch == \"/\" && isEnd) {\n state.tokenize = tokenBase;\n break;\n }\n isEnd = (ch == \"*\");\n }\n return \"comment\";\n}\n\nfunction tokenString(quote) {\n return function(stream, state) {\n var escaped = false, next, end = false;\n while((next = stream.next()) != null) {\n if (next == quote && !escaped) {\n end = true; break;\n }\n escaped = !escaped && next == \"\\\\\";\n }\n if (end || !escaped)\n state.tokenize = tokenBase;\n return \"error\";\n };\n}\n\n\nfunction tokenBase(stream, state) {\n var ch = stream.next();\n\n // is a start of string?\n if (ch == '\"' || ch == \"'\")\n return chain(stream, state, tokenString(ch));\n // is it one of the special chars\n else if(/[\\[\\]{}\\(\\),;\\.]/.test(ch))\n return null;\n // is it a number?\n else if(/\\d/.test(ch)) {\n stream.eatWhile(/[\\w\\.]/);\n return \"number\";\n }\n // multi line comment or operator\n else if (ch == \"/\") {\n if (stream.eat(\"*\")) {\n return chain(stream, state, tokenComment);\n }\n else {\n stream.eatWhile(isOperatorChar);\n return \"operator\";\n }\n }\n // single line comment or operator\n else if (ch==\"-\") {\n if(stream.eat(\"-\")){\n stream.skipToEnd();\n return \"comment\";\n }\n else {\n stream.eatWhile(isOperatorChar);\n return \"operator\";\n }\n }\n // is it an operator\n else if (isOperatorChar.test(ch)) {\n stream.eatWhile(isOperatorChar);\n return \"operator\";\n }\n else {\n // get the while word\n stream.eatWhile(/[\\w\\$_]/);\n // is it one of the listed keywords?\n if (keywords && keywords.propertyIsEnumerable(stream.current().toUpperCase())) {\n //keywords can be used as variables like flatten(group), group.$0 etc..\n if (!stream.eat(\")\") && !stream.eat(\".\"))\n return \"keyword\";\n }\n // is it one of the builtin functions?\n if (builtins && builtins.propertyIsEnumerable(stream.current().toUpperCase()))\n return \"builtin\";\n // is it one of the listed types?\n if (types && types.propertyIsEnumerable(stream.current().toUpperCase()))\n return \"type\";\n // default is a 'variable'\n return \"variable\";\n }\n}\n\n// Interface\nexport const pig = {\n name: \"pig\",\n\n startState: function() {\n return {\n tokenize: tokenBase,\n startOfLine: true\n };\n },\n\n token: function(stream, state) {\n if(stream.eatSpace()) return null;\n var style = state.tokenize(stream, state);\n return style;\n },\n\n languageData: {\n autocomplete: (pBuiltins + pTypes + pKeywords).split(\" \")\n }\n};\n"],"names":["words","str","obj","split","i","length","pBuiltins","pKeywords","pTypes","builtins","keywords","types","isOperatorChar","chain","stream","state","f","tokenize","tokenComment","ch","isEnd","next","tokenBase","quote","escaped","end","test","eatWhile","eat","skipToEnd","propertyIsEnumerable","current","toUpperCase","pig","name","startState","startOfLine","token","eatSpace","languageData","autocomplete"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/1711.index.js b/book/_build/html/_static/1711.index.js new file mode 100644 index 0000000..28e7fc8 --- /dev/null +++ b/book/_build/html/_static/1711.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[1711],{41711:(e,t,r)=>{r.r(t),r.d(t,{stylus:()=>oe});var i=["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","bgsound","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","marquee","menu","menuitem","meta","meter","nav","nobr","noframes","noscript","object","ol","optgroup","option","output","p","param","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","track","u","ul","var","video"],a=["domain","regexp","url-prefix","url"],o=["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"],n=["width","min-width","max-width","height","min-height","max-height","device-width","min-device-width","max-device-width","device-height","min-device-height","max-device-height","aspect-ratio","min-aspect-ratio","max-aspect-ratio","device-aspect-ratio","min-device-aspect-ratio","max-device-aspect-ratio","color","min-color","max-color","color-index","min-color-index","max-color-index","monochrome","min-monochrome","max-monochrome","resolution","min-resolution","max-resolution","scan","grid","dynamic-range","video-dynamic-range"],l=["align-content","align-items","align-self","alignment-adjust","alignment-baseline","anchor-point","animation","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-timing-function","appearance","azimuth","backface-visibility","background","background-attachment","background-clip","background-color","background-image","background-origin","background-position","background-repeat","background-size","baseline-shift","binding","bleed","bookmark-label","bookmark-level","bookmark-state","bookmark-target","border","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-decoration-break","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","clear","clip","color","color-profile","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","content","counter-increment","counter-reset","crop","cue","cue-after","cue-before","cursor","direction","display","dominant-baseline","drop-initial-after-adjust","drop-initial-after-align","drop-initial-before-adjust","drop-initial-before-align","drop-initial-size","drop-initial-value","elevation","empty-cells","fit","fit-position","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","float-offset","flow-from","flow-into","font","font-feature-settings","font-family","font-kerning","font-language-override","font-size","font-size-adjust","font-stretch","font-style","font-synthesis","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-weight","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-position","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","inline-box-align","justify-content","left","letter-spacing","line-break","line-height","line-stacking","line-stacking-ruby","line-stacking-shift","line-stacking-strategy","list-style","list-style-image","list-style-position","list-style-type","margin","margin-bottom","margin-left","margin-right","margin-top","marker-offset","marks","marquee-direction","marquee-loop","marquee-play-count","marquee-speed","marquee-style","max-height","max-width","min-height","min-width","move-to","nav-down","nav-index","nav-left","nav-right","nav-up","object-fit","object-position","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-style","overflow-wrap","overflow-x","overflow-y","padding","padding-bottom","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","page-policy","pause","pause-after","pause-before","perspective","perspective-origin","pitch","pitch-range","play-during","position","presentation-level","punctuation-trim","quotes","region-break-after","region-break-before","region-break-inside","region-fragment","rendering-intent","resize","rest","rest-after","rest-before","richness","right","rotation","rotation-point","ruby-align","ruby-overhang","ruby-position","ruby-span","shape-image-threshold","shape-inside","shape-margin","shape-outside","size","speak","speak-as","speak-header","speak-numeral","speak-punctuation","speech-rate","stress","string-set","tab-size","table-layout","target","target-name","target-new","target-position","text-align","text-align-last","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-style","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-height","text-indent","text-justify","text-outline","text-overflow","text-shadow","text-size-adjust","text-space-collapse","text-transform","text-underline-position","text-wrap","top","transform","transform-origin","transform-style","transition","transition-delay","transition-duration","transition-property","transition-timing-function","unicode-bidi","vertical-align","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","volume","white-space","widows","width","will-change","word-break","word-spacing","word-wrap","z-index","clip-path","clip-rule","mask","enable-background","filter","flood-color","flood-opacity","lighting-color","stop-color","stop-opacity","pointer-events","color-interpolation","color-interpolation-filters","color-rendering","fill","fill-opacity","fill-rule","image-rendering","marker","marker-end","marker-mid","marker-start","shape-rendering","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-rendering","baseline-shift","dominant-baseline","glyph-orientation-horizontal","glyph-orientation-vertical","text-anchor","writing-mode","font-smoothing","osx-font-smoothing"],s=["scrollbar-arrow-color","scrollbar-base-color","scrollbar-dark-shadow-color","scrollbar-face-color","scrollbar-highlight-color","scrollbar-shadow-color","scrollbar-3d-light-color","scrollbar-track-color","shape-inside","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","zoom"],c=["font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"],d=["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"],u=["above","absolute","activeborder","additive","activecaption","afar","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","amharic","amharic-abegede","antialiased","appworkspace","arabic-indic","armenian","asterisks","attr","auto","avoid","avoid-column","avoid-page","avoid-region","background","backwards","baseline","below","bidi-override","binary","bengali","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","buttonface","buttonhighlight","buttonshadow","buttontext","calc","cambodian","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","clear","clip","close-quote","col-resize","collapse","column","compact","condensed","conic-gradient","contain","content","contents","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","dashed","decimal","decimal-leading-zero","default","default-button","destination-atop","destination-in","destination-out","destination-over","devanagari","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic","ethiopic-abegede","ethiopic-abegede-am-et","ethiopic-abegede-gez","ethiopic-abegede-ti-er","ethiopic-abegede-ti-et","ethiopic-halehame-aa-er","ethiopic-halehame-aa-et","ethiopic-halehame-am-et","ethiopic-halehame-gez","ethiopic-halehame-om-et","ethiopic-halehame-sid-et","ethiopic-halehame-so-et","ethiopic-halehame-ti-er","ethiopic-halehame-ti-et","ethiopic-halehame-tig","ethiopic-numeric","ew-resize","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fixed","flat","flex","footnotes","forwards","from","geometricPrecision","georgian","graytext","groove","gujarati","gurmukhi","hand","hangul","hangul-consonant","hebrew","help","hidden","hide","high","higher","highlight","highlighttext","hiragana","hiragana-iroha","horizontal","hsl","hsla","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-table","inset","inside","intrinsic","invert","italic","japanese-formal","japanese-informal","justify","kannada","katakana","katakana-iroha","keep-all","khmer","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","landscape","lao","large","larger","left","level","lighter","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-alpha","lower-armenian","lower-greek","lower-hexadecimal","lower-latin","lower-norwegian","lower-roman","lowercase","ltr","malayalam","match","matrix","matrix3d","media-play-button","media-slider","media-sliderthumb","media-volume-slider","media-volume-sliderthumb","medium","menu","menulist","menulist-button","menutext","message-box","middle","min-intrinsic","mix","mongolian","monospace","move","multiple","myanmar","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","octal","open-quote","optimizeLegibility","optimizeSpeed","oriya","oromo","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","persian","perspective","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row-resize","rtl","run-in","running","s-resize","sans-serif","scale","scale3d","scaleX","scaleY","scaleZ","scroll","scrollbar","scroll-position","se-resize","searchfield","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","semi-condensed","semi-expanded","separate","serif","show","sidama","simp-chinese-formal","simp-chinese-informal","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","solid","somali","source-atop","source-in","source-out","source-over","space","spell-out","square","square-button","standard","start","static","status-bar","stretch","stroke","sub","subpixel-antialiased","super","sw-resize","symbolic","symbols","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tamil","telugu","text","text-bottom","text-top","textarea","textfield","thai","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","tibetan","tigre","tigrinya-er","tigrinya-er-abegede","tigrinya-et","tigrinya-et-abegede","to","top","trad-chinese-formal","trad-chinese-informal","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","up","upper-alpha","upper-armenian","upper-greek","upper-hexadecimal","upper-latin","upper-norwegian","upper-roman","uppercase","urdu","url","var","vertical","vertical-text","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","x-large","x-small","xor","xx-large","xx-small","bicubic","optimizespeed","grayscale","row","row-reverse","wrap","wrap-reverse","column-reverse","flex-start","flex-end","space-between","space-around","unset"],m=["in","and","or","not","is not","is a","is","isnt","defined","if unless"],p=["for","if","else","unless","from","to"],h=["null","true","false","href","title","type","not-allowed","readonly","disabled"],b=i.concat(a,o,n,l,s,d,u,c,m,p,h,["@font-face","@keyframes","@media","@viewport","@page","@host","@supports","@block","@css"]);function g(e){return e=e.sort((function(e,t){return t>e})),new RegExp("^(("+e.join(")|(")+"))\\b")}function f(e){for(var t={},r=0;r]=?|\?:|\~)/,E=g(m),O=f(p),W=new RegExp(/^\-(moz|ms|o|webkit)-/i),A=f(h),R="",S={};function X(e,t){if(R=e.string.match(/(^[\w-]+\s*=\s*$)|(^\s*[\w-]+\s*=\s*[\w-])|(^\s*(\.|#|@|\$|\&|\[|\d|\+|::?|\{|\>|~|\/)?\s*[\w-]*([a-z0-9-]|\*|\/\*)(\(|,)?)/),t.context.line.firstWord=R?R[0].replace(/^\s*/,""):"",t.context.line.indent=e.indentation(),k=e.peek(),e.match("//"))return e.skipToEnd(),["comment","comment"];if(e.match("/*"))return t.tokenize=Y,Y(e,t);if('"'==k||"'"==k)return e.next(),t.tokenize=Z(k),t.tokenize(e,t);if("@"==k)return e.next(),e.eatWhile(/[\w\\-]/),["def",e.current()];if("#"==k){if(e.next(),e.match(/^[0-9a-f]{3}([0-9a-f]([0-9a-f]{2}){0,2})?\b(?!-)/i))return["atom","atom"];if(e.match(/^[a-z][\w-]*/i))return["builtin","hash"]}return e.match(W)?["meta","vendor-prefixes"]:e.match(/^-?[0-9]?\.?[0-9]/)?(e.eatWhile(/[a-z%]/i),["number","unit"]):"!"==k?(e.next(),[e.match(/^(important|optional)/i)?"keyword":"operator","important"]):"."==k&&e.match(/^\.[a-z][\w-]*/i)?["qualifier","qualifier"]:e.match(N)?("("==e.peek()&&(t.tokenize=I),["property","word"]):e.match(/^[a-z][\w-]*\(/i)?(e.backUp(1),["keyword","mixin"]):e.match(/^(\+|-)[a-z][\w-]*\(/i)?(e.backUp(1),["keyword","block-mixin"]):e.string.match(/^\s*&/)&&e.match(/^[-_]+[a-z][\w-]*/)?["qualifier","qualifier"]:e.match(/^(\/|&)(-|_|:|\.|#|[a-z])/)?(e.backUp(1),["variableName.special","reference"]):e.match(/^&{1}\s*$/)?["variableName.special","reference"]:e.match(E)?["operator","operator"]:e.match(/^\$?[-_]*[a-z0-9]+[\w-]*/i)?e.match(/^(\.|\[)[\w-\'\"\]]+/i,!1)&&!H(e.current())?(e.match("."),["variable","variable-name"]):["variable","word"]:e.match(U)?["operator",e.current()]:/[:;,{}\[\]\(\)]/.test(k)?(e.next(),[null,k]):(e.next(),[null,null])}function Y(e,t){for(var r,i=!1;null!=(r=e.next());){if(i&&"/"==r){t.tokenize=null;break}i="*"==r}return["comment","comment"]}function Z(e){return function(t,r){for(var i,a=!1;null!=(i=t.next());){if(i==e&&!a){")"==e&&t.backUp(1);break}a=!a&&"\\"==i}return(i==e||!a&&")"!=e)&&(r.tokenize=null),["string","string"]}}function I(e,t){return e.next(),e.match(/\s*[\"\')]/,!1)?t.tokenize=null:t.tokenize=Z(")"),[null,"("]}function T(e,t,r,i){this.type=e,this.indent=t,this.prev=r,this.line=i||{firstWord:"",indent:0}}function D(e,t,r,i){return i=i>=0?i:t.indentUnit,e.context=new T(r,t.indentation()+i,e.context),r}function F(e,t,r){var i=e.context.indent-t.indentUnit;return r=r||!1,e.context=e.context.prev,r&&(e.context.indent=i),e.context.type}function G(e,t,r,i){for(var a=i||1;a>0;a--)r.context=r.context.prev;return function(e,t,r){return S[r.context.type](e,t,r)}(e,t,r)}function H(e){return e.toLowerCase()in x}function J(e){return(e=e.toLowerCase())in q||e in _}function K(e){return e.toLowerCase()in O}function M(e){return e.toLowerCase().match(W)}function Q(e){var t=e.toLowerCase(),r="variable";return H(e)?r="tag":K(e)?r="block-keyword":J(e)?r="property":t in j||t in A?r="atom":"return"==t||t in B?r="keyword":e.match(/^[A-Z]/)&&(r="string"),r}function V(e,t){return ie(t)&&("{"==e||"]"==e||"hash"==e||"qualifier"==e)||"block-mixin"==e}function ee(e,t){return"{"==e&&t.match(/^\s*\$?[\w-]+/i,!1)}function te(e,t){return":"==e&&t.match(/^[a-z-]+/,!1)}function re(e){return e.sol()||e.string.match(new RegExp("^\\s*"+e.current().replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")))}function ie(e){return e.eol()||e.match(/^\s*$/,!1)}function ae(e){var t=/^\s*[-_]*[a-z0-9]+[\w-]*/i,r="string"==typeof e?e.match(t):e.string.match(t);return r?r[0].replace(/^\s*/,""):""}S.block=function(e,t,r){if("comment"==e&&re(t)||","==e&&ie(t)||"mixin"==e)return D(r,t,"block",0);if(ee(e,t))return D(r,t,"interpolation");if(ie(t)&&"]"==e&&!/^\s*(\.|#|:|\[|\*|&)/.test(t.string)&&!H(ae(t)))return D(r,t,"block",0);if(V(e,t))return D(r,t,"block");if("}"==e&&ie(t))return D(r,t,"block",0);if("variable-name"==e)return t.string.match(/^\s?\$[\w-\.\[\]\'\"]+$/)||K(ae(t))?D(r,t,"variableName"):D(r,t,"variableName",0);if("="==e)return ie(t)||K(ae(t))?D(r,t,"block"):D(r,t,"block",0);if("*"==e&&(ie(t)||t.match(/\s*(,|\.|#|\[|:|{)/,!1)))return v="tag",D(r,t,"block");if(te(e,t))return D(r,t,"pseudo");if(/@(font-face|media|supports|(-moz-)?document)/.test(e))return D(r,t,ie(t)?"block":"atBlock");if(/@(-(moz|ms|o|webkit)-)?keyframes$/.test(e))return D(r,t,"keyframes");if(/@extends?/.test(e))return D(r,t,"extend",0);if(e&&"@"==e.charAt(0))return t.indentation()>0&&J(t.current().slice(1))?(v="variable","block"):/(@import|@require|@charset)/.test(e)?D(r,t,"block",0):D(r,t,"block");if("reference"==e&&ie(t))return D(r,t,"block");if("("==e)return D(r,t,"parens");if("vendor-prefixes"==e)return D(r,t,"vendorPrefixes");if("word"==e){var i=t.current();if("property"==(v=Q(i)))return re(t)?D(r,t,"block",0):(v="atom","block");if("tag"==v){if(/embed|menu|pre|progress|sub|table/.test(i)&&J(ae(t)))return v="atom","block";if(t.string.match(new RegExp("\\[\\s*"+i+"|"+i+"\\s*\\]")))return v="atom","block";if(z.test(i)&&(re(t)&&t.string.match(/=/)||!re(t)&&!t.string.match(/^(\s*\.|#|\&|\[|\/|>|\*)/)&&!H(ae(t))))return v="variable",K(ae(t))?"block":D(r,t,"block",0);if(ie(t))return D(r,t,"block")}if("block-keyword"==v)return v="keyword",t.current(/(if|unless)/)&&!re(t)?"block":D(r,t,"block");if("return"==i)return D(r,t,"block",0);if("variable"==v&&t.string.match(/^\s?\$[\w-\.\[\]\'\"]+$/))return D(r,t,"block")}return r.context.type},S.parens=function(e,t,r){if("("==e)return D(r,t,"parens");if(")"==e)return"parens"==r.context.prev.type?F(r,t):t.string.match(/^[a-z][\w-]*\(/i)&&ie(t)||K(ae(t))||/(\.|#|:|\[|\*|&|>|~|\+|\/)/.test(ae(t))||!t.string.match(/^-?[a-z][\w-\.\[\]\'\"]*\s*=/)&&H(ae(t))?D(r,t,"block"):t.string.match(/^[\$-]?[a-z][\w-\.\[\]\'\"]*\s*=/)||t.string.match(/^\s*(\(|\)|[0-9])/)||t.string.match(/^\s+[a-z][\w-]*\(/i)||t.string.match(/^\s+[\$-]?[a-z]/i)?D(r,t,"block",0):ie(t)?D(r,t,"block"):D(r,t,"block",0);if(e&&"@"==e.charAt(0)&&J(t.current().slice(1))&&(v="variable"),"word"==e){var i=t.current();"tag"==(v=Q(i))&&z.test(i)&&(v="variable"),"property"!=v&&"to"!=i||(v="atom")}return"variable-name"==e?D(r,t,"variableName"):te(e,t)?D(r,t,"pseudo"):r.context.type},S.vendorPrefixes=function(e,t,r){return"word"==e?(v="property",D(r,t,"block",0)):F(r,t)},S.pseudo=function(e,t,r){return J(ae(t.string))?G(e,t,r):(t.match(/^[a-z-]+/),v="variableName.special",ie(t)?D(r,t,"block"):F(r,t))},S.atBlock=function(e,t,r){if("("==e)return D(r,t,"atBlock_parens");if(V(e,t))return D(r,t,"block");if(ee(e,t))return D(r,t,"interpolation");if("word"==e){var i=t.current().toLowerCase();if("tag"==(v=/^(only|not|and|or)$/.test(i)?"keyword":C.hasOwnProperty(i)?"tag":P.hasOwnProperty(i)?"attribute":L.hasOwnProperty(i)?"property":$.hasOwnProperty(i)?"string.special":Q(t.current()))&&ie(t))return D(r,t,"block")}return"operator"==e&&/^(not|and|or)$/.test(t.current())&&(v="keyword"),r.context.type},S.atBlock_parens=function(e,t,r){if("{"==e||"}"==e)return r.context.type;if(")"==e)return ie(t)?D(r,t,"block"):D(r,t,"atBlock");if("word"==e){var i=t.current().toLowerCase();return v=Q(i),/^(max|min)/.test(i)&&(v="property"),"tag"==v&&(v=z.test(i)?"variable":"atom"),r.context.type}return S.atBlock(e,t,r)},S.keyframes=function(e,t,r){return"0"==t.indentation()&&("}"==e&&re(t)||"]"==e||"hash"==e||"qualifier"==e||H(t.current()))?G(e,t,r):"{"==e?D(r,t,"keyframes"):"}"==e?re(t)?F(r,t,!0):D(r,t,"keyframes"):"unit"==e&&/^[0-9]+\%$/.test(t.current())?D(r,t,"keyframes"):"word"==e&&"block-keyword"==(v=Q(t.current()))?(v="keyword",D(r,t,"keyframes")):/@(font-face|media|supports|(-moz-)?document)/.test(e)?D(r,t,ie(t)?"block":"atBlock"):"mixin"==e?D(r,t,"block",0):r.context.type},S.interpolation=function(e,t,r){return"{"==e&&F(r,t)&&D(r,t,"block"),"}"==e?t.string.match(/^\s*(\.|#|:|\[|\*|&|>|~|\+|\/)/i)||t.string.match(/^\s*[a-z]/i)&&H(ae(t))?D(r,t,"block"):!t.string.match(/^(\{|\s*\&)/)||t.match(/\s*[\w-]/,!1)?D(r,t,"block",0):D(r,t,"block"):"variable-name"==e?D(r,t,"variableName",0):("word"==e&&"tag"==(v=Q(t.current()))&&(v="atom"),r.context.type)},S.extend=function(e,t,r){return"["==e||"="==e?"extend":"]"==e?F(r,t):"word"==e?(v=Q(t.current()),"extend"):F(r,t)},S.variableName=function(e,t,r){return"string"==e||"["==e||"]"==e||t.current().match(/^(\.|\$)/)?(t.current().match(/^\.[\w-]+/i)&&(v="variable"),"variableName"):G(e,t,r)};const oe={name:"stylus",startState:function(){return{tokenize:null,state:"block",context:new T("block",0,null)}},token:function(e,t){return!t.tokenize&&e.eatSpace()?null:((w=(t.tokenize||X)(e,t))&&"object"==typeof w&&(y=w[1],w=w[0]),v=w,t.state=S[t.state](y,e,t),v)},indent:function(e,t,r){var i=e.context,a=t&&t.charAt(0),o=i.indent,n=ae(t),l=r.lineIndent(r.pos),s=e.context.prev?e.context.prev.line.firstWord:"",c=e.context.prev?e.context.prev.line.indent:l;return i.prev&&("}"==a&&("block"==i.type||"atBlock"==i.type||"keyframes"==i.type)||")"==a&&("parens"==i.type||"atBlock_parens"==i.type)||"{"==a&&"at"==i.type)?o=i.indent-r.unit:/(\})/.test(a)||(/@|\$|\d/.test(a)||/^\{/.test(t)||/^\s*\/(\/|\*)/.test(t)||/^\s*\/\*/.test(s)||/^\s*[\w-\.\[\]\'\"]+\s*(\?|:|\+)?=/i.test(t)||/^(\+|-)?[a-z][\w-]*\(/i.test(t)||/^return/.test(t)||K(n)?o=l:/(\.|#|:|\[|\*|&|>|~|\+|\/)/.test(a)||H(n)?o=/\,\s*$/.test(s)?c:e.sol()||!/(\.|#|:|\[|\*|&|>|~|\+|\/)/.test(s)&&!H(s)?l:l<=c?c:c+r.unit:/,\s*$/.test(t)||!M(n)&&!J(n)||(o=K(s)?l<=c?c:c+r.unit:/^\{/.test(s)?l<=c?l:c+r.unit:M(s)||J(s)?l>=c?c:l:/^(\.|#|:|\[|\*|&|@|\+|\-|>|~|\/)/.test(s)||/=\s*$/.test(s)||H(s)||/^\$[\w-\.\[\]\'\"]/.test(s)?c+r.unit:l)),o},languageData:{indentOnInput:/^\s*\}$/,commentTokens:{line:"//",block:{open:"/*",close:"*/"}},autocomplete:b}}}}]); +//# sourceMappingURL=1711.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/1711.index.js.map b/book/_build/html/_static/1711.index.js.map new file mode 100644 index 0000000..376a48d --- /dev/null +++ b/book/_build/html/_static/1711.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"1711.index.js","mappings":"6HACA,IAAIA,EAAe,CAAC,IAAI,OAAO,UAAU,OAAO,UAAU,QAAQ,QAAS,IAAK,OAAO,MAAO,MAAM,UAAU,aAAa,OAAO,KAAK,SAAS,SAAS,UAAU,OAAQ,OAAO,MAAM,WAAW,OAAO,WAAW,KAAK,MAAM,UAAU,MAAM,MAAO,KAAK,KAAK,KAAK,QAAQ,WAAW,aAAa,SAAS,SAAS,OAAO,KAAM,KAAK,KAAK,KAAK,KAAK,KAAK,OAAO,SAAS,SAAS,KAAK,OAAO,I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acy-modes/mode/stylus.js"],"sourcesContent":["// developer.mozilla.org/en-US/docs/Web/HTML/Element\nvar tagKeywords_ = [\"a\",\"abbr\",\"address\",\"area\",\"article\",\"aside\",\"audio\", \"b\", \"base\",\"bdi\", \"bdo\",\"bgsound\",\"blockquote\",\"body\",\"br\",\"button\",\"canvas\",\"caption\",\"cite\", \"code\",\"col\",\"colgroup\",\"data\",\"datalist\",\"dd\",\"del\",\"details\",\"dfn\",\"div\", \"dl\",\"dt\",\"em\",\"embed\",\"fieldset\",\"figcaption\",\"figure\",\"footer\",\"form\",\"h1\", \"h2\",\"h3\",\"h4\",\"h5\",\"h6\",\"head\",\"header\",\"hgroup\",\"hr\",\"html\",\"i\",\"iframe\", \"img\",\"input\",\"ins\",\"kbd\",\"keygen\",\"label\",\"legend\",\"li\",\"link\",\"main\",\"map\", \"mark\",\"marquee\",\"menu\",\"menuitem\",\"meta\",\"meter\",\"nav\",\"nobr\",\"noframes\", \"noscript\",\"object\",\"ol\",\"optgroup\",\"option\",\"output\",\"p\",\"param\",\"pre\", \"progress\",\"q\",\"rp\",\"rt\",\"ruby\",\"s\",\"samp\",\"script\",\"section\",\"select\", \"small\",\"source\",\"span\",\"strong\",\"style\",\"sub\",\"summary\",\"sup\",\"table\",\"tbody\",\"td\",\"textarea\",\"tfoot\",\"th\",\"thead\",\"time\",\"tr\",\"track\", \"u\",\"ul\",\"var\",\"video\"];\n\n// github.com/codemirror/CodeMirror/blob/master/mode/css/css.js\n// Note, \"url-prefix\" should precede \"url\" in order to match correctly in documentTypesRegexp\nvar documentTypes_ = [\"domain\", \"regexp\", \"url-prefix\", \"url\"];\nvar mediaTypes_ = [\"all\",\"aural\",\"braille\",\"handheld\",\"print\",\"projection\",\"screen\",\"tty\",\"tv\",\"embossed\"];\nvar mediaFeatures_ = [\"width\",\"min-width\",\"max-width\",\"height\",\"min-height\",\"max-height\",\"device-width\",\"min-device-width\",\"max-device-width\",\"device-height\",\"min-device-height\",\"max-device-height\",\"aspect-ratio\",\"min-aspect-ratio\",\"max-aspect-ratio\",\"device-aspect-ratio\",\"min-device-aspect-ratio\",\"max-device-aspect-ratio\",\"color\",\"min-color\",\"max-color\",\"color-index\",\"min-color-index\",\"max-color-index\",\"monochrome\",\"min-monochrome\",\"max-monochrome\",\"resolution\",\"min-resolution\",\"max-resolution\",\"scan\",\"grid\",\"dynamic-range\",\"video-dynamic-range\"];\nvar propertyKeywords_ = [\"align-content\",\"align-items\",\"align-self\",\"alignment-adjust\",\"alignment-baseline\",\"anchor-point\",\"animation\",\"animation-delay\",\"animation-direction\",\"animation-duration\",\"animation-fill-mode\",\"animation-iteration-count\",\"animation-name\",\"animation-play-state\",\"animation-timing-function\",\"appearance\",\"azimuth\",\"backface-visibility\",\"background\",\"background-attachment\",\"background-clip\",\"background-color\",\"background-image\",\"background-origin\",\"background-position\",\"background-repeat\",\"background-size\",\"baseline-shift\",\"binding\",\"bleed\",\"bookmark-label\",\"bookmark-level\",\"bookmark-state\",\"bookmark-target\",\"border\",\"border-bottom\",\"border-bottom-color\",\"border-bottom-left-radius\",\"border-bottom-right-radius\",\"border-bottom-style\",\"border-bottom-width\",\"border-collapse\",\"border-color\",\"border-image\",\"border-image-outset\",\"border-image-repeat\",\"border-image-slice\",\"border-image-source\",\"border-image-width\",\"border-left\",\"border-left-color\",\"border-left-style\",\"border-left-width\",\"border-radius\",\"border-right\",\"border-right-color\",\"border-right-style\",\"border-right-width\",\"border-spacing\",\"border-style\",\"border-top\",\"border-top-color\",\"border-top-left-radius\",\"border-top-right-radius\",\"border-top-style\",\"border-top-width\",\"border-width\",\"bottom\",\"box-decoration-break\",\"box-shadow\",\"box-sizing\",\"break-after\",\"break-before\",\"break-inside\",\"caption-side\",\"clear\",\"clip\",\"color\",\"color-profile\",\"column-count\",\"column-fill\",\"column-gap\",\"column-rule\",\"column-rule-color\",\"column-rule-style\",\"column-rule-width\",\"column-span\",\"column-width\",\"columns\",\"content\",\"counter-increment\",\"counter-reset\",\"crop\",\"cue\",\"cue-after\",\"cue-before\",\"cursor\",\"direction\",\"display\",\"dominant-baseline\",\"drop-initial-after-adjust\",\"drop-initial-after-align\",\"drop-initial-before-adjust\",\"drop-initial-before-align\",\"drop-initial-size\",\"drop-initial-value\",\"elevation\",\"empty-cells\",\"fit\",\"fit-position\",\"flex\",\"flex-basis\",\"flex-direction\",\"flex-flow\",\"flex-grow\",\"flex-shrink\",\"flex-wrap\",\"float\",\"float-offset\",\"flow-from\",\"flow-into\",\"font\",\"font-feature-settings\",\"font-family\",\"font-kerning\",\"font-language-override\",\"font-size\",\"font-size-adjust\",\"font-stretch\",\"font-style\",\"font-synthesis\",\"font-variant\",\"font-variant-alternates\",\"font-variant-caps\",\"font-variant-east-asian\",\"font-variant-ligatures\",\"font-variant-numeric\",\"font-variant-position\",\"font-weight\",\"grid\",\"grid-area\",\"grid-auto-columns\",\"grid-auto-flow\",\"grid-auto-position\",\"grid-auto-rows\",\"grid-column\",\"grid-column-end\",\"grid-column-start\",\"grid-row\",\"grid-row-end\",\"grid-row-start\",\"grid-template\",\"grid-template-areas\",\"grid-template-columns\",\"grid-template-rows\",\"hanging-punctuation\",\"height\",\"hyphens\",\"icon\",\"image-orientation\",\"image-rendering\",\"image-resolution\",\"inline-box-align\",\"justify-content\",\"left\",\"letter-spacing\",\"line-break\",\"line-height\",\"line-stacking\",\"line-stacking-ruby\",\"line-stacking-shift\",\"line-stacking-strategy\",\"list-style\",\"list-style-image\",\"list-style-position\",\"list-style-type\",\"margin\",\"margin-bottom\",\"margin-left\",\"margin-right\",\"margin-top\",\"marker-offset\",\"marks\",\"marquee-direction\",\"marquee-loop\",\"marquee-play-count\",\"marquee-speed\",\"marquee-style\",\"max-height\",\"max-width\",\"min-height\",\"min-width\",\"move-to\",\"nav-down\",\"nav-index\",\"nav-left\",\"nav-right\",\"nav-up\",\"object-fit\",\"object-position\",\"opacity\",\"order\",\"orphans\",\"outline\",\"outline-color\",\"outline-offset\",\"outline-style\",\"outline-width\",\"overflow\",\"overflow-style\",\"overflow-wrap\",\"overflow-x\",\"overflow-y\",\"padding\",\"padding-bottom\",\"padding-left\",\"padding-right\",\"padding-top\",\"page\",\"page-break-after\",\"page-break-before\",\"page-break-inside\",\"page-policy\",\"pause\",\"pause-after\",\"pause-before\",\"perspective\",\"perspective-origin\",\"pitch\",\"pitch-range\",\"play-during\",\"position\",\"presentation-level\",\"punctuation-trim\",\"quotes\",\"region-break-after\",\"region-break-before\",\"region-break-inside\",\"region-fragment\",\"rendering-intent\",\"resize\",\"rest\",\"rest-after\",\"rest-before\",\"richness\",\"right\",\"rotation\",\"rotation-point\",\"ruby-align\",\"ruby-overhang\",\"ruby-position\",\"ruby-span\",\"shape-image-threshold\",\"shape-inside\",\"shape-margin\",\"shape-outside\",\"size\",\"speak\",\"speak-as\",\"speak-header\",\"speak-numeral\",\"speak-punctuation\",\"speech-rate\",\"stress\",\"string-set\",\"tab-size\",\"table-layout\",\"target\",\"target-name\",\"target-new\",\"target-position\",\"text-align\",\"text-align-last\",\"text-decoration\",\"text-decoration-color\",\"text-decoration-line\",\"text-decoration-skip\",\"text-decoration-style\",\"text-emphasis\",\"text-emphasis-color\",\"text-emphasis-position\",\"text-emphasis-style\",\"text-height\",\"text-indent\",\"text-justify\",\"text-outline\",\"text-overflow\",\"text-shadow\",\"text-size-adjust\",\"text-space-collapse\",\"text-transform\",\"text-underline-position\",\"text-wrap\",\"top\",\"transform\",\"transform-origin\",\"transform-style\",\"transition\",\"transition-delay\",\"transition-duration\",\"transition-property\",\"transition-timing-function\",\"unicode-bidi\",\"vertical-align\",\"visibility\",\"voice-balance\",\"voice-duration\",\"voice-family\",\"voice-pitch\",\"voice-range\",\"voice-rate\",\"voice-stress\",\"voice-volume\",\"volume\",\"white-space\",\"widows\",\"width\",\"will-change\",\"word-break\",\"word-spacing\",\"word-wrap\",\"z-index\",\"clip-path\",\"clip-rule\",\"mask\",\"enable-background\",\"filter\",\"flood-color\",\"flood-opacity\",\"lighting-color\",\"stop-color\",\"stop-opacity\",\"pointer-events\",\"color-interpolation\",\"color-interpolation-filters\",\"color-rendering\",\"fill\",\"fill-opacity\",\"fill-rule\",\"image-rendering\",\"marker\",\"marker-end\",\"marker-mid\",\"marker-start\",\"shape-rendering\",\"stroke\",\"stroke-dasharray\",\"stroke-dashoffset\",\"stroke-linecap\",\"stroke-linejoin\",\"stroke-miterlimit\",\"stroke-opacity\",\"stroke-width\",\"text-rendering\",\"baseline-shift\",\"dominant-baseline\",\"glyph-orientation-horizontal\",\"glyph-orientation-vertical\",\"text-anchor\",\"writing-mode\",\"font-smoothing\",\"osx-font-smoothing\"];\nvar nonStandardPropertyKeywords_ = [\"scrollbar-arrow-color\",\"scrollbar-base-color\",\"scrollbar-dark-shadow-color\",\"scrollbar-face-color\",\"scrollbar-highlight-color\",\"scrollbar-shadow-color\",\"scrollbar-3d-light-color\",\"scrollbar-track-color\",\"shape-inside\",\"searchfield-cancel-button\",\"searchfield-decoration\",\"searchfield-results-button\",\"searchfield-results-decoration\",\"zoom\"];\nvar fontProperties_ = [\"font-family\",\"src\",\"unicode-range\",\"font-variant\",\"font-feature-settings\",\"font-stretch\",\"font-weight\",\"font-style\"];\nvar colorKeywords_ = [\"aliceblue\",\"antiquewhite\",\"aqua\",\"aquamarine\",\"azure\",\"beige\",\"bisque\",\"black\",\"blanchedalmond\",\"blue\",\"blueviolet\",\"brown\",\"burlywood\",\"cadetblue\",\"chartreuse\",\"chocolate\",\"coral\",\"cornflowerblue\",\"cornsilk\",\"crimson\",\"cyan\",\"darkblue\",\"darkcyan\",\"darkgoldenrod\",\"darkgray\",\"darkgreen\",\"darkkhaki\",\"darkmagenta\",\"darkolivegreen\",\"darkorange\",\"darkorchid\",\"darkred\",\"darksalmon\",\"darkseagreen\",\"darkslateblue\",\"darkslategray\",\"darkturquoise\",\"darkviolet\",\"deeppink\",\"deepskyblue\",\"dimgray\",\"dodgerblue\",\"firebrick\",\"floralwhite\",\"forestgreen\",\"fuchsia\",\"gainsboro\",\"ghostwhite\",\"gold\",\"goldenrod\",\"gray\",\"grey\",\"green\",\"greenyellow\",\"honeydew\",\"hotpink\",\"indianred\",\"indigo\",\"ivory\",\"khaki\",\"lavender\",\"lavenderblush\",\"lawngreen\",\"lemonchiffon\",\"lightblue\",\"lightcoral\",\"lightcyan\",\"lightgoldenrodyellow\",\"lightgray\",\"lightgreen\",\"lightpink\",\"lightsalmon\",\"lightseagreen\",\"lightskyblue\",\"lightslategray\",\"lightsteelblue\",\"lightyellow\",\"lime\",\"limegreen\",\"linen\",\"magenta\",\"maroon\",\"mediumaquamarine\",\"mediumblue\",\"mediumorchid\",\"mediumpurple\",\"mediumseagreen\",\"mediumslateblue\",\"mediumspringgreen\",\"mediumturquoise\",\"mediumvioletred\",\"midnightblue\",\"mintcream\",\"mistyrose\",\"moccasin\",\"navajowhite\",\"navy\",\"oldlace\",\"olive\",\"olivedrab\",\"orange\",\"orangered\",\"orchid\",\"palegoldenrod\",\"palegreen\",\"paleturquoise\",\"palevioletred\",\"papayawhip\",\"peachpuff\",\"peru\",\"pink\",\"plum\",\"powderblue\",\"purple\",\"rebeccapurple\",\"red\",\"rosybrown\",\"royalblue\",\"saddlebrown\",\"salmon\",\"sandybrown\",\"seagreen\",\"seashell\",\"sienna\",\"silver\",\"skyblue\",\"slateblue\",\"slategray\",\"snow\",\"springgreen\",\"steelblue\",\"tan\",\"teal\",\"thistle\",\"tomato\",\"turquoise\",\"violet\",\"wheat\",\"white\",\"whitesmoke\",\"yellow\",\"yellowgreen\"];\nvar valueKeywords_ = [\"above\",\"absolute\",\"activeborder\",\"additive\",\"activecaption\",\"afar\",\"after-white-space\",\"ahead\",\"alias\",\"all\",\"all-scroll\",\"alphabetic\",\"alternate\",\"always\",\"amharic\",\"amharic-abegede\",\"antialiased\",\"appworkspace\",\"arabic-indic\",\"armenian\",\"asterisks\",\"attr\",\"auto\",\"avoid\",\"avoid-column\",\"avoid-page\",\"avoid-region\",\"background\",\"backwards\",\"baseline\",\"below\",\"bidi-override\",\"binary\",\"bengali\",\"blink\",\"block\",\"block-axis\",\"bold\",\"bolder\",\"border\",\"border-box\",\"both\",\"bottom\",\"break\",\"break-all\",\"break-word\",\"bullets\",\"button\",\"buttonface\",\"buttonhighlight\",\"buttonshadow\",\"buttontext\",\"calc\",\"cambodian\",\"capitalize\",\"caps-lock-indicator\",\"caption\",\"captiontext\",\"caret\",\"cell\",\"center\",\"checkbox\",\"circle\",\"cjk-decimal\",\"cjk-earthly-branch\",\"cjk-heavenly-stem\",\"cjk-ideographic\",\"clear\",\"clip\",\"close-quote\",\"col-resize\",\"collapse\",\"column\",\"compact\",\"condensed\",\"conic-gradient\",\"contain\",\"content\",\"contents\",\"content-box\",\"context-menu\",\"continuous\",\"copy\",\"counter\",\"counters\",\"cover\",\"crop\",\"cross\",\"crosshair\",\"currentcolor\",\"cursive\",\"cyclic\",\"dashed\",\"decimal\",\"decimal-leading-zero\",\"default\",\"default-button\",\"destination-atop\",\"destination-in\",\"destination-out\",\"destination-over\",\"devanagari\",\"disc\",\"discard\",\"disclosure-closed\",\"disclosure-open\",\"document\",\"dot-dash\",\"dot-dot-dash\",\"dotted\",\"double\",\"down\",\"e-resize\",\"ease\",\"ease-in\",\"ease-in-out\",\"ease-out\",\"element\",\"ellipse\",\"ellipsis\",\"embed\",\"end\",\"ethiopic\",\"ethiopic-abegede\",\"ethiopic-abegede-am-et\",\"ethiopic-abegede-gez\",\"ethiopic-abegede-ti-er\",\"ethiopic-abegede-ti-et\",\"ethiopic-halehame-aa-er\",\"ethiopic-halehame-aa-et\",\"ethiopic-halehame-am-et\",\"ethiopic-halehame-gez\",\"ethiopic-halehame-om-et\",\"ethiopic-halehame-sid-et\",\"ethiopic-halehame-so-et\",\"ethiopic-halehame-ti-er\",\"ethiopic-halehame-ti-et\",\"ethiopic-halehame-tig\",\"ethiopic-numeric\",\"ew-resize\",\"expanded\",\"extends\",\"extra-condensed\",\"extra-expanded\",\"fantasy\",\"fast\",\"fill\",\"fixed\",\"flat\",\"flex\",\"footnotes\",\"forwards\",\"from\",\"geometricPrecision\",\"georgian\",\"graytext\",\"groove\",\"gujarati\",\"gurmukhi\",\"hand\",\"hangul\",\"hangul-consonant\",\"hebrew\",\"help\",\"hidden\",\"hide\",\"high\",\"higher\",\"highlight\",\"highlighttext\",\"hiragana\",\"hiragana-iroha\",\"horizontal\",\"hsl\",\"hsla\",\"icon\",\"ignore\",\"inactiveborder\",\"inactivecaption\",\"inactivecaptiontext\",\"infinite\",\"infobackground\",\"infotext\",\"inherit\",\"initial\",\"inline\",\"inline-axis\",\"inline-block\",\"inline-flex\",\"inline-table\",\"inset\",\"inside\",\"intrinsic\",\"invert\",\"italic\",\"japanese-formal\",\"japanese-informal\",\"justify\",\"kannada\",\"katakana\",\"katakana-iroha\",\"keep-all\",\"khmer\",\"korean-hangul-formal\",\"korean-hanja-formal\",\"korean-hanja-informal\",\"landscape\",\"lao\",\"large\",\"larger\",\"left\",\"level\",\"lighter\",\"line-through\",\"linear\",\"linear-gradient\",\"lines\",\"list-item\",\"listbox\",\"listitem\",\"local\",\"logical\",\"loud\",\"lower\",\"lower-alpha\",\"lower-armenian\",\"lower-greek\",\"lower-hexadecimal\",\"lower-latin\",\"lower-norwegian\",\"lower-roman\",\"lowercase\",\"ltr\",\"malayalam\",\"match\",\"matrix\",\"matrix3d\",\"media-play-button\",\"media-slider\",\"media-sliderthumb\",\"media-volume-slider\",\"media-volume-sliderthumb\",\"medium\",\"menu\",\"menulist\",\"menulist-button\",\"menutext\",\"message-box\",\"middle\",\"min-intrinsic\",\"mix\",\"mongolian\",\"monospace\",\"move\",\"multiple\",\"myanmar\",\"n-resize\",\"narrower\",\"ne-resize\",\"nesw-resize\",\"no-close-quote\",\"no-drop\",\"no-open-quote\",\"no-repeat\",\"none\",\"normal\",\"not-allowed\",\"nowrap\",\"ns-resize\",\"numbers\",\"numeric\",\"nw-resize\",\"nwse-resize\",\"oblique\",\"octal\",\"open-quote\",\"optimizeLegibility\",\"optimizeSpeed\",\"oriya\",\"oromo\",\"outset\",\"outside\",\"outside-shape\",\"overlay\",\"overline\",\"padding\",\"padding-box\",\"painted\",\"page\",\"paused\",\"persian\",\"perspective\",\"plus-darker\",\"plus-lighter\",\"pointer\",\"polygon\",\"portrait\",\"pre\",\"pre-line\",\"pre-wrap\",\"preserve-3d\",\"progress\",\"push-button\",\"radial-gradient\",\"radio\",\"read-only\",\"read-write\",\"read-write-plaintext-only\",\"rectangle\",\"region\",\"relative\",\"repeat\",\"repeating-linear-gradient\",\"repeating-radial-gradient\",\"repeating-conic-gradient\",\"repeat-x\",\"repeat-y\",\"reset\",\"reverse\",\"rgb\",\"rgba\",\"ridge\",\"right\",\"rotate\",\"rotate3d\",\"rotateX\",\"rotateY\",\"rotateZ\",\"round\",\"row-resize\",\"rtl\",\"run-in\",\"running\",\"s-resize\",\"sans-serif\",\"scale\",\"scale3d\",\"scaleX\",\"scaleY\",\"scaleZ\",\"scroll\",\"scrollbar\",\"scroll-position\",\"se-resize\",\"searchfield\",\"searchfield-cancel-button\",\"searchfield-decoration\",\"searchfield-results-button\",\"searchfield-results-decoration\",\"semi-condensed\",\"semi-expanded\",\"separate\",\"serif\",\"show\",\"sidama\",\"simp-chinese-formal\",\"simp-chinese-informal\",\"single\",\"skew\",\"skewX\",\"skewY\",\"skip-white-space\",\"slide\",\"slider-horizontal\",\"slider-vertical\",\"sliderthumb-horizontal\",\"sliderthumb-vertical\",\"slow\",\"small\",\"small-caps\",\"small-caption\",\"smaller\",\"solid\",\"somali\",\"source-atop\",\"source-in\",\"source-out\",\"source-over\",\"space\",\"spell-out\",\"square\",\"square-button\",\"standard\",\"start\",\"static\",\"status-bar\",\"stretch\",\"stroke\",\"sub\",\"subpixel-antialiased\",\"super\",\"sw-resize\",\"symbolic\",\"symbols\",\"table\",\"table-caption\",\"table-cell\",\"table-column\",\"table-column-group\",\"table-footer-group\",\"table-header-group\",\"table-row\",\"table-row-group\",\"tamil\",\"telugu\",\"text\",\"text-bottom\",\"text-top\",\"textarea\",\"textfield\",\"thai\",\"thick\",\"thin\",\"threeddarkshadow\",\"threedface\",\"threedhighlight\",\"threedlightshadow\",\"threedshadow\",\"tibetan\",\"tigre\",\"tigrinya-er\",\"tigrinya-er-abegede\",\"tigrinya-et\",\"tigrinya-et-abegede\",\"to\",\"top\",\"trad-chinese-formal\",\"trad-chinese-informal\",\"translate\",\"translate3d\",\"translateX\",\"translateY\",\"translateZ\",\"transparent\",\"ultra-condensed\",\"ultra-expanded\",\"underline\",\"up\",\"upper-alpha\",\"upper-armenian\",\"upper-greek\",\"upper-hexadecimal\",\"upper-latin\",\"upper-norwegian\",\"upper-roman\",\"uppercase\",\"urdu\",\"url\",\"var\",\"vertical\",\"vertical-text\",\"visible\",\"visibleFill\",\"visiblePainted\",\"visibleStroke\",\"visual\",\"w-resize\",\"wait\",\"wave\",\"wider\",\"window\",\"windowframe\",\"windowtext\",\"words\",\"x-large\",\"x-small\",\"xor\",\"xx-large\",\"xx-small\",\"bicubic\",\"optimizespeed\",\"grayscale\",\"row\",\"row-reverse\",\"wrap\",\"wrap-reverse\",\"column-reverse\",\"flex-start\",\"flex-end\",\"space-between\",\"space-around\", \"unset\"];\n\nvar wordOperatorKeywords_ = [\"in\",\"and\",\"or\",\"not\",\"is not\",\"is a\",\"is\",\"isnt\",\"defined\",\"if unless\"],\n blockKeywords_ = [\"for\",\"if\",\"else\",\"unless\", \"from\", \"to\"],\n commonAtoms_ = [\"null\",\"true\",\"false\",\"href\",\"title\",\"type\",\"not-allowed\",\"readonly\",\"disabled\"],\n commonDef_ = [\"@font-face\", \"@keyframes\", \"@media\", \"@viewport\", \"@page\", \"@host\", \"@supports\", \"@block\", \"@css\"];\n\nvar hintWords = tagKeywords_.concat(documentTypes_,mediaTypes_,mediaFeatures_,\n propertyKeywords_,nonStandardPropertyKeywords_,\n colorKeywords_,valueKeywords_,fontProperties_,\n wordOperatorKeywords_,blockKeywords_,\n commonAtoms_,commonDef_);\n\nfunction wordRegexp(words) {\n words = words.sort(function(a,b){return b > a;});\n return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\");\n}\n\nfunction keySet(array) {\n var keys = {};\n for (var i = 0; i < array.length; ++i) keys[array[i]] = true;\n return keys;\n}\n\nfunction escapeRegExp(text) {\n return text.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, \"\\\\$&\");\n}\n\nvar tagKeywords = keySet(tagKeywords_),\n tagVariablesRegexp = /^(a|b|i|s|col|em)$/i,\n propertyKeywords = keySet(propertyKeywords_),\n nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_),\n valueKeywords = keySet(valueKeywords_),\n colorKeywords = keySet(colorKeywords_),\n documentTypes = keySet(documentTypes_),\n documentTypesRegexp = wordRegexp(documentTypes_),\n mediaFeatures = keySet(mediaFeatures_),\n mediaTypes = keySet(mediaTypes_),\n fontProperties = keySet(fontProperties_),\n operatorsRegexp = /^\\s*([.]{2,3}|&&|\\|\\||\\*\\*|[?!=:]?=|[-+*\\/%<>]=?|\\?:|\\~)/,\n wordOperatorKeywordsRegexp = wordRegexp(wordOperatorKeywords_),\n blockKeywords = keySet(blockKeywords_),\n vendorPrefixesRegexp = new RegExp(/^\\-(moz|ms|o|webkit)-/i),\n commonAtoms = keySet(commonAtoms_),\n firstWordMatch = \"\",\n states = {},\n ch,\n style,\n type,\n override;\n\n/**\n * Tokenizers\n */\nfunction tokenBase(stream, state) {\n firstWordMatch = stream.string.match(/(^[\\w-]+\\s*=\\s*$)|(^\\s*[\\w-]+\\s*=\\s*[\\w-])|(^\\s*(\\.|#|@|\\$|\\&|\\[|\\d|\\+|::?|\\{|\\>|~|\\/)?\\s*[\\w-]*([a-z0-9-]|\\*|\\/\\*)(\\(|,)?)/);\n state.context.line.firstWord = firstWordMatch ? firstWordMatch[0].replace(/^\\s*/, \"\") : \"\";\n state.context.line.indent = stream.indentation();\n ch = stream.peek();\n\n // Line comment\n if (stream.match(\"//\")) {\n stream.skipToEnd();\n return [\"comment\", \"comment\"];\n }\n // Block comment\n if (stream.match(\"/*\")) {\n state.tokenize = tokenCComment;\n return tokenCComment(stream, state);\n }\n // String\n if (ch == \"\\\"\" || ch == \"'\") {\n stream.next();\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n }\n // Def\n if (ch == \"@\") {\n stream.next();\n stream.eatWhile(/[\\w\\\\-]/);\n return [\"def\", stream.current()];\n }\n // ID selector or Hex color\n if (ch == \"#\") {\n stream.next();\n // Hex color\n if (stream.match(/^[0-9a-f]{3}([0-9a-f]([0-9a-f]{2}){0,2})?\\b(?!-)/i)) {\n return [\"atom\", \"atom\"];\n }\n // ID selector\n if (stream.match(/^[a-z][\\w-]*/i)) {\n return [\"builtin\", \"hash\"];\n }\n }\n // Vendor prefixes\n if (stream.match(vendorPrefixesRegexp)) {\n return [\"meta\", \"vendor-prefixes\"];\n }\n // Numbers\n if (stream.match(/^-?[0-9]?\\.?[0-9]/)) {\n stream.eatWhile(/[a-z%]/i);\n return [\"number\", \"unit\"];\n }\n // !important|optional\n if (ch == \"!\") {\n stream.next();\n return [stream.match(/^(important|optional)/i) ? \"keyword\": \"operator\", \"important\"];\n }\n // Class\n if (ch == \".\" && stream.match(/^\\.[a-z][\\w-]*/i)) {\n return [\"qualifier\", \"qualifier\"];\n }\n // url url-prefix domain regexp\n if (stream.match(documentTypesRegexp)) {\n if (stream.peek() == \"(\") state.tokenize = tokenParenthesized;\n return [\"property\", \"word\"];\n }\n // Mixins / Functions\n if (stream.match(/^[a-z][\\w-]*\\(/i)) {\n stream.backUp(1);\n return [\"keyword\", \"mixin\"];\n }\n // Block mixins\n if (stream.match(/^(\\+|-)[a-z][\\w-]*\\(/i)) {\n stream.backUp(1);\n return [\"keyword\", \"block-mixin\"];\n }\n // Parent Reference BEM naming\n if (stream.string.match(/^\\s*&/) && stream.match(/^[-_]+[a-z][\\w-]*/)) {\n return [\"qualifier\", \"qualifier\"];\n }\n // / Root Reference & Parent Reference\n if (stream.match(/^(\\/|&)(-|_|:|\\.|#|[a-z])/)) {\n stream.backUp(1);\n return [\"variableName.special\", \"reference\"];\n }\n if (stream.match(/^&{1}\\s*$/)) {\n return [\"variableName.special\", \"reference\"];\n }\n // Word operator\n if (stream.match(wordOperatorKeywordsRegexp)) {\n return [\"operator\", \"operator\"];\n }\n // Word\n if (stream.match(/^\\$?[-_]*[a-z0-9]+[\\w-]*/i)) {\n // Variable\n if (stream.match(/^(\\.|\\[)[\\w-\\'\\\"\\]]+/i, false)) {\n if (!wordIsTag(stream.current())) {\n stream.match('.');\n return [\"variable\", \"variable-name\"];\n }\n }\n return [\"variable\", \"word\"];\n }\n // Operators\n if (stream.match(operatorsRegexp)) {\n return [\"operator\", stream.current()];\n }\n // Delimiters\n if (/[:;,{}\\[\\]\\(\\)]/.test(ch)) {\n stream.next();\n return [null, ch];\n }\n // Non-detected items\n stream.next();\n return [null, null];\n}\n\n/**\n * Token comment\n */\nfunction tokenCComment(stream, state) {\n var maybeEnd = false, ch;\n while ((ch = stream.next()) != null) {\n if (maybeEnd && ch == \"/\") {\n state.tokenize = null;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return [\"comment\", \"comment\"];\n}\n\n/**\n * Token string\n */\nfunction tokenString(quote) {\n return function(stream, state) {\n var escaped = false, ch;\n while ((ch = stream.next()) != null) {\n if (ch == quote && !escaped) {\n if (quote == \")\") stream.backUp(1);\n break;\n }\n escaped = !escaped && ch == \"\\\\\";\n }\n if (ch == quote || !escaped && quote != \")\") state.tokenize = null;\n return [\"string\", \"string\"];\n };\n}\n\n/**\n * Token parenthesized\n */\nfunction tokenParenthesized(stream, state) {\n stream.next(); // Must be \"(\"\n if (!stream.match(/\\s*[\\\"\\')]/, false))\n state.tokenize = tokenString(\")\");\n else\n state.tokenize = null;\n return [null, \"(\"];\n}\n\n/**\n * Context management\n */\nfunction Context(type, indent, prev, line) {\n this.type = type;\n this.indent = indent;\n this.prev = prev;\n this.line = line || {firstWord: \"\", indent: 0};\n}\n\nfunction pushContext(state, stream, type, indent) {\n indent = indent >= 0 ? indent : stream.indentUnit;\n state.context = new Context(type, stream.indentation() + indent, state.context);\n return type;\n}\n\nfunction popContext(state, stream, currentIndent) {\n var contextIndent = state.context.indent - stream.indentUnit;\n currentIndent = currentIndent || false;\n state.context = state.context.prev;\n if (currentIndent) state.context.indent = contextIndent;\n return state.context.type;\n}\n\nfunction pass(type, stream, state) {\n return states[state.context.type](type, stream, state);\n}\n\nfunction popAndPass(type, stream, state, n) {\n for (var i = n || 1; i > 0; i--)\n state.context = state.context.prev;\n return pass(type, stream, state);\n}\n\n\n/**\n * Parser\n */\nfunction wordIsTag(word) {\n return word.toLowerCase() in tagKeywords;\n}\n\nfunction wordIsProperty(word) {\n word = word.toLowerCase();\n return word in propertyKeywords || word in fontProperties;\n}\n\nfunction wordIsBlock(word) {\n return word.toLowerCase() in blockKeywords;\n}\n\nfunction wordIsVendorPrefix(word) {\n return word.toLowerCase().match(vendorPrefixesRegexp);\n}\n\nfunction wordAsValue(word) {\n var wordLC = word.toLowerCase();\n var override = \"variable\";\n if (wordIsTag(word)) override = \"tag\";\n else if (wordIsBlock(word)) override = \"block-keyword\";\n else if (wordIsProperty(word)) override = \"property\";\n else if (wordLC in valueKeywords || wordLC in commonAtoms) override = \"atom\";\n else if (wordLC == \"return\" || wordLC in colorKeywords) override = \"keyword\";\n\n // Font family\n else if (word.match(/^[A-Z]/)) override = \"string\";\n return override;\n}\n\nfunction typeIsBlock(type, stream) {\n return ((endOfLine(stream) && (type == \"{\" || type == \"]\" || type == \"hash\" || type == \"qualifier\")) || type == \"block-mixin\");\n}\n\nfunction typeIsInterpolation(type, stream) {\n return type == \"{\" && stream.match(/^\\s*\\$?[\\w-]+/i, false);\n}\n\nfunction typeIsPseudo(type, stream) {\n return type == \":\" && stream.match(/^[a-z-]+/, false);\n}\n\nfunction startOfLine(stream) {\n return stream.sol() || stream.string.match(new RegExp(\"^\\\\s*\" + escapeRegExp(stream.current())));\n}\n\nfunction endOfLine(stream) {\n return stream.eol() || stream.match(/^\\s*$/, false);\n}\n\nfunction firstWordOfLine(line) {\n var re = /^\\s*[-_]*[a-z0-9]+[\\w-]*/i;\n var result = typeof line == \"string\" ? line.match(re) : line.string.match(re);\n return result ? result[0].replace(/^\\s*/, \"\") : \"\";\n}\n\n\n/**\n * Block\n */\nstates.block = function(type, stream, state) {\n if ((type == \"comment\" && startOfLine(stream)) ||\n (type == \",\" && endOfLine(stream)) ||\n type == \"mixin\") {\n return pushContext(state, stream, \"block\", 0);\n }\n if (typeIsInterpolation(type, stream)) {\n return pushContext(state, stream, \"interpolation\");\n }\n if (endOfLine(stream) && type == \"]\") {\n if (!/^\\s*(\\.|#|:|\\[|\\*|&)/.test(stream.string) && !wordIsTag(firstWordOfLine(stream))) {\n return pushContext(state, stream, \"block\", 0);\n }\n }\n if (typeIsBlock(type, stream)) {\n return pushContext(state, stream, \"block\");\n }\n if (type == \"}\" && endOfLine(stream)) {\n return pushContext(state, stream, \"block\", 0);\n }\n if (type == \"variable-name\") {\n if (stream.string.match(/^\\s?\\$[\\w-\\.\\[\\]\\'\\\"]+$/) || wordIsBlock(firstWordOfLine(stream))) {\n return pushContext(state, stream, \"variableName\");\n }\n else {\n return pushContext(state, stream, \"variableName\", 0);\n }\n }\n if (type == \"=\") {\n if (!endOfLine(stream) && !wordIsBlock(firstWordOfLine(stream))) {\n return pushContext(state, stream, \"block\", 0);\n }\n return pushContext(state, stream, \"block\");\n }\n if (type == \"*\") {\n if (endOfLine(stream) || stream.match(/\\s*(,|\\.|#|\\[|:|{)/,false)) {\n override = \"tag\";\n return pushContext(state, stream, \"block\");\n }\n }\n if (typeIsPseudo(type, stream)) {\n return pushContext(state, stream, \"pseudo\");\n }\n if (/@(font-face|media|supports|(-moz-)?document)/.test(type)) {\n return pushContext(state, stream, endOfLine(stream) ? \"block\" : \"atBlock\");\n }\n if (/@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) {\n return pushContext(state, stream, \"keyframes\");\n }\n if (/@extends?/.test(type)) {\n return pushContext(state, stream, \"extend\", 0);\n }\n if (type && type.charAt(0) == \"@\") {\n\n // Property Lookup\n if (stream.indentation() > 0 && wordIsProperty(stream.current().slice(1))) {\n override = \"variable\";\n return \"block\";\n }\n if (/(@import|@require|@charset)/.test(type)) {\n return pushContext(state, stream, \"block\", 0);\n }\n return pushContext(state, stream, \"block\");\n }\n if (type == \"reference\" && endOfLine(stream)) {\n return pushContext(state, stream, \"block\");\n }\n if (type == \"(\") {\n return pushContext(state, stream, \"parens\");\n }\n\n if (type == \"vendor-prefixes\") {\n return pushContext(state, stream, \"vendorPrefixes\");\n }\n if (type == \"word\") {\n var word = stream.current();\n override = wordAsValue(word);\n\n if (override == \"property\") {\n if (startOfLine(stream)) {\n return pushContext(state, stream, \"block\", 0);\n } else {\n override = \"atom\";\n return \"block\";\n }\n }\n\n if (override == \"tag\") {\n\n // tag is a css value\n if (/embed|menu|pre|progress|sub|table/.test(word)) {\n if (wordIsProperty(firstWordOfLine(stream))) {\n override = \"atom\";\n return \"block\";\n }\n }\n\n // tag is an attribute\n if (stream.string.match(new RegExp(\"\\\\[\\\\s*\" + word + \"|\" + word +\"\\\\s*\\\\]\"))) {\n override = \"atom\";\n return \"block\";\n }\n\n // tag is a variable\n if (tagVariablesRegexp.test(word)) {\n if ((startOfLine(stream) && stream.string.match(/=/)) ||\n (!startOfLine(stream) &&\n !stream.string.match(/^(\\s*\\.|#|\\&|\\[|\\/|>|\\*)/) &&\n !wordIsTag(firstWordOfLine(stream)))) {\n override = \"variable\";\n if (wordIsBlock(firstWordOfLine(stream))) return \"block\";\n return pushContext(state, stream, \"block\", 0);\n }\n }\n\n if (endOfLine(stream)) return pushContext(state, stream, \"block\");\n }\n if (override == \"block-keyword\") {\n override = \"keyword\";\n\n // Postfix conditionals\n if (stream.current(/(if|unless)/) && !startOfLine(stream)) {\n return \"block\";\n }\n return pushContext(state, stream, \"block\");\n }\n if (word == \"return\") return pushContext(state, stream, \"block\", 0);\n\n // Placeholder selector\n if (override == \"variable\" && stream.string.match(/^\\s?\\$[\\w-\\.\\[\\]\\'\\\"]+$/)) {\n return pushContext(state, stream, \"block\");\n }\n }\n return state.context.type;\n};\n\n\n/**\n * Parens\n */\nstates.parens = function(type, stream, state) {\n if (type == \"(\") return pushContext(state, stream, \"parens\");\n if (type == \")\") {\n if (state.context.prev.type == \"parens\") {\n return popContext(state, stream);\n }\n if ((stream.string.match(/^[a-z][\\w-]*\\(/i) && endOfLine(stream)) ||\n wordIsBlock(firstWordOfLine(stream)) ||\n /(\\.|#|:|\\[|\\*|&|>|~|\\+|\\/)/.test(firstWordOfLine(stream)) ||\n (!stream.string.match(/^-?[a-z][\\w-\\.\\[\\]\\'\\\"]*\\s*=/) &&\n wordIsTag(firstWordOfLine(stream)))) {\n return pushContext(state, stream, \"block\");\n }\n if (stream.string.match(/^[\\$-]?[a-z][\\w-\\.\\[\\]\\'\\\"]*\\s*=/) ||\n stream.string.match(/^\\s*(\\(|\\)|[0-9])/) ||\n stream.string.match(/^\\s+[a-z][\\w-]*\\(/i) ||\n stream.string.match(/^\\s+[\\$-]?[a-z]/i)) {\n return pushContext(state, stream, \"block\", 0);\n }\n if (endOfLine(stream)) return pushContext(state, stream, \"block\");\n else return pushContext(state, stream, \"block\", 0);\n }\n if (type && type.charAt(0) == \"@\" && wordIsProperty(stream.current().slice(1))) {\n override = \"variable\";\n }\n if (type == \"word\") {\n var word = stream.current();\n override = wordAsValue(word);\n if (override == \"tag\" && tagVariablesRegexp.test(word)) {\n override = \"variable\";\n }\n if (override == \"property\" || word == \"to\") override = \"atom\";\n }\n if (type == \"variable-name\") {\n return pushContext(state, stream, \"variableName\");\n }\n if (typeIsPseudo(type, stream)) {\n return pushContext(state, stream, \"pseudo\");\n }\n return state.context.type;\n};\n\n\n/**\n * Vendor prefixes\n */\nstates.vendorPrefixes = function(type, stream, state) {\n if (type == \"word\") {\n override = \"property\";\n return pushContext(state, stream, \"block\", 0);\n }\n return popContext(state, stream);\n};\n\n\n/**\n * Pseudo\n */\nstates.pseudo = function(type, stream, state) {\n if (!wordIsProperty(firstWordOfLine(stream.string))) {\n stream.match(/^[a-z-]+/);\n override = \"variableName.special\";\n if (endOfLine(stream)) return pushContext(state, stream, \"block\");\n return popContext(state, stream);\n }\n return popAndPass(type, stream, state);\n};\n\n\n/**\n * atBlock\n */\nstates.atBlock = function(type, stream, state) {\n if (type == \"(\") return pushContext(state, stream, \"atBlock_parens\");\n if (typeIsBlock(type, stream)) {\n return pushContext(state, stream, \"block\");\n }\n if (typeIsInterpolation(type, stream)) {\n return pushContext(state, stream, \"interpolation\");\n }\n if (type == \"word\") {\n var word = stream.current().toLowerCase();\n if (/^(only|not|and|or)$/.test(word))\n override = \"keyword\";\n else if (documentTypes.hasOwnProperty(word))\n override = \"tag\";\n else if (mediaTypes.hasOwnProperty(word))\n override = \"attribute\";\n else if (mediaFeatures.hasOwnProperty(word))\n override = \"property\";\n else if (nonStandardPropertyKeywords.hasOwnProperty(word))\n override = \"string.special\";\n else override = wordAsValue(stream.current());\n if (override == \"tag\" && endOfLine(stream)) {\n return pushContext(state, stream, \"block\");\n }\n }\n if (type == \"operator\" && /^(not|and|or)$/.test(stream.current())) {\n override = \"keyword\";\n }\n return state.context.type;\n};\n\nstates.atBlock_parens = function(type, stream, state) {\n if (type == \"{\" || type == \"}\") return state.context.type;\n if (type == \")\") {\n if (endOfLine(stream)) return pushContext(state, stream, \"block\");\n else return pushContext(state, stream, \"atBlock\");\n }\n if (type == \"word\") {\n var word = stream.current().toLowerCase();\n override = wordAsValue(word);\n if (/^(max|min)/.test(word)) override = \"property\";\n if (override == \"tag\") {\n tagVariablesRegexp.test(word) ? override = \"variable\" : override = \"atom\";\n }\n return state.context.type;\n }\n return states.atBlock(type, stream, state);\n};\n\n\n/**\n * Keyframes\n */\nstates.keyframes = function(type, stream, state) {\n if (stream.indentation() == \"0\" && ((type == \"}\" && startOfLine(stream)) || type == \"]\" || type == \"hash\"\n || type == \"qualifier\" || wordIsTag(stream.current()))) {\n return popAndPass(type, stream, state);\n }\n if (type == \"{\") return pushContext(state, stream, \"keyframes\");\n if (type == \"}\") {\n if (startOfLine(stream)) return popContext(state, stream, true);\n else return pushContext(state, stream, \"keyframes\");\n }\n if (type == \"unit\" && /^[0-9]+\\%$/.test(stream.current())) {\n return pushContext(state, stream, \"keyframes\");\n }\n if (type == \"word\") {\n override = wordAsValue(stream.current());\n if (override == \"block-keyword\") {\n override = \"keyword\";\n return pushContext(state, stream, \"keyframes\");\n }\n }\n if (/@(font-face|media|supports|(-moz-)?document)/.test(type)) {\n return pushContext(state, stream, endOfLine(stream) ? \"block\" : \"atBlock\");\n }\n if (type == \"mixin\") {\n return pushContext(state, stream, \"block\", 0);\n }\n return state.context.type;\n};\n\n\n/**\n * Interpolation\n */\nstates.interpolation = function(type, stream, state) {\n if (type == \"{\") popContext(state, stream) && pushContext(state, stream, \"block\");\n if (type == \"}\") {\n if (stream.string.match(/^\\s*(\\.|#|:|\\[|\\*|&|>|~|\\+|\\/)/i) ||\n (stream.string.match(/^\\s*[a-z]/i) && wordIsTag(firstWordOfLine(stream)))) {\n return pushContext(state, stream, \"block\");\n }\n if (!stream.string.match(/^(\\{|\\s*\\&)/) ||\n stream.match(/\\s*[\\w-]/,false)) {\n return pushContext(state, stream, \"block\", 0);\n }\n return pushContext(state, stream, \"block\");\n }\n if (type == \"variable-name\") {\n return pushContext(state, stream, \"variableName\", 0);\n }\n if (type == \"word\") {\n override = wordAsValue(stream.current());\n if (override == \"tag\") override = \"atom\";\n }\n return state.context.type;\n};\n\n\n/**\n * Extend/s\n */\nstates.extend = function(type, stream, state) {\n if (type == \"[\" || type == \"=\") return \"extend\";\n if (type == \"]\") return popContext(state, stream);\n if (type == \"word\") {\n override = wordAsValue(stream.current());\n return \"extend\";\n }\n return popContext(state, stream);\n};\n\n\n/**\n * Variable name\n */\nstates.variableName = function(type, stream, state) {\n if (type == \"string\" || type == \"[\" || type == \"]\" || stream.current().match(/^(\\.|\\$)/)) {\n if (stream.current().match(/^\\.[\\w-]+/i)) override = \"variable\";\n return \"variableName\";\n }\n return popAndPass(type, stream, state);\n};\n\nexport const stylus = {\n name: \"stylus\",\n startState: function() {\n return {\n tokenize: null,\n state: \"block\",\n context: new Context(\"block\", 0, null)\n };\n },\n token: function(stream, state) {\n if (!state.tokenize && stream.eatSpace()) return null;\n style = (state.tokenize || tokenBase)(stream, state);\n if (style && typeof style == \"object\") {\n type = style[1];\n style = style[0];\n }\n override = style;\n state.state = states[state.state](type, stream, state);\n return override;\n },\n indent: function(state, textAfter, iCx) {\n var cx = state.context,\n ch = textAfter && textAfter.charAt(0),\n indent = cx.indent,\n lineFirstWord = firstWordOfLine(textAfter),\n lineIndent = iCx.lineIndent(iCx.pos),\n prevLineFirstWord = state.context.prev ? state.context.prev.line.firstWord : \"\",\n prevLineIndent = state.context.prev ? state.context.prev.line.indent : lineIndent;\n\n if (cx.prev &&\n (ch == \"}\" && (cx.type == \"block\" || cx.type == \"atBlock\" || cx.type == \"keyframes\") ||\n ch == \")\" && (cx.type == \"parens\" || cx.type == \"atBlock_parens\") ||\n ch == \"{\" && (cx.type == \"at\"))) {\n indent = cx.indent - iCx.unit;\n } else if (!(/(\\})/.test(ch))) {\n if (/@|\\$|\\d/.test(ch) ||\n /^\\{/.test(textAfter) ||\n/^\\s*\\/(\\/|\\*)/.test(textAfter) ||\n /^\\s*\\/\\*/.test(prevLineFirstWord) ||\n /^\\s*[\\w-\\.\\[\\]\\'\\\"]+\\s*(\\?|:|\\+)?=/i.test(textAfter) ||\n/^(\\+|-)?[a-z][\\w-]*\\(/i.test(textAfter) ||\n/^return/.test(textAfter) ||\n wordIsBlock(lineFirstWord)) {\n indent = lineIndent;\n } else if (/(\\.|#|:|\\[|\\*|&|>|~|\\+|\\/)/.test(ch) || wordIsTag(lineFirstWord)) {\n if (/\\,\\s*$/.test(prevLineFirstWord)) {\n indent = prevLineIndent;\n } else if (!state.sol() && (/(\\.|#|:|\\[|\\*|&|>|~|\\+|\\/)/.test(prevLineFirstWord) || wordIsTag(prevLineFirstWord))) {\n indent = lineIndent <= prevLineIndent ? prevLineIndent : prevLineIndent + iCx.unit;\n } else {\n indent = lineIndent;\n }\n } else if (!/,\\s*$/.test(textAfter) && (wordIsVendorPrefix(lineFirstWord) || wordIsProperty(lineFirstWord))) {\n if (wordIsBlock(prevLineFirstWord)) {\n indent = lineIndent <= prevLineIndent ? prevLineIndent : prevLineIndent + iCx.unit;\n } else if (/^\\{/.test(prevLineFirstWord)) {\n indent = lineIndent <= prevLineIndent ? lineIndent : prevLineIndent + iCx.unit;\n } else if (wordIsVendorPrefix(prevLineFirstWord) || wordIsProperty(prevLineFirstWord)) {\n indent = lineIndent >= prevLineIndent ? prevLineIndent : lineIndent;\n } else if (/^(\\.|#|:|\\[|\\*|&|@|\\+|\\-|>|~|\\/)/.test(prevLineFirstWord) ||\n /=\\s*$/.test(prevLineFirstWord) ||\n wordIsTag(prevLineFirstWord) ||\n /^\\$[\\w-\\.\\[\\]\\'\\\"]/.test(prevLineFirstWord)) {\n indent = prevLineIndent + iCx.unit;\n } else {\n indent = lineIndent;\n }\n }\n }\n return indent;\n },\n languageData: {\n indentOnInput: /^\\s*\\}$/,\n commentTokens: {line: \"//\", block: {open: \"/*\", close: \"*/\"}},\n autocomplete: hintWords\n }\n};\n"],"names":["tagKeywords_","documentTypes_","mediaTypes_","mediaFeatures_","propertyKeywords_","nonStandardPropertyKeywords_","fontProperties_","colorKeywords_","valueKeywords_","wordOperatorKeywords_","blockKeywords_","commonAtoms_","hintWords","concat","wordRegexp","words","sort","a","b","RegExp","join","keySet","array","keys","i","length","ch","style","type","override","tagKeywords","tagVariablesRegexp","propertyKeywords","nonStandardPropertyKeywords","valueKeywords","colorKeywords","documentTypes","documentTypesRegexp","mediaFeatures","mediaTypes","fontProperties","operatorsRegexp","wordOperatorKeywordsRegexp","blockKeywords","vendorPrefixesRegexp","commonAtoms","firstWordMatch","states","tokenBase","stream","state","string","match","context","line","firstWord","replace","indent","indentation","peek","skipToEnd","tokenize","tokenCComment","next","tokenString","eatWhile","current","tokenParenthesized","backUp","wordIsTag","test","maybeEnd","quote","escaped","Context","prev","this","pushContext","indentUnit","popContext","currentIndent","contextIndent","popAndPass","n","pass","word","toLowerCase","wordIsProperty","wordIsBlock","wordIsVendorPrefix","wordAsValue","wordLC","typeIsBlock","endOfLine","typeIsInterpolation","typeIsPseudo","startOfLine","sol","eol","firstWordOfLine","re","result","block","charAt","slice","parens","vendorPrefixes","pseudo","atBlock","hasOwnProperty","atBlock_parens","keyframes","interpolation","extend","variableName","stylus","name","startState","token","eatSpace","textAfter","iCx","cx","lineFirstWord","lineIndent","pos","prevLineFirstWord","prevLineIndent","unit","languageData","indentOnInput","commentTokens","open","close","autocomplete"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/1757.index.js b/book/_build/html/_static/1757.index.js new file mode 100644 index 0000000..c4e406f --- /dev/null +++ b/book/_build/html/_static/1757.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[1757],{51757:(e,t,n)=>{n.r(t),n.d(t,{vb:()=>F});var r="error";function a(e){return new RegExp("^(("+e.join(")|(")+"))\\b","i")}var i=new RegExp("^[\\+\\-\\*/%&\\\\|\\^~<>!]"),o=new RegExp("^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]"),c=new RegExp("^((==)|(<>)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))"),s=new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))"),u=new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))"),l=new RegExp("^[_A-Za-z][_A-Za-z0-9]*"),d=["class","module","sub","enum","select","while","if","function","get","set","property","try","structure","synclock","using","with"],h=["else","elseif","case","catch","finally"],m=["next","loop"],f=["and","andalso","or","orelse","xor","in","not","is","isnot","like"],p=a(f),b=["#const","#else","#elseif","#end","#if","#region","addhandler","addressof","alias","as","byref","byval","cbool","cbyte","cchar","cdate","cdbl","cdec","cint","clng","cobj","compare","const","continue","csbyte","cshort","csng","cstr","cuint","culng","cushort","declare","default","delegate","dim","directcast","each","erase","error","event","exit","explicit","false","for","friend","gettype","goto","handles","implements","imports","infer","inherits","interface","isfalse","istrue","lib","me","mod","mustinherit","mustoverride","my","mybase","myclass","namespace","narrowing","new","nothing","notinheritable","notoverridable","of","off","on","operator","option","optional","out","overloads","overridable","overrides","paramarray","partial","private","protected","public","raiseevent","readonly","redim","removehandler","resume","return","shadows","shared","static","step","stop","strict","then","throw","to","true","trycast","typeof","until","until","when","widening","withevents","writeonly"],g=["object","boolean","char","string","byte","sbyte","short","ushort","int16","uint16","integer","uinteger","int32","uint32","long","ulong","int64","uint64","decimal","single","double","float","date","datetime","intptr","uintptr"],k=a(b),y=a(g),v='"',w=a(d),x=a(h),I=a(m),z=a(["end"]),L=a(["do"]);function E(e,t){t.currentIndent++}function C(e,t){t.currentIndent--}function R(e,t){if(e.eatSpace())return null;var n,a,d;if("'"===e.peek())return e.skipToEnd(),"comment";if(e.match(/^((&H)|(&O))?[0-9\.a-f]/i,!1)){var h=!1;if((e.match(/^\d*\.\d+F?/i)||e.match(/^\d+\.\d*F?/)||e.match(/^\.\d+F?/))&&(h=!0),h)return e.eat(/J/i),"number";var m=!1;if(e.match(/^&H[0-9a-f]+/i)||e.match(/^&O[0-7]+/i)?m=!0:e.match(/^[1-9]\d*F?/)?(e.eat(/J/i),m=!0):e.match(/^0(?![\dx])/i)&&(m=!0),m)return e.eat(/L/i),"number"}return e.match(v)?(t.tokenize=(n=e.current(),a=1==n.length,d="string",function(e,t){for(;!e.eol();){if(e.eatWhile(/[^'"]/),e.match(n))return t.tokenize=R,d;e.eat(/['"]/)}return a&&(t.tokenize=R),d}),t.tokenize(e,t)):e.match(u)||e.match(s)?null:e.match(c)||e.match(i)||e.match(p)?"operator":e.match(o)?null:e.match(L)?(E(0,t),t.doInCurrentLine=!0,"keyword"):e.match(w)?(t.doInCurrentLine?t.doInCurrentLine=!1:E(0,t),"keyword"):e.match(x)?"keyword":e.match(z)?(C(0,t),C(0,t),"keyword"):e.match(I)?(C(0,t),"keyword"):e.match(y)||e.match(k)?"keyword":e.match(l)?"variable":(e.next(),r)}const F={name:"vb",startState:function(){return{tokenize:R,lastToken:null,currentIndent:0,nextLineIndent:0,doInCurrentLine:!1}},token:function(e,t){e.sol()&&(t.currentIndent+=t.nextLineIndent,t.nextLineIndent=0,t.doInCurrentLine=0);var n=function(e,t){var n=t.tokenize(e,t),a=e.current();if("."===a)return"variable"===(n=t.tokenize(e,t))?"variable":r;var i="[({".indexOf(a);return-1!==i&&E(0,t),-1!==(i="])}".indexOf(a))&&C(0,t)?r:n}(e,t);return t.lastToken={style:n,content:e.current()},n},indent:function(e,t,n){var r=t.replace(/^\s+|\s+$/g,"");return r.match(I)||r.match(z)||r.match(x)?n.unit*(e.currentIndent-1):e.currentIndent<0?0:e.currentIndent*n.unit},languageData:{closeBrackets:{brackets:["(","[","{",'"']},commentTokens:{line:"'"},autocomplete:d.concat(h).concat(m).concat(f).concat(b).concat(g)}}}}]); +//# sourceMappingURL=1757.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/1757.index.js.map b/book/_build/html/_static/1757.index.js.map new file mode 100644 index 0000000..874e36e --- /dev/null +++ b/book/_build/html/_static/1757.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"1757.index.js","mappings":"wHAAA,IAAIA,EAAa,QAEjB,SAASC,EAAWC,GAClB,OAAO,IAAIC,OAAO,MAAQD,EAAME,KAAK,OAAS,QAAS,IACzD,CAEA,IAAIC,EAAkB,IAAIF,OAAO,+BAC7BG,EAAmB,IAAIH,OAAO,kCAC9BI,EAAkB,IAAIJ,OAAO,uDAC7BK,EAAmB,IAAIL,OAAO,wDAC9BM,EAAmB,IAAIN,OAAO,kCAC9BO,EAAc,IAAIP,OAAO,2BAEzBQ,EAAkB,CAAC,QAAQ,SAAU,MAAM,OAAO,SAAS,QAAQ,KAAK,WAAY,MAAM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MAAMjB,GAAgByC,EAAGG,MAAMtC,EAAMC,cAAc,GACzHD,EAAMC,cAAgB,EAAU,EAC5BD,EAAMC,cAAgBkC,EAAGG,IAClC,EAEAC,aAAc,CACZC,cAAe,CAACC,SAAU,CAAC,IAAK,IAAK,IAAK,MAC1CC,cAAe,CAACC,KAAM,KACtBC,aAAc7D,EAAgB8D,OAAO7D,GAAgB6D,OAAO5D,GACzD4D,OAAO3D,GAAkB2D,OAAOzD,GAAgByD,OAAOxD,I","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/vb.js"],"sourcesContent":["var ERRORCLASS = 'error';\n\nfunction wordRegexp(words) {\n return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\", \"i\");\n}\n\nvar singleOperators = new RegExp(\"^[\\\\+\\\\-\\\\*/%&\\\\\\\\|\\\\^~<>!]\");\nvar singleDelimiters = new RegExp('^[\\\\(\\\\)\\\\[\\\\]\\\\{\\\\}@,:`=;\\\\.]');\nvar doubleOperators = new RegExp(\"^((==)|(<>)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\\\*\\\\*))\");\nvar doubleDelimiters = new RegExp(\"^((\\\\+=)|(\\\\-=)|(\\\\*=)|(%=)|(/=)|(&=)|(\\\\|=)|(\\\\^=))\");\nvar tripleDelimiters = new RegExp(\"^((//=)|(>>=)|(<<=)|(\\\\*\\\\*=))\");\nvar identifiers = new RegExp(\"^[_A-Za-z][_A-Za-z0-9]*\");\n\nvar openingKeywords = ['class','module', 'sub','enum','select','while','if','function', 'get','set','property', 'try', 'structure', 'synclock', 'using', 'with'];\nvar middleKeywords = ['else','elseif','case', 'catch', 'finally'];\nvar endKeywords = ['next','loop'];\n\nvar operatorKeywords = ['and', \"andalso\", 'or', 'orelse', 'xor', 'in', 'not', 'is', 'isnot', 'like'];\nvar wordOperators = wordRegexp(operatorKeywords);\n\nvar commonKeywords = [\"#const\", \"#else\", \"#elseif\", \"#end\", \"#if\", \"#region\", \"addhandler\", \"addressof\", \"alias\", \"as\", \"byref\", \"byval\", \"cbool\", \"cbyte\", \"cchar\", \"cdate\", \"cdbl\", \"cdec\", \"cint\", \"clng\", \"cobj\", \"compare\", \"const\", \"continue\", \"csbyte\", \"cshort\", \"csng\", \"cstr\", \"cuint\", \"culng\", \"cushort\", \"declare\", \"default\", \"delegate\", \"dim\", \"directcast\", \"each\", \"erase\", \"error\", \"event\", \"exit\", \"explicit\", \"false\", \"for\", \"friend\", \"gettype\", \"goto\", \"handles\", \"implements\", \"imports\", \"infer\", \"inherits\", \"interface\", \"isfalse\", \"istrue\", \"lib\", \"me\", \"mod\", \"mustinherit\", \"mustoverride\", \"my\", \"mybase\", \"myclass\", \"namespace\", \"narrowing\", \"new\", \"nothing\", \"notinheritable\", \"notoverridable\", \"of\", \"off\", \"on\", \"operator\", \"option\", \"optional\", \"out\", \"overloads\", \"overridable\", \"overrides\", \"paramarray\", \"partial\", \"private\", \"protected\", \"public\", \"raiseevent\", \"readonly\", \"redim\", \"removehandler\", \"resume\", \"return\", \"shadows\", \"shared\", \"static\", \"step\", \"stop\", \"strict\", \"then\", \"throw\", \"to\", \"true\", \"trycast\", \"typeof\", \"until\", \"until\", \"when\", \"widening\", \"withevents\", \"writeonly\"];\n\nvar commontypes = ['object', 'boolean', 'char', 'string', 'byte', 'sbyte', 'short', 'ushort', 'int16', 'uint16', 'integer', 'uinteger', 'int32', 'uint32', 'long', 'ulong', 'int64', 'uint64', 'decimal', 'single', 'double', 'float', 'date', 'datetime', 'intptr', 'uintptr'];\n\nvar keywords = wordRegexp(commonKeywords);\nvar types = wordRegexp(commontypes);\nvar stringPrefixes = '\"';\n\nvar opening = wordRegexp(openingKeywords);\nvar middle = wordRegexp(middleKeywords);\nvar closing = wordRegexp(endKeywords);\nvar doubleClosing = wordRegexp(['end']);\nvar doOpening = wordRegexp(['do']);\n\nvar indentInfo = null;\n\nfunction indent(_stream, state) {\n state.currentIndent++;\n}\n\nfunction dedent(_stream, state) {\n state.currentIndent--;\n}\n// tokenizers\nfunction tokenBase(stream, state) {\n if (stream.eatSpace()) {\n return null;\n }\n\n var ch = stream.peek();\n\n // Handle Comments\n if (ch === \"'\") {\n stream.skipToEnd();\n return 'comment';\n }\n\n\n // Handle Number Literals\n if (stream.match(/^((&H)|(&O))?[0-9\\.a-f]/i, false)) {\n var floatLiteral = false;\n // Floats\n if (stream.match(/^\\d*\\.\\d+F?/i)) { floatLiteral = true; }\n else if (stream.match(/^\\d+\\.\\d*F?/)) { floatLiteral = true; }\n else if (stream.match(/^\\.\\d+F?/)) { floatLiteral = true; }\n\n if (floatLiteral) {\n // Float literals may be \"imaginary\"\n stream.eat(/J/i);\n return 'number';\n }\n // Integers\n var intLiteral = false;\n // Hex\n if (stream.match(/^&H[0-9a-f]+/i)) { intLiteral = true; }\n // Octal\n else if (stream.match(/^&O[0-7]+/i)) { intLiteral = true; }\n // Decimal\n else if (stream.match(/^[1-9]\\d*F?/)) {\n // Decimal literals may be \"imaginary\"\n stream.eat(/J/i);\n // TODO - Can you have imaginary longs?\n intLiteral = true;\n }\n // Zero by itself with no other piece of number.\n else if (stream.match(/^0(?![\\dx])/i)) { intLiteral = true; }\n if (intLiteral) {\n // Integer literals may be \"long\"\n stream.eat(/L/i);\n return 'number';\n }\n }\n\n // Handle Strings\n if (stream.match(stringPrefixes)) {\n state.tokenize = tokenStringFactory(stream.current());\n return state.tokenize(stream, state);\n }\n\n // Handle operators and Delimiters\n if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {\n return null;\n }\n if (stream.match(doubleOperators)\n || stream.match(singleOperators)\n || stream.match(wordOperators)) {\n return 'operator';\n }\n if (stream.match(singleDelimiters)) {\n return null;\n }\n if (stream.match(doOpening)) {\n indent(stream,state);\n state.doInCurrentLine = true;\n return 'keyword';\n }\n if (stream.match(opening)) {\n if (! state.doInCurrentLine)\n indent(stream,state);\n else\n state.doInCurrentLine = false;\n return 'keyword';\n }\n if (stream.match(middle)) {\n return 'keyword';\n }\n\n if (stream.match(doubleClosing)) {\n dedent(stream,state);\n dedent(stream,state);\n return 'keyword';\n }\n if (stream.match(closing)) {\n dedent(stream,state);\n return 'keyword';\n }\n\n if (stream.match(types)) {\n return 'keyword';\n }\n\n if (stream.match(keywords)) {\n return 'keyword';\n }\n\n if (stream.match(identifiers)) {\n return 'variable';\n }\n\n // Handle non-detected items\n stream.next();\n return ERRORCLASS;\n}\n\nfunction tokenStringFactory(delimiter) {\n var singleline = delimiter.length == 1;\n var OUTCLASS = 'string';\n\n return function(stream, state) {\n while (!stream.eol()) {\n stream.eatWhile(/[^'\"]/);\n if (stream.match(delimiter)) {\n state.tokenize = tokenBase;\n return OUTCLASS;\n } else {\n stream.eat(/['\"]/);\n }\n }\n if (singleline) {\n state.tokenize = tokenBase;\n }\n return OUTCLASS;\n };\n}\n\n\nfunction tokenLexer(stream, state) {\n var style = state.tokenize(stream, state);\n var current = stream.current();\n\n // Handle '.' connected identifiers\n if (current === '.') {\n style = state.tokenize(stream, state);\n if (style === 'variable') {\n return 'variable';\n } else {\n return ERRORCLASS;\n }\n }\n\n\n var delimiter_index = '[({'.indexOf(current);\n if (delimiter_index !== -1) {\n indent(stream, state );\n }\n if (indentInfo === 'dedent') {\n if (dedent(stream, state)) {\n return ERRORCLASS;\n }\n }\n delimiter_index = '])}'.indexOf(current);\n if (delimiter_index !== -1) {\n if (dedent(stream, state)) {\n return ERRORCLASS;\n }\n }\n\n return style;\n}\n\nexport const vb = {\n name: \"vb\",\n\n startState: function() {\n return {\n tokenize: tokenBase,\n lastToken: null,\n currentIndent: 0,\n nextLineIndent: 0,\n doInCurrentLine: false\n\n\n };\n },\n\n token: function(stream, state) {\n if (stream.sol()) {\n state.currentIndent += state.nextLineIndent;\n state.nextLineIndent = 0;\n state.doInCurrentLine = 0;\n }\n var style = tokenLexer(stream, state);\n\n state.lastToken = {style:style, content: stream.current()};\n\n\n\n return style;\n },\n\n indent: function(state, textAfter, cx) {\n var trueText = textAfter.replace(/^\\s+|\\s+$/g, '') ;\n if (trueText.match(closing) || trueText.match(doubleClosing) || trueText.match(middle)) return cx.unit*(state.currentIndent-1);\n if(state.currentIndent < 0) return 0;\n return state.currentIndent * cx.unit;\n },\n\n languageData: {\n closeBrackets: {brackets: [\"(\", \"[\", \"{\", '\"']},\n commentTokens: {line: \"'\"},\n autocomplete: openingKeywords.concat(middleKeywords).concat(endKeywords)\n .concat(operatorKeywords).concat(commonKeywords).concat(commontypes)\n }\n};\n"],"names":["ERRORCLASS","wordRegexp","words","RegExp","join","singleOperators","singleDelimiters","doubleOperators","doubleDelimiters","tripleDelimiters","identifiers","openingKeywords","middleKeywords","endKeywords","operatorKeywords","wordOperators","commonKeywords","commontypes","keywords","types","stringPrefixes","opening","middle","closing","doubleClosing","doOpening","indent","_stream","state","currentIndent","dedent","tokenBase","stream","eatSpace","delimiter","singleline","OUTCLASS","peek","skipToEnd","match","floatLiteral","eat","intLiteral","tokenize","current","length","eol","eatWhile","doInCurrentLine","next","vb","name","startState","lastToken","nextLineIndent","token","sol","style","delimiter_index","indexOf","tokenLexer","content","textAfter","cx","trueText","replace","unit","languageData","closeBrackets","brackets","commentTokens","line","autocomplete","concat"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/1803.index.js b/book/_build/html/_static/1803.index.js new file mode 100644 index 0000000..ca9849c --- /dev/null +++ b/book/_build/html/_static/1803.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[1803],{21803:(t,a,e)=>{e.r(a),e.d(a,{troff:()=>h});var n={};function r(t){if(t.eatSpace())return null;var a=t.sol(),e=t.next();if("\\"===e)return t.match("fB")||t.match("fR")||t.match("fI")||t.match("u")||t.match("d")||t.match("%")||t.match("&")?"string":t.match("m[")?(t.skipTo("]"),t.next(),"string"):t.match("s+")||t.match("s-")?(t.eatWhile(/[\d-]/),"string"):t.match("(")||t.match("*(")?(t.eatWhile(/[\w-]/),"string"):"string";if(a&&("."===e||"'"===e)&&t.eat("\\")&&t.eat('"'))return t.skipToEnd(),"comment";if(a&&"."===e){if(t.match("B ")||t.match("I ")||t.match("R "))return"attribute";if(t.match("TH ")||t.match("SH ")||t.match("SS ")||t.match("HP "))return t.skipToEnd(),"quote";if(t.match(/[A-Z]/)&&t.match(/[A-Z]/)||t.match(/[a-z]/)&&t.match(/[a-z]/))return"attribute"}t.eatWhile(/[\w-]/);var r=t.current();return n.hasOwnProperty(r)?n[r]:null}function c(t,a){return(a.tokens[0]||r)(t,a)}const h={name:"troff",startState:function(){return{tokens:[]}},token:function(t,a){return c(t,a)}}}}]); +//# sourceMappingURL=1803.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/1803.index.js.map b/book/_build/html/_static/1803.index.js.map new file mode 100644 index 0000000..c961f6f --- /dev/null +++ b/book/_build/html/_static/1803.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"1803.index.js","mappings":"2HAAA,IAAIA,EAAQ,CAAC,EAEb,SAASC,EAAUC,GACjB,GAAIA,EAAOC,WAAY,OAAO,KAE9B,IAAIC,EAAMF,EAAOE,MACbC,EAAKH,EAAOI,OAEhB,GAAW,OAAPD,EACF,OAAIH,EAAOK,MAAM,OAASL,EAAOK,MAAM,OAASL,EAAOK,MAAM,OACzDL,EAAOK,MAAM,MAASL,EAAOK,MAAM,MACnCL,EAAOK,MAAM,MAASL,EAAOK,MAAM,KAC9B,SAELL,EAAOK,MAAM,OACfL,EAAOM,OAAO,KACdN,EAAOI,OACA,UAELJ,EAAOK,MAAM,OAASL,EAAOK,MAAM,OACrCL,EAAOO,SAAS,SACT,UAELP,EAAOK,MAAM,MAASL,EAAOK,MAAM,OACrCL,EAAOO,SAAS,SACT,UAEF,SAET,GAAIL,IAAe,MAAPC,GAAqB,MAAPA,IACpBH,EAAOQ,IAAI,OAASR,EAAOQ,IAAI,KAEjC,OADAR,EAAOS,YACA,UAGX,GAAIP,GAAc,MAAPC,EAAY,CACrB,GAAIH,EAAOK,MAAM,OAASL,EAAOK,MAAM,OAASL,EAAOK,MAAM,MAC3D,MAAO,YAET,GAAIL,EAAOK,MAAM,QAAUL,EAAOK,MAAM,QAAUL,EAAOK,MAAM,QAAUL,EAAOK,MAAM,OAEpF,OADAL,EAAOS,YACA,QAET,GAAKT,EAAOK,MAAM,UAAYL,EAAOK,MAAM,UAAcL,EAAOK,MAAM,UAAYL,EAAOK,MAAM,SAC7F,MAAO,WAEX,CACAL,EAAOO,SAAS,SAChB,IAAIG,EAAMV,EAAOW,UACjB,OAAOb,EAAMc,eAAeF,GAAOZ,EAAMY,GAAO,IAClD,CAEA,SAASG,EAASb,EAAQc,GACxB,OAAQA,EAAMC,OAAO,IAAMhB,GAAYC,EAAQc,EACjD,CAEO,MAAME,EAAQ,CACnBC,KAAM,QACNC,WAAY,WAAY,MAAO,CAACH,OAAO,GAAI,EAC3CI,MAAO,SAASnB,EAAQc,GACtB,OAAOD,EAASb,EAAQc,EAC1B,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/troff.js"],"sourcesContent":["var words = {};\n\nfunction tokenBase(stream) {\n if (stream.eatSpace()) return null;\n\n var sol = stream.sol();\n var ch = stream.next();\n\n if (ch === '\\\\') {\n if (stream.match('fB') || stream.match('fR') || stream.match('fI') ||\n stream.match('u') || stream.match('d') ||\n stream.match('%') || stream.match('&')) {\n return 'string';\n }\n if (stream.match('m[')) {\n stream.skipTo(']');\n stream.next();\n return 'string';\n }\n if (stream.match('s+') || stream.match('s-')) {\n stream.eatWhile(/[\\d-]/);\n return 'string';\n }\n if (stream.match('\\(') || stream.match('*\\(')) {\n stream.eatWhile(/[\\w-]/);\n return 'string';\n }\n return 'string';\n }\n if (sol && (ch === '.' || ch === '\\'')) {\n if (stream.eat('\\\\') && stream.eat('\\\"')) {\n stream.skipToEnd();\n return 'comment';\n }\n }\n if (sol && ch === '.') {\n if (stream.match('B ') || stream.match('I ') || stream.match('R ')) {\n return 'attribute';\n }\n if (stream.match('TH ') || stream.match('SH ') || stream.match('SS ') || stream.match('HP ')) {\n stream.skipToEnd();\n return 'quote';\n }\n if ((stream.match(/[A-Z]/) && stream.match(/[A-Z]/)) || (stream.match(/[a-z]/) && stream.match(/[a-z]/))) {\n return 'attribute';\n }\n }\n stream.eatWhile(/[\\w-]/);\n var cur = stream.current();\n return words.hasOwnProperty(cur) ? words[cur] : null;\n}\n\nfunction tokenize(stream, state) {\n return (state.tokens[0] || tokenBase) (stream, state);\n};\n\nexport const troff = {\n name: \"troff\",\n startState: function() {return {tokens:[]};},\n token: function(stream, state) {\n return tokenize(stream, state);\n }\n};\n"],"names":["words","tokenBase","stream","eatSpace","sol","ch","next","match","skipTo","eatWhile","eat","skipToEnd","cur","current","hasOwnProperty","tokenize","state","tokens","troff","name","startState","token"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/1814.index.js b/book/_build/html/_static/1814.index.js new file mode 100644 index 0000000..ae0b933 --- /dev/null +++ b/book/_build/html/_static/1814.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[1814],{81814:(e,t,n)=>{function a(e){for(var t={},n=0;n_});var i=a(["abstract","accept","allocatable","allocate","array","assign","asynchronous","backspace","bind","block","byte","call","case","class","close","common","contains","continue","cycle","data","deallocate","decode","deferred","dimension","do","elemental","else","encode","end","endif","entry","enumerator","equivalence","exit","external","extrinsic","final","forall","format","function","generic","go","goto","if","implicit","import","include","inquire","intent","interface","intrinsic","module","namelist","non_intrinsic","non_overridable","none","nopass","nullify","open","optional","options","parameter","pass","pause","pointer","print","private","program","protected","public","pure","read","recursive","result","return","rewind","save","select","sequence","stop","subroutine","target","then","to","type","use","value","volatile","where","while","write"]),r=a(["abort","abs","access","achar","acos","adjustl","adjustr","aimag","aint","alarm","all","allocated","alog","amax","amin","amod","and","anint","any","asin","associated","atan","besj","besjn","besy","besyn","bit_size","btest","cabs","ccos","ceiling","cexp","char","chdir","chmod","clog","cmplx","command_argument_count","complex","conjg","cos","cosh","count","cpu_time","cshift","csin","csqrt","ctime","c_funloc","c_loc","c_associated","c_null_ptr","c_null_funptr","c_f_pointer","c_null_char","c_alert","c_backspace","c_form_feed","c_new_line","c_carriage_return","c_horizontal_tab","c_vertical_tab","dabs","dacos","dasin","datan","date_and_time","dbesj","dbesj","dbesjn","dbesy","dbesy","dbesyn","dble","dcos","dcosh","ddim","derf","derfc","dexp","digits","dim","dint","dlog","dlog","dmax","dmin","dmod","dnint","dot_product","dprod","dsign","dsinh","dsin","dsqrt","dtanh","dtan","dtime","eoshift","epsilon","erf","erfc","etime","exit","exp","exponent","extends_type_of","fdate","fget","fgetc","float","floor","flush","fnum","fputc","fput","fraction","fseek","fstat","ftell","gerror","getarg","get_command","get_command_argument","get_environment_variable","getcwd","getenv","getgid","getlog","getpid","getuid","gmtime","hostnm","huge","iabs","iachar","iand","iargc","ibclr","ibits","ibset","ichar","idate","idim","idint","idnint","ieor","ierrno","ifix","imag","imagpart","index","int","ior","irand","isatty","ishft","ishftc","isign","iso_c_binding","is_iostat_end","is_iostat_eor","itime","kill","kind","lbound","len","len_trim","lge","lgt","link","lle","llt","lnblnk","loc","log","logical","long","lshift","lstat","ltime","matmul","max","maxexponent","maxloc","maxval","mclock","merge","move_alloc","min","minexponent","minloc","minval","mod","modulo","mvbits","nearest","new_line","nint","not","or","pack","perror","precision","present","product","radix","rand","random_number","random_seed","range","real","realpart","rename","repeat","reshape","rrspacing","rshift","same_type_as","scale","scan","second","selected_int_kind","selected_real_kind","set_exponent","shape","short","sign","signal","sinh","sin","sleep","sngl","spacing","spread","sqrt","srand","stat","sum","symlnk","system","system_clock","tan","tanh","time","tiny","transfer","transpose","trim","ttynam","ubound","umask","unlink","unpack","verify","xor","zabs","zcos","zexp","zlog","zsin","zsqrt"]),c=a(["c_bool","c_char","c_double","c_double_complex","c_float","c_float_complex","c_funptr","c_int","c_int16_t","c_int32_t","c_int64_t","c_int8_t","c_int_fast16_t","c_int_fast32_t","c_int_fast64_t","c_int_fast8_t","c_int_least16_t","c_int_least32_t","c_int_least64_t","c_int_least8_t","c_intmax_t","c_intptr_t","c_long","c_long_double","c_long_double_complex","c_long_long","c_ptr","c_short","c_signed_char","c_size_t","character","complex","double","integer","logical","real"]),o=/[+\-*&=<>\/\:]/,s=/^\.(and|or|eq|lt|le|gt|ge|ne|not|eqv|neqv)\./i;function l(e,t){if(e.match(s))return"operator";var n,a=e.next();if("!"==a)return e.skipToEnd(),"comment";if('"'==a||"'"==a)return t.tokenize=(n=a,function(e,t){for(var a,i=!1,r=!1;null!=(a=e.next());){if(a==n&&!i){r=!0;break}i=!i&&"\\"==a}return!r&&i||(t.tokenize=null),"string"}),t.tokenize(e,t);if(/[\[\]\(\),]/.test(a))return null;if(/\d/.test(a))return e.eatWhile(/[\w\.]/),"number";if(o.test(a))return e.eatWhile(o),"operator";e.eatWhile(/[\w\$_]/);var l=e.current().toLowerCase();return i.hasOwnProperty(l)?"keyword":r.hasOwnProperty(l)||c.hasOwnProperty(l)?"builtin":"variable"}const _={name:"fortran",startState:function(){return{tokenize:null}},token:function(e,t){return e.eatSpace()?null:(t.tokenize||l)(e,t)}}}}]); +//# sourceMappingURL=1814.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/1814.index.js.map b/book/_build/html/_static/1814.index.js.map new file mode 100644 index 0000000..46f64da --- /dev/null +++ b/book/_build/html/_static/1814.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"1814.index.js","mappings":"+FAAA,SAASA,EAAMC,GAEb,IADA,IAAIC,EAAO,CAAC,EACHC,EAAI,EAAGA,EAAIF,EAAMG,SAAUD,EAClCD,EAAKD,EAAME,KAAM,EAEnB,OAAOD,CACT,C,8BAEA,IAAIG,EAAWL,EAAM,CACnB,WAAY,SAAU,cAAe,WACrC,QAAS,SAAU,eAAgB,YACnC,OAAQ,QAAS,OAAQ,OAAQ,OACjC,QAAS,QAAS,SAAU,WAC5B,WAAY,QAAS,OAAQ,aAC7B,SAAU,WAAY,YAAa,KACnC,YAAa,OAAQ,SAAU,MAC/B,QAAS,Q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IAgCmBK,EAhCfC,EAAKJ,EAAOK,OAChB,GAAU,KAAND,EAEF,OADAJ,EAAOM,YACA,UAET,GAAU,KAANF,GAAmB,KAANA,EAEf,OADAH,EAAMM,UA0BWJ,EA1BYC,EA2BxB,SAASJ,EAAQC,GAEtB,IADA,IAAqBI,EAAjBG,GAAU,EAAaC,GAAM,EACA,OAAzBJ,EAAOL,EAAOK,SAAiB,CACrC,GAAIA,GAAQF,IAAUK,EAAS,CAC7BC,GAAM,EACN,KACF,CACAD,GAAWA,GAAmB,MAARH,CACxB,CAEA,OADII,GAAQD,IAASP,EAAMM,SAAW,MAC/B,QACT,GArCSN,EAAMM,SAASP,EAAQC,GAEhC,GAAI,cAAcS,KAAKN,GACrB,OAAO,KAET,GAAI,KAAKM,KAAKN,GAEZ,OADAJ,EAAOW,SAAS,UACT,SAET,GAAId,EAAea,KAAKN,GAEtB,OADAJ,EAAOW,SAASd,GACT,WAETG,EAAOW,SAAS,WAChB,IAAIC,EAAOZ,EAAOa,UAAUC,cAE5B,OAAIpB,EAASqB,eAAeH,GACnB,UAELjB,EAASoB,eAAeH,IAAShB,EAAUmB,eAAeH,GACrD,UAEF,UACT,CAmBO,MAAMI,EAAU,CACrBC,KAAM,UACNC,WAAY,WACV,MAAO,CAACX,SAAU,KACpB,EAEAY,MAAO,SAASnB,EAAQC,GACtB,OAAID,EAAOoB,WAAmB,MACjBnB,EAAMM,UAAYR,GAAWC,EAAQC,EAGpD,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/fortran.js"],"sourcesContent":["function words(array) {\n var keys = {};\n for (var i = 0; i < array.length; ++i) {\n keys[array[i]] = true;\n }\n return keys;\n}\n\nvar keywords = words([\n \"abstract\", \"accept\", \"allocatable\", \"allocate\",\n \"array\", \"assign\", \"asynchronous\", \"backspace\",\n \"bind\", \"block\", \"byte\", \"call\", \"case\",\n \"class\", \"close\", \"common\", \"contains\",\n \"continue\", \"cycle\", \"data\", \"deallocate\",\n \"decode\", \"deferred\", \"dimension\", \"do\",\n \"elemental\", \"else\", \"encode\", \"end\",\n \"endif\", \"entry\", \"enumerator\", \"equivalence\",\n \"exit\", \"external\", \"extrinsic\", \"final\",\n \"forall\", \"format\", \"function\", \"generic\",\n \"go\", \"goto\", \"if\", \"implicit\", \"import\", \"include\",\n \"inquire\", \"intent\", \"interface\", \"intrinsic\",\n \"module\", \"namelist\", \"non_intrinsic\",\n \"non_overridable\", \"none\", \"nopass\",\n \"nullify\", \"open\", \"optional\", \"options\",\n \"parameter\", \"pass\", \"pause\", \"pointer\",\n \"print\", \"private\", \"program\", \"protected\",\n \"public\", \"pure\", \"read\", \"recursive\", \"result\",\n \"return\", \"rewind\", \"save\", \"select\", \"sequence\",\n \"stop\", \"subroutine\", \"target\", \"then\", \"to\", \"type\",\n \"use\", \"value\", \"volatile\", \"where\", \"while\",\n \"write\"]);\nvar builtins = words([\"abort\", \"abs\", \"access\", \"achar\", \"acos\",\n \"adjustl\", \"adjustr\", \"aimag\", \"aint\", \"alarm\",\n \"all\", \"allocated\", \"alog\", \"amax\", \"amin\",\n \"amod\", \"and\", \"anint\", \"any\", \"asin\",\n \"associated\", \"atan\", \"besj\", \"besjn\", \"besy\",\n \"besyn\", \"bit_size\", \"btest\", \"cabs\", \"ccos\",\n \"ceiling\", \"cexp\", \"char\", \"chdir\", \"chmod\",\n \"clog\", \"cmplx\", \"command_argument_count\",\n \"complex\", \"conjg\", \"cos\", \"cosh\", \"count\",\n \"cpu_time\", \"cshift\", \"csin\", \"csqrt\", \"ctime\",\n \"c_funloc\", \"c_loc\", \"c_associated\", \"c_null_ptr\",\n \"c_null_funptr\", \"c_f_pointer\", \"c_null_char\",\n \"c_alert\", \"c_backspace\", \"c_form_feed\",\n \"c_new_line\", \"c_carriage_return\",\n \"c_horizontal_tab\", \"c_vertical_tab\", \"dabs\",\n \"dacos\", \"dasin\", \"datan\", \"date_and_time\",\n \"dbesj\", \"dbesj\", \"dbesjn\", \"dbesy\", \"dbesy\",\n \"dbesyn\", \"dble\", \"dcos\", \"dcosh\", \"ddim\", \"derf\",\n \"derfc\", \"dexp\", \"digits\", \"dim\", \"dint\", \"dlog\",\n \"dlog\", \"dmax\", \"dmin\", \"dmod\", \"dnint\",\n \"dot_product\", \"dprod\", \"dsign\", \"dsinh\",\n \"dsin\", \"dsqrt\", \"dtanh\", \"dtan\", \"dtime\",\n \"eoshift\", \"epsilon\", \"erf\", \"erfc\", \"etime\",\n \"exit\", \"exp\", \"exponent\", \"extends_type_of\",\n \"fdate\", \"fget\", \"fgetc\", \"float\", \"floor\",\n \"flush\", \"fnum\", \"fputc\", \"fput\", \"fraction\",\n \"fseek\", \"fstat\", \"ftell\", \"gerror\", \"getarg\",\n \"get_command\", \"get_command_argument\",\n \"get_environment_variable\", \"getcwd\",\n \"getenv\", \"getgid\", \"getlog\", \"getpid\",\n \"getuid\", \"gmtime\", \"hostnm\", \"huge\", \"iabs\",\n \"iachar\", \"iand\", \"iargc\", \"ibclr\", \"ibits\",\n \"ibset\", \"ichar\", \"idate\", \"idim\", \"idint\",\n \"idnint\", \"ieor\", \"ierrno\", \"ifix\", \"imag\",\n \"imagpart\", \"index\", \"int\", \"ior\", \"irand\",\n \"isatty\", \"ishft\", \"ishftc\", \"isign\",\n \"iso_c_binding\", \"is_iostat_end\", \"is_iostat_eor\",\n \"itime\", \"kill\", \"kind\", \"lbound\", \"len\", \"len_trim\",\n \"lge\", \"lgt\", \"link\", \"lle\", \"llt\", \"lnblnk\", \"loc\",\n \"log\", \"logical\", \"long\", \"lshift\", \"lstat\", \"ltime\",\n \"matmul\", \"max\", \"maxexponent\", \"maxloc\", \"maxval\",\n \"mclock\", \"merge\", \"move_alloc\", \"min\", \"minexponent\",\n \"minloc\", \"minval\", \"mod\", \"modulo\", \"mvbits\",\n \"nearest\", \"new_line\", \"nint\", \"not\", \"or\", \"pack\",\n \"perror\", \"precision\", \"present\", \"product\", \"radix\",\n \"rand\", \"random_number\", \"random_seed\", \"range\",\n \"real\", \"realpart\", \"rename\", \"repeat\", \"reshape\",\n \"rrspacing\", \"rshift\", \"same_type_as\", \"scale\",\n \"scan\", \"second\", \"selected_int_kind\",\n \"selected_real_kind\", \"set_exponent\", \"shape\",\n \"short\", \"sign\", \"signal\", \"sinh\", \"sin\", \"sleep\",\n \"sngl\", \"spacing\", \"spread\", \"sqrt\", \"srand\", \"stat\",\n \"sum\", \"symlnk\", \"system\", \"system_clock\", \"tan\",\n \"tanh\", \"time\", \"tiny\", \"transfer\", \"transpose\",\n \"trim\", \"ttynam\", \"ubound\", \"umask\", \"unlink\",\n \"unpack\", \"verify\", \"xor\", \"zabs\", \"zcos\", \"zexp\",\n \"zlog\", \"zsin\", \"zsqrt\"]);\n\nvar dataTypes = words([\"c_bool\", \"c_char\", \"c_double\", \"c_double_complex\",\n \"c_float\", \"c_float_complex\", \"c_funptr\", \"c_int\",\n \"c_int16_t\", \"c_int32_t\", \"c_int64_t\", \"c_int8_t\",\n \"c_int_fast16_t\", \"c_int_fast32_t\", \"c_int_fast64_t\",\n \"c_int_fast8_t\", \"c_int_least16_t\", \"c_int_least32_t\",\n \"c_int_least64_t\", \"c_int_least8_t\", \"c_intmax_t\",\n \"c_intptr_t\", \"c_long\", \"c_long_double\",\n \"c_long_double_complex\", \"c_long_long\", \"c_ptr\",\n \"c_short\", \"c_signed_char\", \"c_size_t\", \"character\",\n \"complex\", \"double\", \"integer\", \"logical\", \"real\"]);\nvar isOperatorChar = /[+\\-*&=<>\\/\\:]/;\nvar litOperator = /^\\.(and|or|eq|lt|le|gt|ge|ne|not|eqv|neqv)\\./i;\n\nfunction tokenBase(stream, state) {\n\n if (stream.match(litOperator)){\n return 'operator';\n }\n\n var ch = stream.next();\n if (ch == \"!\") {\n stream.skipToEnd();\n return \"comment\";\n }\n if (ch == '\"' || ch == \"'\") {\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n }\n if (/[\\[\\]\\(\\),]/.test(ch)) {\n return null;\n }\n if (/\\d/.test(ch)) {\n stream.eatWhile(/[\\w\\.]/);\n return \"number\";\n }\n if (isOperatorChar.test(ch)) {\n stream.eatWhile(isOperatorChar);\n return \"operator\";\n }\n stream.eatWhile(/[\\w\\$_]/);\n var word = stream.current().toLowerCase();\n\n if (keywords.hasOwnProperty(word)){\n return 'keyword';\n }\n if (builtins.hasOwnProperty(word) || dataTypes.hasOwnProperty(word)) {\n return 'builtin';\n }\n return \"variable\";\n}\n\nfunction tokenString(quote) {\n return function(stream, state) {\n var escaped = false, next, end = false;\n while ((next = stream.next()) != null) {\n if (next == quote && !escaped) {\n end = true;\n break;\n }\n escaped = !escaped && next == \"\\\\\";\n }\n if (end || !escaped) state.tokenize = null;\n return \"string\";\n };\n}\n\n// Interface\n\nexport const fortran = {\n name: \"fortran\",\n startState: function() {\n return {tokenize: null};\n },\n\n token: function(stream, state) {\n if (stream.eatSpace()) return null;\n var style = (state.tokenize || tokenBase)(stream, state);\n if (style == \"comment\" || style == \"meta\") return style;\n return style;\n }\n};\n\n"],"names":["words","array","keys","i","length","keywords","builtins","dataTypes","isOperatorChar","litOperator","tokenBase","stream","state","match","quote","ch","next","skipToEnd","tokenize","escaped","end","test","eatWhile","word","current","toLowerCase","hasOwnProperty","fortran","name","startState","token","eatSpace"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/192.index.js b/book/_build/html/_static/192.index.js new file mode 100644 index 0000000..798af6f --- /dev/null +++ b/book/_build/html/_static/192.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[192],{40192:(e,n,t)=>{t.r(n),t.d(n,{fcl:()=>s});var r={term:!0,method:!0,accu:!0,rule:!0,then:!0,is:!0,and:!0,or:!0,if:!0,default:!0},o={var_input:!0,var_output:!0,fuzzify:!0,defuzzify:!0,function_block:!0,ruleblock:!0},i={end_ruleblock:!0,end_defuzzify:!0,end_function_block:!0,end_fuzzify:!0,end_var:!0},a={true:!0,false:!0,nan:!0,real:!0,min:!0,max:!0,cog:!0,cogs:!0},u=/[+\-*&^%:=<>!|\/]/;function c(e,n){var t=e.next();if(/[\d\.]/.test(t))return"."==t?e.match(/^[0-9]+([eE][\-+]?[0-9]+)?/):"0"==t?e.match(/^[xX][0-9a-fA-F]+/)||e.match(/^0[0-7]+/):e.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/),"number";if("/"==t||"("==t){if(e.eat("*"))return n.tokenize=l,l(e,n);if(e.eat("/"))return e.skipToEnd(),"comment"}if(u.test(t))return e.eatWhile(u),"operator";e.eatWhile(/[\w\$_\xa1-\uffff]/);var c=e.current().toLowerCase();return r.propertyIsEnumerable(c)||o.propertyIsEnumerable(c)||i.propertyIsEnumerable(c)?"keyword":a.propertyIsEnumerable(c)?"atom":"variable"}function l(e,n){for(var t,r=!1;t=e.next();){if(("/"==t||")"==t)&&r){n.tokenize=c;break}r="*"==t}return"comment"}function f(e,n,t,r,o){this.indented=e,this.column=n,this.type=t,this.align=r,this.prev=o}const s={name:"fcl",startState:function(e){return{tokenize:null,context:new f(-e,0,"top",!1),indented:0,startOfLine:!0}},token:function(e,n){var t=n.context;if(e.sol()&&(null==t.align&&(t.align=!1),n.indented=e.indentation(),n.startOfLine=!0),e.eatSpace())return null;var r=(n.tokenize||c)(e,n);if("comment"==r)return r;null==t.align&&(t.align=!0);var a=e.current().toLowerCase();return o.propertyIsEnumerable(a)?function(e,n,t){e.context=new f(e.indented,n,"end_block",null,e.context)}(n,e.column()):i.propertyIsEnumerable(a)&&function(e){e.context.prev&&("end_block"==e.context.type&&(e.indented=e.context.indented),e.context=e.context.prev)}(n),n.startOfLine=!1,r},indent:function(e,n,t){if(e.tokenize!=c&&null!=e.tokenize)return 0;var r=e.context,o=i.propertyIsEnumerable(n);return r.align?r.column+(o?0:1):r.indented+(o?0:t.unit)},languageData:{commentTokens:{line:"//",block:{open:"(*",close:"*)"}}}}}}]); +//# sourceMappingURL=192.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/192.index.js.map b/book/_build/html/_static/192.index.js.map new file mode 100644 index 0000000..0ca3fc6 --- /dev/null +++ b/book/_build/html/_static/192.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"192.index.js","mappings":"wHAAA,IAAIA,EAAW,CACb,MAAQ,EACR,QAAU,EAAM,MAAQ,EACxB,MAAQ,EAAM,MAAQ,EAAM,IAAM,EAAM,KAAO,EAAM,IAAM,EAC3D,IAAM,EAAM,SAAW,GAGrBC,EAAe,CACjB,WAAa,EACb,YAAc,EACd,SAAW,EACX,WAAa,EACb,gBAAkB,EAClB,WAAa,GAGXC,EAAa,CACf,eAAiB,EACjB,eAAiB,EACjB,oBAAsB,EACtB,aAAe,EACf,SAAW,GAGTC,EAAQ,CACV,MAAQ,EAAM,OAAS,EAAM,KAAO,EACpC,MAAQ,EAAM,KAAO,EAAM,KAAO,EAAM,KAAO,EAAM,MAAQ,GAG3DC,EAAiB,oBAErB,SAASC,EAAUC,EAAQC,GACzB,IAAIC,EAAKF,EAAOG,OAEhB,GAAI,SAASC,KAAKF,GAQhB,MAPU,KAANA,EACFF,EAAOK,MAAM,8BACE,KAANH,EACTF,EAAOK,MAAM,sBAAwBL,EAAOK,MAAM,YAElDL,EAAOK,MAAM,uCAER,SAGT,GAAU,KAANH,GAAmB,KAANA,EAAW,CAC1B,GAAIF,EAAOM,IAAI,KAEb,OADAL,EAAMM,SAAWC,EACVA,EAAaR,EAAQC,GAE9B,GAAID,EAAOM,IAAI,KAEb,OADAN,EAAOS,YACA,SAEX,CACA,GAAIX,EAAeM,KAAKF,GAEtB,OADAF,EAAOU,SAASZ,GACT,WAETE,EAAOU,SAAS,sBAEhB,IAAIC,EAAMX,EAAOY,UAAUC,cAC3B,OAAInB,EAASoB,qBAAqBH,IAC9BhB,EAAamB,qBAAqBH,IAClCf,EAAWkB,qBAAqBH,GAC3B,UAELd,EAAMiB,qBAAqBH,GAAa,OACrC,UACT,CAGA,SAASH,EAAaR,EAAQC,GAE5B,IADA,IAAsBC,EAAlBa,GAAW,EACRb,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AAM2B,aAAc,EACbM,CACT,EAEAI,OAAQ,SAASrC,EAAOsC,EAAWC,GACjC,GAAIvC,EAAMM,UAAYR,GAA+B,MAAlBE,EAAMM,SAAkB,OAAO,EAClE,IAAIuB,EAAM7B,EAAM0B,QAEZc,EAAU7C,EAAWkB,qBAAqByB,GAC9C,OAAIT,EAAIV,MAAcU,EAAIZ,QAAUuB,EAAU,EAAI,GACtCX,EAAIb,UAAYwB,EAAU,EAAID,EAAGE,KAC/C,EAEAC,aAAc,CACZC,cAAe,CAACC,KAAM,KAAMC,MAAO,CAACC,KAAM,KAAMC,MAAO,Q","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/fcl.js"],"sourcesContent":["var keywords = {\n \"term\": true,\n \"method\": true, \"accu\": true,\n \"rule\": true, \"then\": true, \"is\": true, \"and\": true, \"or\": true,\n \"if\": true, \"default\": true\n};\n\nvar start_blocks = {\n \"var_input\": true,\n \"var_output\": true,\n \"fuzzify\": true,\n \"defuzzify\": true,\n \"function_block\": true,\n \"ruleblock\": true\n};\n\nvar end_blocks = {\n \"end_ruleblock\": true,\n \"end_defuzzify\": true,\n \"end_function_block\": true,\n \"end_fuzzify\": true,\n \"end_var\": true\n};\n\nvar atoms = {\n \"true\": true, \"false\": true, \"nan\": true,\n \"real\": true, \"min\": true, \"max\": true, \"cog\": true, \"cogs\": true\n};\n\nvar isOperatorChar = /[+\\-*&^%:=<>!|\\/]/;\n\nfunction tokenBase(stream, state) {\n var ch = stream.next();\n\n if (/[\\d\\.]/.test(ch)) {\n if (ch == \".\") {\n stream.match(/^[0-9]+([eE][\\-+]?[0-9]+)?/);\n } else if (ch == \"0\") {\n stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/);\n } else {\n stream.match(/^[0-9]*\\.?[0-9]*([eE][\\-+]?[0-9]+)?/);\n }\n return \"number\";\n }\n\n if (ch == \"/\" || ch == \"(\") {\n if (stream.eat(\"*\")) {\n state.tokenize = tokenComment;\n return tokenComment(stream, state);\n }\n if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return \"comment\";\n }\n }\n if (isOperatorChar.test(ch)) {\n stream.eatWhile(isOperatorChar);\n return \"operator\";\n }\n stream.eatWhile(/[\\w\\$_\\xa1-\\uffff]/);\n\n var cur = stream.current().toLowerCase();\n if (keywords.propertyIsEnumerable(cur) ||\n start_blocks.propertyIsEnumerable(cur) ||\n end_blocks.propertyIsEnumerable(cur)) {\n return \"keyword\";\n }\n if (atoms.propertyIsEnumerable(cur)) return \"atom\";\n return \"variable\";\n}\n\n\nfunction tokenComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if ((ch == \"/\" || ch == \")\") && maybeEnd) {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return \"comment\";\n}\n\nfunction Context(indented, column, type, align, prev) {\n this.indented = indented;\n this.column = column;\n this.type = type;\n this.align = align;\n this.prev = prev;\n}\n\nfunction pushContext(state, col, type) {\n return state.context = new Context(state.indented, col, type, null, state.context);\n}\n\nfunction popContext(state) {\n if (!state.context.prev) return;\n var t = state.context.type;\n if (t == \"end_block\")\n state.indented = state.context.indented;\n return state.context = state.context.prev;\n}\n\n// Interface\n\nexport const fcl = {\n name: \"fcl\",\n startState: function(indentUnit) {\n return {\n tokenize: null,\n context: new Context(-indentUnit, 0, \"top\", false),\n indented: 0,\n startOfLine: true\n };\n },\n\n token: function(stream, state) {\n var ctx = state.context;\n if (stream.sol()) {\n if (ctx.align == null) ctx.align = false;\n state.indented = stream.indentation();\n state.startOfLine = true;\n }\n if (stream.eatSpace()) return null;\n\n var style = (state.tokenize || tokenBase)(stream, state);\n if (style == \"comment\") return style;\n if (ctx.align == null) ctx.align = true;\n\n var cur = stream.current().toLowerCase();\n\n if (start_blocks.propertyIsEnumerable(cur)) pushContext(state, stream.column(), \"end_block\");\n else if (end_blocks.propertyIsEnumerable(cur)) popContext(state);\n\n state.startOfLine = false;\n return style;\n },\n\n indent: function(state, textAfter, cx) {\n if (state.tokenize != tokenBase && state.tokenize != null) return 0;\n var ctx = state.context;\n\n var closing = end_blocks.propertyIsEnumerable(textAfter);\n if (ctx.align) return ctx.column + (closing ? 0 : 1);\n else return ctx.indented + (closing ? 0 : cx.unit);\n },\n\n languageData: {\n commentTokens: {line: \"//\", block: {open: \"(*\", close: \"*)\"}}\n }\n};\n\n"],"names":["keywords","start_blocks","end_blocks","atoms","isOperatorChar","tokenBase","stream","state","ch","next","test","match","eat","tokenize","tokenComment","skipToEnd","eatWhile","cur","current","toLowerCase","propertyIsEnumerable","maybeEnd","Context","indented","column","type","align","prev","this","fcl","name","startState","indentUnit","context","startOfLine","token","ctx","sol","indentation","eatSpace","style","col","pushContext","popContext","indent","textAfter","cx","closing","unit","languageData","commentTokens","line","block","open","close"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/2123.index.js b/book/_build/html/_static/2123.index.js new file mode 100644 index 0000000..8763a24 --- /dev/null +++ b/book/_build/html/_static/2123.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[2123],{42123:(e,t,i)=>{i.r(t),i.d(t,{yaml:()=>a});var r=new RegExp("\\b(("+["true","false","on","off","yes","no"].join(")|(")+"))$","i");const a={name:"yaml",token:function(e,t){var i=e.peek(),a=t.escaped;if(t.escaped=!1,"#"==i&&(0==e.pos||/\s/.test(e.string.charAt(e.pos-1))))return e.skipToEnd(),"comment";if(e.match(/^('([^']|\\.)*'?|"([^"]|\\.)*"?)/))return"string";if(t.literal&&e.indentation()>t.keyCol)return e.skipToEnd(),"string";if(t.literal&&(t.literal=!1),e.sol()){if(t.keyCol=0,t.pair=!1,t.pairStart=!1,e.match("---"))return"def";if(e.match("..."))return"def";if(e.match(/^\s*-\s+/))return"meta"}if(e.match(/^(\{|\}|\[|\])/))return"{"==i?t.inlinePairs++:"}"==i?t.inlinePairs--:"["==i?t.inlineList++:t.inlineList--,"meta";if(t.inlineList>0&&!a&&","==i)return e.next(),"meta";if(t.inlinePairs>0&&!a&&","==i)return t.keyCol=0,t.pair=!1,t.pairStart=!1,e.next(),"meta";if(t.pairStart){if(e.match(/^\s*(\||\>)\s*/))return t.literal=!0,"meta";if(e.match(/^\s*(\&|\*)[a-z0-9\._-]+\b/i))return"variable";if(0==t.inlinePairs&&e.match(/^\s*-?[0-9\.\,]+\s?$/))return"number";if(t.inlinePairs>0&&e.match(/^\s*-?[0-9\.\,]+\s?(?=(,|}))/))return"number";if(e.match(r))return"keyword"}return!t.pair&&e.match(/^\s*(?:[,\[\]{}&*!|>'"%@`][^\s'":]|[^,\[\]{}#&*!|>'"%@`])[^#]*?(?=\s*:($|\s))/)?(t.pair=!0,t.keyCol=e.indentation(),"atom"):t.pair&&e.match(/^:\s*/)?(t.pairStart=!0,"meta"):(t.pairStart=!1,t.escaped="\\"==i,e.next(),null)},startState:function(){return{pair:!1,pairStart:!1,keyCol:0,inlinePairs:0,inlineList:0,literal:!1,escaped:!1}},languageData:{commentTokens:{line:"#"}}}}}]); +//# sourceMappingURL=2123.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/2123.index.js.map b/book/_build/html/_static/2123.index.js.map new file mode 100644 index 0000000..223a880 --- /dev/null +++ b/book/_build/html/_static/2123.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2123.index.js","mappings":"0HAAA,IACIA,EAAe,IAAIC,OAAO,QADnB,CAAC,OAAQ,QAAS,KAAM,MAAO,MAAO,MACNC,KAAK,OAAO,MAAO,KAEvD,MAAMC,EAAO,CAClBC,KAAM,OACNC,MAAO,SAASC,EAAQC,GACtB,IAAIC,EAAKF,EAAOG,OACZC,EAAMH,EAAMI,QAGhB,GAFAJ,EAAMI,SAAU,EAEN,KAANH,IAA4B,GAAdF,EAAOM,KAAY,KAAKC,KAAKP,EAAOQ,OAAOC,OAAOT,EAAOM,IAAM,KAE/E,OADAN,EAAOU,YACA,UAGT,GAAIV,EAAOW,MAAM,oCACf,MAAO,SAET,GAAI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,MAAO,CACLL,MAAM,EACNC,WAAW,EACXH,OAAQ,EACRI,YAAa,EACbC,WAAY,EACZP,SAAS,EACTP,SAAS,EAEb,EACAiB,aAAc,CACZC,cAAe,CAACC,KAAM,M","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/yaml.js"],"sourcesContent":["var cons = ['true', 'false', 'on', 'off', 'yes', 'no'];\nvar keywordRegex = new RegExp(\"\\\\b((\"+cons.join(\")|(\")+\"))$\", 'i');\n\nexport const yaml = {\n name: \"yaml\",\n token: function(stream, state) {\n var ch = stream.peek();\n var esc = state.escaped;\n state.escaped = false;\n /* comments */\n if (ch == \"#\" && (stream.pos == 0 || /\\s/.test(stream.string.charAt(stream.pos - 1)))) {\n stream.skipToEnd();\n return \"comment\";\n }\n\n if (stream.match(/^('([^']|\\\\.)*'?|\"([^\"]|\\\\.)*\"?)/))\n return \"string\";\n\n if (state.literal && stream.indentation() > state.keyCol) {\n stream.skipToEnd(); return \"string\";\n } else if (state.literal) { state.literal = false; }\n if (stream.sol()) {\n state.keyCol = 0;\n state.pair = false;\n state.pairStart = false;\n /* document start */\n if(stream.match('---')) { return \"def\"; }\n /* document end */\n if (stream.match('...')) { return \"def\"; }\n /* array list item */\n if (stream.match(/^\\s*-\\s+/)) { return 'meta'; }\n }\n /* inline pairs/lists */\n if (stream.match(/^(\\{|\\}|\\[|\\])/)) {\n if (ch == '{')\n state.inlinePairs++;\n else if (ch == '}')\n state.inlinePairs--;\n else if (ch == '[')\n state.inlineList++;\n else\n state.inlineList--;\n return 'meta';\n }\n\n /* list separator */\n if (state.inlineList > 0 && !esc && ch == ',') {\n stream.next();\n return 'meta';\n }\n /* pairs separator */\n if (state.inlinePairs > 0 && !esc && ch == ',') {\n state.keyCol = 0;\n state.pair = false;\n state.pairStart = false;\n stream.next();\n return 'meta';\n }\n\n /* start of value of a pair */\n if (state.pairStart) {\n /* block literals */\n if (stream.match(/^\\s*(\\||\\>)\\s*/)) { state.literal = true; return 'meta'; };\n /* references */\n if (stream.match(/^\\s*(\\&|\\*)[a-z0-9\\._-]+\\b/i)) { return 'variable'; }\n /* numbers */\n if (state.inlinePairs == 0 && stream.match(/^\\s*-?[0-9\\.\\,]+\\s?$/)) { return 'number'; }\n if (state.inlinePairs > 0 && stream.match(/^\\s*-?[0-9\\.\\,]+\\s?(?=(,|}))/)) { return 'number'; }\n /* keywords */\n if (stream.match(keywordRegex)) { return 'keyword'; }\n }\n\n /* pairs (associative arrays) -> key */\n if (!state.pair && stream.match(/^\\s*(?:[,\\[\\]{}&*!|>'\"%@`][^\\s'\":]|[^,\\[\\]{}#&*!|>'\"%@`])[^#]*?(?=\\s*:($|\\s))/)) {\n state.pair = true;\n state.keyCol = stream.indentation();\n return \"atom\";\n }\n if (state.pair && stream.match(/^:\\s*/)) { state.pairStart = true; return 'meta'; }\n\n /* nothing found, continue */\n state.pairStart = false;\n state.escaped = (ch == '\\\\');\n stream.next();\n return null;\n },\n startState: function() {\n return {\n pair: false,\n pairStart: false,\n keyCol: 0,\n inlinePairs: 0,\n inlineList: 0,\n literal: false,\n escaped: false\n };\n },\n languageData: {\n commentTokens: {line: \"#\"}\n }\n};\n"],"names":["keywordRegex","RegExp","join","yaml","name","token","stream","state","ch","peek","esc","escaped","pos","test","string","charAt","skipToEnd","match","literal","indentation","keyCol","sol","pair","pairStart","inlinePairs","inlineList","next","startState","languageData","commentTokens","line"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/2155.index.js b/book/_build/html/_static/2155.index.js new file mode 100644 index 0000000..a690748 --- /dev/null +++ b/book/_build/html/_static/2155.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[2155],{2155:(e,n,t)=>{t.r(n),t.d(n,{dockerFile:()=>k});var r=t(74391),a="from",o=new RegExp("^(\\s*)\\b("+a+")\\b","i"),s=["run","cmd","entrypoint","shell"],l=new RegExp("^(\\s*)("+s.join("|")+")(\\s+\\[)","i"),i="expose",u=new RegExp("^(\\s*)("+i+")(\\s+)","i"),g="("+[a,i].concat(s).concat(["arg","from","maintainer","label","env","add","copy","volume","user","workdir","onbuild","stopsignal","healthcheck","shell"]).join("|")+")",d=new RegExp("^(\\s*)"+g+"(\\s*)(#.*)?$","i"),x=new RegExp("^(\\s*)"+g+"(\\s+)","i");const k=(0,r.Q)({start:[{regex:/^\s*#.*$/,sol:!0,token:"comment"},{regex:o,token:[null,"keyword"],sol:!0,next:"from"},{regex:d,token:[null,"keyword",null,"error"],sol:!0},{regex:l,token:[null,"keyword",null],sol:!0,next:"array"},{regex:u,token:[null,"keyword",null],sol:!0,next:"expose"},{regex:x,token:[null,"keyword",null],sol:!0,next:"arguments"},{regex:/./,token:null}],from:[{regex:/\s*$/,token:null,next:"start"},{regex:/(\s*)(#.*)$/,token:[null,"error"],next:"start"},{regex:/(\s*\S+\s+)(as)/i,token:[null,"keyword"],next:"start"},{token:null,next:"start"}],single:[{regex:/(?:[^\\']|\\.)/,token:"string"},{regex:/'/,token:"string",pop:!0}],double:[{regex:/(?:[^\\"]|\\.)/,token:"string"},{regex:/"/,token:"string",pop:!0}],array:[{regex:/\]/,token:null,next:"start"},{regex:/"(?:[^\\"]|\\.)*"?/,token:"string"}],expose:[{regex:/\d+$/,token:"number",next:"start"},{regex:/[^\d]+$/,token:null,next:"start"},{regex:/\d+/,token:"number"},{regex:/[^\d]+/,token:null},{token:null,next:"start"}],arguments:[{regex:/^\s*#.*$/,sol:!0,token:"comment"},{regex:/"(?:[^\\"]|\\.)*"?$/,token:"string",next:"start"},{regex:/"/,token:"string",push:"double"},{regex:/'(?:[^\\']|\\.)*'?$/,token:"string",next:"start"},{regex:/'/,token:"string",push:"single"},{regex:/[^#"']+[\\`]$/,token:null},{regex:/[^#"']+$/,token:null,next:"start"},{regex:/[^#"']+/,token:null},{token:null,next:"start"}],languageData:{commentTokens:{line:"#"}}})},74391:(e,n,t)=>{function r(e){a(e,"start");var n={},t=e.languageData||{},r=!1;for(var i in e)if(i!=t&&e.hasOwnProperty(i))for(var u=n[i]=[],g=e[i],d=0;d2&&s.token&&"string"!=typeof s.token){t.pending=[];for(var u=2;u-1)return null;var a=t.indent.length-1,o=e[t.state];e:for(;;){for(var s=0;sr})}}]); +//# sourceMappingURL=2155.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/2155.index.js.map b/book/_build/html/_static/2155.index.js.map new file mode 100644 index 0000000..fca09fd --- /dev/null +++ b/book/_build/html/_static/2155.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2155.index.js","mappings":"8IAEIA,EAAO,OACPC,EAAY,IAAIC,OAAO,cAAgBF,EAAO,OAAQ,KAEtDG,EAAS,CAAC,MAAO,MAAO,aAAc,SACtCC,EAAqB,IAAIF,OAAO,WAAaC,EAAOE,KAAK,KAAO,aAAc,KAE9EC,EAAS,SACTC,EAAc,IAAIL,OAAO,WAAaI,EAAS,UAAW,KAU1DE,EAAmB,IADJ,CAACR,EAAMM,GAAQG,OAAON,GAAQM,OAPpC,CACX,MAAO,OAAQ,aAAc,QAAS,MACtC,MAAO,OAAQ,SAAU,OACzB,UAAW,UAAW,aAAc,cAAe,UAKXJ,KAAK,KAAO,IAClDK,EAAsB,IAAIR,OAAO,UAAYM,EAAmB,gBAAiB,KACjFG,EAA2B,IAAIT,OAAO,UAAYM,EAAmB,SAAU,KAE5E,MAAMI,GAAa,OAAW,CACnCC,MAAO,CAEL,CACEC,MAAO,WACPC,KAAK,EACLC,MAAO,WAET,CACEF,MAAOb,EACPe,MAAO,CAAC,KAAM,WACdD,KAAK,EACLE,KAAM,QAGR,CACEH,MAAOJ,EACPM,MAAO,CAAC,KAAM,UAAW,KAAM,SAC/BD,KAAK,GAEP,CACED,MAAOV,EACPY,MAAO,CAAC,KAAM,UAAW,MACzBD,KAAK,EACLE,KAAM,SAER,CACEH,MAAOP,EACPS,MAAO,CAAC,KAAM,UAAW,MACzBD,KAAK,EACLE,KAAM,UAGR,CACEH,MAAOH,EACPK,MAAO,CAAC,KAAM,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://thebe/../../node_modules/@codemirror/legacy-modes/mode/simple-mode.js"],"sourcesContent":["import {simpleMode} from \"./simple-mode.js\"\n\nvar from = \"from\";\nvar fromRegex = new RegExp(\"^(\\\\s*)\\\\b(\" + from + \")\\\\b\", \"i\");\n\nvar shells = [\"run\", \"cmd\", \"entrypoint\", \"shell\"];\nvar shellsAsArrayRegex = new RegExp(\"^(\\\\s*)(\" + shells.join('|') + \")(\\\\s+\\\\[)\", \"i\");\n\nvar expose = \"expose\";\nvar exposeRegex = new RegExp(\"^(\\\\s*)(\" + expose + \")(\\\\s+)\", \"i\");\n\nvar others = [\n \"arg\", \"from\", \"maintainer\", \"label\", \"env\",\n \"add\", \"copy\", \"volume\", \"user\",\n \"workdir\", \"onbuild\", \"stopsignal\", \"healthcheck\", \"shell\"\n];\n\n// Collect all Dockerfile directives\nvar instructions = [from, expose].concat(shells).concat(others),\n instructionRegex = \"(\" + instructions.join('|') + \")\",\n instructionOnlyLine = new RegExp(\"^(\\\\s*)\" + instructionRegex + \"(\\\\s*)(#.*)?$\", \"i\"),\n instructionWithArguments = new RegExp(\"^(\\\\s*)\" + instructionRegex + \"(\\\\s+)\", \"i\");\n\nexport const dockerFile = simpleMode({\n start: [\n // Block comment: This is a line starting with a comment\n {\n regex: /^\\s*#.*$/,\n sol: true,\n token: \"comment\"\n },\n {\n regex: fromRegex,\n token: [null, \"keyword\"],\n sol: true,\n next: \"from\"\n },\n // Highlight an instruction without any arguments (for convenience)\n {\n regex: instructionOnlyLine,\n token: [null, \"keyword\", null, \"error\"],\n sol: true\n },\n {\n regex: shellsAsArrayRegex,\n token: [null, \"keyword\", null],\n sol: true,\n next: \"array\"\n },\n {\n regex: exposeRegex,\n token: [null, \"keyword\", null],\n sol: true,\n next: \"expose\"\n },\n // Highlight an instruction followed by arguments\n {\n regex: instructionWithArguments,\n token: [null, \"keyword\", null],\n sol: true,\n next: \"arguments\"\n },\n {\n regex: /./,\n token: null\n }\n ],\n from: [\n {\n regex: /\\s*$/,\n token: null,\n next: \"start\"\n },\n {\n // Line comment without instruction arguments is an error\n regex: /(\\s*)(#.*)$/,\n token: [null, \"error\"],\n next: \"start\"\n },\n {\n regex: /(\\s*\\S+\\s+)(as)/i,\n token: [null, \"keyword\"],\n next: \"start\"\n },\n // Fail safe return to start\n {\n token: null,\n next: \"start\"\n }\n ],\n single: [\n {\n regex: /(?:[^\\\\']|\\\\.)/,\n token: \"string\"\n },\n {\n regex: /'/,\n token: \"string\",\n pop: true\n }\n ],\n double: [\n {\n regex: /(?:[^\\\\\"]|\\\\.)/,\n token: \"string\"\n },\n {\n regex: /\"/,\n token: \"string\",\n pop: true\n }\n ],\n array: [\n {\n regex: /\\]/,\n token: null,\n next: \"start\"\n },\n {\n regex: /\"(?:[^\\\\\"]|\\\\.)*\"?/,\n token: \"string\"\n }\n ],\n expose: [\n {\n regex: /\\d+$/,\n token: \"number\",\n next: \"start\"\n },\n {\n regex: /[^\\d]+$/,\n token: null,\n next: \"start\"\n },\n {\n regex: /\\d+/,\n token: \"number\"\n },\n {\n regex: /[^\\d]+/,\n token: null\n },\n // Fail safe return to start\n {\n token: null,\n next: \"start\"\n }\n ],\n arguments: [\n {\n regex: /^\\s*#.*$/,\n sol: true,\n token: \"comment\"\n },\n {\n regex: /\"(?:[^\\\\\"]|\\\\.)*\"?$/,\n token: \"string\",\n next: \"start\"\n },\n {\n regex: /\"/,\n token: \"string\",\n push: \"double\"\n },\n {\n regex: /'(?:[^\\\\']|\\\\.)*'?$/,\n token: \"string\",\n next: \"start\"\n },\n {\n regex: /'/,\n token: \"string\",\n push: \"single\"\n },\n {\n regex: /[^#\"']+[\\\\`]$/,\n token: null\n },\n {\n regex: /[^#\"']+$/,\n token: null,\n next: \"start\"\n },\n {\n regex: /[^#\"']+/,\n token: null\n },\n // Fail safe return to start\n {\n token: null,\n next: \"start\"\n }\n ],\n languageData: {\n commentTokens: {line: \"#\"}\n }\n});\n\n","export function simpleMode(states) {\n ensureState(states, \"start\");\n var states_ = {}, meta = states.languageData || {}, hasIndentation = false;\n for (var state in states) if (state != meta && states.hasOwnProperty(state)) {\n var list = states_[state] = [], orig = states[state];\n for (var i = 0; i < orig.length; i++) {\n var data = orig[i];\n list.push(new Rule(data, states));\n if (data.indent || data.dedent) hasIndentation = true;\n }\n }\n return {\n name: meta.name,\n startState: function() {\n return {state: \"start\", pending: null, indent: hasIndentation ? [] : null};\n },\n copyState: function(state) {\n var s = {state: state.state, pending: state.pending, indent: state.indent && state.indent.slice(0)};\n if (state.stack)\n s.stack = state.stack.slice(0);\n return s;\n },\n token: tokenFunction(states_),\n indent: indentFunction(states_, meta),\n languageData: meta\n }\n};\n\nfunction ensureState(states, name) {\n if (!states.hasOwnProperty(name))\n throw new Error(\"Undefined state \" + name + \" in simple mode\");\n}\n\nfunction toRegex(val, caret) {\n if (!val) return /(?:)/;\n var flags = \"\";\n if (val instanceof RegExp) {\n if (val.ignoreCase) flags = \"i\";\n val = val.source;\n } else {\n val = String(val);\n }\n return new RegExp((caret === false ? \"\" : \"^\") + \"(?:\" + val + \")\", flags);\n}\n\nfunction asToken(val) {\n if (!val) return null;\n if (val.apply) return val\n if (typeof val == \"string\") return val.replace(/\\./g, \" \");\n var result = [];\n for (var i = 0; i < val.length; i++)\n result.push(val[i] && val[i].replace(/\\./g, \" \"));\n return result;\n}\n\nfunction Rule(data, states) {\n if (data.next || data.push) ensureState(states, data.next || data.push);\n this.regex = toRegex(data.regex);\n this.token = asToken(data.token);\n this.data = data;\n}\n\nfunction tokenFunction(states) {\n return function(stream, state) {\n if (state.pending) {\n var pend = state.pending.shift();\n if (state.pending.length == 0) state.pending = null;\n stream.pos += pend.text.length;\n return pend.token;\n }\n\n var curState = states[state.state];\n for (var i = 0; i < curState.length; i++) {\n var rule = curState[i];\n var matches = (!rule.data.sol || stream.sol()) && stream.match(rule.regex);\n if (matches) {\n if (rule.data.next) {\n state.state = rule.data.next;\n } else if (rule.data.push) {\n (state.stack || (state.stack = [])).push(state.state);\n state.state = rule.data.push;\n } else if (rule.data.pop && state.stack && state.stack.length) {\n state.state = state.stack.pop();\n }\n\n if (rule.data.indent)\n state.indent.push(stream.indentation() + stream.indentUnit);\n if (rule.data.dedent)\n state.indent.pop();\n var token = rule.token\n if (token && token.apply) token = token(matches)\n if (matches.length > 2 && rule.token && typeof rule.token != \"string\") {\n state.pending = [];\n for (var j = 2; j < matches.length; j++)\n if (matches[j])\n state.pending.push({text: matches[j], token: rule.token[j - 1]});\n stream.backUp(matches[0].length - (matches[1] ? matches[1].length : 0));\n return token[0];\n } else if (token && token.join) {\n return token[0];\n } else {\n return token;\n }\n }\n }\n stream.next();\n return null;\n };\n}\n\nfunction indentFunction(states, meta) {\n return function(state, textAfter) {\n if (state.indent == null || meta.dontIndentStates && meta.doneIndentState.indexOf(state.state) > -1)\n return null\n\n var pos = state.indent.length - 1, rules = states[state.state];\n scan: for (;;) {\n for (var i = 0; i < rules.length; i++) {\n var rule = rules[i];\n if (rule.data.dedent && rule.data.dedentIfLineStart !== false) {\n var m = rule.regex.exec(textAfter);\n if (m && m[0]) {\n pos--;\n if (rule.next || rule.push) rules = states[rule.next || rule.push];\n textAfter = textAfter.slice(m[0].length);\n continue scan;\n }\n }\n }\n break;\n }\n return pos < 0 ? 0 : state.indent[pos];\n };\n}\n"],"names":["from","fromRegex","RegExp","shells","shellsAsArrayRegex","join","expose","exposeRegex","instructionRegex","concat","instructionOnlyLine","instructionWithArguments","dockerFile","start","regex","sol","token","next","single","pop","double","array","arguments","push","languageData","commentTokens","line","simpleMode","states","ensureState","states_","meta","hasIndentation","state","hasOwnProperty","list","orig","i","length","data","Rule","indent","dedent","name","startState","pending","copyState","s","slice","stack","tokenFunction","indentFunction","Error","this","val","caret","flags","ignoreCase","source","String","toRegex","apply","replace","result","asToken","stream","pend","shift","pos","text","curState","rule","matches","match","indentation","indentUnit","j","backUp","textAfter","dontIndentStates","doneIndentState","indexOf","rules","scan","dedentIfLineStart","m","exec"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/2187.index.js b/book/_build/html/_static/2187.index.js new file mode 100644 index 0000000..3e1b99a --- /dev/null +++ b/book/_build/html/_static/2187.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[2187],{32187:(e,t,n)=>{n.r(t),n.d(t,{brainfuck:()=>m});var o="><+-.,[]".split("");const m={name:"brainfuck",startState:function(){return{commentLine:!1,left:0,right:0,commentLoop:!1}},token:function(e,t){if(e.eatSpace())return null;e.sol()&&(t.commentLine=!1);var n=e.next().toString();return-1===o.indexOf(n)?(t.commentLine=!0,e.eol()&&(t.commentLine=!1),"comment"):!0===t.commentLine?(e.eol()&&(t.commentLine=!1),"comment"):"]"===n||"["===n?("["===n?t.left++:t.right++,"bracket"):"+"===n||"-"===n?"keyword":"<"===n||">"===n?"atom":"."===n||","===n?"def":void(e.eol()&&(t.commentLine=!1))}}}}]); +//# sourceMappingURL=2187.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/2187.index.js.map b/book/_build/html/_static/2187.index.js.map new file mode 100644 index 0000000..3135195 --- /dev/null +++ b/book/_build/html/_static/2187.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2187.index.js","mappings":"+HAAA,IAAIA,EAAU,WAAWC,MAAM,IAcxB,MAAMC,EAAY,CACvBC,KAAM,YACNC,WAAY,WACV,MAAO,CACLC,aAAa,EACbC,KAAM,EACNC,MAAO,EACPC,aAAa,EAEjB,EACAC,MAAO,SAASC,EAAQC,GACtB,GAAID,EAAOE,WAAY,OAAO,KAC3BF,EAAOG,QACRF,EAAMN,aAAc,GAEtB,IAAIS,EAAKJ,EAAOK,OAAOC,WACvB,OAA4B,IAAzBhB,EAAQiB,QAAQH,IA2BjBH,EAAMN,aAAc,EACjBK,EAAOQ,QACRP,EAAMN,aAAc,GAEf,YA9BkB,IAAtBM,EAAMN,aACJK,EAAOQ,QACRP,EAAMN,aAAc,GAEf,WAEC,MAAPS,GAAqB,MAAPA,GACL,MAAPA,EACDH,EAAML,OAGNK,EAAMJ,QAED,WAEM,MAAPO,GAAqB,MAAPA,EACb,UAEM,MAAPA,GAAqB,MAAPA,EACb,OAEM,MAAPA,GAAqB,MAAPA,EACb,WAURJ,EAAOQ,QACRP,EAAMN,aAAc,GAExB,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/brainfuck.js"],"sourcesContent":["var reserve = \"><+-.,[]\".split(\"\");\n/*\n comments can be either:\n placed behind lines\n\n +++ this is a comment\n\n where reserved characters cannot be used\n or in a loop\n [\n this is ok to use [ ] and stuff\n ]\n or preceded by #\n*/\nexport const brainfuck = {\n name: \"brainfuck\",\n startState: function() {\n return {\n commentLine: false,\n left: 0,\n right: 0,\n commentLoop: false\n }\n },\n token: function(stream, state) {\n if (stream.eatSpace()) return null\n if(stream.sol()){\n state.commentLine = false;\n }\n var ch = stream.next().toString();\n if(reserve.indexOf(ch) !== -1){\n if(state.commentLine === true){\n if(stream.eol()){\n state.commentLine = false;\n }\n return \"comment\";\n }\n if(ch === \"]\" || ch === \"[\"){\n if(ch === \"[\"){\n state.left++;\n }\n else{\n state.right++;\n }\n return \"bracket\";\n }\n else if(ch === \"+\" || ch === \"-\"){\n return \"keyword\";\n }\n else if(ch === \"<\" || ch === \">\"){\n return \"atom\";\n }\n else if(ch === \".\" || ch === \",\"){\n return \"def\";\n }\n }\n else{\n state.commentLine = true;\n if(stream.eol()){\n state.commentLine = false;\n }\n return \"comment\";\n }\n if(stream.eol()){\n state.commentLine = false;\n }\n }\n};\n"],"names":["reserve","split","brainfuck","name","startState","commentLine","left","right","commentLoop","token","stream","state","eatSpace","sol","ch","next","toString","indexOf","eol"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/22.index.js b/book/_build/html/_static/22.index.js new file mode 100644 index 0000000..befb168 --- /dev/null +++ b/book/_build/html/_static/22.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[22],{22:(e,t,n)=>{function r(e){for(var t={},n=e.split(" "),r=0;rv});var i,a=r("abstract as assert boolean break byte case catch char class const continue def default do double else enum extends final finally float for goto if implements import in instanceof int interface long native new package private protected public return short static strictfp super switch synchronized threadsafe throw throws trait transient try void volatile while"),o=r("catch class def do else enum finally for if interface switch trait try while"),l=r("return break continue"),s=r("null true false this");function u(e,t){var n=e.next();if('"'==n||"'"==n)return c(n,e,t);if(/[\[\]{}\(\),;\:\.]/.test(n))return i=n,null;if(/\d/.test(n))return e.eatWhile(/[\w\.]/),e.eat(/eE/)&&(e.eat(/\+\-/),e.eatWhile(/\d/)),"number";if("/"==n){if(e.eat("*"))return t.tokenize.push(k),k(e,t);if(e.eat("/"))return e.skipToEnd(),"comment";if(m(t.lastToken,!1))return c(n,e,t)}if("-"==n&&e.eat(">"))return i="->",null;if(/[+\-*&%=<>!?|\/~]/.test(n))return e.eatWhile(/[+\-*&%=<>|~]/),"operator";if(e.eatWhile(/[\w\$_]/),"@"==n)return e.eatWhile(/[\w\$_\.]/),"meta";if("."==t.lastToken)return"property";if(e.eat(":"))return i="proplabel","property";var r=e.current();return s.propertyIsEnumerable(r)?"atom":a.propertyIsEnumerable(r)?(o.propertyIsEnumerable(r)?i="newstatement":l.propertyIsEnumerable(r)&&(i="standalone"),"keyword"):"variable"}function c(e,t,n){var r=!1;if("/"!=e&&t.eat(e)){if(!t.eat(e))return"string";r=!0}function i(t,n){for(var i,a=!1,o=!r;null!=(i=t.next());){if(i==e&&!a){if(!r)break;if(t.match(e+e)){o=!0;break}}if('"'==e&&"$"==i&&!a){if(t.eat("{"))return n.tokenize.push(f()),"string";if(t.match(/^\w/,!1))return n.tokenize.push(p),"string"}a=!a&&"\\"==i}return o&&n.tokenize.pop(),"string"}return n.tokenize.push(i),i(t,n)}function f(){var e=1;function t(t,n){if("}"==t.peek()){if(0==--e)return n.tokenize.pop(),n.tokenize[n.tokenize.length-1](t,n)}else"{"==t.peek()&&e++;return u(t,n)}return t.isBase=!0,t}function p(e,t){var n=e.match(/^(\.|[\w\$_]+)/);return n?"."==n[0]?null:"variable":(t.tokenize.pop(),t.tokenize[t.tokenize.length-1](e,t))}function k(e,t){for(var n,r=!1;n=e.next();){if("/"==n&&r){t.tokenize.pop();break}r="*"==n}return"comment"}function m(e,t){return!e||"operator"==e||"->"==e||/[\.\[\{\(,;:]/.test(e)||"newstatement"==e||"keyword"==e||"proplabel"==e||"standalone"==e&&!t}function h(e,t,n,r,i){this.indented=e,this.column=t,this.type=n,this.align=r,this.prev=i}function d(e,t,n){return e.context=new h(e.indented,t,n,null,e.context)}function y(e){var t=e.context.type;return")"!=t&&"]"!=t&&"}"!=t||(e.indented=e.context.indented),e.context=e.context.prev}u.isBase=!0;const v={name:"groovy",startState:function(e){return{tokenize:[u],context:new h(-e,0,"top",!1),indented:0,startOfLine:!0,lastToken:null}},token:function(e,t){var n=t.context;if(e.sol()&&(null==n.align&&(n.align=!1),t.indented=e.indentation(),t.startOfLine=!0,"statement"!=n.type||m(t.lastToken,!0)||(y(t),n=t.context)),e.eatSpace())return null;i=null;var r=t.tokenize[t.tokenize.length-1](e,t);if("comment"==r)return r;if(null==n.align&&(n.align=!0),";"!=i&&":"!=i||"statement"!=n.type)if("->"==i&&"statement"==n.type&&"}"==n.prev.type)y(t),t.context.align=!1;else if("{"==i)d(t,e.column(),"}");else if("["==i)d(t,e.column(),"]");else if("("==i)d(t,e.column(),")");else if("}"==i){for(;"statement"==n.type;)n=y(t);for("}"==n.type&&(n=y(t));"statement"==n.type;)n=y(t)}else i==n.type?y(t):("}"==n.type||"top"==n.type||"statement"==n.type&&"newstatement"==i)&&d(t,e.column(),"statement");else y(t);return t.startOfLine=!1,t.lastToken=i||r,r},indent:function(e,t,n){if(!e.tokenize[e.tokenize.length-1].isBase)return null;var r=t&&t.charAt(0),i=e.context;"statement"!=i.type||m(e.lastToken,!0)||(i=i.prev);var a=r==i.type;return"statement"==i.type?i.indented+("{"==r?0:n.unit):i.align?i.column+(a?0:1):i.indented+(a?0:n.unit)},languageData:{indentOnInput:/^\s*[{}]$/,commentTokens:{line:"//",block:{open:"/*",close:"*/"}},closeBrackets:{brackets:["(","[","{","'",'"',"'''",'"""']}}}}}]); +//# sourceMappingURL=22.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/22.index.js.map b/book/_build/html/_static/22.index.js.map new file mode 100644 index 0000000..71abac8 --- /dev/null +++ b/book/_build/html/_static/22.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"22.index.js","mappings":"0FAAA,SAASA,EAAMC,GAEb,IADA,IAAIC,EAAM,CAAC,EAAGF,EAAQC,EAAIE,MAAM,KACvBC,EAAI,EAAGA,EAAIJ,EAAMK,SAAUD,EAAGF,EAAIF,EAAMI,KAAM,EACvD,OAAOF,CACT,C,6BACA,IAUII,EAVAC,EAAWP,EACb,4WAKEQ,EAAgBR,EAAM,gFACtBS,EAAqBT,EAAM,yBAC3BU,EAAQV,EAAM,wBAGlB,SAASW,EAAUC,EAAQC,GACzB,IAAIC,EAAKF,EAAOG,OAChB,GAAU,KAAND,GAAmB,KAANA,EACf,OAAOE,EAAYF,EAAIF,EAAQC,GAEjC,GAAI,qBAAqBI,KAAKH,GAE5B,OADAR,EAAUQ,EACH,KAET,GAAI,KAAKG,KAAKH,GAGZ,OAFAF,EAAOM,SAAS,UACZN,EAAOO,IAAI,QAASP,EAAOO,IAAI,QAASP,EAAOM,SAAS,OACrD,SAET,GAAU,KAANJ,EAAW,CACb,GAAIF,EAAOO,IAAI,KAEb,OADAN,EAAMO,SAASC,KAAKC,GACbA,EAAaV,EAAQC,GAE9B,GAAID,EAAOO,IAAI,KAEb,OADAP,EAAOW,YACA,UAET,GAAIC,EAAiBX,EAAMY,WAAW,GACpC,OAAOT,EAAYF,EAAIF,EAAQC,EAEnC,CACA,GAAU,KAANC,GAAaF,EAAOO,IAAI,KAE1B,OADAb,EAAU,KACH,KAET,GAAI,oBAAoBW,KAAKH,GAE3B,OADAF,EAAOM,SAAS,iBACT,WAGT,GADAN,EAAOM,SAA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c,EAAId,MAA8B,aAAZc,EAAId,MAAkC,gBAAXzC,IAC3E6C,EAAYtC,EAAOD,EAAOkC,SAAU,kBAhB6BQ,EAAWzC,GAmB9E,OAFAA,EAAM8C,aAAc,EACpB9C,EAAMY,UAAYnB,GAAW2D,EACtBA,CACT,EAEAC,OAAQ,SAASrD,EAAOsD,EAAWC,GACjC,IAAKvD,EAAMO,SAASP,EAAMO,SAASf,OAAO,GAAGmC,OAAQ,OAAO,KAC5D,IAAI6B,EAAYF,GAAaA,EAAUG,OAAO,GAAIT,EAAMhD,EAAMwC,QAC9C,aAAZQ,EAAId,MAAwBvB,EAAiBX,EAAMY,WAAW,KAAOoC,EAAMA,EAAIZ,MACnF,IAAIsB,EAAUF,GAAaR,EAAId,KAC/B,MAAgB,aAAZc,EAAId,KAA4Bc,EAAIhB,UAAyB,KAAbwB,EAAmB,EAAID,EAAGI,MACrEX,EAAIb,MAAca,EAAIf,QAAUyB,EAAU,EAAI,GAC3CV,EAAIhB,UAAY0B,EAAU,EAAIH,EAAGI,KAC/C,EAEAC,aAAc,CACZC,cAAe,YACfC,cAAe,CAACC,KAAM,KAAMC,MAAO,CAACC,KAAM,KAAMC,MAAO,OACvDC,cAAe,CAACC,SAAU,CAAC,IAAK,IAAK,IAAK,IAAK,IAAK,MAAO,S","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/groovy.js"],"sourcesContent":["function words(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n}\nvar keywords = words(\n \"abstract as assert boolean break byte case catch char class const continue def default \" +\n \"do double else enum extends final finally float for goto if implements import in \" +\n \"instanceof int interface long native new package private protected public return \" +\n \"short static strictfp super switch synchronized threadsafe throw throws trait transient \" +\n \"try void volatile while\");\nvar blockKeywords = words(\"catch class def do else enum finally for if interface switch trait try while\");\nvar standaloneKeywords = words(\"return break continue\");\nvar atoms = words(\"null true false this\");\n\nvar curPunc;\nfunction tokenBase(stream, state) {\n var ch = stream.next();\n if (ch == '\"' || ch == \"'\") {\n return startString(ch, stream, state);\n }\n if (/[\\[\\]{}\\(\\),;\\:\\.]/.test(ch)) {\n curPunc = ch;\n return null;\n }\n if (/\\d/.test(ch)) {\n stream.eatWhile(/[\\w\\.]/);\n if (stream.eat(/eE/)) { stream.eat(/\\+\\-/); stream.eatWhile(/\\d/); }\n return \"number\";\n }\n if (ch == \"/\") {\n if (stream.eat(\"*\")) {\n state.tokenize.push(tokenComment);\n return tokenComment(stream, state);\n }\n if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return \"comment\";\n }\n if (expectExpression(state.lastToken, false)) {\n return startString(ch, stream, state);\n }\n }\n if (ch == \"-\" && stream.eat(\">\")) {\n curPunc = \"->\";\n return null;\n }\n if (/[+\\-*&%=<>!?|\\/~]/.test(ch)) {\n stream.eatWhile(/[+\\-*&%=<>|~]/);\n return \"operator\";\n }\n stream.eatWhile(/[\\w\\$_]/);\n if (ch == \"@\") { stream.eatWhile(/[\\w\\$_\\.]/); return \"meta\"; }\n if (state.lastToken == \".\") return \"property\";\n if (stream.eat(\":\")) { curPunc = \"proplabel\"; return \"property\"; }\n var cur = stream.current();\n if (atoms.propertyIsEnumerable(cur)) { return \"atom\"; }\n if (keywords.propertyIsEnumerable(cur)) {\n if (blockKeywords.propertyIsEnumerable(cur)) curPunc = \"newstatement\";\n else if (standaloneKeywords.propertyIsEnumerable(cur)) curPunc = \"standalone\";\n return \"keyword\";\n }\n return \"variable\";\n}\ntokenBase.isBase = true;\n\nfunction startString(quote, stream, state) {\n var tripleQuoted = false;\n if (quote != \"/\" && stream.eat(quote)) {\n if (stream.eat(quote)) tripleQuoted = true;\n else return \"string\";\n }\n function t(stream, state) {\n var escaped = false, next, end = !tripleQuoted;\n while ((next = stream.next()) != null) {\n if (next == quote && !escaped) {\n if (!tripleQuoted) { break; }\n if (stream.match(quote + quote)) { end = true; break; }\n }\n if (quote == '\"' && next == \"$\" && !escaped) {\n if (stream.eat(\"{\")) {\n state.tokenize.push(tokenBaseUntilBrace());\n return \"string\";\n } else if (stream.match(/^\\w/, false)) {\n state.tokenize.push(tokenVariableDeref);\n return \"string\";\n }\n }\n escaped = !escaped && next == \"\\\\\";\n }\n if (end) state.tokenize.pop();\n return \"string\";\n }\n state.tokenize.push(t);\n return t(stream, state);\n}\n\nfunction tokenBaseUntilBrace() {\n var depth = 1;\n function t(stream, state) {\n if (stream.peek() == \"}\") {\n depth--;\n if (depth == 0) {\n state.tokenize.pop();\n return state.tokenize[state.tokenize.length-1](stream, state);\n }\n } else if (stream.peek() == \"{\") {\n depth++;\n }\n return tokenBase(stream, state);\n }\n t.isBase = true;\n return t;\n}\n\nfunction tokenVariableDeref(stream, state) {\n var next = stream.match(/^(\\.|[\\w\\$_]+)/)\n if (!next) {\n state.tokenize.pop()\n return state.tokenize[state.tokenize.length-1](stream, state)\n }\n return next[0] == \".\" ? null : \"variable\"\n}\n\nfunction tokenComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if (ch == \"/\" && maybeEnd) {\n state.tokenize.pop();\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return \"comment\";\n}\n\nfunction expectExpression(last, newline) {\n return !last || last == \"operator\" || last == \"->\" || /[\\.\\[\\{\\(,;:]/.test(last) ||\n last == \"newstatement\" || last == \"keyword\" || last == \"proplabel\" ||\n (last == \"standalone\" && !newline);\n}\n\nfunction Context(indented, column, type, align, prev) {\n this.indented = indented;\n this.column = column;\n this.type = type;\n this.align = align;\n this.prev = prev;\n}\nfunction pushContext(state, col, type) {\n return state.context = new Context(state.indented, col, type, null, state.context);\n}\nfunction popContext(state) {\n var t = state.context.type;\n if (t == \")\" || t == \"]\" || t == \"}\")\n state.indented = state.context.indented;\n return state.context = state.context.prev;\n}\n\n// Interface\n\nexport const groovy = {\n name: \"groovy\",\n startState: function(indentUnit) {\n return {\n tokenize: [tokenBase],\n context: new Context(-indentUnit, 0, \"top\", false),\n indented: 0,\n startOfLine: true,\n lastToken: null\n };\n },\n\n token: function(stream, state) {\n var ctx = state.context;\n if (stream.sol()) {\n if (ctx.align == null) ctx.align = false;\n state.indented = stream.indentation();\n state.startOfLine = true;\n // Automatic semicolon insertion\n if (ctx.type == \"statement\" && !expectExpression(state.lastToken, true)) {\n popContext(state); ctx = state.context;\n }\n }\n if (stream.eatSpace()) return null;\n curPunc = null;\n var style = state.tokenize[state.tokenize.length-1](stream, state);\n if (style == \"comment\") return style;\n if (ctx.align == null) ctx.align = true;\n\n if ((curPunc == \";\" || curPunc == \":\") && ctx.type == \"statement\") popContext(state);\n // Handle indentation for {x -> \\n ... }\n else if (curPunc == \"->\" && ctx.type == \"statement\" && ctx.prev.type == \"}\") {\n popContext(state);\n state.context.align = false;\n }\n else if (curPunc == \"{\") pushContext(state, stream.column(), \"}\");\n else if (curPunc == \"[\") pushContext(state, stream.column(), \"]\");\n else if (curPunc == \"(\") pushContext(state, stream.column(), \")\");\n else if (curPunc == \"}\") {\n while (ctx.type == \"statement\") ctx = popContext(state);\n if (ctx.type == \"}\") ctx = popContext(state);\n while (ctx.type == \"statement\") ctx = popContext(state);\n }\n else if (curPunc == ctx.type) popContext(state);\n else if (ctx.type == \"}\" || ctx.type == \"top\" || (ctx.type == \"statement\" && curPunc == \"newstatement\"))\n pushContext(state, stream.column(), \"statement\");\n state.startOfLine = false;\n state.lastToken = curPunc || style;\n return style;\n },\n\n indent: function(state, textAfter, cx) {\n if (!state.tokenize[state.tokenize.length-1].isBase) return null;\n var firstChar = textAfter && textAfter.charAt(0), ctx = state.context;\n if (ctx.type == \"statement\" && !expectExpression(state.lastToken, true)) ctx = ctx.prev;\n var closing = firstChar == ctx.type;\n if (ctx.type == \"statement\") return ctx.indented + (firstChar == \"{\" ? 0 : cx.unit);\n else if (ctx.align) return ctx.column + (closing ? 0 : 1);\n else return ctx.indented + (closing ? 0 : cx.unit);\n },\n\n languageData: {\n indentOnInput: /^\\s*[{}]$/,\n commentTokens: {line: \"//\", block: {open: \"/*\", close: \"*/\"}},\n closeBrackets: {brackets: [\"(\", \"[\", \"{\", \"'\", '\"', \"'''\", '\"\"\"']}\n }\n};\n"],"names":["words","str","obj","split","i","length","curPunc","keywords","blockKeywords","standaloneKeywords","atoms","tokenBase","stream","state","ch","next","startString","test","eatWhile","eat","tokenize","push","tokenComment","skipToEnd","expectExpression","lastToken","cur","current","propertyIsEnumerable","quote","tripleQuoted","t","escaped","end","match","tokenBaseUntilBrace","tokenVariableDeref","pop","depth","peek","isBase","maybeEnd","last","newline","Context","indented","column","type","align","prev","this","pushContext","col","context","popContext","groovy","name","startState","indentUnit","startOfLine","token","ctx","sol","indentation","eatSpace","style","indent","textAfter","cx","firstChar","charAt","closing","unit","languageData","indentOnInput","commentTokens","line","block","open","close","closeBrackets","brackets"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/2210.index.js b/book/_build/html/_static/2210.index.js new file mode 100644 index 0000000..fe72f7e --- /dev/null +++ b/book/_build/html/_static/2210.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[2210],{52210:(e,t,r)=>{r.r(t),r.d(t,{pascal:()=>u});var n=function(e){for(var t={},r="absolute and array asm begin case const constructor destructor div do downto else end file for function goto if implementation in inherited inline interface label mod nil not object of operator or packed procedure program record reintroduce repeat self set shl shr string then to type unit until uses var while with xor as class dispinterface except exports finalization finally initialization inline is library on out packed property raise resourcestring threadvar try absolute abstract alias assembler bitpacked break cdecl continue cppdecl cvar default deprecated dynamic enumerator experimental export external far far16 forward generic helper implements index interrupt iocheck local message name near nodefault noreturn nostackframe oldfpccall otherwise overload override pascal platform private protected public published read register reintroduce result safecall saveregisters softfloat specialize static stdcall stored strict unaligned unimplemented varargs virtual write".split(" "),n=0;n!?|\/]/;function o(e,t){var r,o=e.next();if("#"==o&&t.startOfLine)return e.skipToEnd(),"meta";if('"'==o||"'"==o)return t.tokenize=(r=o,function(e,t){for(var n,a=!1,i=!1;null!=(n=e.next());){if(n==r&&!a){i=!0;break}a=!a&&"\\"==n}return!i&&a||(t.tokenize=null),"string"}),t.tokenize(e,t);if("("==o&&e.eat("*"))return t.tokenize=l,l(e,t);if("{"==o)return t.tokenize=s,s(e,t);if(/[\[\]\(\),;\:\.]/.test(o))return null;if(/\d/.test(o))return e.eatWhile(/[\w\.]/),"number";if("/"==o&&e.eat("/"))return e.skipToEnd(),"comment";if(i.test(o))return e.eatWhile(i),"operator";e.eatWhile(/[\w\$_]/);var u=e.current();return n.propertyIsEnumerable(u)?"keyword":a.propertyIsEnumerable(u)?"atom":"variable"}function l(e,t){for(var r,n=!1;r=e.next();){if(")"==r&&n){t.tokenize=null;break}n="*"==r}return"comment"}function s(e,t){for(var r;r=e.next();)if("}"==r){t.tokenize=null;break}return"comment"}const u={name:"pascal",startState:function(){return{tokenize:null}},token:function(e,t){return e.eatSpace()?null:(t.tokenize||o)(e,t)},languageData:{indentOnInput:/^\s*[{}]$/,commentTokens:{block:{open:"(*",close:"*)"}}}}}}]); +//# sourceMappingURL=2210.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/2210.index.js.map b/book/_build/html/_static/2210.index.js.map new file mode 100644 index 0000000..15521f6 --- /dev/null +++ b/book/_build/html/_static/2210.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2210.index.js","mappings":"4HAKA,IAAIA,EALJ,SAAeC,GAEb,IADA,IAAIC,EAAM,CAAC,EAAGC,EAKd,u9BAL0BC,MAAM,KACvBC,EAAI,EAAGA,EAAIF,EAAMG,SAAUD,EAAGH,EAAIC,EAAME,KAAM,EACvD,OAAOH,CACT,CACeC,GAeXI,EAAQ,CAAC,MAAQ,GAEjBC,EAAiB,mBAErB,SAASC,EAAUC,EAAQC,GACzB,IAyCmBC,EAzCfC,EAAKH,EAAOI,OAChB,GAAU,KAAND,GAAaF,EAAMI,YAErB,OADAL,EAAOM,YACA,OAET,GAAU,KAANH,GAAmB,KAANA,EAEf,OADAF,EAAMM,UAmCWL,EAnCYC,EAoCxB,S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B,MACjBtB,EAAMM,UAAYR,GAAWC,EAAQC,EAGpD,EAEAuB,aAAc,CACZC,cAAe,YACfC,cAAe,CAACC,MAAO,CAACC,KAAM,KAAMC,MAAO,Q","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/pascal.js"],"sourcesContent":["function words(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n}\nvar keywords = words(\n \"absolute and array asm begin case const constructor destructor div do \" +\n \"downto else end file for function goto if implementation in inherited \" +\n \"inline interface label mod nil not object of operator or packed procedure \" +\n \"program record reintroduce repeat self set shl shr string then to type \" +\n \"unit until uses var while with xor as class dispinterface except exports \" +\n \"finalization finally initialization inline is library on out packed \" +\n \"property raise resourcestring threadvar try absolute abstract alias \" +\n \"assembler bitpacked break cdecl continue cppdecl cvar default deprecated \" +\n \"dynamic enumerator experimental export external far far16 forward generic \" +\n \"helper implements index interrupt iocheck local message name near \" +\n \"nodefault noreturn nostackframe oldfpccall otherwise overload override \" +\n \"pascal platform private protected public published read register \" +\n \"reintroduce result safecall saveregisters softfloat specialize static \" +\n \"stdcall stored strict unaligned unimplemented varargs virtual write\");\nvar atoms = {\"null\": true};\n\nvar isOperatorChar = /[+\\-*&%=<>!?|\\/]/;\n\nfunction tokenBase(stream, state) {\n var ch = stream.next();\n if (ch == \"#\" && state.startOfLine) {\n stream.skipToEnd();\n return \"meta\";\n }\n if (ch == '\"' || ch == \"'\") {\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n }\n if (ch == \"(\" && stream.eat(\"*\")) {\n state.tokenize = tokenComment;\n return tokenComment(stream, state);\n }\n if (ch == \"{\") {\n state.tokenize = tokenCommentBraces;\n return tokenCommentBraces(stream, state);\n }\n if (/[\\[\\]\\(\\),;\\:\\.]/.test(ch)) {\n return null;\n }\n if (/\\d/.test(ch)) {\n stream.eatWhile(/[\\w\\.]/);\n return \"number\";\n }\n if (ch == \"/\") {\n if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return \"comment\";\n }\n }\n if (isOperatorChar.test(ch)) {\n stream.eatWhile(isOperatorChar);\n return \"operator\";\n }\n stream.eatWhile(/[\\w\\$_]/);\n var cur = stream.current();\n if (keywords.propertyIsEnumerable(cur)) return \"keyword\";\n if (atoms.propertyIsEnumerable(cur)) return \"atom\";\n return \"variable\";\n}\n\nfunction tokenString(quote) {\n return function(stream, state) {\n var escaped = false, next, end = false;\n while ((next = stream.next()) != null) {\n if (next == quote && !escaped) {end = true; break;}\n escaped = !escaped && next == \"\\\\\";\n }\n if (end || !escaped) state.tokenize = null;\n return \"string\";\n };\n}\n\nfunction tokenComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if (ch == \")\" && maybeEnd) {\n state.tokenize = null;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return \"comment\";\n}\n\nfunction tokenCommentBraces(stream, state) {\n var ch;\n while (ch = stream.next()) {\n if (ch == \"}\") {\n state.tokenize = null;\n break;\n }\n }\n return \"comment\";\n}\n\n// Interface\n\nexport const pascal = {\n name: \"pascal\",\n\n startState: function() {\n return {tokenize: null};\n },\n\n token: function(stream, state) {\n if (stream.eatSpace()) return null;\n var style = (state.tokenize || tokenBase)(stream, state);\n if (style == \"comment\" || style == \"meta\") return style;\n return style;\n },\n\n languageData: {\n indentOnInput: /^\\s*[{}]$/,\n commentTokens: {block: {open: \"(*\", close: \"*)\"}}\n }\n};\n"],"names":["keywords","str","obj","words","split","i","length","atoms","isOperatorChar","tokenBase","stream","state","quote","ch","next","startOfLine","skipToEnd","tokenize","escaped","end","eat","tokenComment","tokenCommentBraces","test","eatWhile","cur","current","propertyIsEnumerable","maybeEnd","pascal","name","startState","token","eatSpace","languageData","indentOnInput","commentTokens","block","open","close"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/2377.index.js b/book/_build/html/_static/2377.index.js new file mode 100644 index 0000000..074b741 --- /dev/null +++ b/book/_build/html/_static/2377.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[2377],{22377:(O,r,a)=>{a.r(r),a.d(r,{globalCompletion:()=>g,localCompletionSource:()=>h,python:()=>z,pythonLanguage:()=>U});var Q=a(51392),i=a(86253);const x=10,S=13,o=123,e=92,T=new Set([27,51,52,270,67,133,58,59,251,64,65,74,62,63,154,155,158,115]);function t(O){return O==x||O==S}const s=new Q.Jq(((O,r)=>{let a;if(O.next<0)O.acceptToken(206);else if(r.context.depth<0)t(O.next)&&O.acceptToken(205,1);else if(((a=O.peek(-1))<0||t(a))&&r.canShift(204)){let r=0;for(;32==O.next||9==O.next;)O.advance(),r++;O.next!=x&&O.next!=S&&35!=O.next||O.acceptToken(204,-r)}else t(O.next)&&O.acceptToken(203,1)}),{contextual:!0}),n=new Q.Jq(((O,r)=>{let a=r.context.depth;if(a<0)return;let Q=O.peek(-1);if(Q==x||Q==S){let r=0,Q=0;for(;;){if(32==O.next)r++;else{if(9!=O.next)break;r+=8-r%8}O.advance(),Q++}r!=a&&O.next!=x&&O.next!=S&&35!=O.next&&(rO.depth<0&&T.has(r)?O.parent:O,shift:(O,r,a,Q)=>201==r?new p(O,function(O){let r=0;for(let a=0;aO.hash}),l=new Q.Jq((O=>{for(let r=0;r<5;r++){if(O.next!="print".charCodeAt(r))return;O.advance()}if(!/\w/.test(String.fromCharCode(O.next)))for(let r=0;;r++){let a=O.peek(r);if(32!=a&&9!=a)return void(40!=a&&46!=a&&a!=x&&a!=S&&35!=a&&O.acceptToken(1))}}));function $(O,r,a,i,x){return new Q.Jq((Q=>{let S=Q.pos;for(;!(Q.next<0);)if(Q.next==o){if(Q.peek(1)!=o){if(Q.pos==S)return void Q.acceptToken(i,1);break}Q.advance(2)}else if(Q.next==e)Q.advance(),Q.next>=0&&Q.advance();else{if(Q.next==O&&(1==r||Q.peek(1)==O&&Q.peek(2)==O)){if(Q.pos==S)return void Q.acceptToken(x,r);break}Q.advance()}Q.pos>S&&Q.acceptToken(a)}))}const X=$(39,1,207,2,208),w=$(34,1,209,3,210),Y=$(39,3,211,4,212),c=$(34,3,213,5,214),m=(0,i.Gv)({'async "*" "**" FormatConversion FormatSpec':i.pJ.modifier,"for while if elif else try except finally return raise break continue with pass assert await yield match case":i.pJ.controlKeyword,"in not and or is del":i.pJ.operatorKeyword,"from def class global nonlocal lambda":i.pJ.definitionKeyword,import:i.pJ.moduleKeyword,"with as print":i.pJ.keyword,Boolean:i.pJ.bool,None:i.pJ.null,VariableName:i.pJ.variableName,"CallExpression/VariableName":i.pJ.function(i.pJ.variableName),"FunctionDefinition/VariableName":i.pJ.function(i.pJ.definition(i.pJ.variableName)),"ClassDefinition/VariableName":i.pJ.definition(i.pJ.className),PropertyName:i.pJ.propertyName,"CallExpression/MemberExpression/PropertyName":i.pJ.function(i.pJ.propertyName),Comment:i.pJ.lineComment,Number:i.pJ.number,String:i.pJ.string,FormatString:i.pJ.special(i.pJ.string),UpdateOp:i.pJ.updateOperator,"ArithOp!":i.pJ.arithmeticOperator,BitOp:i.pJ.bitwiseOperator,CompareOp:i.pJ.compareOperator,AssignOp:i.pJ.definitionOperator,Ellipsis:i.pJ.punctuation,At:i.pJ.meta,"( )":i.pJ.paren,"[ ]":i.pJ.squareBracket,"{ }":i.pJ.brace,".":i.pJ.derefOperator,", ;":i.pJ.separator}),d={__proto__:null,await:48,or:58,and:60,in:64,not:66,is:68,if:74,else:76,lambda:80,yield:98,from:100,async:106,for:108,None:168,True:170,False:170,del:184,pass:188,break:192,continue:196,return:200,raise:208,import:212,as:214,global:218,nonlocal:220,assert:224,type:229,elif:242,while:246,try:252,except:254,finally:256,with:260,def:264,class:274,match:285,case:291},f=Q.WQ.deserialize({version:14,states:"#&jO`Q#yOOP$bOSOOO%kQ&nO'#HcOOQS'#Cq'#CqOOQS'#Cr'#CrO'ZQ#xO'#CpO(|Q&nO'#HbOOQS'#Hc'#HcOOQS'#DW'#DWOOQS'#Hb'#HbO)jQ#xO'#DaO)}Q#xO'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sQ0t0mQ0x0rR0y0uR/m.wR/{/^",nodeNames:"⚠ print { { { { Comment Script AssignStatement * BinaryExpression BitOp BitOp BitOp BitOp ArithOp ArithOp @ ArithOp ** UnaryExpression ArithOp BitOp AwaitExpression await ) ( ParenthesizedExpression BinaryExpression or and CompareOp in not is UnaryExpression ConditionalExpression if else LambdaExpression lambda ParamList VariableName AssignOp , : NamedExpression AssignOp YieldExpression yield from TupleExpression ComprehensionExpression async for LambdaExpression ] [ ArrayExpression ArrayComprehensionExpression } { DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression CallExpression ArgList AssignOp MemberExpression . PropertyName Number String FormatString FormatReplacement FormatConversion FormatSpec FormatReplacement FormatReplacement FormatReplacement FormatReplacement ContinuedString Ellipsis None Boolean TypeDef AssignOp UpdateStatement UpdateOp ExpressionStatement DeleteStatement del PassStatement pass BreakStatement break ContinueStatement continue ReturnStatement return YieldStatement PrintStatement RaiseStatement raise ImportStatement import as ScopeStatement global nonlocal AssertStatement assert TypeDefinition type TypeParamList TypeParam StatementGroup ; IfStatement Body elif WhileStatement while ForStatement TryStatement try except finally WithStatement with FunctionDefinition def ParamList AssignOp TypeDef ClassDefinition class DecoratedStatement Decorator At MatchStatement match MatchBody MatchClause case CapturePattern LiteralPattern ArithOp ArithOp AsPattern OrPattern LogicOp AttributePattern SequencePattern MappingPattern StarPattern ClassPattern PatternArgList KeywordPattern KeywordPattern Guard",maxTerm:283,context:q,nodeProps:[["group",-15,8,88,90,91,93,95,97,99,101,102,103,105,108,111,113,"Statement Statement",-22,10,20,23,27,42,51,52,58,59,62,63,64,65,66,69,72,73,74,82,83,84,85,"Expression",-10,117,119,122,124,125,129,131,136,138,141,"Statement",-9,146,147,150,151,153,154,155,156,157,"Pattern"],["openedBy",25,"(",56,"[",60,"{"],["closedBy",26,")",57,"]",61,"}"]],propSources:[m],skippedNodes:[0,6],repeatNodeCount:38,tokenData:"%-W#sR!`OX%TXY=|Y[%T[]=|]p%Tpq=|qr@_r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GT;'S;=`!Mk<%lO!GT!a!I^]U!T&jSOY!GTYZ8^Z]!GT]^8^^r!GTrs!5wsw!GTwx!JVx#O!GT#O#P!LV#P;'S!GT;'S;=`!Mk<%lO!GT!a!J^]U!T&mWOY!GTYZ8^Z]!GT]^8^^r!GTrs!HVsw!GTwx!KVx#O!GT#O#P!LV#P;'S!GT;'S;=`!Mk<%lO!GT!a!K^]U!T&mWOY!GTYZ8^Z]!GT]^8^^r!GTrs!HVsw!GTwx!Agx#O!GT#O#P!LV#P;'S!GT;'S;=`!Mk<%lO!GT!a!L[WU!TOY!GTYZ8^Z]!GT]^8^^;'S!GT;'S;=`!Lt;=`<%l8^<%lO!GT!a!L{Y&jS&mWOr8^rs9Qsw8^wx:dx#O8^#O#P;v#P;'S8^;'S;=`Q<%lO$TP;=`<%l$ei&r!b&jS&mW&g`&SsOr%Trs$@Ssw%Twx$C`x!Q%T!Q![$Q<%lO$Q<%lO$Q<%lO$Q<%lO$Q<%lO$d[O]||-1}],tokenPrec:7372});var b=a(77120),Z=a(21649),u=a(64100);const y=new Z.hr,W=new Set(["Script","Body","FunctionDefinition","ClassDefinition","LambdaExpression","ForStatement","MatchClause"]);function V(O){return(r,a,Q)=>{if(Q)return!1;let i=r.node.getChild("VariableName");return i&&a(i,O),!0}}const R={FunctionDefinition:V("function"),ClassDefinition:V("class"),ForStatement(O,r,a){if(a)for(let a=O.node.firstChild;a;a=a.nextSibling)if("VariableName"==a.name)r(a,"variable");else if("in"==a.name)break},ImportStatement(O,r){var a,Q;let{node:i}=O,x="from"==(null===(a=i.firstChild)||void 0===a?void 0:a.name);for(let O=i.getChild("import");O;O=O.nextSibling)"VariableName"==O.name&&"as"!=(null===(Q=O.nextSibling)||void 0===Q?void 0:Q.name)&&r(O,x?"variable":"namespace")},AssignStatement(O,r){for(let a=O.node.firstChild;a;a=a.nextSibling)if("VariableName"==a.name)r(a,"variable");else if(":"==a.name||"AssignOp"==a.name)break},ParamList(O,r){for(let a=null,Q=O.node.firstChild;Q;Q=Q.nextSibling)"VariableName"!=Q.name||a&&/\*|AssignOp/.test(a.name)||r(Q,"variable"),a=Q},CapturePattern:V("variable"),AsPattern:V("variable"),__proto__:null};function v(O,r){let a=y.get(r);if(a)return a;let Q=[],i=!0;function x(r,a){let i=O.sliceString(r.from,r.to);Q.push({label:i,type:a})}return r.cursor(Z.vj.IncludeAnonymous).iterate((r=>{if(r.name){let O=R[r.name];if(O&&O(r,x,i)||!i&&W.has(r.name))return!1;i=!1}else if(r.to-r.from>8192){for(let a of v(O,r.node))Q.push(a);return!1}})),y.set(r,Q),Q}const j=/^[\w\xa1-\uffff][\w\d\xa1-\uffff]*$/,G=["String","FormatString","Comment","PropertyName"];function h(O){let r=(0,b.qz)(O.state).resolveInner(O.pos,-1);if(G.indexOf(r.name)>-1)return null;let a="VariableName"==r.name||r.to-r.from<20&&j.test(O.state.sliceDoc(r.from,r.to));if(!a&&!O.explicit)return null;let Q=[];for(let a=r;a;a=a.parent)W.has(a.name)&&(Q=Q.concat(v(O.state.doc,a)));return{options:Q,from:a?r.from:O.pos,validFor:j}}const _=["__annotations__","__builtins__","__debug__","__doc__","__import__","__name__","__loader__","__package__","__spec__","False","None","True"].map((O=>({label:O,type:"constant"}))).concat(["ArithmeticError","AssertionError","AttributeError","BaseException","BlockingIOError","BrokenPipeError","BufferError","BytesWarning","ChildProcessError","ConnectionAbortedError","ConnectionError","ConnectionRefusedError","ConnectionResetError","DeprecationWarning","EOFError","Ellipsis","EncodingWarning","EnvironmentError","Exception","FileExistsError","FileNotFoundError","FloatingPointError","FutureWarning","GeneratorExit","IOError","ImportError","ImportWarning","IndentationError","IndexError","InterruptedError","IsADirectoryError","KeyError","KeyboardInterrupt","LookupError","MemoryError","ModuleNotFoundError","NameError","NotADirectoryError","NotImplemented","NotImplementedError","OSError","OverflowError","PendingDeprecationWarning","PermissionError","ProcessLookupError","RecursionError","ReferenceError","ResourceWarning","RuntimeError","RuntimeWarning","StopAsyncIteration","StopIteration","SyntaxError","SyntaxWarning","SystemError","SystemExit","TabError","TimeoutError","TypeError","UnboundLocalError","UnicodeDecodeError","UnicodeEncodeError","UnicodeError","UnicodeTranslateError","UnicodeWarning","UserWarning","ValueError","Warning","ZeroDivisionError"].map((O=>({label:O,type:"type"})))).concat(["bool","bytearray","bytes","classmethod","complex","float","frozenset","int","list","map","memoryview","object","range","set","staticmethod","str","super","tuple","type"].map((O=>({label:O,type:"class"})))).concat(["abs","aiter","all","anext","any","ascii","bin","breakpoint","callable","chr","compile","delattr","dict","dir","divmod","enumerate","eval","exec","exit","filter","format","getattr","globals","hasattr","hash","help","hex","id","input","isinstance","issubclass","iter","len","license","locals","max","min","next","oct","open","ord","pow","print","property","quit","repr","reversed","round","setattr","slice","sorted","sum","vars","zip"].map((O=>({label:O,type:"function"})))),k=[(0,u.Gn)("def ${name}(${params}):\n\t${}",{label:"def",detail:"function",type:"keyword"}),(0,u.Gn)("for ${name} in ${collection}:\n\t${}",{label:"for",detail:"loop",type:"keyword"}),(0,u.Gn)("while ${}:\n\t${}",{label:"while",detail:"loop",type:"keyword"}),(0,u.Gn)("try:\n\t${}\nexcept ${error}:\n\t${}",{label:"try",detail:"/ except block",type:"keyword"}),(0,u.Gn)("if ${}:\n\t\n",{label:"if",detail:"block",type:"keyword"}),(0,u.Gn)("if ${}:\n\t${}\nelse:\n\t${}",{label:"if",detail:"/ else block",type:"keyword"}),(0,u.Gn)("class ${name}:\n\tdef __init__(self, ${params}):\n\t\t\t${}",{label:"class",detail:"definition",type:"keyword"}),(0,u.Gn)("import ${module}",{label:"import",detail:"statement",type:"keyword"}),(0,u.Gn)("from ${module} import ${names}",{label:"from",detail:"import",type:"keyword"})],g=(0,u.eC)(G,(0,u.Mb)(_.concat(k)));function E(O,r){let a=O.baseIndentFor(r),Q=O.lineAt(O.pos,-1),i=Q.from+Q.text.length;return/^\s*($|#)/.test(Q.text)&&O.node.toa?null:a+O.unit}const U=b.qp.define({name:"python",parser:f.configure({props:[b.uj.add({Body:O=>{var r;return null!==(r=E(O,O.node))&&void 0!==r?r:O.continue()},IfStatement:O=>/^\s*(else:|elif )/.test(O.textAfter)?O.baseIndent:O.continue(),TryStatement:O=>/^\s*(except |finally:|else:)/.test(O.textAfter)?O.baseIndent:O.continue(),"TupleExpression ComprehensionExpression ParamList ArgList ParenthesizedExpression":(0,b.vw)({closing:")"}),"DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression":(0,b.vw)({closing:"}"}),"ArrayExpression ArrayComprehensionExpression":(0,b.vw)({closing:"]"}),"String FormatString":()=>null,Script:O=>{if(O.pos+/\s*/.exec(O.textAfter)[0].length>=O.node.to){let r=null;for(let a=O.node,Q=a.to;a=a.lastChild,a&&a.to==Q;)"Body"==a.type.name&&(r=a);if(r){let a=E(O,r);if(null!=a)return a}}return O.continue()}}),b.x0.add({"ArrayExpression DictionaryExpression SetExpression TupleExpression":b.Dv,Body:(O,r)=>({from:O.from+1,to:O.to-(O.to==r.doc.length?0:1)})})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"'''",'"""'],stringPrefixes:["f","fr","rf","r","u","b","br","rb","F","FR","RF","R","U","B","BR","RB"]},commentTokens:{line:"#"},indentOnInput:/^\s*([\}\]\)]|else:|elif |except |finally:)$/}});function z(){return new b.ri(U,[U.data.of({autocomplete:h}),U.data.of({autocomplete:g})])}}}]); +//# sourceMappingURL=2377.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/2377.index.js.map b/book/_build/html/_static/2377.index.js.map new file mode 100644 index 0000000..a87a062 --- /dev/null +++ b/book/_build/html/_static/2377.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2377.index.js","mappings":"8NAIA,MAyCMA,EAAU,GAAIC,EAAiB,GAC/BC,EAAY,IAAyCC,EAAY,GAEjEC,EAAY,IAAIC,IAAI,CAxBE,GACR,GACQ,GAYb,IAHH,GAKE,IAZM,GACa,GAOnB,IAHI,GACa,GAGd,GANQ,GACa,GASlB,IACD,IACA,IAJD,MAiBlB,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,EAAU,KACd,IAAK,IAAIC,EAAMhM,EAAQqH,KAAM2B,EAAKgD,EAAIhD,GAClCgD,EAAMA,EAAIC,UACLD,GAAOA,EAAIhD,IAAMA,GAED,QAAjBgD,EAAI3G,KAAK2C,OACT+D,EAAUC,GAElB,GAAID,EAAS,CACT,IAAIG,EAAavB,EAAW3K,EAAS+L,GACrC,GAAkB,MAAdG,EACA,OAAOA,CACf,CACJ,CACA,OAAOlM,EAAQ8E,UAAU,IAGpB,SAAiB,CAC1B,qEAAsE,KACtEyG,KAAM,CAAClE,EAAMuC,KAAU,CAAGtF,KAAM+C,EAAK/C,KAAO,EAAG0E,GAAI3B,EAAK2B,IAAM3B,EAAK2B,IAAMY,EAAMjB,IAAIpH,OAAS,EAAI,UAI5G4K,aAAc,CACVC,cAAe,CACXC,SAAU,CAAC,IAAK,IAAK,IAAK,IAAK,IAAK,MAAO,OAC3CC,eAAgB,CAAC,IAAK,KAAM,KAAM,IAAK,IAAK,IAAK,KAAM,KACnD,IAAK,KAAM,KAAM,IAAK,IAAK,IAAK,KAAM,OAE9CC,cAAe,CAAEzB,KAAM,KACvB0B,cAAe,kDAMvB,SAASC,IACL,OAAO,IAAI,KAAgBrB,EAAgB,CACvCA,EAAesB,KAAKC,GAAG,CAAEC,aAAclD,IACvC0B,EAAesB,KAAKC,GAAG,CAAEC,aAAclC,KAE/C,C","sources":["webpack://thebe/../../node_modules/@lezer/python/dist/index.js","webpack://thebe/../../node_modules/@codemirror/lang-python/dist/index.js"],"sourcesContent":["import { ExternalTokenizer, ContextTracker, LRParser } from '@lezer/lr';\nimport { styleTags, tags } from '@lezer/highlight';\n\n// This file was generated by lezer-generator. You probably shouldn't edit it.\nconst printKeyword = 1,\n indent = 201,\n dedent = 202,\n newline$1 = 203,\n blankLineStart = 204,\n newlineBracketed = 205,\n eof = 206,\n formatString1Content = 207,\n formatString1Brace = 2,\n formatString1End = 208,\n formatString2Content = 209,\n formatString2Brace = 3,\n formatString2End = 210,\n formatString1lContent = 211,\n formatString1lBrace = 4,\n formatString1lEnd = 212,\n formatString2lContent = 213,\n formatString2lBrace = 5,\n formatString2lEnd = 214,\n ParenL = 26,\n ParenthesizedExpression = 27,\n TupleExpression = 51,\n ComprehensionExpression = 52,\n BracketL = 57,\n ArrayExpression = 58,\n ArrayComprehensionExpression = 59,\n BraceL = 61,\n DictionaryExpression = 62,\n DictionaryComprehensionExpression = 63,\n SetExpression = 64,\n SetComprehensionExpression = 65,\n ArgList = 67,\n subscript = 251,\n FormatString = 74,\n importList = 270,\n TypeParamList = 115,\n ParamList = 133,\n SequencePattern = 154,\n MappingPattern = 155,\n PatternArgList = 158;\n\nconst newline = 10, carriageReturn = 13, space = 32, tab = 9, hash = 35, parenOpen = 40, dot = 46,\n braceOpen = 123, singleQuote = 39, doubleQuote = 34, backslash = 92;\n\nconst bracketed = new Set([\n ParenthesizedExpression, TupleExpression, ComprehensionExpression, importList, ArgList, ParamList,\n ArrayExpression, ArrayComprehensionExpression, subscript,\n SetExpression, SetComprehensionExpression, FormatString,\n DictionaryExpression, DictionaryComprehensionExpression,\n SequencePattern, MappingPattern, PatternArgList, TypeParamList\n]);\n\nfunction isLineBreak(ch) {\n return ch == newline || ch == carriageReturn\n}\n\nconst newlines = new ExternalTokenizer((input, stack) => {\n let prev;\n if (input.next < 0) {\n input.acceptToken(eof);\n } else if (stack.context.depth < 0) {\n if (isLineBreak(input.next)) input.acceptToken(newlineBracketed, 1);\n } else if (((prev = input.peek(-1)) < 0 || isLineBreak(prev)) &&\n stack.canShift(blankLineStart)) {\n let spaces = 0;\n while (input.next == space || input.next == tab) { input.advance(); spaces++; }\n if (input.next == newline || input.next == carriageReturn || input.next == hash)\n input.acceptToken(blankLineStart, -spaces);\n } else if (isLineBreak(input.next)) {\n input.acceptToken(newline$1, 1);\n }\n}, {contextual: true});\n\nconst indentation = new ExternalTokenizer((input, stack) => {\n let cDepth = stack.context.depth;\n if (cDepth < 0) return\n let prev = input.peek(-1);\n if (prev == newline || prev == carriageReturn) {\n let depth = 0, chars = 0;\n for (;;) {\n if (input.next == space) depth++;\n else if (input.next == tab) depth += 8 - (depth % 8);\n else break\n input.advance();\n chars++;\n }\n if (depth != cDepth &&\n input.next != newline && input.next != carriageReturn && input.next != hash) {\n if (depth < cDepth) input.acceptToken(dedent, -chars);\n else input.acceptToken(indent);\n }\n }\n});\n\nfunction IndentLevel(parent, depth) {\n this.parent = parent;\n // -1 means this is not an actual indent level but a set of brackets\n this.depth = depth;\n this.hash = (parent ? parent.hash + parent.hash << 8 : 0) + depth + (depth << 4);\n}\n\nconst topIndent = new IndentLevel(null, 0);\n\nfunction countIndent(space) {\n let depth = 0;\n for (let i = 0; i < space.length; i++)\n depth += space.charCodeAt(i) == tab ? 8 - (depth % 8) : 1;\n return depth\n}\n\nconst trackIndent = new ContextTracker({\n start: topIndent,\n reduce(context, term) {\n return context.depth < 0 && bracketed.has(term) ? context.parent : context\n },\n shift(context, term, stack, input) {\n if (term == indent) return new IndentLevel(context, countIndent(input.read(input.pos, stack.pos)))\n if (term == dedent) return context.parent\n if (term == ParenL || term == BracketL || term == BraceL) return new IndentLevel(context, -1)\n return context\n },\n hash(context) { return context.hash }\n});\n\nconst legacyPrint = new ExternalTokenizer(input => {\n for (let i = 0; i < 5; i++) {\n if (input.next != \"print\".charCodeAt(i)) return\n input.advance();\n }\n if (/\\w/.test(String.fromCharCode(input.next))) return\n for (let off = 0;; off++) {\n let next = input.peek(off);\n if (next == space || next == tab) continue\n if (next != parenOpen && next != dot && next != newline && next != carriageReturn && next != hash)\n input.acceptToken(printKeyword);\n return\n }\n});\n\nfunction formatString(quote, len, content, brace, end) {\n return new ExternalTokenizer(input => {\n let start = input.pos;\n for (;;) {\n if (input.next < 0) {\n break\n } else if (input.next == braceOpen) {\n if (input.peek(1) == braceOpen) {\n input.advance(2);\n } else {\n if (input.pos == start) {\n input.acceptToken(brace, 1);\n return\n }\n break\n }\n } else if (input.next == backslash) {\n input.advance();\n if (input.next >= 0) input.advance();\n } else if (input.next == quote && (len == 1 || input.peek(1) == quote && input.peek(2) == quote)) {\n if (input.pos == start) {\n input.acceptToken(end, len);\n return\n }\n break\n } else {\n input.advance();\n }\n }\n if (input.pos > start) input.acceptToken(content);\n })\n}\n\nconst formatString1 = formatString(singleQuote, 1, formatString1Content, formatString1Brace, formatString1End);\nconst formatString2 = formatString(doubleQuote, 1, formatString2Content, formatString2Brace, formatString2End);\nconst formatString1l = formatString(singleQuote, 3, formatString1lContent, formatString1lBrace, formatString1lEnd);\nconst formatString2l = formatString(doubleQuote, 3, formatString2lContent, formatString2lBrace, formatString2lEnd);\n\nconst pythonHighlighting = styleTags({\n \"async \\\"*\\\" \\\"**\\\" FormatConversion FormatSpec\": tags.modifier,\n \"for while if elif else try except finally return raise break continue with pass assert await yield match case\": tags.controlKeyword,\n \"in not and or is del\": tags.operatorKeyword,\n \"from def class global nonlocal lambda\": tags.definitionKeyword,\n import: tags.moduleKeyword,\n \"with as print\": tags.keyword,\n Boolean: tags.bool,\n None: tags.null,\n VariableName: tags.variableName,\n \"CallExpression/VariableName\": tags.function(tags.variableName),\n \"FunctionDefinition/VariableName\": tags.function(tags.definition(tags.variableName)),\n \"ClassDefinition/VariableName\": tags.definition(tags.className),\n PropertyName: tags.propertyName,\n \"CallExpression/MemberExpression/PropertyName\": tags.function(tags.propertyName),\n Comment: tags.lineComment,\n Number: tags.number,\n String: tags.string,\n FormatString: tags.special(tags.string),\n UpdateOp: tags.updateOperator,\n \"ArithOp!\": tags.arithmeticOperator,\n BitOp: tags.bitwiseOperator,\n CompareOp: tags.compareOperator,\n AssignOp: tags.definitionOperator,\n Ellipsis: tags.punctuation,\n At: tags.meta,\n \"( )\": tags.paren,\n \"[ ]\": tags.squareBracket,\n \"{ }\": tags.brace,\n \".\": tags.derefOperator,\n \", ;\": tags.separator\n});\n\n// This file was generated by lezer-generator. You probably shouldn't edit it.\nconst spec_identifier = {__proto__:null,await:48, or:58, and:60, in:64, not:66, is:68, if:74, else:76, lambda:80, yield:98, from:100, async:106, for:108, None:168, True:170, False:170, del:184, pass:188, break:192, continue:196, return:200, raise:208, import:212, as:214, global:218, nonlocal:220, assert:224, type:229, elif:242, while:246, try:252, except:254, finally:256, with:260, def:264, class:274, match:285, case:291};\nconst parser = LRParser.deserialize({\n version: 14,\n states: \"#&jO`Q#yOOP$bOSOOO%kQ&nO'#HcOOQS'#Cq'#CqOOQS'#Cr'#CrO'ZQ#xO'#CpO(|Q&nO'#HbOOQS'#Hc'#HcOOQS'#DW'#DWOOQS'#Hb'#HbO)jQ#xO'#DaO)}Q#xO'#DhO*_Q#xO'#DlOOQS'#Dw'#DwO*rO,UO'#DwO*zO7[O'#DwO+SOWO'#DxO+_O`O'#DxO+jOpO'#DxO+uO!bO'#DxO-wQ&nO'#HSOOQS'#HS'#HSO'ZQ#xO'#HRO/ZQ&nO'#HROOQS'#Ee'#EeO/rQ#xO'#EfOOQS'#HQ'#HQO/|Q#xO'#HPOOQV'#HP'#HPO0XQ#xO'#F]OOQS'#Ge'#GeO0^Q#xO'#F[OOQV'#IY'#IYOOQV'#HO'#HOOOQV'#Ft'#FtQ`Q#yOOO'ZQ#xO'#CsO0lQ#xO'#DPO0sQ#xO'#DTO1RQ#xO'#HgO1cQ&nO'#EYO'ZQ#xO'#EZOOQS'#E]'#E]OOQS'#E_'#E_OOQS'#Ea'#EaO1wQ#xO'#EcO2_Q#xO'#EgO0XQ#xO'#EiO2rQ&nO'#EiO0XQ#xO'#ElO/rQ#xO'#EoO0XQ#xO'#EqO/rQ#xO'#EwO/rQ#xO'#EzO2}Q#xO'#E|O3UQ#xO'#FRO3aQ#xO'#E}O/rQ#xO'#FRO0XQ#xO'#FTO0XQ#xO'#FYO3fQ#xO'#F_P3mO#xO'#G}POOO)CBq)CBqOOQS'#Cg'#CgOOQS'#Ch'#ChOOQS'#Ci'#CiOOQS'#Cj'#CjOOQS'#Ck'#CkOOQS'#Cl'#ClOOQS'#Cn'#CnO'ZQ#xO,59QO'ZQ#xO,59QO'ZQ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Z#gQ&]#jQ&_#mR-`+lQ(}&WQ)P&ZQ)R&]Q)T&_Q+p)OQ+q)QQ+r)SQ+s)UQ.^-`R/V._Q$m!SQ&{$aQ*R'bR,`*SQ#zmQ$f!PQ$i!QR'T$hQ)h'SR+|)kQ)h'SQ+{)jR+|)kR$k!RR)u'YXqOs*W,dQ$s!WR'c$tQ$z!ZR'd$uR*k'pQ*i'pV-|,s-}.lQ.{.RQ/i.uR/j.vU.t.R.u.vQ/n.xQ/y/^Q0O/dU0Q/f0R0bQ0V/kQ0e0WQ0g0]U0i0^0k0sQ0t0mQ0x0rR0y0uR/m.wR/{/^\",\n nodeNames: \"⚠ print { { { { Comment Script AssignStatement * BinaryExpression BitOp BitOp BitOp BitOp ArithOp ArithOp @ ArithOp ** UnaryExpression ArithOp BitOp AwaitExpression await ) ( ParenthesizedExpression BinaryExpression or and CompareOp in not is UnaryExpression ConditionalExpression if else LambdaExpression lambda ParamList VariableName AssignOp , : NamedExpression AssignOp YieldExpression yield from TupleExpression ComprehensionExpression async for LambdaExpression ] [ ArrayExpression ArrayComprehensionExpression } { DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression CallExpression ArgList AssignOp MemberExpression . PropertyName Number String FormatString FormatReplacement FormatConversion FormatSpec FormatReplacement FormatReplacement FormatReplacement FormatReplacement ContinuedString Ellipsis None Boolean TypeDef AssignOp UpdateStatement UpdateOp ExpressionStatement DeleteStatement del PassStatement pass BreakStatement break ContinueStatement continue ReturnStatement return YieldStatement PrintStatement RaiseStatement raise ImportStatement import as ScopeStatement global nonlocal AssertStatement assert TypeDefinition type TypeParamList TypeParam StatementGroup ; IfStatement Body elif WhileStatement while ForStatement TryStatement try except finally WithStatement with FunctionDefinition def ParamList AssignOp TypeDef ClassDefinition class DecoratedStatement Decorator At MatchStatement match MatchBody MatchClause case CapturePattern LiteralPattern ArithOp ArithOp AsPattern OrPattern LogicOp AttributePattern SequencePattern MappingPattern StarPattern ClassPattern PatternArgList KeywordPattern KeywordPattern Guard\",\n maxTerm: 283,\n context: trackIndent,\n nodeProps: [\n [\"group\", -15,8,88,90,91,93,95,97,99,101,102,103,105,108,111,113,\"Statement Statement\",-22,10,20,23,27,42,51,52,58,59,62,63,64,65,66,69,72,73,74,82,83,84,85,\"Expression\",-10,117,119,122,124,125,129,131,136,138,141,\"Statement\",-9,146,147,150,151,153,154,155,156,157,\"Pattern\"],\n [\"openedBy\", 25,\"(\",56,\"[\",60,\"{\"],\n [\"closedBy\", 26,\")\",57,\"]\",61,\"}\"]\n ],\n propSources: [pythonHighlighting],\n skippedNodes: [0,6],\n repeatNodeCount: 38,\n tokenData: \"%-W#sR!`OX%TXY=|Y[%T[]=|]p%Tpq=|qr@_rsDOst!+|tu%Tuv!Nnvw#!|wx#$Wxy#:Uyz#;Yz{#<^{|#>x|}#@S}!O#AW!O!P#Ci!P!Q#N_!Q!R$!y!R![$&w![!]$1e!]!^$3s!^!_$4w!_!`$7c!`!a$8m!a!b%T!b!c$;U!c!d$W!e!h$W#V#Y$Q<%lO$Xc&r!b&jS&mW%p!TOX%TXY=|Y[%T[]=|]p%Tpq=|qr%Trs&Vsw%Twx/Xx#O%T#O#P?d#P#o%T#o#p8^#p#q%T#q#r8^#r;'S%T;'S;=`=v<%lO%T#s?i[&r!bOY%TYZ=|Z]%T]^=|^#o%T#o#p8^#p#q%T#q#r8^#r;'S%T;'S;=`=P;=`<%l8^<%lO%T!q@hd&r!b&jS&mWOr%Trs&Vsw%Twx/Xx!_%T!_!`Av!`#O%T#O#P7o#P#T%T#T#UBz#U#f%T#f#gBz#g#hBz#h#o%T#o#p8^#p#q%T#q#r8^#r;'S%T;'S;=`=v<%lO%T!qBR]oR&r!b&jS&mWOr%Trs&Vsw%Twx/Xx#O%T#O#P7o#P#o%T#o#p8^#p#q%T#q#r8^#r;'S%T;'S;=`=v<%lO%T!qCV]!nR&r!b&jS&mWOr%Trs&Vsw%Twx/Xx#O%T#O#P7o#P#o%T#o#p8^#p#q%T#q#r8^#r;'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;=`6t;=`<%l!Ag<%lO4`!]!E`P;=`<%l!Ag#o!EhW&mWOr4`rs4zs#O4`#O#P5y#P;'S4`;'S;=`6t;=`<%l!=U<%lO4`#o!FTP;=`<%l!=U#s!F_[U!T&r!bOY!+|YZ%TZ]!+|]^%T^#o!+|#o#p!GT#p#q!+|#q#r!GT#r;'S!+|;'S;=`!Mq;=`<%l8^<%lO!+|!a!G^]U!T&jS&mWOY!GTYZ8^Z]!GT]^8^^r!GTrs!HVsw!GTwx!JVx#O!GT#O#P!LV#P;'S!GT;'S;=`!Mk<%lO!GT!a!H^]U!T&jSOY!GTYZ8^Z]!GT]^8^^r!GTrs!IVsw!GTwx!JVx#O!GT#O#P!LV#P;'S!GT;'S;=`!Mk<%lO!GT!a!I^]U!T&jSOY!GTYZ8^Z]!GT]^8^^r!GTrs!5wsw!GTwx!JVx#O!GT#O#P!LV#P;'S!GT;'S;=`!Mk<%lO!GT!a!J^]U!T&mWOY!GTYZ8^Z]!GT]^8^^r!GTrs!HVsw!GTwx!KVx#O!GT#O#P!LV#P;'S!GT;'S;=`!Mk<%lO!GT!a!K^]U!T&mWOY!GTYZ8^Z]!GT]^8^^r!GTrs!HVsw!GTwx!Agx#O!GT#O#P!LV#P;'S!GT;'S;=`!Mk<%lO!GT!a!L[WU!TOY!GTYZ8^Z]!GT]^8^^;'S!GT;'S;=`!Lt;=`<%l8^<%lO!GT!a!L{Y&jS&mWOr8^rs9Qsw8^wx:dx#O8^#O#P;v#P;'S8^;'S;=`Q<%lO$TP;=`<%l$ei&r!b&jS&mW&g`&SsOr%Trs$@Ssw%Twx$C`x!Q%T!Q![$Q<%lO$Q<%lO$Q<%lO$Q<%lO$Q<%lO$ spec_identifier[value] || -1}],\n tokenPrec: 7372\n});\n\nexport { parser };\n","import { parser } from '@lezer/python';\nimport { syntaxTree, LRLanguage, indentNodeProp, delimitedIndent, foldNodeProp, foldInside, LanguageSupport } from '@codemirror/language';\nimport { NodeWeakMap, IterMode } from '@lezer/common';\nimport { snippetCompletion, ifNotIn, completeFromList } from '@codemirror/autocomplete';\n\nconst cache = /*@__PURE__*/new NodeWeakMap();\nconst ScopeNodes = /*@__PURE__*/new Set([\n \"Script\", \"Body\",\n \"FunctionDefinition\", \"ClassDefinition\", \"LambdaExpression\",\n \"ForStatement\", \"MatchClause\"\n]);\nfunction defID(type) {\n return (node, def, outer) => {\n if (outer)\n return false;\n let id = node.node.getChild(\"VariableName\");\n if (id)\n def(id, type);\n return true;\n };\n}\nconst gatherCompletions = {\n FunctionDefinition: /*@__PURE__*/defID(\"function\"),\n ClassDefinition: /*@__PURE__*/defID(\"class\"),\n ForStatement(node, def, outer) {\n if (outer)\n for (let child = node.node.firstChild; child; child = child.nextSibling) {\n if (child.name == \"VariableName\")\n def(child, \"variable\");\n else if (child.name == \"in\")\n break;\n }\n },\n ImportStatement(_node, def) {\n var _a, _b;\n let { node } = _node;\n let isFrom = ((_a = node.firstChild) === null || _a === void 0 ? void 0 : _a.name) == \"from\";\n for (let ch = node.getChild(\"import\"); ch; ch = ch.nextSibling) {\n if (ch.name == \"VariableName\" && ((_b = ch.nextSibling) === null || _b === void 0 ? void 0 : _b.name) != \"as\")\n def(ch, isFrom ? \"variable\" : \"namespace\");\n }\n },\n AssignStatement(node, def) {\n for (let child = node.node.firstChild; child; child = child.nextSibling) {\n if (child.name == \"VariableName\")\n def(child, \"variable\");\n else if (child.name == \":\" || child.name == \"AssignOp\")\n break;\n }\n },\n ParamList(node, def) {\n for (let prev = null, child = node.node.firstChild; child; child = child.nextSibling) {\n if (child.name == \"VariableName\" && (!prev || !/\\*|AssignOp/.test(prev.name)))\n def(child, \"variable\");\n prev = child;\n }\n },\n CapturePattern: /*@__PURE__*/defID(\"variable\"),\n AsPattern: /*@__PURE__*/defID(\"variable\"),\n __proto__: null\n};\nfunction getScope(doc, node) {\n let cached = cache.get(node);\n if (cached)\n return cached;\n let completions = [], top = true;\n function def(node, type) {\n let name = doc.sliceString(node.from, node.to);\n completions.push({ label: name, type });\n }\n node.cursor(IterMode.IncludeAnonymous).iterate(node => {\n if (node.name) {\n let gather = gatherCompletions[node.name];\n if (gather && gather(node, def, top) || !top && ScopeNodes.has(node.name))\n return false;\n top = false;\n }\n else if (node.to - node.from > 8192) {\n // Allow caching for bigger internal nodes\n for (let c of getScope(doc, node.node))\n completions.push(c);\n return false;\n }\n });\n cache.set(node, completions);\n return completions;\n}\nconst Identifier = /^[\\w\\xa1-\\uffff][\\w\\d\\xa1-\\uffff]*$/;\nconst dontComplete = [\"String\", \"FormatString\", \"Comment\", \"PropertyName\"];\n/**\nCompletion source that looks up locally defined names in\nPython code.\n*/\nfunction localCompletionSource(context) {\n let inner = syntaxTree(context.state).resolveInner(context.pos, -1);\n if (dontComplete.indexOf(inner.name) > -1)\n return null;\n let isWord = inner.name == \"VariableName\" ||\n inner.to - inner.from < 20 && Identifier.test(context.state.sliceDoc(inner.from, inner.to));\n if (!isWord && !context.explicit)\n return null;\n let options = [];\n for (let pos = inner; pos; pos = pos.parent) {\n if (ScopeNodes.has(pos.name))\n options = options.concat(getScope(context.state.doc, pos));\n }\n return {\n options,\n from: isWord ? inner.from : context.pos,\n validFor: Identifier\n };\n}\nconst globals = /*@__PURE__*/[\n \"__annotations__\", \"__builtins__\", \"__debug__\", \"__doc__\", \"__import__\", \"__name__\",\n \"__loader__\", \"__package__\", \"__spec__\",\n \"False\", \"None\", \"True\"\n].map(n => ({ label: n, type: \"constant\" })).concat(/*@__PURE__*/[\n \"ArithmeticError\", \"AssertionError\", \"AttributeError\", \"BaseException\", \"BlockingIOError\",\n \"BrokenPipeError\", \"BufferError\", \"BytesWarning\", \"ChildProcessError\", \"ConnectionAbortedError\",\n \"ConnectionError\", \"ConnectionRefusedError\", \"ConnectionResetError\", \"DeprecationWarning\",\n \"EOFError\", \"Ellipsis\", \"EncodingWarning\", \"EnvironmentError\", \"Exception\", \"FileExistsError\",\n \"FileNotFoundError\", \"FloatingPointError\", \"FutureWarning\", \"GeneratorExit\", \"IOError\",\n \"ImportError\", \"ImportWarning\", \"IndentationError\", \"IndexError\", \"InterruptedError\",\n \"IsADirectoryError\", \"KeyError\", \"KeyboardInterrupt\", \"LookupError\", \"MemoryError\",\n \"ModuleNotFoundError\", \"NameError\", \"NotADirectoryError\", \"NotImplemented\", \"NotImplementedError\",\n \"OSError\", \"OverflowError\", \"PendingDeprecationWarning\", \"PermissionError\", \"ProcessLookupError\",\n \"RecursionError\", \"ReferenceError\", \"ResourceWarning\", \"RuntimeError\", \"RuntimeWarning\",\n \"StopAsyncIteration\", \"StopIteration\", \"SyntaxError\", \"SyntaxWarning\", \"SystemError\",\n \"SystemExit\", \"TabError\", \"TimeoutError\", \"TypeError\", \"UnboundLocalError\", \"UnicodeDecodeError\",\n \"UnicodeEncodeError\", \"UnicodeError\", \"UnicodeTranslateError\", \"UnicodeWarning\", \"UserWarning\",\n \"ValueError\", \"Warning\", \"ZeroDivisionError\"\n].map(n => ({ label: n, type: \"type\" }))).concat(/*@__PURE__*/[\n \"bool\", \"bytearray\", \"bytes\", \"classmethod\", \"complex\", \"float\", \"frozenset\", \"int\", \"list\",\n \"map\", \"memoryview\", \"object\", \"range\", \"set\", \"staticmethod\", \"str\", \"super\", \"tuple\", \"type\"\n].map(n => ({ label: n, type: \"class\" }))).concat(/*@__PURE__*/[\n \"abs\", \"aiter\", \"all\", \"anext\", \"any\", \"ascii\", \"bin\", \"breakpoint\", \"callable\", \"chr\",\n \"compile\", \"delattr\", \"dict\", \"dir\", \"divmod\", \"enumerate\", \"eval\", \"exec\", \"exit\", \"filter\",\n \"format\", \"getattr\", \"globals\", \"hasattr\", \"hash\", \"help\", \"hex\", \"id\", \"input\", \"isinstance\",\n \"issubclass\", \"iter\", \"len\", \"license\", \"locals\", \"max\", \"min\", \"next\", \"oct\", \"open\",\n \"ord\", \"pow\", \"print\", \"property\", \"quit\", \"repr\", \"reversed\", \"round\", \"setattr\", \"slice\",\n \"sorted\", \"sum\", \"vars\", \"zip\"\n].map(n => ({ label: n, type: \"function\" })));\nconst snippets = [\n /*@__PURE__*/snippetCompletion(\"def ${name}(${params}):\\n\\t${}\", {\n label: \"def\",\n detail: \"function\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"for ${name} in ${collection}:\\n\\t${}\", {\n label: \"for\",\n detail: \"loop\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"while ${}:\\n\\t${}\", {\n label: \"while\",\n detail: \"loop\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"try:\\n\\t${}\\nexcept ${error}:\\n\\t${}\", {\n label: \"try\",\n detail: \"/ except block\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"if ${}:\\n\\t\\n\", {\n label: \"if\",\n detail: \"block\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"if ${}:\\n\\t${}\\nelse:\\n\\t${}\", {\n label: \"if\",\n detail: \"/ else block\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"class ${name}:\\n\\tdef __init__(self, ${params}):\\n\\t\\t\\t${}\", {\n label: \"class\",\n detail: \"definition\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"import ${module}\", {\n label: \"import\",\n detail: \"statement\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"from ${module} import ${names}\", {\n label: \"from\",\n detail: \"import\",\n type: \"keyword\"\n })\n];\n/**\nAutocompletion for built-in Python globals and keywords.\n*/\nconst globalCompletion = /*@__PURE__*/ifNotIn(dontComplete, /*@__PURE__*/completeFromList(/*@__PURE__*/globals.concat(snippets)));\n\nfunction indentBody(context, node) {\n let base = context.baseIndentFor(node);\n let line = context.lineAt(context.pos, -1), to = line.from + line.text.length;\n // Don't consider blank, deindented lines at the end of the\n // block part of the block\n if (/^\\s*($|#)/.test(line.text) &&\n context.node.to < to + 100 &&\n !/\\S/.test(context.state.sliceDoc(to, context.node.to)) &&\n context.lineIndent(context.pos, -1) <= base)\n return null;\n // A normally deindenting keyword that appears at a higher\n // indentation than the block should probably be handled by the next\n // level\n if (/^\\s*(else:|elif |except |finally:)/.test(context.textAfter) && context.lineIndent(context.pos, -1) > base)\n return null;\n return base + context.unit;\n}\n/**\nA language provider based on the [Lezer Python\nparser](https://github.com/lezer-parser/python), extended with\nhighlighting and indentation information.\n*/\nconst pythonLanguage = /*@__PURE__*/LRLanguage.define({\n name: \"python\",\n parser: /*@__PURE__*/parser.configure({\n props: [\n /*@__PURE__*/indentNodeProp.add({\n Body: context => { var _a; return (_a = indentBody(context, context.node)) !== null && _a !== void 0 ? _a : context.continue(); },\n IfStatement: cx => /^\\s*(else:|elif )/.test(cx.textAfter) ? cx.baseIndent : cx.continue(),\n TryStatement: cx => /^\\s*(except |finally:|else:)/.test(cx.textAfter) ? cx.baseIndent : cx.continue(),\n \"TupleExpression ComprehensionExpression ParamList ArgList ParenthesizedExpression\": /*@__PURE__*/delimitedIndent({ closing: \")\" }),\n \"DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression\": /*@__PURE__*/delimitedIndent({ closing: \"}\" }),\n \"ArrayExpression ArrayComprehensionExpression\": /*@__PURE__*/delimitedIndent({ closing: \"]\" }),\n \"String FormatString\": () => null,\n Script: context => {\n if (context.pos + /\\s*/.exec(context.textAfter)[0].length >= context.node.to) {\n let endBody = null;\n for (let cur = context.node, to = cur.to;;) {\n cur = cur.lastChild;\n if (!cur || cur.to != to)\n break;\n if (cur.type.name == \"Body\")\n endBody = cur;\n }\n if (endBody) {\n let bodyIndent = indentBody(context, endBody);\n if (bodyIndent != null)\n return bodyIndent;\n }\n }\n return context.continue();\n }\n }),\n /*@__PURE__*/foldNodeProp.add({\n \"ArrayExpression DictionaryExpression SetExpression TupleExpression\": foldInside,\n Body: (node, state) => ({ from: node.from + 1, to: node.to - (node.to == state.doc.length ? 0 : 1) })\n })\n ],\n }),\n languageData: {\n closeBrackets: {\n brackets: [\"(\", \"[\", \"{\", \"'\", '\"', \"'''\", '\"\"\"'],\n stringPrefixes: [\"f\", \"fr\", \"rf\", \"r\", \"u\", \"b\", \"br\", \"rb\",\n \"F\", \"FR\", \"RF\", \"R\", \"U\", \"B\", \"BR\", \"RB\"]\n },\n commentTokens: { line: \"#\" },\n indentOnInput: /^\\s*([\\}\\]\\)]|else:|elif |except |finally:)$/\n }\n});\n/**\nPython language support.\n*/\nfunction python() {\n return new LanguageSupport(pythonLanguage, [\n pythonLanguage.data.of({ autocomplete: localCompletionSource }),\n pythonLanguage.data.of({ autocomplete: globalCompletion }),\n ]);\n}\n\nexport { globalCompletion, localCompletionSource, python, pythonLanguage };\n"],"names":["newline","carriageReturn","braceOpen","backslash","bracketed","Set","isLineBreak","ch","newlines","input","stack","prev","next","acceptToken","context","depth","peek","canShift","spaces","advance","contextual","indentation","cDepth","chars","IndentLevel","parent","this","hash","topIndent","trackIndent","start","reduce","term","has","shift","space","i","length","charCodeAt","countIndent","read","pos","legacyPrint","test","String","fromCharCode","off","formatString","quote","len","content","brace","end","formatString1","formatString2","formatString1l","formatString2l","pythonHighlighting","import","Boolean","None","VariableName","PropertyName","Comment","Number","FormatString","UpdateOp","BitOp","CompareOp","AssignOp","Ellipsis","At","spec_identifier","__proto__","await","or","and","in","not","is","if","else","lambda","yield","from","async","for","True","False","del","pass","break","continue","return","raise","as","global","nonlocal","assert","type","elif","while","try","except","finally","with","def","class","match","case","parser","version","states","stateData","goto","nodeNames","maxTerm","nodeProps","propSources","skippedNodes","repeatNodeCount","tokenData","tokenizers","topRules","specialized","get","value","tokenPrec","cache","ScopeNodes","defID","node","outer","id","getChild","gatherCompletions","FunctionDefinition","ClassDefinition","ForStatement","child","firstChild","nextSibling","name","ImportStatement","_node","_a","_b","isFrom","AssignStatement","ParamList","CapturePattern","AsPattern","getScope","doc","cached","completions","top","sliceString","to","push","label","cursor","iterate","gather","c","set","Identifier","dontComplete","localCompletionSource","inner","state","resolveInner","indexOf","isWord","sliceDoc","explicit","options","concat","validFor","globals","map","n","snippets","detail","globalCompletion","indentBody","base","baseIndentFor","line","lineAt","text","lineIndent","textAfter","unit","pythonLanguage","configure","props","Body","IfStatement","cx","baseIndent","TryStatement","closing","Script","exec","endBody","cur","lastChild","bodyIndent","languageData","closeBrackets","brackets","stringPrefixes","commentTokens","indentOnInput","python","data","of","autocomplete"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/2411.index.js b/book/_build/html/_static/2411.index.js new file mode 100644 index 0000000..76390a7 --- /dev/null +++ b/book/_build/html/_static/2411.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[2411],{32411:(t,e,n)=>{function r(t){function e(t,e){t.cmdState.push(e)}function n(t){return t.cmdState.length>0?t.cmdState[t.cmdState.length-1]:null}function r(t,e,n){return function(){this.name=t,this.bracketNo=0,this.style=e,this.styles=n,this.argument=null,this.styleIdentifier=function(){return this.styles[this.bracketNo-1]||null},this.openBracket=function(){return this.bracketNo++,"bracket"},this.closeBracket=function(){}}}var a={};function i(t,e){t.f=e}function c(t,r){var c;if(t.match(/^\\[a-zA-Z@\xc0-\u1fff\u2060-\uffff]+/)){var f=t.current().slice(1);return e(r,c=new(c=a.hasOwnProperty(f)?a[f]:a.DEFAULT)),i(r,o),c.style}if(t.match(/^\\[$&%#{}_]/))return"tag";if(t.match(/^\\[,;!\/\\]/))return"tag";if(t.match("\\["))return i(r,(function(t,e){return u(t,e,"\\]")})),"keyword";if(t.match("\\("))return i(r,(function(t,e){return u(t,e,"\\)")})),"keyword";if(t.match("$$"))return i(r,(function(t,e){return u(t,e,"$$")})),"keyword";if(t.match("$"))return i(r,(function(t,e){return u(t,e,"$")})),"keyword";var m=t.next();return"%"==m?(t.skipToEnd(),"comment"):"}"==m||"]"==m?(c=n(r))?(c.closeBracket(m),i(r,o),"bracket"):"error":"{"==m||"["==m?(e(r,c=new(c=a.DEFAULT)),"bracket"):/\d/.test(m)?(t.eatWhile(/[\w.%]/),"atom"):(t.eatWhile(/[\w\-_]/),c=function(t){for(var e=t.cmdState,n=e.length-1;n>=0;n--){var r=e[n];if("DEFAULT"!=r.name)return r}return{styleIdentifier:function(){return null}}}(r),"begin"==c.name&&(c.argument=t.current()),c.styleIdentifier())}function u(t,e,n){if(t.eatSpace())return null;if(n&&t.match(n))return i(e,c),"keyword";if(t.match(/^\\[a-zA-Z@]+/))return"tag";if(t.match(/^[a-zA-Z]+/))return"variableName.special";if(t.match(/^\\[$&%#{}_]/))return"tag";if(t.match(/^\\[,;!\/]/))return"tag";if(t.match(/^[\^_&]/))return"tag";if(t.match(/^[+\-<>|=,\/@!*:;'"`~#?]/))return null;if(t.match(/^(\d+\.\d*|\d*\.\d+|\d+)/))return"number";var r=t.next();return"{"==r||"}"==r||"["==r||"]"==r||"("==r||")"==r?"bracket":"%"==r?(t.skipToEnd(),"comment"):"error"}function o(t,e){var r=t.peek();return"{"==r||"["==r?(n(e).openBracket(r),t.eat(r),i(e,c),"bracket"):/[ \t\r]/.test(r)?(t.eat(r),null):(i(e,c),function(t){var e=t.cmdState.pop();e&&e.closeBracket()}(e),c(t,e))}return a.importmodule=r("importmodule","tag",["string","builtin"]),a.documentclass=r("documentclass","tag",["","atom"]),a.usepackage=r("usepackage","tag",["atom"]),a.begin=r("begin","tag",["atom"]),a.end=r("end","tag",["atom"]),a.label=r("label","tag",["atom"]),a.ref=r("ref","tag",["atom"]),a.eqref=r("eqref","tag",["atom"]),a.cite=r("cite","tag",["atom"]),a.bibitem=r("bibitem","tag",["atom"]),a.Bibitem=r("Bibitem","tag",["atom"]),a.RBibitem=r("RBibitem","tag",["atom"]),a.DEFAULT=function(){this.name="DEFAULT",this.style="tag",this.styleIdentifier=this.openBracket=this.closeBracket=function(){}},{name:"stex",startState:function(){return{cmdState:[],f:t?function(t,e){return u(t,e)}:c}},copyState:function(t){return{cmdState:t.cmdState.slice(),f:t.f}},token:function(t,e){return e.f(t,e)},blankLine:function(t){t.f=c,t.cmdState.length=0},languageData:{commentTokens:{line:"%"}}}}n.r(e),n.d(e,{stex:()=>a,stexMath:()=>i});const a=r(!1),i=r(!0)}}]); +//# sourceMappingURL=2411.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/2411.index.js.map b/book/_build/html/_static/2411.index.js.map new file mode 100644 index 0000000..22f22d1 --- /dev/null +++ b/book/_build/html/_static/2411.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2411.index.js","mappings":"+FAAA,SAASA,EAAOC,GACd,SAASC,EAAYC,EAAOC,GAC1BD,EAAME,SAASC,KAAKF,EACtB,CAEA,SAASG,EAAYJ,GACnB,OAAIA,EAAME,SAASG,OAAS,EACnBL,EAAME,SAASF,EAAME,SAASG,OAAS,GAEvC,IAEX,CAsBA,SAASC,EAAiBC,EAAYC,EAAUC,GAC9C,OAAO,WACLC,KAAKC,KAAOJ,EACZG,KAAKE,UAAY,EACjBF,KAAKG,MAAQL,EACbE,KAAKD,OAASA,EACdC,KAAKI,SAAW,KAEhBJ,KAAKK,gBAAkB,WACrB,OAAOL,KAAKD,OAAOC,KAAKE,UAAY,IAAM,IAC5C,EACAF,KAAKM,YAAc,WAEjB,OADAN,KAAKE,YACE,SACT,EACAF,KAAKO,aAAe,WAAY,CAClC,CACF,CAEA,IAAIC,EAAU,CAAC,EAuBf,SAASC,EAASnB,EAAOoB,GACvBpB,EAAMoB,EAAIA,CACZ,CAGA,SAASC,EAAOC,EAAQtB,GACtB,IAAIuB,EAEJ,GAAID,EAAOE,MAAM,yCAA0C,CACzD,IAAIC,EAAUH,EAAOI,UAAUC,MAAM,GAKrC,OAFA5B,EAAYC,EADZuB,EAAO,IADPA,EAAOL,EAAQU,eAAeH,GAAWP,EAAQO,GAAWP,EAAiB,UAG7EC,EAASnB,EAAO6B,GACTN,EAAKV,KACd,CAGA,GAAIS,EAAOE,MAAM,gBACf,MAAO,MAIT,GAAIF,EAAOE,MAAM,gBACf,MAAO,MAIT,GAAIF,EAAOE,MAAM,OAEf,OADAL,EAASnB,GAAO,SAASsB,EAAQtB,GAAQ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B,QAAIZ,EAAiB,UAAa,MAAO,CAAC,SAC7DY,EAAmB,QAAIZ,EAAiB,UAAa,MAAO,CAAC,SAC7DY,EAAmB,SAAIZ,EAAiB,WAAa,MAAO,CAAC,SAE7DY,EAAiB,QAAI,WACnBR,KAAKC,KAAO,UACZD,KAAKG,MAAQ,MAEbH,KAAKK,gBAAkBL,KAAKM,YAAcN,KAAKO,aAAe,WAAY,CAC5E,EA8IO,CACLN,KAAM,OACNkC,WAAY,WAEV,MAAO,CACL3C,SAAU,GACVkB,EAHMtB,EAAW,SAASwB,EAAQtB,GAAQ,OAAO8B,EAAWR,EAAQtB,EAAQ,EAAIqB,EAKpF,EACAyB,UAAW,SAASC,GAClB,MAAO,CACL7C,SAAU6C,EAAE7C,SAASyB,QACrBP,EAAG2B,EAAE3B,EAET,EACA4B,MAAO,SAASC,EAAQjD,GACtB,OAAOA,EAAMoB,EAAE6B,EAAQjD,EACzB,EACAkD,UAAW,SAASlD,GAClBA,EAAMoB,EAAIC,EACVrB,EAAME,SAASG,OAAS,CAC1B,EACA8C,aAAc,CACZC,cAAe,CAACC,KAAM,MAG5B,C,0CAEO,MAAMC,EAAOzD,GAAO,GACd0D,EAAW1D,GAAO,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/stex.js"],"sourcesContent":["function mkStex(mathMode) {\n function pushCommand(state, command) {\n state.cmdState.push(command);\n }\n\n function peekCommand(state) {\n if (state.cmdState.length > 0) {\n return state.cmdState[state.cmdState.length - 1];\n } else {\n return null;\n }\n }\n\n function popCommand(state) {\n var plug = state.cmdState.pop();\n if (plug) {\n plug.closeBracket();\n }\n }\n\n // returns the non-default plugin closest to the end of the list\n function getMostPowerful(state) {\n var context = state.cmdState;\n for (var i = context.length - 1; i >= 0; i--) {\n var plug = context[i];\n if (plug.name == \"DEFAULT\") {\n continue;\n }\n return plug;\n }\n return { styleIdentifier: function() { return null; } };\n }\n\n function addPluginPattern(pluginName, cmdStyle, styles) {\n return function () {\n this.name = pluginName;\n this.bracketNo = 0;\n this.style = cmdStyle;\n this.styles = styles;\n this.argument = null; // \\begin and \\end have arguments that follow. These are stored in the plugin\n\n this.styleIdentifier = function() {\n return this.styles[this.bracketNo - 1] || null;\n };\n this.openBracket = function() {\n this.bracketNo++;\n return \"bracket\";\n };\n this.closeBracket = function() {};\n };\n }\n\n var plugins = {};\n\n plugins[\"importmodule\"] = addPluginPattern(\"importmodule\", \"tag\", [\"string\", \"builtin\"]);\n plugins[\"documentclass\"] = addPluginPattern(\"documentclass\", \"tag\", [\"\", \"atom\"]);\n plugins[\"usepackage\"] = addPluginPattern(\"usepackage\", \"tag\", [\"atom\"]);\n plugins[\"begin\"] = addPluginPattern(\"begin\", \"tag\", [\"atom\"]);\n plugins[\"end\"] = addPluginPattern(\"end\", \"tag\", [\"atom\"]);\n\n plugins[\"label\" ] = addPluginPattern(\"label\" , \"tag\", [\"atom\"]);\n plugins[\"ref\" ] = addPluginPattern(\"ref\" , \"tag\", [\"atom\"]);\n plugins[\"eqref\" ] = addPluginPattern(\"eqref\" , \"tag\", [\"atom\"]);\n plugins[\"cite\" ] = addPluginPattern(\"cite\" , \"tag\", [\"atom\"]);\n plugins[\"bibitem\" ] = addPluginPattern(\"bibitem\" , \"tag\", [\"atom\"]);\n plugins[\"Bibitem\" ] = addPluginPattern(\"Bibitem\" , \"tag\", [\"atom\"]);\n plugins[\"RBibitem\" ] = addPluginPattern(\"RBibitem\" , \"tag\", [\"atom\"]);\n\n plugins[\"DEFAULT\"] = function () {\n this.name = \"DEFAULT\";\n this.style = \"tag\";\n\n this.styleIdentifier = this.openBracket = this.closeBracket = function() {};\n };\n\n function setState(state, f) {\n state.f = f;\n }\n\n // called when in a normal (no environment) context\n function normal(source, state) {\n var plug;\n // Do we look like '\\command' ? If so, attempt to apply the plugin 'command'\n if (source.match(/^\\\\[a-zA-Z@\\xc0-\\u1fff\\u2060-\\uffff]+/)) {\n var cmdName = source.current().slice(1);\n plug = plugins.hasOwnProperty(cmdName) ? plugins[cmdName] : plugins[\"DEFAULT\"];\n plug = new plug();\n pushCommand(state, plug);\n setState(state, beginParams);\n return plug.style;\n }\n\n // escape characters\n if (source.match(/^\\\\[$&%#{}_]/)) {\n return \"tag\";\n }\n\n // white space control characters\n if (source.match(/^\\\\[,;!\\/\\\\]/)) {\n return \"tag\";\n }\n\n // find if we're starting various math modes\n if (source.match(\"\\\\[\")) {\n setState(state, function(source, state){ return inMathMode(source, state, \"\\\\]\"); });\n return \"keyword\";\n }\n if (source.match(\"\\\\(\")) {\n setState(state, function(source, state){ return inMathMode(source, state, \"\\\\)\"); });\n return \"keyword\";\n }\n if (source.match(\"$$\")) {\n setState(state, function(source, state){ return inMathMode(source, state, \"$$\"); });\n return \"keyword\";\n }\n if (source.match(\"$\")) {\n setState(state, function(source, state){ return inMathMode(source, state, \"$\"); });\n return \"keyword\";\n }\n\n var ch = source.next();\n if (ch == \"%\") {\n source.skipToEnd();\n return \"comment\";\n } else if (ch == '}' || ch == ']') {\n plug = peekCommand(state);\n if (plug) {\n plug.closeBracket(ch);\n setState(state, beginParams);\n } else {\n return \"error\";\n }\n return \"bracket\";\n } else if (ch == '{' || ch == '[') {\n plug = plugins[\"DEFAULT\"];\n plug = new plug();\n pushCommand(state, plug);\n return \"bracket\";\n } else if (/\\d/.test(ch)) {\n source.eatWhile(/[\\w.%]/);\n return \"atom\";\n } else {\n source.eatWhile(/[\\w\\-_]/);\n plug = getMostPowerful(state);\n if (plug.name == 'begin') {\n plug.argument = source.current();\n }\n return plug.styleIdentifier();\n }\n }\n\n function inMathMode(source, state, endModeSeq) {\n if (source.eatSpace()) {\n return null;\n }\n if (endModeSeq && source.match(endModeSeq)) {\n setState(state, normal);\n return \"keyword\";\n }\n if (source.match(/^\\\\[a-zA-Z@]+/)) {\n return \"tag\";\n }\n if (source.match(/^[a-zA-Z]+/)) {\n return \"variableName.special\";\n }\n // escape characters\n if (source.match(/^\\\\[$&%#{}_]/)) {\n return \"tag\";\n }\n // white space control characters\n if (source.match(/^\\\\[,;!\\/]/)) {\n return \"tag\";\n }\n // special math-mode characters\n if (source.match(/^[\\^_&]/)) {\n return \"tag\";\n }\n // non-special characters\n if (source.match(/^[+\\-<>|=,\\/@!*:;'\"`~#?]/)) {\n return null;\n }\n if (source.match(/^(\\d+\\.\\d*|\\d*\\.\\d+|\\d+)/)) {\n return \"number\";\n }\n var ch = source.next();\n if (ch == \"{\" || ch == \"}\" || ch == \"[\" || ch == \"]\" || ch == \"(\" || ch == \")\") {\n return \"bracket\";\n }\n\n if (ch == \"%\") {\n source.skipToEnd();\n return \"comment\";\n }\n return \"error\";\n }\n\n function beginParams(source, state) {\n var ch = source.peek(), lastPlug;\n if (ch == '{' || ch == '[') {\n lastPlug = peekCommand(state);\n lastPlug.openBracket(ch);\n source.eat(ch);\n setState(state, normal);\n return \"bracket\";\n }\n if (/[ \\t\\r]/.test(ch)) {\n source.eat(ch);\n return null;\n }\n setState(state, normal);\n popCommand(state);\n\n return normal(source, state);\n }\n\n return {\n name: \"stex\",\n startState: function() {\n var f = mathMode ? function(source, state){ return inMathMode(source, state); } : normal;\n return {\n cmdState: [],\n f: f\n };\n },\n copyState: function(s) {\n return {\n cmdState: s.cmdState.slice(),\n f: s.f\n };\n },\n token: function(stream, state) {\n return state.f(stream, state);\n },\n blankLine: function(state) {\n state.f = normal;\n state.cmdState.length = 0;\n },\n languageData: {\n commentTokens: {line: \"%\"}\n }\n };\n};\n\nexport const stex = mkStex(false)\nexport const stexMath = mkStex(true)\n"],"names":["mkStex","mathMode","pushCommand","state","command","cmdState","push","peekCommand","length","addPluginPattern","pluginName","cmdStyle","styles","this","name","bracketNo","style","argument","styleIdentifier","openBracket","closeBracket","plugins","setState","f","normal","source","plug","match","cmdName","current","slice","hasOwnProperty","beginParams","inMathMode","ch","next","skipToEnd","test","eatWhile","context","i","getMostPowerful","endModeSeq","eatSpace","peek","eat","pop","popCommand","startState","copyState","s","token","stream","blankLine","languageData","commentTokens","line","stex","stexMath"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/2444.index.js b/book/_build/html/_static/2444.index.js new file mode 100644 index 0000000..50935fa --- /dev/null +++ b/book/_build/html/_static/2444.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[2444],{12444:(e,t,n)=>{n.r(t),n.d(t,{cypher:()=>h});var r,a=function(e){return new RegExp("^(?:"+e.join("|")+")$","i")},o=function(e){r=null;var t=e.next();if('"'===t)return e.match(/^.*?"/),"string";if("'"===t)return e.match(/^.*?'/),"string";if(/[{}\(\),\.;\[\]]/.test(t))return r=t,"punctuation";if("/"===t&&e.eat("/"))return e.skipToEnd(),"comment";if(u.test(t))return e.eatWhile(u),null;if(e.eatWhile(/[_\w\d]/),e.eat(":"))return e.eatWhile(/[\w\d_\-]/),"atom";var n=e.current();return l.test(n)?"builtin":c.test(n)?"def":d.test(n)||p.test(n)?"keyword":"variable"},s=function(e,t,n){return e.context={prev:e.context,indent:e.indent,col:n,type:t}},i=function(e){return e.indent=e.context.indent,e.context=e.context.prev},l=a(["abs","acos","allShortestPaths","asin","atan","atan2","avg","ceil","coalesce","collect","cos","cot","count","degrees","e","endnode","exp","extract","filter","floor","haversin","head","id","keys","labels","last","left","length","log","log10","lower","ltrim","max","min","node","nodes","percentileCont","percentileDisc","pi","radians","rand","range","reduce","rel","relationship","relationships","replace","reverse","right","round","rtrim","shortestPath","sign","sin","size","split","sqrt","startnode","stdev","stdevp","str","substring","sum","tail","tan","timestamp","toFloat","toInt","toString","trim","type","upper"]),c=a(["all","and","any","contains","exists","has","in","none","not","or","single","xor"]),d=a(["as","asc","ascending","assert","by","case","commit","constraint","create","csv","cypher","delete","desc","descending","detach","distinct","drop","else","end","ends","explain","false","fieldterminator","foreach","from","headers","in","index","is","join","limit","load","match","merge","null","on","optional","order","periodic","profile","remove","return","scan","set","skip","start","starts","then","true","union","unique","unwind","using","when","where","with","call","yield"]),p=a(["access","active","assign","all","alter","as","catalog","change","copy","create","constraint","constraints","current","database","databases","dbms","default","deny","drop","element","elements","exists","from","grant","graph","graphs","if","index","indexes","label","labels","management","match","name","names","new","node","nodes","not","of","on","or","password","populated","privileges","property","read","relationship","relationships","remove","replace","required","revoke","role","roles","set","show","start","status","stop","suspended","to","traverse","type","types","user","users","with","write"]),u=/[*+\-<>=&|~%^]/;const h={name:"cypher",startState:function(){return{tokenize:o,context:null,indent:0,col:0}},token:function(e,t){if(e.sol()&&(t.context&&null==t.context.align&&(t.context.align=!1),t.indent=e.indentation()),e.eatSpace())return null;var n=t.tokenize(e,t);if("comment"!==n&&t.context&&null==t.context.align&&"pattern"!==t.context.type&&(t.context.align=!0),"("===r)s(t,")",e.column());else if("["===r)s(t,"]",e.column());else if("{"===r)s(t,"}",e.column());else if(/[\]\}\)]/.test(r)){for(;t.context&&"pattern"===t.context.type;)i(t);t.context&&r===t.context.type&&i(t)}else"."===r&&t.context&&"pattern"===t.context.type?i(t):/atom|string|variable/.test(n)&&t.context&&(/[\}\]]/.test(t.context.type)?s(t,"pattern",e.column()):"pattern"!==t.context.type||t.context.align||(t.context.align=!0,t.context.col=e.column()));return n},indent:function(e,t,n){var r=t&&t.charAt(0),a=e.context;if(/[\]\}]/.test(r))for(;a&&"pattern"===a.type;)a=a.prev;var o=a&&r===a.type;return a?"keywords"===a.type?null:a.align?a.col+(o?0:1):a.indent+(o?0:n.unit):0}}}}]); +//# sourceMappingURL=2444.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/2444.index.js.map b/book/_build/html/_static/2444.index.js.map new file mode 100644 index 0000000..1e5f25b --- /dev/null +++ b/book/_build/html/_static/2444.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2444.index.js","mappings":"4HAAA,IAiDIA,EAjDAC,EAAa,SAASC,GACxB,OAAO,IAAIC,OAAO,OAASD,EAAME,KAAK,KAAO,KAAM,IACrD,EAEIC,EAAY,SAASC,GACvBN,EAAU,KACV,IAAIO,EAAKD,EAAOE,OAChB,GAAU,MAAND,EAE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://thebe/../../node_modules/@codemirror/legacy-modes/mode/cypher.js"],"sourcesContent":["var wordRegexp = function(words) {\n return new RegExp(\"^(?:\" + words.join(\"|\") + \")$\", \"i\");\n};\n\nvar tokenBase = function(stream/*, state*/) {\n curPunc = null;\n var ch = stream.next();\n if (ch ==='\"') {\n stream.match(/^.*?\"/);\n return \"string\";\n }\n if (ch === \"'\") {\n stream.match(/^.*?'/);\n return \"string\";\n }\n if (/[{}\\(\\),\\.;\\[\\]]/.test(ch)) {\n curPunc = ch;\n return \"punctuation\";\n } else if (ch === \"/\" && stream.eat(\"/\")) {\n stream.skipToEnd();\n return \"comment\";\n } else if (operatorChars.test(ch)) {\n stream.eatWhile(operatorChars);\n return null;\n } else {\n stream.eatWhile(/[_\\w\\d]/);\n if (stream.eat(\":\")) {\n stream.eatWhile(/[\\w\\d_\\-]/);\n return \"atom\";\n }\n var word = stream.current();\n if (funcs.test(word)) return \"builtin\";\n if (preds.test(word)) return \"def\";\n if (keywords.test(word) || systemKeywords.test(word)) return \"keyword\";\n return \"variable\";\n }\n};\nvar pushContext = function(state, type, col) {\n return state.context = {\n prev: state.context,\n indent: state.indent,\n col: col,\n type: type\n };\n};\nvar popContext = function(state) {\n state.indent = state.context.indent;\n return state.context = state.context.prev;\n};\nvar curPunc;\nvar funcs = wordRegexp([\"abs\", \"acos\", \"allShortestPaths\", \"asin\", \"atan\", \"atan2\", \"avg\", \"ceil\", \"coalesce\", \"collect\", \"cos\", \"cot\", \"count\", \"degrees\", \"e\", \"endnode\", \"exp\", \"extract\", \"filter\", \"floor\", \"haversin\", \"head\", \"id\", \"keys\", \"labels\", \"last\", \"left\", \"length\", \"log\", \"log10\", \"lower\", \"ltrim\", \"max\", \"min\", \"node\", \"nodes\", \"percentileCont\", \"percentileDisc\", \"pi\", \"radians\", \"rand\", \"range\", \"reduce\", \"rel\", \"relationship\", \"relationships\", \"replace\", \"reverse\", \"right\", \"round\", \"rtrim\", \"shortestPath\", \"sign\", \"sin\", \"size\", \"split\", \"sqrt\", \"startnode\", \"stdev\", \"stdevp\", \"str\", \"substring\", \"sum\", \"tail\", \"tan\", \"timestamp\", \"toFloat\", \"toInt\", \"toString\", \"trim\", \"type\", \"upper\"]);\nvar preds = wordRegexp([\"all\", \"and\", \"any\", \"contains\", \"exists\", \"has\", \"in\", \"none\", \"not\", \"or\", \"single\", \"xor\"]);\nvar keywords = wordRegexp([\"as\", \"asc\", \"ascending\", \"assert\", \"by\", \"case\", \"commit\", \"constraint\", \"create\", \"csv\", \"cypher\", \"delete\", \"desc\", \"descending\", \"detach\", \"distinct\", \"drop\", \"else\", \"end\", \"ends\", \"explain\", \"false\", \"fieldterminator\", \"foreach\", \"from\", \"headers\", \"in\", \"index\", \"is\", \"join\", \"limit\", \"load\", \"match\", \"merge\", \"null\", \"on\", \"optional\", \"order\", \"periodic\", \"profile\", \"remove\", \"return\", \"scan\", \"set\", \"skip\", \"start\", \"starts\", \"then\", \"true\", \"union\", \"unique\", \"unwind\", \"using\", \"when\", \"where\", \"with\", \"call\", \"yield\"]);\nvar systemKeywords = wordRegexp([\"access\", \"active\", \"assign\", \"all\", \"alter\", \"as\", \"catalog\", \"change\", \"copy\", \"create\", \"constraint\", \"constraints\", \"current\", \"database\", \"databases\", \"dbms\", \"default\", \"deny\", \"drop\", \"element\", \"elements\", \"exists\", \"from\", \"grant\", \"graph\", \"graphs\", \"if\", \"index\", \"indexes\", \"label\", \"labels\", \"management\", \"match\", \"name\", \"names\", \"new\", \"node\", \"nodes\", \"not\", \"of\", \"on\", \"or\", \"password\", \"populated\", \"privileges\", \"property\", \"read\", \"relationship\", \"relationships\", \"remove\", \"replace\", \"required\", \"revoke\", \"role\", \"roles\", \"set\", \"show\", \"start\", \"status\", \"stop\", \"suspended\", \"to\", \"traverse\", \"type\", \"types\", \"user\", \"users\", \"with\", \"write\"]);\nvar operatorChars = /[*+\\-<>=&|~%^]/;\n\nexport const cypher = {\n name: \"cypher\",\n startState: function() {\n return {\n tokenize: tokenBase,\n context: null,\n indent: 0,\n col: 0\n };\n },\n token: function(stream, state) {\n if (stream.sol()) {\n if (state.context && (state.context.align == null)) {\n state.context.align = false;\n }\n state.indent = stream.indentation();\n }\n if (stream.eatSpace()) {\n return null;\n }\n var style = state.tokenize(stream, state);\n if (style !== \"comment\" && state.context && (state.context.align == null) && state.context.type !== \"pattern\") {\n state.context.align = true;\n }\n if (curPunc === \"(\") {\n pushContext(state, \")\", stream.column());\n } else if (curPunc === \"[\") {\n pushContext(state, \"]\", stream.column());\n } else if (curPunc === \"{\") {\n pushContext(state, \"}\", stream.column());\n } else if (/[\\]\\}\\)]/.test(curPunc)) {\n while (state.context && state.context.type === \"pattern\") {\n popContext(state);\n }\n if (state.context && curPunc === state.context.type) {\n popContext(state);\n }\n } else if (curPunc === \".\" && state.context && state.context.type === \"pattern\") {\n popContext(state);\n } else if (/atom|string|variable/.test(style) && state.context) {\n if (/[\\}\\]]/.test(state.context.type)) {\n pushContext(state, \"pattern\", stream.column());\n } else if (state.context.type === \"pattern\" && !state.context.align) {\n state.context.align = true;\n state.context.col = stream.column();\n }\n }\n return style;\n },\n indent: function(state, textAfter, cx) {\n var firstChar = textAfter && textAfter.charAt(0);\n var context = state.context;\n if (/[\\]\\}]/.test(firstChar)) {\n while (context && context.type === \"pattern\") {\n context = context.prev;\n }\n }\n var closing = context && firstChar === context.type;\n if (!context) return 0;\n if (context.type === \"keywords\") return null\n if (context.align) return context.col + (closing ? 0 : 1);\n return context.indent + (closing ? 0 : cx.unit);\n }\n};\n"],"names":["curPunc","wordRegexp","words","RegExp","join","tokenBase","stream","ch","next","match","test","eat","skipToEnd","operatorChars","eatWhile","word","current","funcs","preds","keywords","systemKeywords","pushContext","state","type","col","context","prev","indent","popContext","cypher","name","startState","tokenize","token","sol","align","indentation","eatSpace","style","column","textAfter","cx","firstChar","charAt","closing","unit"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/2519.index.js b/book/_build/html/_static/2519.index.js new file mode 100644 index 0000000..830bc69 --- /dev/null +++ b/book/_build/html/_static/2519.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[2519],{62519:(e,t,a)=>{a.r(t),a.d(t,{spreadsheet:()=>s});const s={name:"spreadsheet",startState:function(){return{stringType:null,stack:[]}},token:function(e,t){if(e){switch(0===t.stack.length&&('"'!=e.peek()&&"'"!=e.peek()||(t.stringType=e.peek(),e.next(),t.stack.unshift("string"))),t.stack[0]){case"string":for(;"string"===t.stack[0]&&!e.eol();)e.peek()===t.stringType?(e.next(),t.stack.shift()):"\\"===e.peek()?(e.next(),e.next()):e.match(/^.[^\\\"\']*/);return"string";case"characterClass":for(;"characterClass"===t.stack[0]&&!e.eol();)e.match(/^[^\]\\]+/)||e.match(/^\\./)||t.stack.shift();return"operator"}var a=e.peek();switch(a){case"[":return e.next(),t.stack.unshift("characterClass"),"bracket";case":":return e.next(),"operator";case"\\":return e.match(/\\[a-z]+/)?"string.special":(e.next(),"atom");case".":case",":case";":case"*":case"-":case"+":case"^":case"<":case"/":case"=":return e.next(),"atom";case"$":return e.next(),"builtin"}return e.match(/\d+/)?e.match(/^\w+/)?"error":"number":e.match(/^[a-zA-Z_]\w*/)?e.match(/(?=[\(.])/,!1)?"keyword":"variable":-1!=["[","]","(",")","{","}"].indexOf(a)?(e.next(),"bracket"):(e.eatSpace()||e.next(),null)}}}}}]); +//# sourceMappingURL=2519.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/2519.index.js.map b/book/_build/html/_static/2519.index.js.map new file mode 100644 index 0000000..d373d5f --- /dev/null +++ b/book/_build/html/_static/2519.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2519.index.js","mappings":"iIAAO,MAAMA,EAAc,CACzBC,KAAM,cAENC,WAAY,WACV,MAAO,CACLC,WAAY,KACZC,MAAO,GAEX,EACAC,MAAO,SAAUC,EAAQC,GACvB,GAAKD,EAAL,CAcA,OAX2B,IAAvBC,EAAMH,MAAMI,SAEQ,KAAjBF,EAAOG,QAAoC,KAAjBH,EAAOG,SACpCF,EAAMJ,WAAaG,EAAOG,OAC1BH,EAAOI,OACPH,EAAMH,MAAMO,QAAQ,YAMhBJ,EAAMH,MAAM,IACpB,IAAK,SACH,KAA0B,WAAnBG,EAAMH,MAAM,KAAoBE,EAAOM,OACxCN,EAAOG,SAAWF,EAAMJ,YAC1BG,EAAOI,OACPH,EAAMH,MAAMS,SACe,OAAlBP,EAAOG,QAChBH,EAAOI,OACPJ,EAAOI,QAEPJ,EAAOQ,MAAM,gBAGjB,MAAO,SAET,IAAK,iBACH,KAA0B,mBAAnBP,EAAMH,MAAM,KAA4BE,EAAOM,OAC9CN,EAAOQ,MAAM,cAAgBR,EAAOQ,MAAM,SAC9CP,EAAMH,MAAMS,QAEhB,MAAO,WAGT,IAAIJ,EAAOH,EAAOG,OAGlB,OAAQA,GACR,IAAK,IAGH,OAFAH,EAAOI,OACPH,EAAMH,MAAMO,QAAQ,kBACb,UACT,IAAK,IAEH,OADAL,EAAOI,OACA,WACT,IAAK,KACH,OAAIJ,EAAOQ,MAAM,YAAoB,kBAEnCR,EAAOI,OACA,QAEX,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IAEH,OADAJ,EAAOI,OACA,OACT,IAAK,IAEH,OADAJ,EAAOI,OACA,UAGT,OAAIJ,EAAOQ,MAAM,OACXR,EAAOQ,MAAM,QAAgB,QAC1B,SACER,EAAOQ,MAAM,iBAClBR,EAAOQ,MAAM,aAAa,GAAe,UACtC,YACmD,GAAjD,CAAC,IAAK,IAAK,IAAK,IAAK,IAAK,KAAKC,QAAQN,IAChDH,EAAOI,OACA,YACGJ,EAAOU,YACjBV,EAAOI,OAEF,KAnFY,CAoFrB,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/spreadsheet.js"],"sourcesContent":["export const spreadsheet = {\n name: \"spreadsheet\",\n\n startState: function () {\n return {\n stringType: null,\n stack: []\n };\n },\n token: function (stream, state) {\n if (!stream) return;\n\n //check for state changes\n if (state.stack.length === 0) {\n //strings\n if ((stream.peek() == '\"') || (stream.peek() == \"'\")) {\n state.stringType = stream.peek();\n stream.next(); // Skip quote\n state.stack.unshift(\"string\");\n }\n }\n\n //return state\n //stack has\n switch (state.stack[0]) {\n case \"string\":\n while (state.stack[0] === \"string\" && !stream.eol()) {\n if (stream.peek() === state.stringType) {\n stream.next(); // Skip quote\n state.stack.shift(); // Clear flag\n } else if (stream.peek() === \"\\\\\") {\n stream.next();\n stream.next();\n } else {\n stream.match(/^.[^\\\\\\\"\\']*/);\n }\n }\n return \"string\";\n\n case \"characterClass\":\n while (state.stack[0] === \"characterClass\" && !stream.eol()) {\n if (!(stream.match(/^[^\\]\\\\]+/) || stream.match(/^\\\\./)))\n state.stack.shift();\n }\n return \"operator\";\n }\n\n var peek = stream.peek();\n\n //no stack\n switch (peek) {\n case \"[\":\n stream.next();\n state.stack.unshift(\"characterClass\");\n return \"bracket\";\n case \":\":\n stream.next();\n return \"operator\";\n case \"\\\\\":\n if (stream.match(/\\\\[a-z]+/)) return \"string.special\";\n else {\n stream.next();\n return \"atom\";\n }\n case \".\":\n case \",\":\n case \";\":\n case \"*\":\n case \"-\":\n case \"+\":\n case \"^\":\n case \"<\":\n case \"/\":\n case \"=\":\n stream.next();\n return \"atom\";\n case \"$\":\n stream.next();\n return \"builtin\";\n }\n\n if (stream.match(/\\d+/)) {\n if (stream.match(/^\\w+/)) return \"error\";\n return \"number\";\n } else if (stream.match(/^[a-zA-Z_]\\w*/)) {\n if (stream.match(/(?=[\\(.])/, false)) return \"keyword\";\n return \"variable\";\n } else if ([\"[\", \"]\", \"(\", \")\", \"{\", \"}\"].indexOf(peek) != -1) {\n stream.next();\n return \"bracket\";\n } else if (!stream.eatSpace()) {\n stream.next();\n }\n return null;\n }\n};\n"],"names":["spreadsheet","name","startState","stringType","stack","token","stream","state","length","peek","next","unshift","eol","shift","match","indexOf","eatSpace"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/2719.index.js b/book/_build/html/_static/2719.index.js new file mode 100644 index 0000000..6a4474f --- /dev/null +++ b/book/_build/html/_static/2719.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[2719],{22719:(e,t,n)=>{function r(e){return new RegExp("^(("+e.join(")|(")+"))\\b")}n.r(t),n.d(t,{cython:()=>u,mkPython:()=>l,python:()=>s});var i=r(["and","or","not","is"]),a=["as","assert","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","lambda","pass","raise","return","try","while","with","yield","in","False","True"],o=["abs","all","any","bin","bool","bytearray","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip","__import__","NotImplemented","Ellipsis","__debug__"];function c(e){return e.scopes[e.scopes.length-1]}function l(e){for(var t="error",n=e.delimiters||e.singleDelimiters||/^[\(\)\[\]\{\}@,:`=;\.\\]/,l=[e.singleOperators,e.doubleOperators,e.doubleDelimiters,e.tripleDelimiters,e.operators||/^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@]|\.\.\.)/],s=0;si?x(e,n):a0&&v(e,n)&&(o+=" "+t),o}return k(e,n)}function k(r,a,o){if(r.eatSpace())return null;if(!o&&r.match(/^#.*/))return"comment";if(r.match(/^[0-9\.]/,!1)){var c=!1;if(r.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)&&(c=!0),r.match(/^[\d_]+\.\d*/)&&(c=!0),r.match(/^\.\d+/)&&(c=!0),c)return r.eat(/J/i),"number";var s=!1;if(r.match(/^0x[0-9a-f_]+/i)&&(s=!0),r.match(/^0b[01_]+/i)&&(s=!0),r.match(/^0o[0-7_]+/i)&&(s=!0),r.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)&&(r.eat(/J/i),s=!0),r.match(/^0(?![\dx])/i)&&(s=!0),s)return r.eat(/L/i),"number"}if(r.match(h))return-1!==r.current().toLowerCase().indexOf("f")?(a.tokenize=function(n,r){for(;"rubf".indexOf(n.charAt(0).toLowerCase())>=0;)n=n.substr(1);var i=1==n.length,a="string";function o(e){return function(t,n){var r=k(t,n,!0);return"punctuation"==r&&("{"==t.current()?n.tokenize=o(e+1):"}"==t.current()&&(n.tokenize=e>1?o(e-1):c)),r}}function c(c,l){for(;!c.eol();)if(c.eatWhile(/[^'"\{\}\\]/),c.eat("\\")){if(c.next(),i&&c.eol())return a}else{if(c.match(n))return l.tokenize=r,a;if(c.match("{{"))return a;if(c.match("{",!1))return l.tokenize=o(0),c.current()?a:l.tokenize(c,l);if(c.match("}}"))return a;if(c.match("}"))return t;c.eat(/['"]/)}if(i){if(e.singleLineStringErrors)return t;l.tokenize=r}return a}return c.isString=!0,c}(r.current(),a.tokenize),a.tokenize(r,a)):(a.tokenize=function(n,r){for(;"rubf".indexOf(n.charAt(0).toLowerCase())>=0;)n=n.substr(1);var i=1==n.length,a="string";function o(o,c){for(;!o.eol();)if(o.eatWhile(/[^'"\\]/),o.eat("\\")){if(o.next(),i&&o.eol())return a}else{if(o.match(n))return c.tokenize=r,a;o.eat(/['"]/)}if(i){if(e.singleLineStringErrors)return t;c.tokenize=r}return a}return o.isString=!0,o}(r.current(),a.tokenize),a.tokenize(r,a));for(var u=0;u1&&c(t).offset>n;){if("py"!=c(t).type)return!0;t.scopes.pop()}return c(t).offset!=n}return{name:"python",startState:function(){return{tokenize:g,scopes:[{offset:0,type:"py",align:null}],indent:0,lastToken:null,lambda:!1,dedent:0}},token:function(e,n){var r=n.errorToken;r&&(n.errorToken=!1);var i=function(e,n){e.sol()&&(n.beginningOfLine=!0,n.dedent=!1);var r=n.tokenize(e,n),i=e.current();if(n.beginningOfLine&&"@"==i)return e.match(m,!1)?"meta":d?"operator":t;if(/\S/.test(i)&&(n.beginningOfLine=!1),"variable"!=r&&"builtin"!=r||"meta"!=n.lastToken||(r="meta"),"pass"!=i&&"return"!=i||(n.dedent=!0),"lambda"==i&&(n.lambda=!0),":"==i&&!n.lambda&&"py"==c(n).type&&e.match(/^\s*(?:#|$)/,!1)&&x(e,n),1==i.length&&!/string|comment/.test(r)){var a="[({".indexOf(i);if(-1!=a&&function(e,t,n){var r=e.match(/^[\s\[\{\(]*(?:#|$)/,!1)?null:e.column()+1;t.scopes.push({offset:t.indent+(u||e.indentUnit),type:n,align:r})}(e,n,"])}".slice(a,a+1)),-1!=(a="])}".indexOf(i))){if(c(n).type!=i)return t;n.indent=n.scopes.pop().offset-(u||e.indentUnit)}}return n.dedent&&e.eol()&&"py"==c(n).type&&n.scopes.length>1&&n.scopes.pop(),r}(e,n);return i&&"comment"!=i&&(n.lastToken="keyword"==i||"punctuation"==i?e.current():i),"punctuation"==i&&(i=null),e.eol()&&n.lambda&&(n.lambda=!1),r?t:i},indent:function(e,t,n){if(e.tokenize!=g)return e.tokenize.isString?null:0;var r=c(e),i=r.type==t.charAt(0)||"py"==r.type&&!e.dedent&&/^(else:|elif |except |finally:)/.test(t);return null!=r.align?r.align-(i?1:0):r.offset-(i?u||n.unit:0)},languageData:{autocomplete:a.concat(o).concat(["exec","print"]),indentOnInput:/^\s*([\}\]\)]|else:|elif |except |finally:)$/,commentTokens:{line:"#"},closeBrackets:{brackets:["(","[","{","'",'"',"'''",'"""']}}}}const s=l({}),u=l({extra_keywords:("by cdef cimport cpdef ctypedef enum except extern gil include nogil property public readonly struct union DEF IF ELIF ELSE","by cdef cimport cpdef ctypedef enum except extern gil include nogil property public readonly struct union DEF IF ELIF ELSE".split(" "))})}}]); +//# sourceMappingURL=2719.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/2719.index.js.map b/book/_build/html/_static/2719.index.js.map new file mode 100644 index 0000000..ba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AO9C,EADoBL,EAAMiC,OAASjC,EAAMC,OAAOuE,MAAMnC,QAAUtB,GAAiBe,EAAO4C,WAEtG,CACF,CAIA,OAHI1E,EAAMyC,QAAUX,EAAOmC,OAA4B,MAAnBlE,EAAIC,GAAOmC,MAAgBnC,EAAMC,OAAOC,OAAS,GACnFF,EAAMC,OAAOuE,MAER5B,CACT,CAmBgB4C,CAAW1D,EAAQ9B,GAQ/B,OANI4C,GAAkB,WAATA,IACX5C,EAAMgC,UAAsB,WAATY,GAA+B,eAATA,EAA0Bd,EAAOqB,UAAYP,GAC3E,eAATA,IAAwBA,EAAQ,MAEhCd,EAAOmC,OAASjE,EAAM+E,SACxB/E,EAAM+E,QAAS,GACVE,EAAS5E,EAAauC,CAC/B,EAEAX,OAAQ,SAASjC,EAAOyF,EAAWC,GACjC,GAAI1F,EAAMsD,UAAYzB,EACpB,OAAO7B,EAAMsD,SAASe,SAAW,KAAO,EAE1C,IAAIsB,EAAQ5F,EAAIC,GACZ4F,EAAUD,EAAMxD,MAAQsD,EAAUhC,OAAO,IAC3B,MAAdkC,EAAMxD,OAAiBnC,EAAMyC,QAAU,kCAAkC0C,KAAKM,GAClF,OAAmB,MAAfE,EAAMhB,MACDgB,EAAMhB,OAASiB,EAAU,EAAI,GAE7BD,EAAMtD,QAAUuD,EAAU7E,GAAiB2E,EAAGG,KAAO,EAChE,EAEAC,aAAc,CACZC,aAAclG,EAAeuB,OAAOtB,GAAgBsB,OAAO,CAAC,OAAQ,UACpE4E,cAAe,+CACfC,cAAe,CAACC,KAAM,KACtBC,cAAe,CAACC,SAAU,CAAC,IAAK,IAAK,IAAK,IAAK,IAAK,MAAO,SAGjE,CAIO,MAAMC,EAASlG,EAAS,CAAC,GAEnBmG,EAASnG,EAAS,CAC7BgB,gBAAsB,0PALeoF,MAAM,O","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/python.js"],"sourcesContent":["function wordRegexp(words) {\n return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\");\n}\n\nvar wordOperators = wordRegexp([\"and\", \"or\", \"not\", \"is\"]);\nvar commonKeywords = [\"as\", \"assert\", \"break\", \"class\", \"continue\",\n \"def\", \"del\", \"elif\", \"else\", \"except\", \"finally\",\n \"for\", \"from\", \"global\", \"if\", \"import\",\n \"lambda\", \"pass\", \"raise\", \"return\",\n \"try\", \"while\", \"with\", \"yield\", \"in\", \"False\", \"True\"];\nvar commonBuiltins = [\"abs\", \"all\", \"any\", \"bin\", \"bool\", \"bytearray\", \"callable\", \"chr\",\n \"classmethod\", \"compile\", \"complex\", \"delattr\", \"dict\", \"dir\", \"divmod\",\n \"enumerate\", \"eval\", \"filter\", \"float\", \"format\", \"frozenset\",\n \"getattr\", \"globals\", \"hasattr\", \"hash\", \"help\", \"hex\", \"id\",\n \"input\", \"int\", \"isinstance\", \"issubclass\", \"iter\", \"len\",\n \"list\", \"locals\", \"map\", \"max\", \"memoryview\", \"min\", \"next\",\n \"object\", \"oct\", \"open\", \"ord\", \"pow\", \"property\", \"range\",\n \"repr\", \"reversed\", \"round\", \"set\", \"setattr\", \"slice\",\n \"sorted\", \"staticmethod\", \"str\", \"sum\", \"super\", \"tuple\",\n \"type\", \"vars\", \"zip\", \"__import__\", \"NotImplemented\",\n \"Ellipsis\", \"__debug__\"];\n\nfunction top(state) {\n return state.scopes[state.scopes.length - 1];\n}\n\nexport function mkPython(parserConf) {\n var ERRORCLASS = \"error\";\n\n var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\\(\\)\\[\\]\\{\\}@,:`=;\\.\\\\]/;\n // (Backwards-compatibility with old, cumbersome config system)\n var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters,\n parserConf.operators || /^([-+*/%\\/&|^]=?|[<>=]+|\\/\\/=?|\\*\\*=?|!=|[~!@]|\\.\\.\\.)/]\n for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1)\n\n var hangingIndent = parserConf.hangingIndent;\n\n var myKeywords = commonKeywords, myBuiltins = commonBuiltins;\n if (parserConf.extra_keywords != undefined)\n myKeywords = myKeywords.concat(parserConf.extra_keywords);\n\n if (parserConf.extra_builtins != undefined)\n myBuiltins = myBuiltins.concat(parserConf.extra_builtins);\n\n var py3 = !(parserConf.version && Number(parserConf.version) < 3)\n if (py3) {\n // since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator\n var identifiers = parserConf.identifiers|| /^[_A-Za-z\\u00A1-\\uFFFF][_A-Za-z0-9\\u00A1-\\uFFFF]*/;\n myKeywords = myKeywords.concat([\"nonlocal\", \"None\", \"aiter\", \"anext\", \"async\", \"await\", \"breakpoint\", \"match\", \"case\"]);\n myBuiltins = myBuiltins.concat([\"ascii\", \"bytes\", \"exec\", \"print\"]);\n var stringPrefixes = new RegExp(\"^(([rbuf]|(br)|(rb)|(fr)|(rf))?('{3}|\\\"{3}|['\\\"]))\", \"i\");\n } else {\n var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/;\n myKeywords = myKeywords.concat([\"exec\", \"print\"]);\n myBuiltins = myBuiltins.concat([\"apply\", \"basestring\", \"buffer\", \"cmp\", \"coerce\", \"execfile\",\n \"file\", \"intern\", \"long\", \"raw_input\", \"reduce\", \"reload\",\n \"unichr\", \"unicode\", \"xrange\", \"None\"]);\n var stringPrefixes = new RegExp(\"^(([rubf]|(ur)|(br))?('{3}|\\\"{3}|['\\\"]))\", \"i\");\n }\n var keywords = wordRegexp(myKeywords);\n var builtins = wordRegexp(myBuiltins);\n\n // tokenizers\n function tokenBase(stream, state) {\n var sol = stream.sol() && state.lastToken != \"\\\\\"\n if (sol) state.indent = stream.indentation()\n // Handle scope changes\n if (sol && top(state).type == \"py\") {\n var scopeOffset = top(state).offset;\n if (stream.eatSpace()) {\n var lineOffset = stream.indentation();\n if (lineOffset > scopeOffset)\n pushPyScope(stream, state);\n else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != \"#\")\n state.errorToken = true;\n return null;\n } else {\n var style = tokenBaseInner(stream, state);\n if (scopeOffset > 0 && dedent(stream, state))\n style += \" \" + ERRORCLASS;\n return style;\n }\n }\n return tokenBaseInner(stream, state);\n }\n\n function tokenBaseInner(stream, state, inFormat) {\n if (stream.eatSpace()) return null;\n\n // Handle Comments\n if (!inFormat && stream.match(/^#.*/)) return \"comment\";\n\n // Handle Number Literals\n if (stream.match(/^[0-9\\.]/, false)) {\n var floatLiteral = false;\n // Floats\n if (stream.match(/^[\\d_]*\\.\\d+(e[\\+\\-]?\\d+)?/i)) { floatLiteral = true; }\n if (stream.match(/^[\\d_]+\\.\\d*/)) { floatLiteral = true; }\n if (stream.match(/^\\.\\d+/)) { floatLiteral = true; }\n if (floatLiteral) {\n // Float literals may be \"imaginary\"\n stream.eat(/J/i);\n return \"number\";\n }\n // Integers\n var intLiteral = false;\n // Hex\n if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true;\n // Binary\n if (stream.match(/^0b[01_]+/i)) intLiteral = true;\n // Octal\n if (stream.match(/^0o[0-7_]+/i)) intLiteral = true;\n // Decimal\n if (stream.match(/^[1-9][\\d_]*(e[\\+\\-]?[\\d_]+)?/)) {\n // Decimal literals may be \"imaginary\"\n stream.eat(/J/i);\n // TODO - Can you have imaginary longs?\n intLiteral = true;\n }\n // Zero by itself with no other piece of number.\n if (stream.match(/^0(?![\\dx])/i)) intLiteral = true;\n if (intLiteral) {\n // Integer literals may be \"long\"\n stream.eat(/L/i);\n return \"number\";\n }\n }\n\n // Handle Strings\n if (stream.match(stringPrefixes)) {\n var isFmtString = stream.current().toLowerCase().indexOf('f') !== -1;\n if (!isFmtString) {\n state.tokenize = tokenStringFactory(stream.current(), state.tokenize);\n return state.tokenize(stream, state);\n } else {\n state.tokenize = formatStringFactory(stream.current(), state.tokenize);\n return state.tokenize(stream, state);\n }\n }\n\n for (var i = 0; i < operators.length; i++)\n if (stream.match(operators[i])) return \"operator\"\n\n if (stream.match(delimiters)) return \"punctuation\";\n\n if (state.lastToken == \".\" && stream.match(identifiers))\n return \"property\";\n\n if (stream.match(keywords) || stream.match(wordOperators))\n return \"keyword\";\n\n if (stream.match(builtins))\n return \"builtin\";\n\n if (stream.match(/^(self|cls)\\b/))\n return \"self\";\n\n if (stream.match(identifiers)) {\n if (state.lastToken == \"def\" || state.lastToken == \"class\")\n return \"def\";\n return \"variable\";\n }\n\n // Handle non-detected items\n stream.next();\n return inFormat ? null :ERRORCLASS;\n }\n\n function formatStringFactory(delimiter, tokenOuter) {\n while (\"rubf\".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)\n delimiter = delimiter.substr(1);\n\n var singleline = delimiter.length == 1;\n var OUTCLASS = \"string\";\n\n function tokenNestedExpr(depth) {\n return function(stream, state) {\n var inner = tokenBaseInner(stream, state, true)\n if (inner == \"punctuation\") {\n if (stream.current() == \"{\") {\n state.tokenize = tokenNestedExpr(depth + 1)\n } else if (stream.current() == \"}\") {\n if (depth > 1) state.tokenize = tokenNestedExpr(depth - 1)\n else state.tokenize = tokenString\n }\n }\n return inner\n }\n }\n\n function tokenString(stream, state) {\n while (!stream.eol()) {\n stream.eatWhile(/[^'\"\\{\\}\\\\]/);\n if (stream.eat(\"\\\\\")) {\n stream.next();\n if (singleline && stream.eol())\n return OUTCLASS;\n } else if (stream.match(delimiter)) {\n state.tokenize = tokenOuter;\n return OUTCLASS;\n } else if (stream.match('{{')) {\n // ignore {{ in f-str\n return OUTCLASS;\n } else if (stream.match('{', false)) {\n // switch to nested mode\n state.tokenize = tokenNestedExpr(0)\n if (stream.current()) return OUTCLASS;\n else return state.tokenize(stream, state)\n } else if (stream.match('}}')) {\n return OUTCLASS;\n } else if (stream.match('}')) {\n // single } in f-string is an error\n return ERRORCLASS;\n } else {\n stream.eat(/['\"]/);\n }\n }\n if (singleline) {\n if (parserConf.singleLineStringErrors)\n return ERRORCLASS;\n else\n state.tokenize = tokenOuter;\n }\n return OUTCLASS;\n }\n tokenString.isString = true;\n return tokenString;\n }\n\n function tokenStringFactory(delimiter, tokenOuter) {\n while (\"rubf\".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)\n delimiter = delimiter.substr(1);\n\n var singleline = delimiter.length == 1;\n var OUTCLASS = \"string\";\n\n function tokenString(stream, state) {\n while (!stream.eol()) {\n stream.eatWhile(/[^'\"\\\\]/);\n if (stream.eat(\"\\\\\")) {\n stream.next();\n if (singleline && stream.eol())\n return OUTCLASS;\n } else if (stream.match(delimiter)) {\n state.tokenize = tokenOuter;\n return OUTCLASS;\n } else {\n stream.eat(/['\"]/);\n }\n }\n if (singleline) {\n if (parserConf.singleLineStringErrors)\n return ERRORCLASS;\n else\n state.tokenize = tokenOuter;\n }\n return OUTCLASS;\n }\n tokenString.isString = true;\n return tokenString;\n }\n\n function pushPyScope(stream, state) {\n while (top(state).type != \"py\") state.scopes.pop()\n state.scopes.push({offset: top(state).offset + stream.indentUnit,\n type: \"py\",\n align: null})\n }\n\n function pushBracketScope(stream, state, type) {\n var align = stream.match(/^[\\s\\[\\{\\(]*(?:#|$)/, false) ? null : stream.column() + 1\n state.scopes.push({offset: state.indent + (hangingIndent || stream.indentUnit),\n type: type,\n align: align})\n }\n\n function dedent(stream, state) {\n var indented = stream.indentation();\n while (state.scopes.length > 1 && top(state).offset > indented) {\n if (top(state).type != \"py\") return true;\n state.scopes.pop();\n }\n return top(state).offset != indented;\n }\n\n function tokenLexer(stream, state) {\n if (stream.sol()) {\n state.beginningOfLine = true;\n state.dedent = false;\n }\n\n var style = state.tokenize(stream, state);\n var current = stream.current();\n\n // Handle decorators\n if (state.beginningOfLine && current == \"@\")\n return stream.match(identifiers, false) ? \"meta\" : py3 ? \"operator\" : ERRORCLASS;\n\n if (/\\S/.test(current)) state.beginningOfLine = false;\n\n if ((style == \"variable\" || style == \"builtin\")\n && state.lastToken == \"meta\")\n style = \"meta\";\n\n // Handle scope changes.\n if (current == \"pass\" || current == \"return\")\n state.dedent = true;\n\n if (current == \"lambda\") state.lambda = true;\n if (current == \":\" && !state.lambda && top(state).type == \"py\" && stream.match(/^\\s*(?:#|$)/, false))\n pushPyScope(stream, state);\n\n if (current.length == 1 && !/string|comment/.test(style)) {\n var delimiter_index = \"[({\".indexOf(current);\n if (delimiter_index != -1)\n pushBracketScope(stream, state, \"])}\".slice(delimiter_index, delimiter_index+1));\n\n delimiter_index = \"])}\".indexOf(current);\n if (delimiter_index != -1) {\n if (top(state).type == current) state.indent = state.scopes.pop().offset - (hangingIndent || stream.indentUnit)\n else return ERRORCLASS;\n }\n }\n if (state.dedent && stream.eol() && top(state).type == \"py\" && state.scopes.length > 1)\n state.scopes.pop();\n\n return style;\n }\n\n return {\n name: \"python\",\n\n startState: function() {\n return {\n tokenize: tokenBase,\n scopes: [{offset: 0, type: \"py\", align: null}],\n indent: 0,\n lastToken: null,\n lambda: false,\n dedent: 0\n };\n },\n\n token: function(stream, state) {\n var addErr = state.errorToken;\n if (addErr) state.errorToken = false;\n var style = tokenLexer(stream, state);\n\n if (style && style != \"comment\")\n state.lastToken = (style == \"keyword\" || style == \"punctuation\") ? stream.current() : style;\n if (style == \"punctuation\") style = null;\n\n if (stream.eol() && state.lambda)\n state.lambda = false;\n return addErr ? ERRORCLASS : style;\n },\n\n indent: function(state, textAfter, cx) {\n if (state.tokenize != tokenBase)\n return state.tokenize.isString ? null : 0;\n\n var scope = top(state)\n var closing = scope.type == textAfter.charAt(0) ||\n scope.type == \"py\" && !state.dedent && /^(else:|elif |except |finally:)/.test(textAfter)\n if (scope.align != null)\n return scope.align - (closing ? 1 : 0)\n else\n return scope.offset - (closing ? hangingIndent || cx.unit : 0)\n },\n\n languageData: {\n autocomplete: commonKeywords.concat(commonBuiltins).concat([\"exec\", \"print\"]),\n indentOnInput: /^\\s*([\\}\\]\\)]|else:|elif |except |finally:)$/,\n commentTokens: {line: \"#\"},\n closeBrackets: {brackets: [\"(\", \"[\", \"{\", \"'\", '\"', \"'''\", '\"\"\"']}\n }\n };\n};\n\nvar words = function(str) { return str.split(\" \"); };\n\nexport const python = mkPython({})\n\nexport const cython = mkPython({\n extra_keywords: words(\"by cdef cimport cpdef ctypedef enum except \"+\n \"extern gil include nogil property public \"+\n \"readonly struct union DEF IF ELIF ELSE\")\n})\n"],"names":["wordRegexp","words","RegExp","join","wordOperators","commonKeywords","commonBuiltins","top","state","scopes","length","mkPython","parserConf","ERRORCLASS","delimiters","singleDelimiters","operators","singleOperators","doubleOperators","doubleDelimiters","tripleDelimiters","i","splice","hangingIndent","myKeywords","myBuiltins","undefined","extra_keywords","concat","extra_builtins","py3","version","Number","identifiers","stringPrefixes","keywords","builtins","tokenBase","stream","sol","lastToken","indent","indentation","type","scopeOffset","offset","eatSpace","lineOffset","pushPyScope","dedent","peek","errorToken","style","tokenBaseInner","inFormat","match","floatLiteral","eat","intLiteral","current","toLowerCase","indexOf","tokenize","delimiter","tokenOuter","charAt","substr","singleline","OUTCLASS","tokenNestedExpr","depth","inner","tokenString","eol","eatWhile","next","singleLineStringErrors","isString","formatStringFactory","tokenStringFactory","pop","push","indentUnit","align","indented","name","startState","lambda","token","addErr","beginningOfLine","test","delimiter_index","column","pushBracketScope","slice","tokenLexer","textAfter","cx","scope","closing","unit","languageData","autocomplete","indentOnInput","commentTokens","line","closeBrackets","brackets","python","cython","split"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/2766.index.js b/book/_build/html/_static/2766.index.js new file mode 100644 index 0000000..3c0c245 --- /dev/null +++ b/book/_build/html/_static/2766.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[2766],{42766:(e,t,n)=>{function r(e){for(var t={},n=e.split(" "),r=0;rs});const i={keywords:r("DEFINITIONS OBJECTS IF DERIVED INFORMATION ACTION REPLY ANY NAMED CHARACTERIZED BEHAVIOUR REGISTERED WITH AS IDENTIFIED CONSTRAINED BY PRESENT BEGIN IMPORTS FROM UNITS SYNTAX MIN-ACCESS MAX-ACCESS MINACCESS MAXACCESS REVISION STATUS DESCRIPTION SEQUENCE SET COMPONENTS OF CHOICE DistinguishedName ENUMERATED SIZE MODULE END INDEX AUGMENTS EXTENSIBILITY IMPLIED EXPORTS"),cmipVerbs:r("ACTIONS ADD GET NOTIFICATIONS REPLACE REMOVE"),compareTypes:r("OPTIONAL DEFAULT MANAGED MODULE-TYPE MODULE_IDENTITY MODULE-COMPLIANCE OBJECT-TYPE OBJECT-IDENTITY OBJECT-COMPLIANCE MODE CONFIRMED CONDITIONAL SUBORDINATE SUPERIOR CLASS TRUE FALSE NULL TEXTUAL-CONVENTION"),status:r("current deprecated mandatory obsolete"),tags:r("APPLICATION AUTOMATIC EXPLICIT IMPLICIT PRIVATE TAGS UNIVERSAL"),storage:r("BOOLEAN INTEGER OBJECT IDENTIFIER BIT OCTET STRING UTCTime InterfaceIndex IANAifType CMIP-Attribute REAL PACKAGE PACKAGES IpAddress PhysAddress NetworkAddress BITS BMPString TimeStamp TimeTicks TruthValue RowStatus DisplayString GeneralString GraphicString IA5String NumericString PrintableString SnmpAdminString TeletexString UTF8String VideotexString VisibleString StringStore ISO646String T61String UniversalString Unsigned32 Integer32 Gauge Gauge32 Counter Counter32 Counter64"),modifier:r("ATTRIBUTE ATTRIBUTES MANDATORY-GROUP MANDATORY-GROUPS GROUP GROUPS ELEMENTS EQUALITY ORDERING SUBSTRINGS DEFINED"),accessTypes:r("not-accessible accessible-for-notify read-only read-create read-write"),multiLineStrings:!0};function s(e){var t,n=e.keywords||i.keywords,r=e.cmipVerbs||i.cmipVerbs,s=e.compareTypes||i.compareTypes,a=e.status||i.status,E=e.tags||i.tags,I=e.storage||i.storage,o=e.modifier||i.modifier,T=e.accessTypes||i.accessTypes,S=e.multiLineStrings||i.multiLineStrings,u=!1!==e.indentStatements,l=/[\|\^]/;function A(e,i){var u,A=e.next();if('"'==A||"'"==A)return i.tokenize=(u=A,function(e,t){for(var n,r=!1,i=!1;null!=(n=e.next());){if(n==u&&!r){var s=e.peek();s&&("b"!=(s=s.toLowerCase())&&"h"!=s&&"o"!=s||e.next()),i=!0;break}r=!r&&"\\"==n}return(i||!r&&!S)&&(t.tokenize=null),"string"}),i.tokenize(e,i);if(/[\[\]\(\){}:=,;]/.test(A))return t=A,"punctuation";if("-"==A&&e.eat("-"))return e.skipToEnd(),"comment";if(/\d/.test(A))return e.eatWhile(/[\w\.]/),"number";if(l.test(A))return e.eatWhile(l),"operator";e.eatWhile(/[\w\-]/);var N=e.current();return n.propertyIsEnumerable(N)?"keyword":r.propertyIsEnumerable(N)?"variableName":s.propertyIsEnumerable(N)?"atom":a.propertyIsEnumerable(N)?"comment":E.propertyIsEnumerable(N)?"typeName":I.propertyIsEnumerable(N)||o.propertyIsEnumerable(N)||T.propertyIsEnumerable(N)?"modifier":"variableName"}function N(e,t,n,r,i){this.indented=e,this.column=t,this.type=n,this.align=r,this.prev=i}function p(e,t,n){var r=e.indented;return e.context&&"statement"==e.context.type&&(r=e.context.indented),e.context=new N(r,t,n,null,e.context)}function c(e){var t=e.context.type;return")"!=t&&"]"!=t&&"}"!=t||(e.indented=e.context.indented),e.context=e.context.prev}return{name:"asn1",startState:function(){return{tokenize:null,context:new N(-2,0,"top",!1),indented:0,startOfLine:!0}},token:function(e,n){var r=n.context;if(e.sol()&&(null==r.align&&(r.align=!1),n.indented=e.indentation(),n.startOfLine=!0),e.eatSpace())return null;t=null;var i=(n.tokenize||A)(e,n);if("comment"==i)return i;if(null==r.align&&(r.align=!0),";"!=t&&":"!=t&&","!=t||"statement"!=r.type)if("{"==t)p(n,e.column(),"}");else if("["==t)p(n,e.column(),"]");else if("("==t)p(n,e.column(),")");else if("}"==t){for(;"statement"==r.type;)r=c(n);for("}"==r.type&&(r=c(n));"statement"==r.type;)r=c(n)}else t==r.type?c(n):u&&(("}"==r.type||"top"==r.type)&&";"!=t||"statement"==r.type&&"newstatement"==t)&&p(n,e.column(),"statement");else c(n);return n.startOfLine=!1,i},languageData:{indentOnInput:/^\s*[{}]$/,commentTokens:{line:"--"}}}}}}]); +//# sourceMappingURL=2766.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/2766.index.js.map b/book/_build/html/_static/2766.index.js.map new file mode 100644 index 0000000..8263242 --- /dev/null +++ b/book/_build/html/_static/2766.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2766.index.js","mappings":"+FAAA,SAASA,EAAMC,GAEb,IADA,IAAIC,EAAM,CAAC,EAAGF,EAAQC,EAAIE,MAAM,KACvBC,EAAI,EAAGA,EAAIJ,EAAMK,SAAUD,EAAGF,EAAIF,EAAMI,KAAM,EACvD,OAAOF,CACT,C,2BAEA,MAAMI,EAAW,CACfC,SAAUP,EAAM,oXAQhBQ,UAAWR,EAAM,gDACjBS,aAAcT,EAAM,iNAKpBU,OAAQV,EAAM,yCACdW,KAAMX,EAAM,kEAEZY,QAASZ,EAAM,oeAUfa,SAAUb,EAAM,oHAGhBc,YAAad,EAAM,yEAEnBe,kBAAkB,GAGb,SAASC,EAAKC,GACnB,IAWIC,EAXAX,EAAWU,EAAaV,UAAYD,EAASC,SAC7CC,EAAYS,EAAaT,WAAaF,EAASE,UAC/CC,EAAeQ,EAAaR,cAAgBH,EAASG,aACrDC,EAASO,EAAaP,QAAUJ,EAASI,OACzCC,EAAOM,EAAaN,MAAQL,EAASK,KACrCC,EAAUK,EAAaL,SAAWN,EAASM,QAC3CC,EAAWI,EAAaJ,UAAYP,EAASO,SAC7CC,EAAcG,EAAaH,aAAcR,EAASQ,YAClDC,EAAmBE,EAAaF,kBAAoBT,EAASS,iBAC7DI,GAAqD,IAAlCF,EAAaE,iBAChCC,EAAiB,SAGrB,SAASC,EAAUC,EAAQC,GACzB,IAsCmBC,EAtCfC,EAAKH,EAAOI,OAChB,GAAU,KAAND,GAAmB,KAANA,EAEf,OADAF,EAAMI,UAoCWH,EApCYC,EAqCxB,SAASH,EAAQC,GAEtB,IADA,IAAqBG,EAAjBE,GAAU,EAAaC,GAAM,EACA,OAAzBH,EAAOJ,EAAOI,SAAiB,CACrC,GAAIA,GAAQF,IAAUI,EAAQ,CAC5B,I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AOD,EAAOoB,SAAU,kBAdpCS,EAAW5B,GAiBb,OADAA,EAAMgC,aAAc,EACbM,CACT,EAEAC,aAAc,CACZC,cAAe,YACfC,cAAe,CAACC,KAAM,OAG5B,C","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/asn1.js"],"sourcesContent":["function words(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n}\n\nconst defaults = {\n keywords: words(\"DEFINITIONS OBJECTS IF DERIVED INFORMATION ACTION\" +\n \" REPLY ANY NAMED CHARACTERIZED BEHAVIOUR REGISTERED\" +\n \" WITH AS IDENTIFIED CONSTRAINED BY PRESENT BEGIN\" +\n \" IMPORTS FROM UNITS SYNTAX MIN-ACCESS MAX-ACCESS\" +\n \" MINACCESS MAXACCESS REVISION STATUS DESCRIPTION\" +\n \" SEQUENCE SET COMPONENTS OF CHOICE DistinguishedName\" +\n \" ENUMERATED SIZE MODULE END INDEX AUGMENTS EXTENSIBILITY\" +\n \" IMPLIED EXPORTS\"),\n cmipVerbs: words(\"ACTIONS ADD GET NOTIFICATIONS REPLACE REMOVE\"),\n compareTypes: words(\"OPTIONAL DEFAULT MANAGED MODULE-TYPE MODULE_IDENTITY\" +\n \" MODULE-COMPLIANCE OBJECT-TYPE OBJECT-IDENTITY\" +\n \" OBJECT-COMPLIANCE MODE CONFIRMED CONDITIONAL\" +\n \" SUBORDINATE SUPERIOR CLASS TRUE FALSE NULL\" +\n \" TEXTUAL-CONVENTION\"),\n status: words(\"current deprecated mandatory obsolete\"),\n tags: words(\"APPLICATION AUTOMATIC EXPLICIT IMPLICIT PRIVATE TAGS\" +\n \" UNIVERSAL\"),\n storage: words(\"BOOLEAN INTEGER OBJECT IDENTIFIER BIT OCTET STRING\" +\n \" UTCTime InterfaceIndex IANAifType CMIP-Attribute\" +\n \" REAL PACKAGE PACKAGES IpAddress PhysAddress\" +\n \" NetworkAddress BITS BMPString TimeStamp TimeTicks\" +\n \" TruthValue RowStatus DisplayString GeneralString\" +\n \" GraphicString IA5String NumericString\" +\n \" PrintableString SnmpAdminString TeletexString\" +\n \" UTF8String VideotexString VisibleString StringStore\" +\n \" ISO646String T61String UniversalString Unsigned32\" +\n \" Integer32 Gauge Gauge32 Counter Counter32 Counter64\"),\n modifier: words(\"ATTRIBUTE ATTRIBUTES MANDATORY-GROUP MANDATORY-GROUPS\" +\n \" GROUP GROUPS ELEMENTS EQUALITY ORDERING SUBSTRINGS\" +\n \" DEFINED\"),\n accessTypes: words(\"not-accessible accessible-for-notify read-only\" +\n \" read-create read-write\"),\n multiLineStrings: true\n}\n\nexport function asn1(parserConfig) {\n var keywords = parserConfig.keywords || defaults.keywords,\n cmipVerbs = parserConfig.cmipVerbs || defaults.cmipVerbs,\n compareTypes = parserConfig.compareTypes || defaults.compareTypes,\n status = parserConfig.status || defaults.status,\n tags = parserConfig.tags || defaults.tags,\n storage = parserConfig.storage || defaults.storage,\n modifier = parserConfig.modifier || defaults.modifier,\n accessTypes = parserConfig.accessTypes|| defaults.accessTypes,\n multiLineStrings = parserConfig.multiLineStrings || defaults.multiLineStrings,\n indentStatements = parserConfig.indentStatements !== false;\n var isOperatorChar = /[\\|\\^]/;\n var curPunc;\n\n function tokenBase(stream, state) {\n var ch = stream.next();\n if (ch == '\"' || ch == \"'\") {\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n }\n if (/[\\[\\]\\(\\){}:=,;]/.test(ch)) {\n curPunc = ch;\n return \"punctuation\";\n }\n if (ch == \"-\"){\n if (stream.eat(\"-\")) {\n stream.skipToEnd();\n return \"comment\";\n }\n }\n if (/\\d/.test(ch)) {\n stream.eatWhile(/[\\w\\.]/);\n return \"number\";\n }\n if (isOperatorChar.test(ch)) {\n stream.eatWhile(isOperatorChar);\n return \"operator\";\n }\n\n stream.eatWhile(/[\\w\\-]/);\n var cur = stream.current();\n if (keywords.propertyIsEnumerable(cur)) return \"keyword\";\n if (cmipVerbs.propertyIsEnumerable(cur)) return \"variableName\";\n if (compareTypes.propertyIsEnumerable(cur)) return \"atom\";\n if (status.propertyIsEnumerable(cur)) return \"comment\";\n if (tags.propertyIsEnumerable(cur)) return \"typeName\";\n if (storage.propertyIsEnumerable(cur)) return \"modifier\";\n if (modifier.propertyIsEnumerable(cur)) return \"modifier\";\n if (accessTypes.propertyIsEnumerable(cur)) return \"modifier\";\n\n return \"variableName\";\n }\n\n function tokenString(quote) {\n return function(stream, state) {\n var escaped = false, next, end = false;\n while ((next = stream.next()) != null) {\n if (next == quote && !escaped){\n var afterNext = stream.peek();\n //look if the character if the quote is like the B in '10100010'B\n if (afterNext){\n afterNext = afterNext.toLowerCase();\n if(afterNext == \"b\" || afterNext == \"h\" || afterNext == \"o\")\n stream.next();\n }\n end = true; break;\n }\n escaped = !escaped && next == \"\\\\\";\n }\n if (end || !(escaped || multiLineStrings))\n state.tokenize = null;\n return \"string\";\n };\n }\n\n function Context(indented, column, type, align, prev) {\n this.indented = indented;\n this.column = column;\n this.type = type;\n this.align = align;\n this.prev = prev;\n }\n function pushContext(state, col, type) {\n var indent = state.indented;\n if (state.context && state.context.type == \"statement\")\n indent = state.context.indented;\n return state.context = new Context(indent, col, type, null, state.context);\n }\n function popContext(state) {\n var t = state.context.type;\n if (t == \")\" || t == \"]\" || t == \"}\")\n state.indented = state.context.indented;\n return state.context = state.context.prev;\n }\n\n //Interface\n return {\n name: \"asn1\",\n startState: function() {\n return {\n tokenize: null,\n context: new Context(-2, 0, \"top\", false),\n indented: 0,\n startOfLine: true\n };\n },\n\n token: function(stream, state) {\n var ctx = state.context;\n if (stream.sol()) {\n if (ctx.align == null) ctx.align = false;\n state.indented = stream.indentation();\n state.startOfLine = true;\n }\n if (stream.eatSpace()) return null;\n curPunc = null;\n var style = (state.tokenize || tokenBase)(stream, state);\n if (style == \"comment\") return style;\n if (ctx.align == null) ctx.align = true;\n\n if ((curPunc == \";\" || curPunc == \":\" || curPunc == \",\")\n && ctx.type == \"statement\"){\n popContext(state);\n }\n else if (curPunc == \"{\") pushContext(state, stream.column(), \"}\");\n else if (curPunc == \"[\") pushContext(state, stream.column(), \"]\");\n else if (curPunc == \"(\") pushContext(state, stream.column(), \")\");\n else if (curPunc == \"}\") {\n while (ctx.type == \"statement\") ctx = popContext(state);\n if (ctx.type == \"}\") ctx = popContext(state);\n while (ctx.type == \"statement\") ctx = popContext(state);\n }\n else if (curPunc == ctx.type) popContext(state);\n else if (indentStatements && (((ctx.type == \"}\" || ctx.type == \"top\")\n && curPunc != ';') || (ctx.type == \"statement\"\n && curPunc == \"newstatement\")))\n pushContext(state, stream.column(), \"statement\");\n\n state.startOfLine = false;\n return style;\n },\n\n languageData: {\n indentOnInput: /^\\s*[{}]$/,\n commentTokens: {line: \"--\"}\n }\n };\n};\n"],"names":["words","str","obj","split","i","length","defaults","keywords","cmipVerbs","compareTypes","status","tags","storage","modifier","accessTypes","multiLineStrings","asn1","parserConfig","curPunc","indentStatements","isOperatorChar","tokenBase","stream","state","quote","ch","next","tokenize","escaped","end","afterNext","peek","toLowerCase","test","eat","skipToEnd","eatWhile","cur","current","propertyIsEnumerable","Context","indented","column","type","align","prev","this","pushContext","col","indent","context","popContext","t","name","startState","startOfLine","token","ctx","sol","indentation","eatSpace","style","languageData","indentOnInput","commentTokens","line"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/2795.index.js b/book/_build/html/_static/2795.index.js new file mode 100644 index 0000000..10033cd --- /dev/null +++ b/book/_build/html/_static/2795.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[2795],{82795:(e,t,n)=>{function r(e){for(var t={},n=e.split(","),r=0;rh});var o,a=r("null"),l={"`":i,$:i},u=!1,s=r("abs,access,after,alias,all,and,architecture,array,assert,attribute,begin,block,body,buffer,bus,case,component,configuration,constant,disconnect,downto,else,elsif,end,end block,end case,end component,end for,end generate,end if,end loop,end process,end record,end units,entity,exit,file,for,function,generate,generic,generic map,group,guarded,if,impure,in,inertial,inout,is,label,library,linkage,literal,loop,map,mod,nand,new,next,nor,null,of,on,open,or,others,out,package,package body,port,port map,postponed,procedure,process,pure,range,record,register,reject,rem,report,return,rol,ror,select,severity,signal,sla,sll,sra,srl,subtype,then,to,transport,type,unaffected,units,until,use,variable,wait,when,while,with,xnor,xor"),c=r("architecture,entity,begin,case,port,else,elsif,end,for,function,if"),p=/[&|~>{n.r(t),n.d(t,{nsis:()=>i});const i=(0,n(74391).Q)({start:[{regex:/(?:[+-]?)(?:0x[\d,a-f]+)|(?:0o[0-7]+)|(?:0b[0,1]+)|(?:\d+.?\d*)/,token:"number"},{regex:/"(?:[^\\"]|\\.)*"?/,token:"string"},{regex:/'(?:[^\\']|\\.)*'?/,token:"string"},{regex:/`(?:[^\\`]|\\.)*`?/,token:"string"},{regex:/^\s*(?:\!(addincludedir|addplugindir|appendfile|assert|cd|define|delfile|echo|error|execute|finalize|getdllversion|gettlbversion|include|insertmacro|macro|macroend|makensis|packhdr|pragma|searchparse|searchreplace|system|tempfile|undef|uninstfinalize|verbose|warning))\b/i,token:"keyword"},{regex:/^\s*(?:\!(if(?:n?def)?|ifmacron?def|macro))\b/i,token:"keyword",indent:!0},{regex:/^\s*(?:\!(else|endif|macroend))\b/i,token:"keyword",dedent:!0},{regex:/^\s*(?:Abort|AddBrandingImage|AddSize|AllowRootDirInstall|AllowSkipFiles|AutoCloseWindow|BGFont|BGGradient|BrandingText|BringToFront|Call|CallInstDLL|Caption|ChangeUI|CheckBitmap|ClearErrors|CompletedText|ComponentText|CopyFiles|CRCCheck|CreateDirectory|CreateFont|CreateShortCut|Delete|DeleteINISec|DeleteINIStr|DeleteRegKey|DeleteRegValue|DetailPrint|DetailsButtonText|DirText|DirVar|DirVerify|EnableWindow|EnumRegKey|EnumRegValue|Exch|Exec|ExecShell|ExecShellWait|ExecWait|ExpandEnvStrings|File|FileBufSize|FileClose|FileErrorText|FileOpen|FileRead|FileReadByte|FileReadUTF16LE|FileReadWord|FileWriteUTF16LE|FileSeek|FileWrite|FileWriteByte|FileWriteWord|FindClose|FindFirst|FindNext|FindWindow|FlushINI|GetCurInstType|GetCurrentAddress|GetDlgItem|GetDLLVersion|GetDLLVersionLocal|GetErrorLevel|GetFileTime|GetFileTimeLocal|GetFullPathName|GetFunctionAddress|GetInstDirError|GetKnownFolderPath|GetLabelAddress|GetTempFileName|GetWinVer|Goto|HideWindow|Icon|IfAbort|IfErrors|IfFileExists|IfRebootFlag|IfRtlLanguage|IfShellVarContextAll|IfSilent|InitPluginsDir|InstallButtonText|InstallColors|InstallDir|InstallDirRegKey|InstProgressFlags|InstType|InstTypeGetText|InstTypeSetText|Int64Cmp|Int64CmpU|Int64Fmt|IntCmp|IntCmpU|IntFmt|IntOp|IntPtrCmp|IntPtrCmpU|IntPtrOp|IsWindow|LangString|LicenseBkColor|LicenseData|LicenseForceSelection|LicenseLangString|LicenseText|LoadAndSetImage|LoadLanguageFile|LockWindow|LogSet|LogText|ManifestDPIAware|ManifestLongPathAware|ManifestMaxVersionTested|ManifestSupportedOS|MessageBox|MiscButtonText|Name|Nop|OutFile|Page|PageCallbacks|PEAddResource|PEDllCharacteristics|PERemoveResource|PESubsysVer|Pop|Push|Quit|ReadEnvStr|ReadINIStr|ReadRegDWORD|ReadRegStr|Reboot|RegDLL|Rename|RequestExecutionLevel|ReserveFile|Return|RMDir|SearchPath|SectionGetFlags|SectionGetInstTypes|SectionGetSize|SectionGetText|SectionIn|SectionSetFlags|SectionSetInstTypes|SectionSetSize|SectionSetText|SendMessage|SetAutoClose|SetBrandingImage|SetCompress|SetCompressor|SetCompressorDictSize|SetCtlColors|SetCurInstType|SetDatablockOptimize|SetDateSave|SetDetailsPrint|SetDetailsView|SetErrorLevel|SetErrors|SetFileAttributes|SetFont|SetOutPath|SetOverwrite|SetRebootFlag|SetRegView|SetShellVarContext|SetSilent|ShowInstDetails|ShowUninstDetails|ShowWindow|SilentInstall|SilentUnInstall|Sleep|SpaceTexts|StrCmp|StrCmpS|StrCpy|StrLen|SubCaption|Target|Unicode|UninstallButtonText|UninstallCaption|UninstallIcon|UninstallSubCaption|UninstallText|UninstPage|UnRegDLL|Var|VIAddVersionKey|VIFileVersion|VIProductVersion|WindowIcon|WriteINIStr|WriteRegBin|WriteRegDWORD|WriteRegExpandStr|WriteRegMultiStr|WriteRegNone|WriteRegStr|WriteUninstaller|XPStyle)\b/i,token:"keyword"},{regex:/^\s*(?:Function|PageEx|Section(?:Group)?)\b/i,token:"keyword",indent:!0},{regex:/^\s*(?:(Function|PageEx|Section(?:Group)?)End)\b/i,token:"keyword",dedent:!0},{regex:/\b(?:ARCHIVE|FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_OFFLINE|FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_TEMPORARY|HIDDEN|HKCC|HKCR(32|64)?|HKCU(32|64)?|HKDD|HKEY_CLASSES_ROOT|HKEY_CURRENT_CONFIG|HKEY_CURRENT_USER|HKEY_DYN_DATA|HKEY_LOCAL_MACHINE|HKEY_PERFORMANCE_DATA|HKEY_USERS|HKLM(32|64)?|HKPD|HKU|IDABORT|IDCANCEL|IDD_DIR|IDD_INST|IDD_INSTFILES|IDD_LICENSE|IDD_SELCOM|IDD_UNINST|IDD_VERIFY|IDIGNORE|IDNO|IDOK|IDRETRY|IDYES|MB_ABORTRETRYIGNORE|MB_DEFBUTTON1|MB_DEFBUTTON2|MB_DEFBUTTON3|MB_DEFBUTTON4|MB_ICONEXCLAMATION|MB_ICONINFORMATION|MB_ICONQUESTION|MB_ICONSTOP|MB_OK|MB_OKCANCEL|MB_RETRYCANCEL|MB_RIGHT|MB_RTLREADING|MB_SETFOREGROUND|MB_TOPMOST|MB_USERICON|MB_YESNO|MB_YESNOCANCEL|NORMAL|OFFLINE|READONLY|SHCTX|SHELL_CONTEXT|SW_HIDE|SW_SHOWDEFAULT|SW_SHOWMAXIMIZED|SW_SHOWMINIMIZED|SW_SHOWNORMAL|SYSTEM|TEMPORARY)\b/i,token:"atom"},{regex:/\b(?:admin|all|amd64-unicode|auto|both|bottom|bzip2|components|current|custom|directory|false|force|hide|highest|ifdiff|ifnewer|instfiles|lastused|leave|left|license|listonly|lzma|nevershow|none|normal|notset|off|on|right|show|silent|silentlog|textonly|top|true|try|un\.components|un\.custom|un\.directory|un\.instfiles|un\.license|uninstConfirm|user|Win10|Win7|Win8|WinVista|x-86-(ansi|unicode)|zlib)\b/i,token:"builtin"},{regex:/\$\{(?:And(?:If(?:Not)?|Unless)|Break|Case(?:2|3|4|5|Else)?|Continue|Default|Do(?:Until|While)?|Else(?:If(?:Not)?|Unless)?|End(?:If|Select|Switch)|Exit(?:Do|For|While)|For(?:Each)?|If(?:Cmd|Not(?:Then)?|Then)?|Loop(?:Until|While)?|Or(?:If(?:Not)?|Unless)|Select|Switch|Unless|While)\}/i,token:"variable-2",indent:!0},{regex:/\$\{(?:BannerTrimPath|DirState|DriveSpace|Get(BaseName|Drives|ExeName|ExePath|FileAttributes|FileExt|FileName|FileVersion|Options|OptionsS|Parameters|Parent|Root|Size|Time)|Locate|RefreshShellIcons)\}/i,token:"variable-2",dedent:!0},{regex:/\$\{(?:Memento(?:Section(?:Done|End|Restore|Save)?|UnselectedSection))\}/i,token:"variable-2",dedent:!0},{regex:/\$\{(?:Config(?:Read|ReadS|Write|WriteS)|File(?:Join|ReadFromEnd|Recode)|Line(?:Find|Read|Sum)|Text(?:Compare|CompareS)|TrimNewLines)\}/i,token:"variable-2",dedent:!0},{regex:/\$\{(?:(?:At(?:Least|Most)|Is)(?:ServicePack|Win(?:7|8|10|95|98|200(?:0|3|8(?:R2)?)|ME|NT4|Vista|XP))|Is(?:NT|Server))\}/i,token:"variable",dedent:!0},{regex:/\$\{(?:StrFilterS?|Version(?:Compare|Convert)|Word(?:AddS?|Find(?:(?:2|3)X)?S?|InsertS?|ReplaceS?))\}/i,token:"keyword",dedent:!0},{regex:/\$\{(?:RunningX64)\}/i,token:"variable",dedent:!0},{regex:/\$\{(?:Disable|Enable)X64FSRedirection\}/i,token:"keyword",dedent:!0},{regex:/(#|;).*/,token:"comment"},{regex:/\/\*/,token:"comment",next:"comment"},{regex:/[-+\/*=<>!]+/,token:"operator"},{regex:/\$\w[\w\.]*/,token:"variable"},{regex:/\${[\!\w\.:-]+}/,token:"variableName.constant"},{regex:/\$\([\!\w\.:-]+\)/,token:"atom"}],comment:[{regex:/.*?\*\//,token:"comment",next:"start"},{regex:/.*/,token:"comment"}],languageData:{name:"nsis",indentOnInput:/^\s*((Function|PageEx|Section|Section(Group)?)End|(\!(endif|macroend))|\$\{(End(If|Unless|While)|Loop(Until)|Next)\})$/i,commentTokens:{line:"#",block:{open:"/*",close:"*/"}}}})},74391:(e,t,n)=>{function i(e){r(e,"start");var t={},n=e.languageData||{},i=!1;for(var l in e)if(l!=n&&e.hasOwnProperty(l))for(var d=t[l]=[],S=e[l],c=0;c2&&a.token&&"string"!=typeof a.token){n.pending=[];for(var d=2;d-1)return null;var r=n.indent.length-1,o=e[n.state];e:for(;;){for(var a=0;ai})}}]); +//# sourceMappingURL=2870.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/2870.index.js.map b/book/_build/html/_static/2870.index.js.map new file mode 100644 index 0000000..4fb8066 --- /dev/null +++ b/book/_build/html/_static/2870.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"2870.index.js","mappings":"0HACO,MAAMA,GAAO,E,SAAA,GAAW,CAC7BC,MAAM,CAEJ,CAACC,MAAO,kEAAmEC,MAAO,UAGlF,CAAED,MAAO,qBAAsBC,MAAO,UACtC,CAAED,MAAO,qBAAsBC,MAAO,UACtC,CAAED,MAAO,qBAAsBC,MAAO,UAGtC,CAACD,MAAO,kRAAmRC,MAAO,WAGlS,CAACD,MAAO,iDAAkDC,MAAO,UAAWC,QAAQ,GACpF,CAACF,MAAO,qCAAsCC,MAAO,UAAWE,QAAQ,GAGxE,CAACH,MAA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,EAAGA,EAAIN,EAAQjC,OAAQuC,IAC9BN,EAAQM,IACV5C,EAAMU,QAAQH,KAAK,CAAC4B,KAAMG,EAAQM,GAAI/D,MAAOwD,EAAKxD,MAAM+D,EAAI,KAEhE,OADAb,EAAOc,OAAOP,EAAQ,GAAGjC,QAAUiC,EAAQ,GAAKA,EAAQ,GAAGjC,OAAS,IAC7DxB,EAAM,EACf,CAAO,OAAIA,GAASA,EAAMiE,KACjBjE,EAAM,GAENA,CAEX,CACF,CAEA,OADAkD,EAAO/C,OACA,IACT,CACF,CAEA,SAASgC,EAAerB,EAAQG,GAC9B,OAAO,SAASE,EAAO+C,GACrB,GAAoB,MAAhB/C,EAAMlB,QAAkBgB,EAAKkD,kBAAoBlD,EAAKmD,gBAAgBC,QAAQlD,EAAMA,QAAU,EAChG,OAAO,KAET,IAAIkC,EAAMlC,EAAMlB,OAAOuB,OAAS,EAAG8C,EAAQxD,EAAOK,EAAMA,OACxDoD,EAAM,OAAS,CACb,IAAK,IAAIhD,EAAI,EAAGA,EAAI+C,EAAM9C,OAAQD,IAAK,CACrC,IAAIiC,EAAOc,EAAM/C,GACjB,GAAIiC,EAAK/B,KAAKvB,SAA0C,IAAhCsD,EAAK/B,KAAK+C,kBAA6B,CAC7D,IAAIC,EAAIjB,EAAKzD,MAAM2E,KAAKR,GACxB,GAAIO,GAAKA,EAAE,GAAI,CACbpB,KACIG,EAAKrD,MAAQqD,EAAK9B,QAAM4C,EAAQxD,EAAO0C,EAAKrD,MAAQqD,EAAK9B,OAC7DwC,EAAYA,EAAUlC,MAAMyC,EAAE,GAAGjD,QACjC,SAAS+C,CACX,CACF,CACF,CACA,KACF,CACA,OAAOlB,EAAM,EAAI,EAAIlC,EAAMlB,OAAOoD,EACpC,CACF,C","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/nsis.js","webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/simple-mode.js"],"sourcesContent":["import {simpleMode} from \"./simple-mode.js\"\nexport const nsis = simpleMode({\n start:[\n // Numbers\n {regex: /(?:[+-]?)(?:0x[\\d,a-f]+)|(?:0o[0-7]+)|(?:0b[0,1]+)|(?:\\d+.?\\d*)/, token: \"number\"},\n\n // Strings\n { regex: /\"(?:[^\\\\\"]|\\\\.)*\"?/, token: \"string\" },\n { regex: /'(?:[^\\\\']|\\\\.)*'?/, token: \"string\" },\n { regex: /`(?:[^\\\\`]|\\\\.)*`?/, token: \"string\" },\n\n // Compile Time Commands\n {regex: /^\\s*(?:\\!(addincludedir|addplugindir|appendfile|assert|cd|define|delfile|echo|error|execute|finalize|getdllversion|gettlbversion|include|insertmacro|macro|macroend|makensis|packhdr|pragma|searchparse|searchreplace|system|tempfile|undef|uninstfinalize|verbose|warning))\\b/i, token: \"keyword\"},\n\n // Conditional Compilation\n {regex: /^\\s*(?:\\!(if(?:n?def)?|ifmacron?def|macro))\\b/i, token: \"keyword\", indent: true},\n {regex: /^\\s*(?:\\!(else|endif|macroend))\\b/i, token: \"keyword\", dedent: true},\n\n // Runtime Commands\n {regex: /^\\s*(?:Abort|AddBrandingImage|AddSize|AllowRootDirInstall|AllowSkipFiles|AutoCloseWindow|BGFont|BGGradient|BrandingText|BringToFront|Call|CallInstDLL|Caption|ChangeUI|CheckBitmap|ClearErrors|CompletedText|ComponentText|CopyFiles|CRCCheck|CreateDirectory|CreateFont|CreateShortCut|Delete|DeleteINISec|DeleteINIStr|DeleteRegKey|DeleteRegValue|DetailPrint|DetailsButtonText|DirText|DirVar|DirVerify|EnableWindow|EnumRegKey|EnumRegValue|Exch|Exec|ExecShell|ExecShellWait|ExecWait|ExpandEnvStrings|File|FileBufSize|FileClose|FileErrorText|FileOpen|FileRead|FileReadByte|FileReadUTF16LE|FileReadWord|FileWriteUTF16LE|FileSeek|FileWrite|FileWriteByte|FileWriteWord|FindClose|FindFirst|FindNext|FindWindow|FlushINI|GetCurInstType|GetCurrentAddress|GetDlgItem|GetDLLVersion|GetDLLVersionLocal|GetErrorLevel|GetFileTime|GetFileTimeLocal|GetFullPathName|GetFunctionAddress|GetInstDirError|GetKnownFolderPath|GetLabelAddress|GetTempFileName|GetWinVer|Goto|HideWindow|Icon|IfAbort|IfErrors|IfFileExists|IfRebootFlag|IfRtlLanguage|IfShellVarContextAll|IfSilent|InitPluginsDir|InstallButtonText|InstallColors|InstallDir|InstallDirRegKey|InstProgressFlags|InstType|InstTypeGetText|InstTypeSetText|Int64Cmp|Int64CmpU|Int64Fmt|IntCmp|IntCmpU|IntFmt|IntOp|IntPtrCmp|IntPtrCmpU|IntPtrOp|IsWindow|LangString|LicenseBkColor|LicenseData|LicenseForceSelection|LicenseLangString|LicenseText|LoadAndSetImage|LoadLanguageFile|LockWindow|LogSet|LogText|ManifestDPIAware|ManifestLongPathAware|ManifestMaxVersionTested|ManifestSupportedOS|MessageBox|MiscButtonText|Name|Nop|OutFile|Page|PageCallbacks|PEAddResource|PEDllCharacteristics|PERemoveResource|PESubsysVer|Pop|Push|Quit|ReadEnvStr|ReadINIStr|ReadRegDWORD|ReadRegStr|Reboot|RegDLL|Rename|RequestExecutionLevel|ReserveFile|Return|RMDir|SearchPath|SectionGetFlags|SectionGetInstTypes|SectionGetSize|SectionGetText|SectionIn|SectionSetFlags|SectionSetInstTypes|SectionSetSize|SectionSetText|SendMessage|SetAutoClose|SetBrandingImage|SetCompress|SetCompressor|SetCompressorDictSize|SetCtlColors|SetCurInstType|SetDatablockOptimize|SetDateSave|SetDetailsPrint|SetDetailsView|SetErrorLevel|SetErrors|SetFileAttributes|SetFont|SetOutPath|SetOverwrite|SetRebootFlag|SetRegView|SetShellVarContext|SetSilent|ShowInstDetails|ShowUninstDetails|ShowWindow|SilentInstall|SilentUnInstall|Sleep|SpaceTexts|StrCmp|StrCmpS|StrCpy|StrLen|SubCaption|Target|Unicode|UninstallButtonText|UninstallCaption|UninstallIcon|UninstallSubCaption|UninstallText|UninstPage|UnRegDLL|Var|VIAddVersionKey|VIFileVersion|VIProductVersion|WindowIcon|WriteINIStr|WriteRegBin|WriteRegDWORD|WriteRegExpandStr|WriteRegMultiStr|WriteRegNone|WriteRegStr|WriteUninstaller|XPStyle)\\b/i, token: \"keyword\"},\n {regex: /^\\s*(?:Function|PageEx|Section(?:Group)?)\\b/i, token: \"keyword\", indent: true},\n {regex: /^\\s*(?:(Function|PageEx|Section(?:Group)?)End)\\b/i, token: \"keyword\", dedent: true},\n\n // Command Options\n {regex: /\\b(?:ARCHIVE|FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_OFFLINE|FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_TEMPORARY|HIDDEN|HKCC|HKCR(32|64)?|HKCU(32|64)?|HKDD|HKEY_CLASSES_ROOT|HKEY_CURRENT_CONFIG|HKEY_CURRENT_USER|HKEY_DYN_DATA|HKEY_LOCAL_MACHINE|HKEY_PERFORMANCE_DATA|HKEY_USERS|HKLM(32|64)?|HKPD|HKU|IDABORT|IDCANCEL|IDD_DIR|IDD_INST|IDD_INSTFILES|IDD_LICENSE|IDD_SELCOM|IDD_UNINST|IDD_VERIFY|IDIGNORE|IDNO|IDOK|IDRETRY|IDYES|MB_ABORTRETRYIGNORE|MB_DEFBUTTON1|MB_DEFBUTTON2|MB_DEFBUTTON3|MB_DEFBUTTON4|MB_ICONEXCLAMATION|MB_ICONINFORMATION|MB_ICONQUESTION|MB_ICONSTOP|MB_OK|MB_OKCANCEL|MB_RETRYCANCEL|MB_RIGHT|MB_RTLREADING|MB_SETFOREGROUND|MB_TOPMOST|MB_USERICON|MB_YESNO|MB_YESNOCANCEL|NORMAL|OFFLINE|READONLY|SHCTX|SHELL_CONTEXT|SW_HIDE|SW_SHOWDEFAULT|SW_SHOWMAXIMIZED|SW_SHOWMINIMIZED|SW_SHOWNORMAL|SYSTEM|TEMPORARY)\\b/i, token: \"atom\"},\n {regex: /\\b(?:admin|all|amd64-unicode|auto|both|bottom|bzip2|components|current|custom|directory|false|force|hide|highest|ifdiff|ifnewer|instfiles|lastused|leave|left|license|listonly|lzma|nevershow|none|normal|notset|off|on|right|show|silent|silentlog|textonly|top|true|try|un\\.components|un\\.custom|un\\.directory|un\\.instfiles|un\\.license|uninstConfirm|user|Win10|Win7|Win8|WinVista|x-86-(ansi|unicode)|zlib)\\b/i, token: \"builtin\"},\n\n // LogicLib.nsh\n {regex: /\\$\\{(?:And(?:If(?:Not)?|Unless)|Break|Case(?:2|3|4|5|Else)?|Continue|Default|Do(?:Until|While)?|Else(?:If(?:Not)?|Unless)?|End(?:If|Select|Switch)|Exit(?:Do|For|While)|For(?:Each)?|If(?:Cmd|Not(?:Then)?|Then)?|Loop(?:Until|While)?|Or(?:If(?:Not)?|Unless)|Select|Switch|Unless|While)\\}/i, token: \"variable-2\", indent: true},\n\n // FileFunc.nsh\n {regex: /\\$\\{(?:BannerTrimPath|DirState|DriveSpace|Get(BaseName|Drives|ExeName|ExePath|FileAttributes|FileExt|FileName|FileVersion|Options|OptionsS|Parameters|Parent|Root|Size|Time)|Locate|RefreshShellIcons)\\}/i, token: \"variable-2\", dedent: true},\n\n // Memento.nsh\n {regex: /\\$\\{(?:Memento(?:Section(?:Done|End|Restore|Save)?|UnselectedSection))\\}/i, token: \"variable-2\", dedent: true},\n\n // TextFunc.nsh\n {regex: /\\$\\{(?:Config(?:Read|ReadS|Write|WriteS)|File(?:Join|ReadFromEnd|Recode)|Line(?:Find|Read|Sum)|Text(?:Compare|CompareS)|TrimNewLines)\\}/i, token: \"variable-2\", dedent: true},\n\n // WinVer.nsh\n {regex: /\\$\\{(?:(?:At(?:Least|Most)|Is)(?:ServicePack|Win(?:7|8|10|95|98|200(?:0|3|8(?:R2)?)|ME|NT4|Vista|XP))|Is(?:NT|Server))\\}/i, token: \"variable\", dedent: true},\n\n // WordFunc.nsh\n {regex: /\\$\\{(?:StrFilterS?|Version(?:Compare|Convert)|Word(?:AddS?|Find(?:(?:2|3)X)?S?|InsertS?|ReplaceS?))\\}/i, token: \"keyword\", dedent: true},\n\n // x64.nsh\n {regex: /\\$\\{(?:RunningX64)\\}/i, token: \"variable\", dedent: true},\n {regex: /\\$\\{(?:Disable|Enable)X64FSRedirection\\}/i, token: \"keyword\", dedent: true},\n\n // Line Comment\n {regex: /(#|;).*/, token: \"comment\"},\n\n // Block Comment\n {regex: /\\/\\*/, token: \"comment\", next: \"comment\"},\n\n // Operator\n {regex: /[-+\\/*=<>!]+/, token: \"operator\"},\n\n // Variable\n {regex: /\\$\\w[\\w\\.]*/, token: \"variable\"},\n\n // Constant\n {regex: /\\${[\\!\\w\\.:-]+}/, token: \"variableName.constant\"},\n\n // Language String\n {regex: /\\$\\([\\!\\w\\.:-]+\\)/, token: \"atom\"}\n ],\n comment: [\n {regex: /.*?\\*\\//, token: \"comment\", next: \"start\"},\n {regex: /.*/, token: \"comment\"}\n ],\n languageData: {\n name: \"nsis\",\n indentOnInput: /^\\s*((Function|PageEx|Section|Section(Group)?)End|(\\!(endif|macroend))|\\$\\{(End(If|Unless|While)|Loop(Until)|Next)\\})$/i,\n commentTokens: {line: \"#\", block: {open: \"/*\", close: \"*/\"}}\n }\n});\n\n","export function simpleMode(states) {\n ensureState(states, \"start\");\n var states_ = {}, meta = states.languageData || {}, hasIndentation = false;\n for (var state in states) if (state != meta && states.hasOwnProperty(state)) {\n var list = states_[state] = [], orig = states[state];\n for (var i = 0; i < orig.length; i++) {\n var data = orig[i];\n list.push(new Rule(data, states));\n if (data.indent || data.dedent) hasIndentation = true;\n }\n }\n return {\n name: meta.name,\n startState: function() {\n return {state: \"start\", pending: null, indent: hasIndentation ? [] : null};\n },\n copyState: function(state) {\n var s = {state: state.state, pending: state.pending, indent: state.indent && state.indent.slice(0)};\n if (state.stack)\n s.stack = state.stack.slice(0);\n return s;\n },\n token: tokenFunction(states_),\n indent: indentFunction(states_, meta),\n languageData: meta\n }\n};\n\nfunction ensureState(states, name) {\n if (!states.hasOwnProperty(name))\n throw new Error(\"Undefined state \" + name + \" in simple mode\");\n}\n\nfunction toRegex(val, caret) {\n if (!val) return /(?:)/;\n var flags = \"\";\n if (val instanceof RegExp) {\n if (val.ignoreCase) flags = \"i\";\n val = val.source;\n } else {\n val = String(val);\n }\n return new RegExp((caret === false ? \"\" : \"^\") + \"(?:\" + val + \")\", flags);\n}\n\nfunction asToken(val) {\n if (!val) return null;\n if (val.apply) return val\n if (typeof val == \"string\") return val.replace(/\\./g, \" \");\n var result = [];\n for (var i = 0; i < val.length; i++)\n result.push(val[i] && val[i].replace(/\\./g, \" \"));\n return result;\n}\n\nfunction Rule(data, states) {\n if (data.next || data.push) ensureState(states, data.next || data.push);\n this.regex = toRegex(data.regex);\n this.token = asToken(data.token);\n this.data = data;\n}\n\nfunction tokenFunction(states) {\n return function(stream, state) {\n if (state.pending) {\n var pend = state.pending.shift();\n if (state.pending.length == 0) state.pending = null;\n stream.pos += pend.text.length;\n return pend.token;\n }\n\n var curState = states[state.state];\n for (var i = 0; i < curState.length; i++) {\n var rule = curState[i];\n var matches = (!rule.data.sol || stream.sol()) && stream.match(rule.regex);\n if (matches) {\n if (rule.data.next) {\n state.state = rule.data.next;\n } else if (rule.data.push) {\n (state.stack || (state.stack = [])).push(state.state);\n state.state = rule.data.push;\n } else if (rule.data.pop && state.stack && state.stack.length) {\n state.state = state.stack.pop();\n }\n\n if (rule.data.indent)\n state.indent.push(stream.indentation() + stream.indentUnit);\n if (rule.data.dedent)\n state.indent.pop();\n var token = rule.token\n if (token && token.apply) token = token(matches)\n if (matches.length > 2 && rule.token && typeof rule.token != \"string\") {\n state.pending = [];\n for (var j = 2; j < matches.length; j++)\n if (matches[j])\n state.pending.push({text: matches[j], token: rule.token[j - 1]});\n stream.backUp(matches[0].length - (matches[1] ? matches[1].length : 0));\n return token[0];\n } else if (token && token.join) {\n return token[0];\n } else {\n return token;\n }\n }\n }\n stream.next();\n return null;\n };\n}\n\nfunction indentFunction(states, meta) {\n return function(state, textAfter) {\n if (state.indent == null || meta.dontIndentStates && meta.doneIndentState.indexOf(state.state) > -1)\n return null\n\n var pos = state.indent.length - 1, rules = states[state.state];\n scan: for (;;) {\n for (var i = 0; i < rules.length; i++) {\n var rule = rules[i];\n if (rule.data.dedent && rule.data.dedentIfLineStart !== false) {\n var m = rule.regex.exec(textAfter);\n if (m && m[0]) {\n pos--;\n if (rule.next || rule.push) rules = states[rule.next || rule.push];\n textAfter = textAfter.slice(m[0].length);\n continue scan;\n }\n }\n }\n break;\n }\n return pos < 0 ? 0 : state.indent[pos];\n };\n}\n"],"names":["nsis","start","regex","token","indent","dedent","next","comment","languageData","name","indentOnInput","commentTokens","line","block","open","close","simpleMode","states","ensureState","states_","meta","hasIndentation","state","hasOwnProperty","list","orig","i","length","data","push","Rule","startState","pending","copyState","s","slice","stack","tokenFunction","indentFunction","Error","this","val","caret","flags","RegExp","ignoreCase","source","String","toRegex","apply","replace","result","asToken","stream","pend","shift","pos","text","curState","rule","matches","sol","match","pop","indentation","indentUnit","j","backUp","join","textAfter","dontIndentStates","doneIndentState","indexOf","rules","scan","dedentIfLineStart","m","exec"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/296.thebe-lite.min.js b/book/_build/html/_static/296.thebe-lite.min.js new file mode 100644 index 0000000..f4fc763 --- /dev/null +++ b/book/_build/html/_static/296.thebe-lite.min.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe_lite=self.webpackChunkthebe_lite||[]).push([[296],{3296:(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{__webpack_require__.d(__webpack_exports__,{O:()=>Yt});var ni=Object.create,Me=Object.defineProperty,ai=Object.getOwnPropertyDescriptor,oi=Object.getOwnPropertyNames,si=Object.getPrototypeOf,ri=Object.prototype.hasOwnProperty,ce=(t,e)=>()=>(t&&(e=t(t=0)),e),F=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),li=(t,e)=>{for(var i in e)Me(t,i,{get:e[i],enumerable:!0})},ci=(t,e,i,a)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let n of oi(e))!ri.call(t,n)&&n!==i&&Me(t,n,{get:()=>e[n],enumerable:!(a=ai(e,n))||a.enumerable});return t},se=(t,e,i)=>(i=null!=t?ni(si(t)):{},ci(!e&&t&&t.__esModule?i:Me(i,"default",{value:t,enumerable:!0}),t)),Ye=F(((t,e)=>{var i,a;i=t,a=function(t){function e(t,e){let i=0;for(let a of t)if(!1===e(a,i++))return!1;return!0}var i;t.ArrayExt=void 0,function(t){function e(t,e,i=0,a=-1){let n,o=t.length;if(0===o)return-1;i=i<0?Math.max(0,i+o):Math.min(i,o-1),n=(a=a<0?Math.max(0,a+o):Math.min(a,o-1))=i)return;let a=t[e];for(let a=e+1;a0;){let a=r>>1,n=l+a;i(t[n],e)<0?(l=n+1,r-=a+1):r=a}return l},t.upperBound=function(t,e,i,a=0,n=-1){let o=t.length;if(0===o)return 0;let l=a=a<0?Math.max(0,a+o):Math.min(a,o-1),r=(n=n<0?Math.max(0,n+o):Math.min(n,o-1))-a+1;for(;r>0;){let a=r>>1,n=l+a;i(t[n],e)>0?r=a:(l=n+1,r-=a+1)}return l},t.shallowEqual=function(t,e,i){if(t===e)return!0;if(t.length!==e.length)return!1;for(let a=0,n=t.length;a=l&&(i=n<0?l-1:l),void 0===a?a=n<0?-1:l:a<0?a=Math.max(a+l,n<0?-1:0):a>=l&&(a=n<0?l-1:l),o=n<0&&a>=i||n>0&&i>=a?0:n<0?Math.floor((a-i+1)/n+1):Math.floor((a-i-1)/n+1);let r=[];for(let e=0;e=(a=a<0?Math.max(0,a+n):Math.min(a,n-1)))return;let l=a-i+1;if(e>0?e%=l:e<0&&(e=(e%l+l)%l),0===e)return;let r=i+e;o(t,i,r-1),o(t,r,a),o(t,i,a)},t.fill=function(t,e,i=0,a=-1){let n,o=t.length;if(0!==o){i=i<0?Math.max(0,i+o):Math.min(i,o-1),n=(a=a<0?Math.max(0,a+o):Math.min(a,o-1))e;--i)t[i]=t[i-1];t[e]=i},t.removeAt=l,t.removeFirstOf=function(t,i,a=0,n=-1){let o=e(t,i,a,n);return-1!==o&&l(t,o),o},t.removeLastOf=function(t,e,a=-1,n=0){let o=i(t,e,a,n);return-1!==o&&l(t,o),o},t.removeAllOf=function(t,e,i=0,a=-1){let n=t.length;if(0===n)return 0;i=i<0?Math.max(0,i+n):Math.min(i,n-1),a=a<0?Math.max(0,a+n):Math.min(a,n-1);let o=0;for(let l=0;l=i&&l<=a&&t[l]===e||a=i)&&t[l]===e?o++:o>0&&(t[l-o]=t[l]);return o>0&&(t.length=n-o),o},t.removeFirstWhere=function(t,e,i=0,n=-1){let o,r=a(t,e,i,n);return-1!==r&&(o=l(t,r)),{index:r,value:o}},t.removeLastWhere=function(t,e,i=-1,a=0){let o,r=n(t,e,i,a);return-1!==r&&(o=l(t,r)),{index:r,value:o}},t.removeAllWhere=function(t,e,i=0,a=-1){let n=t.length;if(0===n)return 0;i=i<0?Math.max(0,i+n):Math.min(i,n-1),a=a<0?Math.max(0,a+n):Math.min(a,n-1);let o=0;for(let l=0;l=i&&l<=a&&e(t[l],l)||a=i)&&e(t[l],l)?o++:o>0&&(t[l-o]=t[l]);return o>0&&(t.length=n-o),o}}(t.ArrayExt||(t.ArrayExt={})),(i||(i={})).rangeLength=function(t,e,i){return 0===i?1/0:t>e&&i>0||te?1:0}}(t.StringExt||(t.StringExt={})),t.chain=function*(...t){for(let e of t)yield*e},t.each=function(t,e){let i=0;for(let a of t)if(!1===e(a,i++))return},t.empty=function*(){},t.enumerate=function*(t,e=0){for(let i of t)yield[e++,i]},t.every=e,t.filter=function*(t,e){let i=0;for(let a of t)e(a,i++)&&(yield a)},t.find=function(t,e){let i=0;for(let a of t)if(e(a,i++))return a},t.findIndex=function(t,e){let i=0;for(let a of t)if(e(a,i++))return i-1;return-1},t.map=function*(t,e){let i=0;for(let a of t)yield e(a,i++)},t.max=function(t,e){let i;for(let a of t)void 0!==i?e(a,i)>0&&(i=a):i=a;return i},t.min=function(t,e){let i;for(let a of t)void 0!==i?e(a,i)<0&&(i=a):i=a;return i},t.minmax=function(t,e){let i,a,n=!0;for(let o of t)n?(i=o,a=o,n=!1):e(o,i)<0?i=o:e(o,a)>0&&(a=o);return n?void 0:[i,a]},t.once=function*(t){yield t},t.range=function*(t,e,a){void 0===e?(e=t,t=0,a=1):void 0===a&&(a=1);let n=i.rangeLength(t,e,a);for(let e=0;e-1;e--)yield t[e]},t.some=function(t,e){let i=0;for(let a of t)if(e(a,i++))return!0;return!1},t.stride=function*(t,e){let i=0;for(let a of t)i++%e==0&&(yield a)},t.take=function*(t,e){if(e<1)return;let i,a=t[Symbol.iterator]();for(;0t[Symbol.iterator]())),a=i.map((t=>t.next()));for(;e(a,(t=>!t.done));a=i.map((t=>t.next())))yield a.map((t=>t.value))}},"object"==typeof t&&void 0!==e?a(t):"function"==typeof define&&__webpack_require__.amdO?define(["exports"],a):a((i="undefined"!=typeof globalThis?globalThis:i||self).lumino_algorithm={})})),pe=F(((t,e)=>{var i,a;i=t,a=function(t){function e(t){let e=0;for(let i=0,a=t.length;i>>0),t[i]=255&e,e>>>=8}t.JSONExt=void 0,function(t){function e(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t}function i(t){return Array.isArray(t)}t.emptyObject=Object.freeze({}),t.emptyArray=Object.freeze([]),t.isPrimitive=e,t.isArray=i,t.isObject=function(t){return!e(t)&&!i(t)},t.deepEqual=function t(a,n){if(a===n)return!0;if(e(a)||e(n))return!1;let o=i(a),l=i(n);return o===l&&(o&&l?function(e,i){if(e===i)return!0;if(e.length!==i.length)return!1;for(let a=0,n=e.length;a{let t="undefined"!=typeof window&&(window.crypto||window.msCrypto)||null;return t&&"function"==typeof t.getRandomValues?function(e){return t.getRandomValues(e)}:e})(),t.UUID=void 0,(t.UUID||(t.UUID={})).uuid4=function(t){let e=new Uint8Array(16),i=new Array(256);for(let t=0;t<16;++t)i[t]="0"+t.toString(16);for(let t=16;t<256;++t)i[t]=t.toString(16);return function(){return t(e),e[6]=64|15&e[6],e[8]=128|63&e[8],i[e[0]]+i[e[1]]+i[e[2]]+i[e[3]]+"-"+i[e[4]]+i[e[5]]+"-"+i[e[6]]+i[e[7]]+"-"+i[e[8]]+i[e[9]]+"-"+i[e[10]]+i[e[11]]+i[e[12]]+i[e[13]]+i[e[14]]+i[e[15]]}}(t.Random.getRandomValues),t.MimeData=class{constructor(){this._types=[],this._values=[]}types(){return this._types.slice()}hasData(t){return-1!==this._types.indexOf(t)}getData(t){let e=this._types.indexOf(t);return-1!==e?this._values[e]:void 0}setData(t,e){this.clearData(t),this._types.push(t),this._values.push(e)}clearData(t){let e=this._types.indexOf(t);-1!==e&&(this._types.splice(e,1),this._values.splice(e,1))}clear(){this._types.length=0,this._values.length=0}},t.PromiseDelegate=class{constructor(){this.promise=new Promise(((t,e)=>{this._resolve=t,this._reject=e}))}resolve(t){(0,this._resolve)(t)}reject(t){(0,this._reject)(t)}},t.Token=class{constructor(t,e){this.name=t,this.description=null!=e?e:"",this._tokenStructuralPropertyT=null}}},"object"==typeof t&&void 0!==e?a(t):"function"==typeof define&&__webpack_require__.amdO?define(["exports"],a):a((i="undefined"!=typeof globalThis?globalThis:i||self).lumino_coreutils={})})),Xe=F(((t,e)=>{var i,a;i=t,a=function(t,e,i){class a{constructor(t){this.sender=t}connect(t,e){return o.connect(this,t,e)}disconnect(t,e){return o.disconnect(this,t,e)}emit(t){o.emit(this,t)}}var n,o;(n=a||(a={})).disconnectBetween=function(t,e){o.disconnectBetween(t,e)},n.disconnectSender=function(t){o.disconnectSender(t)},n.disconnectReceiver=function(t){o.disconnectReceiver(t)},n.disconnectAll=function(t){o.disconnectAll(t)},n.clearData=function(t){o.disconnectAll(t)},n.getExceptionHandler=function(){return o.exceptionHandler},n.setExceptionHandler=function(t){let e=o.exceptionHandler;return o.exceptionHandler=t,e};class l extends a{constructor(){super(...arguments),this._pending=new i.PromiseDelegate}async*[Symbol.asyncIterator](){let t=this._pending;for(;;)try{let{args:e,next:i}=await t.promise;t=i,yield e}catch{return}}emit(t){let e=this._pending,a=this._pending=new i.PromiseDelegate;e.resolve({args:t,next:a}),super.emit(t)}stop(){this._pending.promise.catch((()=>{})),this._pending.reject("stop"),this._pending=new i.PromiseDelegate}}(function(t){function i(t){let e=n.get(t);if(e&&0!==e.length){for(let t of e){if(!t.signal)continue;let e=t.thisArg||t.slot;t.signal=null,c(o.get(e))}c(e)}}function a(t){let e=o.get(t);if(e&&0!==e.length){for(let t of e){if(!t.signal)continue;let e=t.signal.sender;t.signal=null,c(n.get(e))}c(e)}}t.exceptionHandler=t=>{console.error(t)},t.connect=function(t,e,i){i=i||void 0;let a=n.get(t.sender);if(a||(a=[],n.set(t.sender,a)),p(a,t,e,i))return!1;let l=i||e,r=o.get(l);r||(r=[],o.set(l,r));let s={signal:t,slot:e,thisArg:i};return a.push(s),r.push(s),!0},t.disconnect=function(t,e,i){i=i||void 0;let a=n.get(t.sender);if(!a||0===a.length)return!1;let l=p(a,t,e,i);if(!l)return!1;let r=i||e,s=o.get(r);return l.signal=null,c(a),c(s),!0},t.disconnectBetween=function(t,e){let i=n.get(t);if(!i||0===i.length)return;let a=o.get(e);if(a&&0!==a.length){for(let e of a)e.signal&&e.signal.sender===t&&(e.signal=null);c(i),c(a)}},t.disconnectSender=i,t.disconnectReceiver=a,t.disconnectAll=function(t){i(t),a(t)},t.emit=function(t,e){let i=n.get(t.sender);if(i&&0!==i.length)for(let a=0,n=i.length;at.signal===i&&t.slot===a&&t.thisArg===n))}function s(e,i){let{signal:a,slot:n,thisArg:o}=e;try{n.call(o,a.sender,i)}catch(e){t.exceptionHandler(e)}}function c(t){0===l.size&&r(d),l.add(t)}function d(){l.forEach(m),l.clear()}function m(t){e.ArrayExt.removeAllWhere(t,u)}function u(t){return null===t.signal}})(o||(o={})),t.Signal=a,t.Stream=l},"object"==typeof t&&void 0!==e?a(t,Ye(),pe()):"function"==typeof define&&__webpack_require__.amdO?define(["exports","@lumino/algorithm","@lumino/coreutils"],a):a((i="undefined"!=typeof globalThis?globalThis:i||self).lumino_signaling={},i.lumino_algorithm,i.lumino_coreutils)})),et=F((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ActivityMonitor=void 0;var e=Xe();t.ActivityMonitor=class{constructor(t){this._timer=-1,this._timeout=-1,this._isDisposed=!1,this._activityStopped=new e.Signal(this),t.signal.connect(this._onSignalFired,this),this._timeout=t.timeout||1e3}get activityStopped(){return this._activityStopped}get timeout(){return this._timeout}set timeout(t){this._timeout=t}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,e.Signal.clearData(this))}_onSignalFired(t,e){clearTimeout(this._timer),this._sender=t,this._args=e,this._timer=setTimeout((()=>{this._activityStopped.emit({sender:this._sender,args:this._args})}),this._timeout)}}})),it=F((t=>{Object.defineProperty(t,"__esModule",{value:!0})})),nt=F((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MarkdownCodeBlocks=void 0,function(t){t.CODE_BLOCK_MARKER="```";let e=[".markdown",".mdown",".mkdn",".md",".mkd",".mdwn",".mdtxt",".mdtext",".text",".txt",".Rmd"];class i{constructor(t){this.startLine=t,this.code="",this.endLine=-1}}t.MarkdownCodeBlock=i,t.isMarkdown=function(t){return e.indexOf(t)>-1},t.findMarkdownCodeBlocks=function(e){if(!e||""===e)return[];let a=e.split("\n"),n=[],o=null;for(let e=0;e{function i(t){return!("number"!=typeof t&&!/^0x[0-9a-f]+$/i.test(t))||/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(t)}function a(t,e){return"constructor"===e&&"function"==typeof t[e]||"__proto__"===e}e.exports=function(t,e){e||(e={});var n={bools:{},strings:{},unknownFn:null};"function"==typeof e.unknown&&(n.unknownFn=e.unknown),"boolean"==typeof e.boolean&&e.boolean?n.allBools=!0:[].concat(e.boolean).filter(Boolean).forEach((function(t){n.bools[t]=!0}));var o={};function l(t){return o[t].some((function(t){return n.bools[t]}))}Object.keys(e.alias||{}).forEach((function(t){o[t]=[].concat(e.alias[t]),o[t].forEach((function(e){o[e]=[t].concat(o[t].filter((function(t){return e!==t})))}))})),[].concat(e.string).filter(Boolean).forEach((function(t){n.strings[t]=!0,o[t]&&[].concat(o[t]).forEach((function(t){n.strings[t]=!0}))}));var r=e.default||{},p={_:[]};function s(t,e,i){for(var o=t,l=0;l{function i(t){if("string"!=typeof t)throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}function a(t,e){for(var i,a="",n=0,o=-1,l=0,r=0;r<=t.length;++r){if(r2){var p=a.lastIndexOf("/");if(p!==a.length-1){-1===p?(a="",n=0):n=(a=a.slice(0,p)).length-1-a.lastIndexOf("/"),o=r,l=0;continue}}else if(2===a.length||1===a.length){a="",n=0,o=r,l=0;continue}e&&(a.length>0?a+="/..":a="..",n=2)}else a.length>0?a+="/"+t.slice(o+1,r):a=t.slice(o+1,r),n=r-o-1;o=r,l=0}else 46===i&&-1!==l?++l:l=-1}return a}var n={resolve:function(){for(var t,e="",n=!1,o=arguments.length-1;o>=-1&&!n;o--){var l;o>=0?l=arguments[o]:(void 0===t&&(t=process.cwd()),l=t),i(l),0!==l.length&&(e=l+"/"+e,n=47===l.charCodeAt(0))}return e=a(e,!n),n?e.length>0?"/"+e:"/":e.length>0?e:"."},normalize:function(t){if(i(t),0===t.length)return".";var e=47===t.charCodeAt(0),n=47===t.charCodeAt(t.length-1);return 0===(t=a(t,!e)).length&&!e&&(t="."),t.length>0&&n&&(t+="/"),e?"/"+t:t},isAbsolute:function(t){return i(t),t.length>0&&47===t.charCodeAt(0)},join:function(){if(0===arguments.length)return".";for(var t,e=0;e0&&(void 0===t?t=a:t+="/"+a)}return void 0===t?".":n.normalize(t)},relative:function(t,e){if(i(t),i(e),t===e||(t=n.resolve(t))===(e=n.resolve(e)))return"";for(var a=1;as){if(47===e.charCodeAt(r+d))return e.slice(r+d+1);if(0===d)return e.slice(r+d)}else l>s&&(47===t.charCodeAt(a+d)?c=d:0===d&&(c=0));break}var m=t.charCodeAt(a+d);if(m!==e.charCodeAt(r+d))break;47===m&&(c=d)}var u="";for(d=a+c+1;d<=o;++d)(d===o||47===t.charCodeAt(d))&&(0===u.length?u+="..":u+="/..");return u.length>0?u+e.slice(r+c):(r+=c,47===e.charCodeAt(r)&&++r,e.slice(r))},_makeLong:function(t){return t},dirname:function(t){if(i(t),0===t.length)return".";for(var e=t.charCodeAt(0),a=47===e,n=-1,o=!0,l=t.length-1;l>=1;--l)if(47===(e=t.charCodeAt(l))){if(!o){n=l;break}}else o=!1;return-1===n?a?"/":".":a&&1===n?"//":t.slice(0,n)},basename:function(t,e){if(void 0!==e&&"string"!=typeof e)throw new TypeError('"ext" argument must be a string');i(t);var a,n=0,o=-1,l=!0;if(void 0!==e&&e.length>0&&e.length<=t.length){if(e.length===t.length&&e===t)return"";var r=e.length-1,p=-1;for(a=t.length-1;a>=0;--a){var s=t.charCodeAt(a);if(47===s){if(!l){n=a+1;break}}else-1===p&&(l=!1,p=a+1),r>=0&&(s===e.charCodeAt(r)?-1==--r&&(o=a):(r=-1,o=p))}return n===o?o=p:-1===o&&(o=t.length),t.slice(n,o)}for(a=t.length-1;a>=0;--a)if(47===t.charCodeAt(a)){if(!l){n=a+1;break}}else-1===o&&(l=!1,o=a+1);return-1===o?"":t.slice(n,o)},extname:function(t){i(t);for(var e=-1,a=0,n=-1,o=!0,l=0,r=t.length-1;r>=0;--r){var p=t.charCodeAt(r);if(47!==p)-1===n&&(o=!1,n=r+1),46===p?-1===e?e=r:1!==l&&(l=1):-1!==e&&(l=-1);else if(!o){a=r+1;break}}return-1===e||-1===n||0===l||1===l&&e===n-1&&e===a+1?"":t.slice(e,n)},format:function(t){if(null===t||"object"!=typeof t)throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof t);return function(t,e){var i=e.dir||e.root,a=e.base||(e.name||"")+(e.ext||"");return i?i===e.root?i+a:i+"/"+a:a}(0,t)},parse:function(t){i(t);var e={root:"",dir:"",base:"",ext:"",name:""};if(0===t.length)return e;var a,n=t.charCodeAt(0),o=47===n;o?(e.root="/",a=1):a=0;for(var l=-1,r=0,p=-1,s=!0,c=t.length-1,d=0;c>=a;--c)if(47!==(n=t.charCodeAt(c)))-1===p&&(s=!1,p=c+1),46===n?-1===l?l=c:1!==d&&(d=1):-1!==l&&(d=-1);else if(!s){r=c+1;break}return-1===l||-1===p||0===d||1===d&&l===p-1&&l===r+1?-1!==p&&(e.base=e.name=0===r&&o?t.slice(1,p):t.slice(r,p)):(0===r&&o?(e.name=t.slice(1,l),e.base=t.slice(1,p)):(e.name=t.slice(r,l),e.base=t.slice(r,p)),e.ext=t.slice(l,p)),r>0?e.dir=t.slice(0,r-1):o&&(e.dir="/"),e},sep:"/",delimiter:":",win32:null,posix:null};n.posix=n,e.exports=n})),dt=F(((t,e)=>{e.exports=function(t,e){if(e=e.split(":")[0],!(t=+t))return!1;switch(e){case"http":case"ws":return 80!==t;case"https":case"wss":return 443!==t;case"ftp":return 21!==t;case"gopher":return 70!==t;case"file":return!1}return 0!==t}})),ut=F((t=>{var e=Object.prototype.hasOwnProperty;function i(t){try{return decodeURIComponent(t.replace(/\+/g," "))}catch{return null}}function a(t){try{return encodeURIComponent(t)}catch{return null}}t.stringify=function(t,i){i=i||"";var n,o,l=[];for(o in"string"!=typeof i&&(i="?"),t)if(e.call(t,o)){if(!(n=t[o])&&(null==n||isNaN(n))&&(n=""),o=a(o),n=a(n),null===o||null===n)continue;l.push(o+"="+n)}return l.length?i+l.join("&"):""},t.parse=function(t){for(var e,a=/([^=?#&]+)=?([^&]*)/g,n={};e=a.exec(t);){var o=i(e[1]),l=i(e[2]);null===o||null===l||o in n||(n[o]=l)}return n}})),_t=F(((t,e)=>{var i=dt(),a=ut(),n=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/,o=/[\n\r\t]/g,l=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,r=/:\d+$/,p=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,s=/^[a-zA-Z]:/;function c(t){return(t||"").toString().replace(n,"")}var d=[["#","hash"],["?","query"],function(t,e){return f(e.protocol)?t.replace(/\\/g,"/"):t},["/","pathname"],["@","auth",1],[NaN,"host",void 0,1,1],[/:(\d*)$/,"port",void 0,1],[NaN,"hostname",void 0,1,1]],m={hash:1,query:1};function u(t){var e,i=("undefined"!=typeof window?window:void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:{}).location||{},a={},n=typeof(t=t||i);if("blob:"===t.protocol)a=new v(unescape(t.pathname),{});else if("string"===n)for(e in a=new v(t,{}),m)delete a[e];else if("object"===n){for(e in t)e in m||(a[e]=t[e]);void 0===a.slashes&&(a.slashes=l.test(t.href))}return a}function f(t){return"file:"===t||"ftp:"===t||"http:"===t||"https:"===t||"ws:"===t||"wss:"===t}function h(t,e){t=(t=c(t)).replace(o,""),e=e||{};var i,a=p.exec(t),n=a[1]?a[1].toLowerCase():"",l=!!a[2],r=!!a[3],s=0;return l?r?(i=a[2]+a[3]+a[4],s=a[2].length+a[3].length):(i=a[2]+a[4],s=a[2].length):r?(i=a[3]+a[4],s=a[3].length):i=a[4],"file:"===n?s>=2&&(i=i.slice(2)):f(n)?i=a[4]:n?l&&(i=i.slice(2)):s>=2&&f(e.protocol)&&(i=a[4]),{protocol:n,slashes:l||f(n),slashesCount:s,rest:i}}function v(t,e,n){if(t=(t=c(t)).replace(o,""),!(this instanceof v))return new v(t,e,n);var l,r,p,m,x,g,b=d.slice(),w=typeof e,y=this,_=0;for("object"!==w&&"string"!==w&&(n=e,e=null),n&&"function"!=typeof n&&(n=a.parse),l=!(r=h(t||"",e=u(e))).protocol&&!r.slashes,y.slashes=r.slashes||l&&e.slashes,y.protocol=r.protocol||e.protocol||"",t=r.rest,("file:"===r.protocol&&(2!==r.slashesCount||s.test(t))||!r.slashes&&(r.protocol||r.slashesCount<2||!f(y.protocol)))&&(b[3]=[/(.*)/,"pathname"]);_{var e=t&&t.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(t,"__esModule",{value:!0}),t.URLExt=void 0;var i=ke(),a=e(_t());!function(t){function e(t){if("undefined"!=typeof document&&document){let e=document.createElement("a");return e.href=t,e}return(0,a.default)(t)}function n(...t){let e=(0,a.default)(t[0],{}),n=""===e.protocol&&e.slashes;n&&(e=(0,a.default)(t[0],"https:"+t[0]));let o=`${n?"":e.protocol}${e.slashes?"//":""}${e.auth}${e.auth?"@":""}${e.host}`,l=i.posix.join(`${o&&"/"!==e.pathname[0]?"/":""}${e.pathname}`,...t.slice(1));return`${o}${"."===l?"":l}`}t.parse=e,t.getHostName=function(t){return(0,a.default)(t).hostname},t.normalize=function(t){return t&&e(t).toString()},t.join=n,t.encodeParts=function(t){return n(...t.split("/").map(encodeURIComponent))},t.objectToQueryString=function(t){let e=Object.keys(t).filter((t=>t.length>0));return e.length?"?"+e.map((e=>{let i=encodeURIComponent(String(t[e]));return e+(i?"="+i:"")})).join("&"):""},t.queryStringToObject=function(t){return t.replace(/^\?/,"").split("&").reduce(((t,e)=>{let[i,a]=e.split("=");return i.length>0&&(t[i]=decodeURIComponent(a||"")),t}),{})},t.isLocal=function(t){let{protocol:i}=e(t);return(!i||0!==t.toLowerCase().indexOf(i))&&0!==t.indexOf("/")}}(t.URLExt||(t.URLExt={}))})),kt=F(((exports,module)=>{var __importDefault=exports&&exports.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.PageConfig=void 0;var coreutils_1=pe(),minimist_1=__importDefault(rt()),url_1=Ne(),PageConfig;(function(PageConfig){function getOption(name){if(configData)return configData[name]||getBodyData(name);configData=Object.create(null);let found=!1;if("undefined"!=typeof document&&document){let t=document.getElementById("jupyter-config-data");t&&(configData=JSON.parse(t.textContent||""),found=!0)}if(!found&&"undefined"!=typeof process&&process.argv)try{let cli=(0,minimist_1.default)(process.argv.slice(2)),path=ke(),fullPath="";"jupyter-config-data"in cli?fullPath=path.resolve(cli["jupyter-config-data"]):"JUPYTER_CONFIG_DATA"in{}&&(fullPath=path.resolve({}.JUPYTER_CONFIG_DATA)),fullPath&&(configData=eval("require")(fullPath))}catch(t){console.error(t)}if(coreutils_1.JSONExt.isObject(configData))for(let t in configData)"string"!=typeof configData[t]&&(configData[t]=JSON.stringify(configData[t]));else configData=Object.create(null);return configData[name]||getBodyData(name)}function setOption(t,e){let i=getOption(t);return configData[t]=e,i}function getBaseUrl(){return url_1.URLExt.normalize(getOption("baseUrl")||"/")}function getTreeUrl(){return url_1.URLExt.join(getBaseUrl(),getOption("treeUrl"))}function getShareUrl(){return url_1.URLExt.normalize(getOption("shareUrl")||getBaseUrl())}function getTreeShareUrl(){return url_1.URLExt.normalize(url_1.URLExt.join(getShareUrl(),getOption("treeUrl")))}function getUrl(t){var e,i,a,n;let o=t.toShare?getShareUrl():getBaseUrl(),l=null!==(e=t.mode)&&void 0!==e?e:getOption("mode"),r=null!==(i=t.workspace)&&void 0!==i?i:getOption("workspace"),p="single-document"===l?"doc":"lab";o=url_1.URLExt.join(o,p),r!==PageConfig.defaultWorkspace&&(o=url_1.URLExt.join(o,"workspaces",encodeURIComponent(null!==(a=getOption("workspace"))&&void 0!==a?a:PageConfig.defaultWorkspace)));let s=null!==(n=t.treePath)&&void 0!==n?n:getOption("treePath");return s&&(o=url_1.URLExt.join(o,"tree",url_1.URLExt.encodeParts(s))),o}function getWsUrl(t){let e=getOption("wsUrl");if(!e){if(0!==(t=t?url_1.URLExt.normalize(t):getBaseUrl()).indexOf("http"))return"";e="ws"+t.slice(4)}return url_1.URLExt.normalize(e)}function getNBConvertURL({path:t,format:e,download:i}){let a=url_1.URLExt.encodeParts(t),n=url_1.URLExt.join(getBaseUrl(),"nbconvert",e,a);return i?n+"?download=true":n}function getToken(){return getOption("token")||getBodyData("jupyterApiToken")}function getNotebookVersion(){let t=getOption("notebookVersion");return""===t?[0,0,0]:JSON.parse(t)}PageConfig.getOption=getOption,PageConfig.setOption=setOption,PageConfig.getBaseUrl=getBaseUrl,PageConfig.getTreeUrl=getTreeUrl,PageConfig.getShareUrl=getShareUrl,PageConfig.getTreeShareUrl=getTreeShareUrl,PageConfig.getUrl=getUrl,PageConfig.defaultWorkspace="default",PageConfig.getWsUrl=getWsUrl,PageConfig.getNBConvertURL=getNBConvertURL,PageConfig.getToken=getToken,PageConfig.getNotebookVersion=getNotebookVersion;let configData=null,Extension;function getBodyData(t){if("undefined"==typeof document||!document.body)return"";let e=document.body.dataset[t];return void 0===e?"":decodeURIComponent(e)}!function(t){function e(t){try{let e=getOption(t);if(e)return JSON.parse(e)}catch(e){console.warn(`Unable to parse ${t}.`,e)}return[]}t.deferred=e("deferredExtensions"),t.disabled=e("disabledExtensions"),t.isDeferred=function(e){let i=e.indexOf(":"),a="";return-1!==i&&(a=e.slice(0,i)),t.deferred.some((t=>t===e||a&&t===a))},t.isDisabled=function(e){let i=e.indexOf(":"),a="";return-1!==i&&(a=e.slice(0,i)),t.disabled.some((t=>t===e||a&&t===a))}}(Extension=PageConfig.Extension||(PageConfig.Extension={}))})(PageConfig=exports.PageConfig||(exports.PageConfig={}))})),jt=F((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PathExt=void 0;var e=ke();!function(t){function i(t){return 0===t.indexOf("/")&&(t=t.slice(1)),t}t.join=function(...t){let a=e.posix.join(...t);return"."===a?"":i(a)},t.basename=function(t,i){return e.posix.basename(t,i)},t.dirname=function(t){let a=i(e.posix.dirname(t));return"."===a?"":a},t.extname=function(t){return e.posix.extname(t)},t.normalize=function(t){return""===t?"":i(e.posix.normalize(t))},t.resolve=function(...t){return i(e.posix.resolve(...t))},t.relative=function(t,a){return i(e.posix.relative(t,a))},t.normalizeExtension=function(t){return t.length>0&&0!==t.indexOf(".")&&(t=`.${t}`),t},t.removeSlash=i}(t.PathExt||(t.PathExt={}))})),Ct=F((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.signalToPromise=void 0;var e=pe();t.signalToPromise=function(t,i){let a=new e.PromiseDelegate;function n(){t.disconnect(o)}function o(t,e){n(),a.resolve([t,e])}return t.connect(o),(null!=i?i:0)>0&&setTimeout((()=>{n(),a.reject(`Signal not emitted within ${i} ms.`)}),i),a.promise}})),Ot=F((t=>{var e;Object.defineProperty(t,"__esModule",{value:!0}),t.Text=void 0,(e=t.Text||(t.Text={})).jsIndexToCharIndex=function(t,e){return t},e.charIndexToJsIndex=function(t,e){return t},e.camelCase=function(t,e=!1){return t.replace(/^(\w)|[\s-_:]+(\w)/g,(function(t,i,a){return a?a.toUpperCase():e?i.toUpperCase():i.toLowerCase()}))},e.titleCase=function(t){return(t||"").toLowerCase().split(" ").map((t=>t.charAt(0).toUpperCase()+t.slice(1))).join(" ")}})),Pt=F((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Time=void 0;var e,i=[{name:"years",milliseconds:31536e6},{name:"months",milliseconds:2592e6},{name:"days",milliseconds:864e5},{name:"hours",milliseconds:36e5},{name:"minutes",milliseconds:6e4},{name:"seconds",milliseconds:1e3}];(e=t.Time||(t.Time={})).formatHuman=function(t){let e=document.documentElement.lang||"en",a=new Intl.RelativeTimeFormat(e,{numeric:"auto"}),n=new Date(t).getTime()-Date.now();for(let t of i){let e=Math.ceil(n/t.milliseconds);if(0!==e)return a.format(e,t.name)}return a.format(0,"seconds")},e.format=function(t){let e=document.documentElement.lang||"en";return new Intl.DateTimeFormat(e,{dateStyle:"short",timeStyle:"short"}).format(new Date(t))}})),xe=F((t=>{var e=t&&t.__createBinding||(Object.create?function(t,e,i,a){void 0===a&&(a=i);var n=Object.getOwnPropertyDescriptor(e,i);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(t,a,n)}:function(t,e,i,a){void 0===a&&(a=i),t[a]=e[i]}),i=t&&t.__exportStar||function(t,i){for(var a in t)"default"!==a&&!Object.prototype.hasOwnProperty.call(i,a)&&e(i,t,a)};Object.defineProperty(t,"__esModule",{value:!0}),i(et(),t),i(it(),t),i(nt(),t),i(kt(),t),i(jt(),t),i(Ct(),t),i(Ot(),t),i(Pt(),t),i(Ne(),t)})),zt=F(((t,e)=>{function i(){this._types=Object.create(null),this._extensions=Object.create(null);for(let t=0;t{e.exports={"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]}})),Dt=F(((t,e)=>{e.exports={"application/prs.cww":["cww"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.sap.vds":["vds"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]}})),Tt=F(((t,e)=>{var i=zt();e.exports=new i(Et(),Dt())})),At,qt,Le,Ti,Y,ne,Ai,Fe=ce((()=>{var t;At=se(xe()),qt=se(Tt()),Le=se(pe()),Ti=new Le.Token("@jupyterlite/contents:IContents"),(t=Y||(Y={})).JSON="application/json",t.PLAIN_TEXT="text/plain",t.OCTET_STREAM="octet/stream",function(t){let e=JSON.parse(At.PageConfig.getOption("fileTypes")||"{}");t.getType=function(t,i=null){t=t.toLowerCase();for(let i of Object.values(e))for(let e of i.extensions||[])if(e===t&&i.mimeTypes&&i.mimeTypes.length)return i.mimeTypes[0];return qt.default.getType(t)||i||Y.OCTET_STREAM},t.hasFormat=function(t,i){t=t.toLowerCase();for(let a of Object.values(e))if(a.fileFormat===i)for(let e of a.extensions||[])if(e===t)return!0;return!1}}(ne||(ne={})),Ai=new Le.Token("@jupyterlite/contents:IBroadcastChannelWrapper")})),oe,X,Lt,Ut,Nt,Be,Se,Ft=ce((()=>{oe=se(xe()),X=se(xe()),Fe(),Lt=se(pe()),Ut="JupyterLite Storage",Nt=5,Be=class{constructor(t){this.reduceBytesToString=(t,e)=>t+String.fromCharCode(e),this._serverContents=new Map,this._storageName=Ut,this._storageDrivers=null,this._localforage=t.localforage,this._storageName=t.storageName||Ut,this._storageDrivers=t.storageDrivers||null,this._ready=new Lt.PromiseDelegate}async initialize(){await this.initStorage(),this._ready.resolve(void 0)}async initStorage(){this._storage=this.createDefaultStorage(),this._counters=this.createDefaultCounters(),this._checkpoints=this.createDefaultCheckpoints()}get ready(){return this._ready.promise}get storage(){return this.ready.then((()=>this._storage))}get counters(){return this.ready.then((()=>this._counters))}get checkpoints(){return this.ready.then((()=>this._checkpoints))}get defaultStorageOptions(){let t=this._storageDrivers&&this._storageDrivers.length?this._storageDrivers:null;return{version:1,name:this._storageName,...t?{driver:t}:{}}}createDefaultStorage(){return this._localforage.createInstance({description:"Offline Storage for Notebooks and Files",storeName:"files",...this.defaultStorageOptions})}createDefaultCounters(){return this._localforage.createInstance({description:"Store the current file suffix counters",storeName:"counters",...this.defaultStorageOptions})}createDefaultCheckpoints(){return this._localforage.createInstance({description:"Offline Storage for Checkpoints",storeName:"checkpoints",...this.defaultStorageOptions})}async newUntitled(t){var e,i,a;let n,o=null!==(e=null==t?void 0:t.path)&&void 0!==e?e:"",l=null!==(i=null==t?void 0:t.type)&&void 0!==i?i:"notebook",r=(new Date).toISOString(),p=X.PathExt.dirname(o),s=X.PathExt.basename(o),c=X.PathExt.extname(o),d=await this.get(p),m="";switch(o&&!c&&d?(p=`${o}/`,m=""):p&&s?(p=`${p}/`,m=s):(p="",m=o),l){case"directory":m=`Untitled Folder${await this._incrementCounter("directory")||""}`,n={name:m,path:`${p}${m}`,last_modified:r,created:r,format:"json",mimetype:"",content:null,size:0,writable:!0,type:"directory"};break;case"notebook":{let t=await this._incrementCounter("notebook");m=m||`Untitled${t||""}.ipynb`,n={name:m,path:`${p}${m}`,last_modified:r,created:r,format:"json",mimetype:Y.JSON,content:Se.EMPTY_NB,size:JSON.stringify(Se.EMPTY_NB).length,writable:!0,type:"notebook"};break}default:{let e,i=null!==(a=null==t?void 0:t.ext)&&void 0!==a?a:".txt",o=await this._incrementCounter("file"),l=ne.getType(i)||Y.OCTET_STREAM;e=ne.hasFormat(i,"text")||-1!==l.indexOf("text")?"text":-1!==i.indexOf("json")||-1!==i.indexOf("ipynb")?"json":"base64",m=m||`untitled${o||""}${i}`,n={name:m,path:`${p}${m}`,last_modified:r,created:r,format:e,mimetype:l,content:"",size:0,writable:!0,type:"file"};break}}let u=n.path;return await(await this.storage).setItem(u,n),n}async copy(t,e){let i=X.PathExt.basename(t);for(e=""===e?"":`${e.slice(1)}/`;await this.get(`${e}${i}`,{content:!0});){let t=X.PathExt.extname(i);i=`${i.replace(t,"")} (copy)${t}`}let a=`${e}${i}`,n=await this.get(t,{content:!0});if(!n)throw Error(`Could not find file with path ${t}`);return n={...n,name:i,path:a},await(await this.storage).setItem(a,n),n}async get(t,e){if(""===(t=decodeURIComponent(t.replace(/^\//,""))))return await this._getFolder(t);let i=await this.storage,a=await i.getItem(t),n=await this._getServerContents(t,e),o=a||n;if(!o)return null;if(null==e||!e.content)return{size:0,...o,content:null};if("directory"===o.type){let e=new Map;await i.iterate(((i,a)=>{a===`${t}/${i.name}`&&e.set(i.name,i)}));let a=n?n.content:Array.from((await this._getServerDirectory(t)).values());for(let t of a)e.has(t.name)||e.set(t.name,t);let l=[...e.values()];return{name:X.PathExt.basename(t),path:t,last_modified:o.last_modified,created:o.created,format:"json",mimetype:Y.JSON,content:l,size:0,writable:!0,type:"directory"}}return o}async rename(t,e){let i=decodeURIComponent(t),a=await this.get(i,{content:!0});if(!a)throw Error(`Could not find file with path ${i}`);let n=(new Date).toISOString(),o=X.PathExt.basename(e),l={...a,name:o,path:e,last_modified:n},r=await this.storage;if(await r.setItem(e,l),await r.removeItem(i),await(await this.checkpoints).removeItem(i),"directory"===a.type){let i;for(i of a.content)await this.rename(oe.URLExt.join(t,i.name),oe.URLExt.join(e,i.name))}return l}async save(t,e={}){var i;t=decodeURIComponent(t);let a=X.PathExt.extname(null!==(i=e.name)&&void 0!==i?i:""),n=e.chunk,o=!!n&&(n>1||-1===n),l=await this.get(t,{content:o});if(l||(l=await this.newUntitled({path:t,ext:a,type:"file"})),!l)return null;let r=l.content,p=(new Date).toISOString();if(l={...l,...e,last_modified:p},e.content&&"base64"===e.format){let t=!n||-1===n;if(".ipynb"===a){let i=this._handleChunk(e.content,r,o);l={...l,content:t?JSON.parse(i):i,format:"json",type:"notebook",size:i.length}}else if(ne.hasFormat(a,"json")){let i=this._handleChunk(e.content,r,o);l={...l,content:t?JSON.parse(i):i,format:"json",type:"file",size:i.length}}else if(ne.hasFormat(a,"text")){let t=this._handleChunk(e.content,r,o);l={...l,content:t,format:"text",type:"file",size:t.length}}else{let t=e.content;l={...l,content:t,size:atob(t).length}}}return await(await this.storage).setItem(t,l),l}async delete(t){let e=`${t=decodeURIComponent(t)}/`,i=(await(await this.storage).keys()).filter((i=>i===t||i.startsWith(e)));await Promise.all(i.map(this.forgetPath,this))}async forgetPath(t){await Promise.all([(await this.storage).removeItem(t),(await this.checkpoints).removeItem(t)])}async createCheckpoint(t){var e;let i=await this.checkpoints;t=decodeURIComponent(t);let a=await this.get(t,{content:!0});if(!a)throw Error(`Could not find file with path ${t}`);let n=(null!==(e=await i.getItem(t))&&void 0!==e?e:[]).filter(Boolean);return n.push(a),n.length>Nt&&n.splice(0,n.length-Nt),await i.setItem(t,n),{id:""+(n.length-1),last_modified:a.last_modified}}async listCheckpoints(t){return(await(await this.checkpoints).getItem(t)||[]).filter(Boolean).map(this.normalizeCheckpoint,this)}normalizeCheckpoint(t,e){return{id:e.toString(),last_modified:t.last_modified}}async restoreCheckpoint(t,e){t=decodeURIComponent(t);let i=(await(await this.checkpoints).getItem(t)||[])[parseInt(e)];await(await this.storage).setItem(t,i)}async deleteCheckpoint(t,e){t=decodeURIComponent(t);let i=await(await this.checkpoints).getItem(t)||[],a=parseInt(e);i.splice(a,1),await(await this.checkpoints).setItem(t,i)}_handleChunk(t,e,i){let a=decodeURIComponent(escape(atob(t)));return i?e+a:a}async _getFolder(t){let e=new Map;await(await this.storage).iterate(((t,i)=>{i.includes("/")||e.set(t.path,t)}));for(let i of(await this._getServerDirectory(t)).values())e.has(i.path)||e.set(i.path,i);return t&&0===e.size?null:{name:"",path:t,last_modified:new Date(0).toISOString(),created:new Date(0).toISOString(),format:"json",mimetype:Y.JSON,content:Array.from(e.values()),size:0,writable:!0,type:"directory"}}async _getServerContents(t,e){let i=X.PathExt.basename(t),a=(await this._getServerDirectory(oe.URLExt.join(t,".."))).get(i);if(!a)return null;if(a=a||{name:i,path:t,last_modified:new Date(0).toISOString(),created:new Date(0).toISOString(),format:"text",mimetype:Y.PLAIN_TEXT,type:"file",writable:!0,size:0,content:""},null!=e&&e.content)if("directory"===a.type){let e=await this._getServerDirectory(t);a={...a,content:Array.from(e.values())}}else{let e=oe.URLExt.join(oe.PageConfig.getBaseUrl(),"files",t),n=await fetch(e);if(!n.ok)return null;let o=a.mimetype||n.headers.get("Content-Type"),l=X.PathExt.extname(i);if("notebook"===a.type||ne.hasFormat(l,"json")||-1!==(null==o?void 0:o.indexOf("json"))||t.match(/\.(ipynb|[^/]*json[^/]*)$/)){let t=await n.text();a={...a,content:JSON.parse(t),format:"json",mimetype:a.mimetype||Y.JSON,size:t.length}}else if(ne.hasFormat(l,"text")||-1!==o.indexOf("text")){let t=await n.text();a={...a,content:t,format:"text",mimetype:o||Y.PLAIN_TEXT,size:t.length}}else{let t=await n.arrayBuffer(),e=new Uint8Array(t);a={...a,content:btoa(e.reduce(this.reduceBytesToString,"")),format:"base64",mimetype:o||Y.OCTET_STREAM,size:e.length}}}return a}async _getServerDirectory(t){let e=this._serverContents.get(t)||new Map;if(!this._serverContents.has(t)){let i=oe.URLExt.join(oe.PageConfig.getBaseUrl(),"api/contents",t,"all.json");try{let t=await fetch(i),a=JSON.parse(await t.text());for(let t of a.content)e.set(t.name,t)}catch(t){console.warn(`don't worry, about ${t}... nothing's broken. If there had been a\n file at ${i}, you might see some more files.`)}this._serverContents.set(t,e)}return e}async _incrementCounter(t){var e;let i=await this.counters,a=(null!==(e=await i.getItem(t))&&void 0!==e?e:-1)+1;return await i.setItem(t,a),a}},(Se||(Se={})).EMPTY_NB={metadata:{orig_nbformat:4},nbformat_minor:4,nbformat:4,cells:[]}})),ze,Bt,qi,Ui,$t=ce((()=>{ze=16895,Bt=33206,qi=1,Ui=2})),Wt,He,De,Ni,Li,Ht,Re,Ee,Ie,$e,We=ce((()=>{Wt=":",He="/api/drive.v1",De=4096,Ni=new TextEncoder,Li=new TextDecoder("utf-8"),Ht={0:!1,1:!0,2:!0,64:!0,65:!0,66:!0,129:!0,193:!0,514:!0,577:!0,578:!0,705:!0,706:!0,1024:!0,1025:!0,1026:!0,1089:!0,1090:!0,1153:!0,1154:!0,1217:!0,1218:!0,4096:!0,4098:!0},Re=class{constructor(t){this.fs=t}open(t){let e=this.fs.realPath(t.node);this.fs.FS.isFile(t.node.mode)&&(t.file=this.fs.API.get(e))}close(t){if(!this.fs.FS.isFile(t.node.mode)||!t.file)return;let e=this.fs.realPath(t.node),i=t.flags,a="string"==typeof i?parseInt(i,10):i;a&=8191;let n=!0;a in Ht&&(n=Ht[a]),n&&this.fs.API.put(e,t.file),t.file=void 0}read(t,e,i,a,n){if(a<=0||void 0===t.file||n>=(t.file.data.length||0))return 0;let o=Math.min(t.file.data.length-n,a);return e.set(t.file.data.subarray(n,n+o),i),o}write(t,e,i,a,n){var o;if(a<=0||void 0===t.file)return 0;if(t.node.timestamp=Date.now(),n+a>((null===(o=t.file)||void 0===o?void 0:o.data.length)||0)){let e=t.file.data?t.file.data:new Uint8Array;t.file.data=new Uint8Array(n+a),t.file.data.set(e)}return t.file.data.set(e.subarray(i,i+a),n),a}llseek(t,e,i){let a=e;if(1===i)a+=t.position;else if(2===i&&this.fs.FS.isFile(t.node.mode)){if(void 0===t.file)throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES.EPERM);a+=t.file.data.length}if(a<0)throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES.EINVAL);return a}},Ee=class{constructor(t){this.fs=t}getattr(t){return{...this.fs.API.getattr(this.fs.realPath(t)),mode:t.mode,ino:t.id}}setattr(t,e){for(let[i,a]of Object.entries(e))switch(i){case"mode":t.mode=a;break;case"timestamp":t.timestamp=a;break;default:console.warn("setattr",i,"of",a,"on",t,"not yet implemented")}}lookup(t,e){let i=this.fs.PATH.join2(this.fs.realPath(t),e),a=this.fs.API.lookup(i);if(!a.ok)throw this.fs.FS.genericErrors[this.fs.ERRNO_CODES.ENOENT];return this.fs.createNode(t,e,a.mode,0)}mknod(t,e,i,a){let n=this.fs.PATH.join2(this.fs.realPath(t),e);return this.fs.API.mknod(n,i),this.fs.createNode(t,e,i,a)}rename(t,e,i){this.fs.API.rename(t.parent?this.fs.PATH.join2(this.fs.realPath(t.parent),t.name):t.name,this.fs.PATH.join2(this.fs.realPath(e),i)),t.name=i,t.parent=e}unlink(t,e){this.fs.API.rmdir(this.fs.PATH.join2(this.fs.realPath(t),e))}rmdir(t,e){this.fs.API.rmdir(this.fs.PATH.join2(this.fs.realPath(t),e))}readdir(t){return this.fs.API.readdir(this.fs.realPath(t))}symlink(t,e,i){throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES.EPERM)}readlink(t){throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES.EPERM)}},Ie=class{constructor(t,e,i,a,n){this._baseUrl=t,this._driveName=e,this._mountpoint=i,this.FS=a,this.ERRNO_CODES=n}request(t){let e=new XMLHttpRequest;e.open("POST",encodeURI(this.endpoint),!1);try{e.send(JSON.stringify(t))}catch(t){console.error(t)}if(e.status>=400)throw new this.FS.ErrnoError(this.ERRNO_CODES.EINVAL);return JSON.parse(e.responseText)}lookup(t){return this.request({method:"lookup",path:this.normalizePath(t)})}getmode(t){return Number.parseInt(this.request({method:"getmode",path:this.normalizePath(t)}))}mknod(t,e){return this.request({method:"mknod",path:this.normalizePath(t),data:{mode:e}})}rename(t,e){return this.request({method:"rename",path:this.normalizePath(t),data:{newPath:this.normalizePath(e)}})}readdir(t){let e=this.request({method:"readdir",path:this.normalizePath(t)});return e.push("."),e.push(".."),e}rmdir(t){return this.request({method:"rmdir",path:this.normalizePath(t)})}get(t){let e=this.request({method:"get",path:this.normalizePath(t)}),i=e.content,a=e.format;switch(a){case"json":case"text":return{data:Ni.encode(i),format:a};case"base64":{let t=atob(i),e=t.length,n=new Uint8Array(e);for(let i=0;i{Ke=se(xe()),We(),Je=class{constructor(t){this.isDisposed=!1,this._onMessage=async t=>{if(!this._channel)return;let{_contents:e}=this,i=t.data,a=null==i?void 0:i.path;if("broadcast.ts"!==(null==i?void 0:i.receiver))return;let n,o=null;switch(null==i?void 0:i.method){case"readdir":n=await e.get(a,{content:!0}),o=[],"directory"===n.type&&n.content&&(o=n.content.map((t=>t.name)));break;case"rmdir":await e.delete(a);break;case"rename":await e.rename(a,i.data.newPath);break;case"getmode":n=await e.get(a),o="directory"===n.type?16895:33206;break;case"lookup":try{n=await e.get(a),o={ok:!0,mode:"directory"===n.type?16895:33206}}catch{o={ok:!1}}break;case"mknod":n=await e.newUntitled({path:Ke.PathExt.dirname(a),type:16895===Number.parseInt(i.data.mode)?"directory":"file",ext:Ke.PathExt.extname(a)}),await e.rename(n.path,a);break;case"getattr":{n=await e.get(a);let t=new Date(0).toISOString();o={dev:1,nlink:1,uid:0,gid:0,rdev:0,size:n.size||0,blksize:De,blocks:Math.ceil(n.size||0/De),atime:n.last_modified||t,mtime:n.last_modified||t,ctime:n.created||t,timestamp:0};break}case"get":if(n=await e.get(a,{content:!0}),"directory"===n.type)break;o={content:"json"===n.format?JSON.stringify(n.content):n.content,format:n.format};break;case"put":await e.save(a,{content:"json"===i.data.format?JSON.parse(i.data.data):i.data.data,type:"file",format:i.data.format});break;default:o=null}this._channel.postMessage(o)},this._channel=null,this._enabled=!1,this._contents=t.contents}get enabled(){return this._enabled}enable(){this._channel?console.warn("BroadcastChannel already created and enabled"):(this._channel=new BroadcastChannel(He),this._channel.addEventListener("message",this._onMessage),this._enabled=!0)}disable(){this._channel&&(this._channel.removeEventListener("message",this._onMessage),this._channel=null),this._enabled=!1}dispose(){this.isDisposed||(this.disable(),this.isDisposed=!0)}}})),Jt={};li(Jt,{BLOCK_SIZE:()=>De,BroadcastChannelWrapper:()=>Je,Contents:()=>Be,ContentsAPI:()=>Ie,DIR_MODE:()=>ze,DRIVE_API_PATH:()=>He,DRIVE_SEPARATOR:()=>Wt,DriveFS:()=>$e,DriveFSEmscriptenNodeOps:()=>Ee,DriveFSEmscriptenStreamOps:()=>Re,FILE:()=>ne,FILE_MODE:()=>Bt,IBroadcastChannelWrapper:()=>Ai,IContents:()=>Ti,MIME:()=>Y,SEEK_CUR:()=>qi,SEEK_END:()=>Ui});var Vt=ce((()=>{Ft(),We(),Fe(),Kt(),$t()})),Yt=class{constructor(){this._options=null,this._initializer=null,this._pyodide=null,this._localPath="",this._driveName="",this._driveFS=null,this._initialized=new Promise(((t,e)=>{this._initializer={resolve:t,reject:e}}))}async initialize(t){var e;if(this._options=t,t.location.includes(":")){let e=t.location.split(":");this._driveName=e[0],this._localPath=e[1]}else this._driveName="",this._localPath=t.location;await this.initRuntime(t),await this.initFilesystem(t),await this.initPackageManager(t),await this.initKernel(t),await this.initGlobals(t),null==(e=this._initializer)||e.resolve()}async initRuntime(t){let e,{pyodideUrl:i,indexUrl:a}=t;i.endsWith(".mjs")?e=(await __webpack_require__(265)(i)).loadPyodide:(importScripts(i),e=self.loadPyodide),this._pyodide=await e({indexURL:a})}async initPackageManager(t){if(!this._options)throw new Error("Uninitialized");let{pipliteWheelUrl:e,disablePyPIFallback:i,pipliteUrls:a}=this._options;await this._pyodide.loadPackage(["micropip"]),await this._pyodide.runPythonAsync(`\n import micropip\n await micropip.install('${e}', keep_going=True)\n import piplite.piplite\n piplite.piplite._PIPLITE_DISABLE_PYPI = ${i?"True":"False"}\n piplite.piplite._PIPLITE_URLS = ${JSON.stringify(a)}\n `)}async initKernel(t){await this._pyodide.runPythonAsync("\n await piplite.install(['sqlite3'], keep_going=True);\n await piplite.install(['ipykernel'], keep_going=True);\n await piplite.install(['comm'], keep_going=True);\n await piplite.install(['pyodide_kernel'], keep_going=True);\n await piplite.install(['ipython'], keep_going=True);\n import pyodide_kernel\n "),t.mountDrive&&this._localPath&&await this._pyodide.runPythonAsync(`\n import os;\n os.chdir("${this._localPath}");\n `)}async initGlobals(t){let{globals:e}=this._pyodide;this._kernel=e.get("pyodide_kernel").kernel_instance.copy(),this._stdout_stream=e.get("pyodide_kernel").stdout_stream.copy(),this._stderr_stream=e.get("pyodide_kernel").stderr_stream.copy(),this._interpreter=this._kernel.interpreter.copy(),this._interpreter.send_comm=this.sendComm.bind(this)}async initFilesystem(t){if(t.mountDrive){let e="/drive",{FS:i,PATH:a,ERRNO_CODES:n}=this._pyodide,{baseUrl:o}=t,{DriveFS:l}=await Promise.resolve().then((()=>(Vt(),Jt))),r=new l({FS:i,PATH:a,ERRNO_CODES:n,baseUrl:o,driveName:this._driveName,mountpoint:e});i.mkdir(e),i.mount(r,{},e),i.chdir(e),this._driveFS=r}}mapToObject(t){let e=t instanceof Array?[]:{};return t.forEach(((t,i)=>{e[i]=t instanceof Map||t instanceof Array?this.mapToObject(t):t})),e}formatResult(t){if(!(t instanceof this._pyodide.ffi.PyProxy))return t;let e=t.toJs();return this.mapToObject(e)}async setup(t){await this._initialized,this._kernel._parent_header=this._pyodide.toPy(t)}async execute(t,e){await this.setup(e);let i=(t,e)=>{let i={name:this.formatResult(t),text:this.formatResult(e)};postMessage({parentHeader:this.formatResult(this._kernel._parent_header).header,bundle:i,type:"stream"})};this._stdout_stream.publish_stream_callback=i,this._stderr_stream.publish_stream_callback=i,this._interpreter.display_pub.clear_output_callback=t=>{let e={wait:this.formatResult(t)};postMessage({parentHeader:this.formatResult(this._kernel._parent_header).header,bundle:e,type:"clear_output"})},this._interpreter.display_pub.display_data_callback=(t,e,i)=>{let a={data:this.formatResult(t),metadata:this.formatResult(e),transient:this.formatResult(i)};postMessage({parentHeader:this.formatResult(this._kernel._parent_header).header,bundle:a,type:"display_data"})},this._interpreter.display_pub.update_display_data_callback=(t,e,i)=>{let a={data:this.formatResult(t),metadata:this.formatResult(e),transient:this.formatResult(i)};postMessage({parentHeader:this.formatResult(this._kernel._parent_header).header,bundle:a,type:"update_display_data"})},this._interpreter.displayhook.publish_execution_result=(t,e,i)=>{let a={execution_count:t,data:this.formatResult(e),metadata:this.formatResult(i)};postMessage({parentHeader:this.formatResult(this._kernel._parent_header).header,bundle:a,type:"execute_result"})},this._interpreter.input=this.input.bind(this),this._interpreter.getpass=this.getpass.bind(this);let a=await this._kernel.run(t.code),n=this.formatResult(a);return"error"===n.status&&((t,e,i)=>{let a={ename:t,evalue:e,traceback:i};postMessage({parentHeader:this.formatResult(this._kernel._parent_header).header,bundle:a,type:"execute_error"})})(n.ename,n.evalue,n.traceback),n}async complete(t,e){await this.setup(e);let i=this._kernel.complete(t.code,t.cursor_pos);return this.formatResult(i)}async inspect(t,e){await this.setup(e);let i=this._kernel.inspect(t.code,t.cursor_pos,t.detail_level);return this.formatResult(i)}async isComplete(t,e){await this.setup(e);let i=this._kernel.is_complete(t.code);return this.formatResult(i)}async commInfo(t,e){await this.setup(e);let i=this._kernel.comm_info(t.target_name);return{comms:this.formatResult(i),status:"ok"}}async commOpen(t,e){await this.setup(e);let i=this._kernel.comm_manager.comm_open(this._pyodide.toPy(null),this._pyodide.toPy(null),this._pyodide.toPy(t));return this.formatResult(i)}async commMsg(t,e){await this.setup(e);let i=this._kernel.comm_manager.comm_msg(this._pyodide.toPy(null),this._pyodide.toPy(null),this._pyodide.toPy(t));return this.formatResult(i)}async commClose(t,e){await this.setup(e);let i=this._kernel.comm_manager.comm_close(this._pyodide.toPy(null),this._pyodide.toPy(null),this._pyodide.toPy(t));return this.formatResult(i)}async inputReply(t,e){await this.setup(e),this._resolveInputReply(t)}async sendInputRequest(t,e){let i={prompt:t,password:e};postMessage({type:"input_request",parentHeader:this.formatResult(this._kernel._parent_header).header,content:i})}async getpass(t){return t=void 0===t?"":t,await this.sendInputRequest(t,!0),(await new Promise((t=>{this._resolveInputReply=t}))).value}async input(t){return t=void 0===t?"":t,await this.sendInputRequest(t,!1),(await new Promise((t=>{this._resolveInputReply=t}))).value}async sendComm(t,e,i,a,n){postMessage({type:t,content:this.formatResult(e),metadata:this.formatResult(i),ident:this.formatResult(a),buffers:this.formatResult(n),parentHeader:this.formatResult(this._kernel._parent_header).header})}}}}]); +//# sourceMappingURL=296.thebe-lite.min.js.map \ No newline at end of file diff --git a/book/_build/html/_static/296.thebe-lite.min.js.map b/book/_build/html/_static/296.thebe-lite.min.js.map new file mode 100644 index 0000000..c0e853c --- /dev/null +++ b/book/_build/html/_static/296.thebe-lite.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"296.thebe-lite.min.js","mappings":"uNAAA,IAAIA,GAAGC,OAAOC,OAAWC,GAAGF,OAAOG,eAAmBC,GAAGJ,OAAOK,yBAA6BC,GAAGN,OAA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II,EAAE8J,KAAKyjB,QAAQgD,aAAaG,WAAW5mB,KAAKmiB,SAASyC,KAAK,MAAM5kB,KAAKmiB,SAASyC,KAAK,MAAM5kB,KAAKmiB,SAASyC,KAAKlvB,IAAI,OAAOsK,KAAKukB,aAAaruB,EAAE,CAACqM,iBAAiB7M,EAAEI,SAASkK,KAAK6kB,MAAM/uB,GAAGkK,KAAK6mB,mBAAmBnxB,EAAE,CAAC6M,uBAAuB7M,EAAEI,GAAG,IAAII,EAAE,CAAC4wB,OAAOpxB,EAAE4W,SAASxW,GAAGsqB,YAAY,CAAC5I,KAAK,gBAAgBsN,aAAa9kB,KAAKukB,aAAavkB,KAAKyjB,QAAQkB,gBAAgBI,OAAOjN,QAAQ5hB,GAAG,CAACqM,cAAc7M,GAAG,OAAOA,OAAY,IAAHA,EAAe,GAAGA,QAAQsK,KAAK+mB,iBAAiBrxB,GAAE,UAAW,IAAIkL,SAAQzK,IAAI6J,KAAK6mB,mBAAmB1wB,MAAKI,KAAK,CAACgM,YAAY7M,GAAG,OAAOA,OAAY,IAAHA,EAAe,GAAGA,QAAQsK,KAAK+mB,iBAAiBrxB,GAAE,UAAW,IAAIkL,SAAQzK,IAAI6J,KAAK6mB,mBAAmB1wB,MAAKI,KAAK,CAACgM,eAAe7M,EAAEI,EAAEI,EAAEC,EAAE0J,GAAGugB,YAAY,CAAC5I,KAAK9hB,EAAEoiB,QAAQ9X,KAAKukB,aAAazuB,GAAG4jB,SAAS1Z,KAAKukB,aAAaruB,GAAG8wB,MAAMhnB,KAAKukB,aAAapuB,GAAG8wB,QAAQjnB,KAAKukB,aAAa1kB,GAAGilB,aAAa9kB,KAAKukB,aAAavkB,KAAKyjB,QAAQkB,gBAAgBI,QAAQ,E","sources":["webpack://thebe-lite/./node_modules/@jupyterlite/pyodide-kernel/lib/worker.js"],"sourcesContent":["var ni=Object.create;var Me=Object.defineProperty;var ai=Object.getOwnPropertyDescriptor;var oi=Object.getOwnPropertyNames;var si=Object.getPrototypeOf,ri=Object.prototype.hasOwnProperty;var ce=(n,e)=>()=>(n&&(e=n(n=0)),e);var F=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),li=(n,e)=>{for(var t in e)Me(n,t,{get:e[t],enumerable:!0})},ci=(n,e,t,i)=>{if(e&&typeof e==\"object\"||typeof e==\"function\")for(let a of oi(e))!ri.call(n,a)&&a!==t&&Me(n,a,{get:()=>e[a],enumerable:!(i=ai(e,a))||i.enumerable});return n};var se=(n,e,t)=>(t=n!=null?ni(si(n)):{},ci(e||!n||!n.__esModule?Me(t,\"default\",{value:n,enumerable:!0}):t,n));var Ye=F((be,Ve)=>{(function(n,e){typeof be==\"object\"&&typeof Ve!=\"undefined\"?e(be):typeof define==\"function\"&&define.amd?define([\"exports\"],e):(n=typeof globalThis!=\"undefined\"?globalThis:n||self,e(n.lumino_algorithm={}))})(be,function(n){\"use strict\";n.ArrayExt=void 0,function(u){function v(g,w,d=0,p=-1){let f=g.length;if(f===0)return-1;d<0?d=Math.max(0,d+f):d=Math.min(d,f-1),p<0?p=Math.max(0,p+f):p=Math.min(p,f-1);let _;p0;){let Z=U>>1,fe=k+Z;d(g[fe],w)<0?(k=fe+1,U-=Z+1):U=Z}return k}u.lowerBound=A;function H(g,w,d,p=0,f=-1){let _=g.length;if(_===0)return 0;p<0?p=Math.max(0,p+_):p=Math.min(p,_-1),f<0?f=Math.max(0,f+_):f=Math.min(f,_-1);let k=p,U=f-p+1;for(;U>0;){let Z=U>>1,fe=k+Z;d(g[fe],w)>0?U=Z:(k=fe+1,U-=Z+1)}return k}u.upperBound=H;function L(g,w,d){if(g===w)return!0;if(g.length!==w.length)return!1;for(let p=0,f=g.length;p=_&&(d=f<0?_-1:_),p===void 0?p=f<0?-1:_:p<0?p=Math.max(p+_,f<0?-1:0):p>=_&&(p=f<0?_-1:_);let k;f<0&&p>=d||f>0&&d>=p?k=0:f<0?k=Math.floor((p-d+1)/f+1):k=Math.floor((p-d-1)/f+1);let U=[];for(let Z=0;Z=p))return;let _=p-d+1;if(w>0?w=w%_:w<0&&(w=(w%_+_)%_),w===0)return;let k=d+w;K(g,d,k-1),K(g,k,p),K(g,d,p)}u.rotate=G;function Q(g,w,d=0,p=-1){let f=g.length;if(f===0)return;d<0?d=Math.max(0,d+f):d=Math.min(d,f-1),p<0?p=Math.max(0,p+f):p=Math.min(p,f-1);let _;pw;--f)g[f]=g[f-1];g[w]=d}u.insert=Zt;function me(g,w){let d=g.length;if(w<0&&(w+=d),w<0||w>=d)return;let p=g[w];for(let f=w+1;f=d&&k<=p&&g[k]===w||p=d)&&g[k]===w?_++:_>0&&(g[k-_]=g[k]);return _>0&&(g.length=f-_),_}u.removeAllOf=Qt;function ei(g,w,d=0,p=-1){let f,_=y(g,w,d,p);return _!==-1&&(f=me(g,_)),{index:_,value:f}}u.removeFirstWhere=ei;function ti(g,w,d=-1,p=0){let f,_=M(g,w,d,p);return _!==-1&&(f=me(g,_)),{index:_,value:f}}u.removeLastWhere=ti;function ii(g,w,d=0,p=-1){let f=g.length;if(f===0)return 0;d<0?d=Math.max(0,d+f):d=Math.min(d,f-1),p<0?p=Math.max(0,p+f):p=Math.min(p,f-1);let _=0;for(let k=0;k=d&&k<=p&&w(g[k],k)||p=d)&&w(g[k],k)?_++:_>0&&(g[k-_]=g[k]);return _>0&&(g.length=f-_),_}u.removeAllWhere=ii}(n.ArrayExt||(n.ArrayExt={}));function*e(...u){for(let v of u)yield*v}function*t(){}function*i(u,v=0){for(let x of u)yield[v++,x]}function*a(u,v){let x=0;for(let y of u)v(y,x++)&&(yield y)}function o(u,v){let x=0;for(let y of u)if(v(y,x++))return y}function r(u,v){let x=0;for(let y of u)if(v(y,x++))return x-1;return-1}function s(u,v){let x;for(let y of u){if(x===void 0){x=y;continue}v(y,x)<0&&(x=y)}return x}function l(u,v){let x;for(let y of u){if(x===void 0){x=y;continue}v(y,x)>0&&(x=y)}return x}function m(u,v){let x=!0,y,M;for(let B of u)x?(y=B,M=B,x=!1):v(B,y)<0?y=B:v(B,M)>0&&(M=B);return x?void 0:[y,M]}function h(u){return Array.from(u)}function c(u){let v={};for(let[x,y]of u)v[x]=y;return v}function b(u,v){let x=0;for(let y of u)if(v(y,x++)===!1)return}function j(u,v){let x=0;for(let y of u)if(v(y,x++)===!1)return!1;return!0}function C(u,v){let x=0;for(let y of u)if(v(y,x++))return!0;return!1}function*q(u,v){let x=0;for(let y of u)yield v(y,x++)}function*O(u,v,x){v===void 0?(v=u,u=0,x=1):x===void 0&&(x=1);let y=S.rangeLength(u,v,x);for(let M=0;My&&M>0||x-1;v--)yield u[v]}function V(u){let v=[],x=new Set,y=new Map;for(let T of u)M(T);for(let[T]of y)B(T);return v;function M(T){let[A,H]=T,L=y.get(H);L?L.push(A):y.set(H,[A])}function B(T){if(x.has(T))return;x.add(T);let A=y.get(T);if(A)for(let H of A)B(H);v.push(T)}}function*D(u,v){let x=0;for(let y of u)x++%v===0&&(yield y)}n.StringExt=void 0,function(u){function v(T,A,H=0){let L=new Array(A.length);for(let W=0,$=H,K=A.length;WA?1:0}u.cmp=B}(n.StringExt||(n.StringExt={}));function*z(u,v){if(v<1)return;let x=u[Symbol.iterator](),y;for(;0y[Symbol.iterator]()),x=v.map(y=>y.next());for(;j(x,y=>!y.done);x=v.map(y=>y.next()))yield x.map(y=>y.value)}n.chain=e,n.each=b,n.empty=t,n.enumerate=i,n.every=j,n.filter=a,n.find=o,n.findIndex=r,n.map=q,n.max=l,n.min=s,n.minmax=m,n.once=P,n.range=O,n.reduce=R,n.repeat=I,n.retro=N,n.some=C,n.stride=D,n.take=z,n.toArray=h,n.toObject=c,n.topologicSort=V,n.zip=E})});var pe=F((we,Ze)=>{(function(n,e){typeof we==\"object\"&&typeof Ze!=\"undefined\"?e(we):typeof define==\"function\"&&define.amd?define([\"exports\"],e):(n=typeof globalThis!=\"undefined\"?globalThis:n||self,e(n.lumino_coreutils={}))})(we,function(n){\"use strict\";n.JSONExt=void 0,function(r){r.emptyObject=Object.freeze({}),r.emptyArray=Object.freeze([]);function s(O){return O===null||typeof O==\"boolean\"||typeof O==\"number\"||typeof O==\"string\"}r.isPrimitive=s;function l(O){return Array.isArray(O)}r.isArray=l;function m(O){return!s(O)&&!l(O)}r.isObject=m;function h(O,S){if(O===S)return!0;if(s(O)||s(S))return!1;let R=l(O),I=l(S);return R!==I?!1:R&&I?b(O,S):j(O,S)}r.deepEqual=h;function c(O){return s(O)?O:l(O)?C(O):q(O)}r.deepCopy=c;function b(O,S){if(O===S)return!0;if(O.length!==S.length)return!1;for(let R=0,I=O.length;R{this._resolve=s,this._reject=l})}resolve(s){let l=this._resolve;l(s)}reject(s){let l=this._reject;l(s)}}class i{constructor(s,l){this.name=s,this.description=l!=null?l:\"\",this._tokenStructuralPropertyT=null}}function a(r){let s=0;for(let l=0,m=r.length;l>>0),r[l]=s&255,s>>>=8}n.Random=void 0,function(r){r.getRandomValues=(()=>{let s=typeof window!=\"undefined\"&&(window.crypto||window.msCrypto)||null;return s&&typeof s.getRandomValues==\"function\"?function(m){return s.getRandomValues(m)}:a})()}(n.Random||(n.Random={}));function o(r){let s=new Uint8Array(16),l=new Array(256);for(let m=0;m<16;++m)l[m]=\"0\"+m.toString(16);for(let m=16;m<256;++m)l[m]=m.toString(16);return function(){return r(s),s[6]=64|s[6]&15,s[8]=128|s[8]&63,l[s[0]]+l[s[1]]+l[s[2]]+l[s[3]]+\"-\"+l[s[4]]+l[s[5]]+\"-\"+l[s[6]]+l[s[7]]+\"-\"+l[s[8]]+l[s[9]]+\"-\"+l[s[10]]+l[s[11]]+l[s[12]]+l[s[13]]+l[s[14]]+l[s[15]]}}n.UUID=void 0,function(r){r.uuid4=o(n.Random.getRandomValues)}(n.UUID||(n.UUID={})),n.MimeData=e,n.PromiseDelegate=t,n.Token=i})});var Xe=F((ye,Ge)=>{(function(n,e){typeof ye==\"object\"&&typeof Ge!=\"undefined\"?e(ye,Ye(),pe()):typeof define==\"function\"&&define.amd?define([\"exports\",\"@lumino/algorithm\",\"@lumino/coreutils\"],e):(n=typeof globalThis!=\"undefined\"?globalThis:n||self,e(n.lumino_signaling={},n.lumino_algorithm,n.lumino_coreutils))})(ye,function(n,e,t){\"use strict\";class i{constructor(s){this.sender=s}connect(s,l){return o.connect(this,s,l)}disconnect(s,l){return o.disconnect(this,s,l)}emit(s){o.emit(this,s)}}(function(r){function s(C,q){o.disconnectBetween(C,q)}r.disconnectBetween=s;function l(C){o.disconnectSender(C)}r.disconnectSender=l;function m(C){o.disconnectReceiver(C)}r.disconnectReceiver=m;function h(C){o.disconnectAll(C)}r.disconnectAll=h;function c(C){o.disconnectAll(C)}r.clearData=c;function b(){return o.exceptionHandler}r.getExceptionHandler=b;function j(C){let q=o.exceptionHandler;return o.exceptionHandler=C,q}r.setExceptionHandler=j})(i||(i={}));class a extends i{constructor(){super(...arguments),this._pending=new t.PromiseDelegate}async*[Symbol.asyncIterator](){let s=this._pending;for(;;)try{let{args:l,next:m}=await s.promise;s=m,yield l}catch{return}}emit(s){let l=this._pending,m=this._pending=new t.PromiseDelegate;l.resolve({args:s,next:m}),super.emit(s)}stop(){this._pending.promise.catch(()=>{}),this._pending.reject(\"stop\"),this._pending=new t.PromiseDelegate}}var o;(function(r){r.exceptionHandler=z=>{console.error(z)};function s(z,E,u){u=u||void 0;let v=C.get(z.sender);if(v||(v=[],C.set(z.sender,v)),R(v,z,E,u))return!1;let x=u||E,y=q.get(x);y||(y=[],q.set(x,y));let M={signal:z,slot:E,thisArg:u};return v.push(M),y.push(M),!0}r.connect=s;function l(z,E,u){u=u||void 0;let v=C.get(z.sender);if(!v||v.length===0)return!1;let x=R(v,z,E,u);if(!x)return!1;let y=u||E,M=q.get(y);return x.signal=null,P(v),P(M),!0}r.disconnect=l;function m(z,E){let u=C.get(z);if(!u||u.length===0)return;let v=q.get(E);if(!(!v||v.length===0)){for(let x of v)x.signal&&x.signal.sender===z&&(x.signal=null);P(u),P(v)}}r.disconnectBetween=m;function h(z){let E=C.get(z);if(!(!E||E.length===0)){for(let u of E){if(!u.signal)continue;let v=u.thisArg||u.slot;u.signal=null,P(q.get(v))}P(E)}}r.disconnectSender=h;function c(z){let E=q.get(z);if(!(!E||E.length===0)){for(let u of E){if(!u.signal)continue;let v=u.signal.sender;u.signal=null,P(C.get(v))}P(E)}}r.disconnectReceiver=c;function b(z){h(z),c(z)}r.disconnectAll=b;function j(z,E){let u=C.get(z.sender);if(!(!u||u.length===0))for(let v=0,x=u.length;vtypeof requestAnimationFrame==\"function\"?requestAnimationFrame:setImmediate)();function R(z,E,u,v){return e.find(z,x=>x.signal===E&&x.slot===u&&x.thisArg===v)}function I(z,E){let{signal:u,slot:v,thisArg:x}=z;try{v.call(x,u.sender,E)}catch(y){r.exceptionHandler(y)}}function P(z){O.size===0&&S(N),O.add(z)}function N(){O.forEach(V),O.clear()}function V(z){e.ArrayExt.removeAllWhere(z,D)}function D(z){return z.signal===null}})(o||(o={})),n.Signal=i,n.Stream=a})});var et=F(_e=>{\"use strict\";Object.defineProperty(_e,\"__esModule\",{value:!0});_e.ActivityMonitor=void 0;var Qe=Xe(),Te=class{constructor(e){this._timer=-1,this._timeout=-1,this._isDisposed=!1,this._activityStopped=new Qe.Signal(this),e.signal.connect(this._onSignalFired,this),this._timeout=e.timeout||1e3}get activityStopped(){return this._activityStopped}get timeout(){return this._timeout}set timeout(e){this._timeout=e}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,Qe.Signal.clearData(this))}_onSignalFired(e,t){clearTimeout(this._timer),this._sender=e,this._args=t,this._timer=setTimeout(()=>{this._activityStopped.emit({sender:this._sender,args:this._args})},this._timeout)}};_e.ActivityMonitor=Te});var it=F(tt=>{\"use strict\";Object.defineProperty(tt,\"__esModule\",{value:!0})});var nt=F(ue=>{\"use strict\";Object.defineProperty(ue,\"__esModule\",{value:!0});ue.MarkdownCodeBlocks=void 0;var pi;(function(n){n.CODE_BLOCK_MARKER=\"```\";let e=[\".markdown\",\".mdown\",\".mkdn\",\".md\",\".mkd\",\".mdwn\",\".mdtxt\",\".mdtext\",\".text\",\".txt\",\".Rmd\"];class t{constructor(r){this.startLine=r,this.code=\"\",this.endLine=-1}}n.MarkdownCodeBlock=t;function i(o){return e.indexOf(o)>-1}n.isMarkdown=i;function a(o){if(!o||o===\"\")return[];let r=o.split(`\n`),s=[],l=null;for(let m=0;m{\"use strict\";function di(n,e){var t=n;e.slice(0,-1).forEach(function(a){t=t[a]||{}});var i=e[e.length-1];return i in t}function at(n){return typeof n==\"number\"||/^0x[0-9a-f]+$/i.test(n)?!0:/^[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(e[-+]?\\d+)?$/.test(n)}function ot(n,e){return e===\"constructor\"&&typeof n[e]==\"function\"||e===\"__proto__\"}st.exports=function(n,e){e||(e={});var t={bools:{},strings:{},unknownFn:null};typeof e.unknown==\"function\"&&(t.unknownFn=e.unknown),typeof e.boolean==\"boolean\"&&e.boolean?t.allBools=!0:[].concat(e.boolean).filter(Boolean).forEach(function(P){t.bools[P]=!0});var i={};function a(P){return i[P].some(function(N){return t.bools[N]})}Object.keys(e.alias||{}).forEach(function(P){i[P]=[].concat(e.alias[P]),i[P].forEach(function(N){i[N]=[P].concat(i[P].filter(function(V){return N!==V}))})}),[].concat(e.string).filter(Boolean).forEach(function(P){t.strings[P]=!0,i[P]&&[].concat(i[P]).forEach(function(N){t.strings[N]=!0})});var o=e.default||{},r={_:[]};function s(P,N){return t.allBools&&/^--[^=]+$/.test(N)||t.strings[P]||t.bools[P]||i[P]}function l(P,N,V){for(var D=P,z=0;z{\"use strict\";function ee(n){if(typeof n!=\"string\")throw new TypeError(\"Path must be a string. Received \"+JSON.stringify(n))}function lt(n,e){for(var t=\"\",i=0,a=-1,o=0,r,s=0;s<=n.length;++s){if(s2){var l=t.lastIndexOf(\"/\");if(l!==t.length-1){l===-1?(t=\"\",i=0):(t=t.slice(0,l),i=t.length-1-t.lastIndexOf(\"/\")),a=s,o=0;continue}}else if(t.length===2||t.length===1){t=\"\",i=0,a=s,o=0;continue}}e&&(t.length>0?t+=\"/..\":t=\"..\",i=2)}else t.length>0?t+=\"/\"+n.slice(a+1,s):t=n.slice(a+1,s),i=s-a-1;a=s,o=0}else r===46&&o!==-1?++o:o=-1}return t}function mi(n,e){var t=e.dir||e.root,i=e.base||(e.name||\"\")+(e.ext||\"\");return t?t===e.root?t+i:t+n+i:i}var de={resolve:function(){for(var e=\"\",t=!1,i,a=arguments.length-1;a>=-1&&!t;a--){var o;a>=0?o=arguments[a]:(i===void 0&&(i=process.cwd()),o=i),ee(o),o.length!==0&&(e=o+\"/\"+e,t=o.charCodeAt(0)===47)}return e=lt(e,!t),t?e.length>0?\"/\"+e:\"/\":e.length>0?e:\".\"},normalize:function(e){if(ee(e),e.length===0)return\".\";var t=e.charCodeAt(0)===47,i=e.charCodeAt(e.length-1)===47;return e=lt(e,!t),e.length===0&&!t&&(e=\".\"),e.length>0&&i&&(e+=\"/\"),t?\"/\"+e:e},isAbsolute:function(e){return ee(e),e.length>0&&e.charCodeAt(0)===47},join:function(){if(arguments.length===0)return\".\";for(var e,t=0;t0&&(e===void 0?e=i:e+=\"/\"+i)}return e===void 0?\".\":de.normalize(e)},relative:function(e,t){if(ee(e),ee(t),e===t||(e=de.resolve(e),t=de.resolve(t),e===t))return\"\";for(var i=1;im){if(t.charCodeAt(r+c)===47)return t.slice(r+c+1);if(c===0)return t.slice(r+c)}else o>m&&(e.charCodeAt(i+c)===47?h=c:c===0&&(h=0));break}var b=e.charCodeAt(i+c),j=t.charCodeAt(r+c);if(b!==j)break;b===47&&(h=c)}var C=\"\";for(c=i+h+1;c<=a;++c)(c===a||e.charCodeAt(c)===47)&&(C.length===0?C+=\"..\":C+=\"/..\");return C.length>0?C+t.slice(r+h):(r+=h,t.charCodeAt(r)===47&&++r,t.slice(r))},_makeLong:function(e){return e},dirname:function(e){if(ee(e),e.length===0)return\".\";for(var t=e.charCodeAt(0),i=t===47,a=-1,o=!0,r=e.length-1;r>=1;--r)if(t=e.charCodeAt(r),t===47){if(!o){a=r;break}}else o=!1;return a===-1?i?\"/\":\".\":i&&a===1?\"//\":e.slice(0,a)},basename:function(e,t){if(t!==void 0&&typeof t!=\"string\")throw new TypeError('\"ext\" argument must be a string');ee(e);var i=0,a=-1,o=!0,r;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return\"\";var s=t.length-1,l=-1;for(r=e.length-1;r>=0;--r){var m=e.charCodeAt(r);if(m===47){if(!o){i=r+1;break}}else l===-1&&(o=!1,l=r+1),s>=0&&(m===t.charCodeAt(s)?--s===-1&&(a=r):(s=-1,a=l))}return i===a?a=l:a===-1&&(a=e.length),e.slice(i,a)}else{for(r=e.length-1;r>=0;--r)if(e.charCodeAt(r)===47){if(!o){i=r+1;break}}else a===-1&&(o=!1,a=r+1);return a===-1?\"\":e.slice(i,a)}},extname:function(e){ee(e);for(var t=-1,i=0,a=-1,o=!0,r=0,s=e.length-1;s>=0;--s){var l=e.charCodeAt(s);if(l===47){if(!o){i=s+1;break}continue}a===-1&&(o=!1,a=s+1),l===46?t===-1?t=s:r!==1&&(r=1):t!==-1&&(r=-1)}return t===-1||a===-1||r===0||r===1&&t===a-1&&t===i+1?\"\":e.slice(t,a)},format:function(e){if(e===null||typeof e!=\"object\")throw new TypeError('The \"pathObject\" argument must be of type Object. Received type '+typeof e);return mi(\"/\",e)},parse:function(e){ee(e);var t={root:\"\",dir:\"\",base:\"\",ext:\"\",name:\"\"};if(e.length===0)return t;var i=e.charCodeAt(0),a=i===47,o;a?(t.root=\"/\",o=1):o=0;for(var r=-1,s=0,l=-1,m=!0,h=e.length-1,c=0;h>=o;--h){if(i=e.charCodeAt(h),i===47){if(!m){s=h+1;break}continue}l===-1&&(m=!1,l=h+1),i===46?r===-1?r=h:c!==1&&(c=1):r!==-1&&(c=-1)}return r===-1||l===-1||c===0||c===1&&r===l-1&&r===s+1?l!==-1&&(s===0&&a?t.base=t.name=e.slice(1,l):t.base=t.name=e.slice(s,l)):(s===0&&a?(t.name=e.slice(1,r),t.base=e.slice(1,l)):(t.name=e.slice(s,r),t.base=e.slice(s,l)),t.ext=e.slice(r,l)),s>0?t.dir=e.slice(0,s-1):a&&(t.dir=\"/\"),t},sep:\"/\",delimiter:\":\",win32:null,posix:null};de.posix=de;ct.exports=de});var dt=F((Ji,pt)=>{\"use strict\";pt.exports=function(e,t){if(t=t.split(\":\")[0],e=+e,!e)return!1;switch(t){case\"http\":case\"ws\":return e!==80;case\"https\":case\"wss\":return e!==443;case\"ftp\":return e!==21;case\"gopher\":return e!==70;case\"file\":return!1}return e!==0}});var ut=F(Ae=>{\"use strict\";var fi=Object.prototype.hasOwnProperty,ui;function mt(n){try{return decodeURIComponent(n.replace(/\\+/g,\" \"))}catch{return null}}function ft(n){try{return encodeURIComponent(n)}catch{return null}}function hi(n){for(var e=/([^=?#&]+)=?([^&]*)/g,t={},i;i=e.exec(n);){var a=mt(i[1]),o=mt(i[2]);a===null||o===null||a in t||(t[a]=o)}return t}function vi(n,e){e=e||\"\";var t=[],i,a;typeof e!=\"string\"&&(e=\"?\");for(a in n)if(fi.call(n,a)){if(i=n[a],!i&&(i===null||i===ui||isNaN(i))&&(i=\"\"),a=ft(a),i=ft(i),a===null||i===null)continue;t.push(a+\"=\"+i)}return t.length?e+t.join(\"&\"):\"\"}Ae.stringify=vi;Ae.parse=hi});var _t=F((Yi,yt)=>{\"use strict\";var vt=dt(),je=ut(),gi=/^[\\x00-\\x20\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+/,gt=/[\\n\\r\\t]/g,xi=/^[A-Za-z][A-Za-z0-9+-.]*:\\/\\//,xt=/:\\d+$/,bi=/^([a-z][a-z0-9.+-]*:)?(\\/\\/)?([\\\\/]+)?([\\S\\s]*)/i,wi=/^[a-zA-Z]:/;function Ue(n){return(n||\"\").toString().replace(gi,\"\")}var qe=[[\"#\",\"hash\"],[\"?\",\"query\"],function(e,t){return te(t.protocol)?e.replace(/\\\\/g,\"/\"):e},[\"/\",\"pathname\"],[\"@\",\"auth\",1],[NaN,\"host\",void 0,1,1],[/:(\\d*)$/,\"port\",void 0,1],[NaN,\"hostname\",void 0,1,1]],ht={hash:1,query:1};function bt(n){var e;typeof window!=\"undefined\"?e=window:typeof global!=\"undefined\"?e=global:typeof self!=\"undefined\"?e=self:e={};var t=e.location||{};n=n||t;var i={},a=typeof n,o;if(n.protocol===\"blob:\")i=new ie(unescape(n.pathname),{});else if(a===\"string\"){i=new ie(n,{});for(o in ht)delete i[o]}else if(a===\"object\"){for(o in n)o in ht||(i[o]=n[o]);i.slashes===void 0&&(i.slashes=xi.test(n.href))}return i}function te(n){return n===\"file:\"||n===\"ftp:\"||n===\"http:\"||n===\"https:\"||n===\"ws:\"||n===\"wss:\"}function wt(n,e){n=Ue(n),n=n.replace(gt,\"\"),e=e||{};var t=bi.exec(n),i=t[1]?t[1].toLowerCase():\"\",a=!!t[2],o=!!t[3],r=0,s;return a?o?(s=t[2]+t[3]+t[4],r=t[2].length+t[3].length):(s=t[2]+t[4],r=t[2].length):o?(s=t[3]+t[4],r=t[3].length):s=t[4],i===\"file:\"?r>=2&&(s=s.slice(2)):te(i)?s=t[4]:i?a&&(s=s.slice(2)):r>=2&&te(e.protocol)&&(s=t[4]),{protocol:i,slashes:a||te(i),slashesCount:r,rest:s}}function yi(n,e){if(n===\"\")return e;for(var t=(e||\"/\").split(\"/\").slice(0,-1).concat(n.split(\"/\")),i=t.length,a=t[i-1],o=!1,r=0;i--;)t[i]===\".\"?t.splice(i,1):t[i]===\"..\"?(t.splice(i,1),r++):r&&(i===0&&(o=!0),t.splice(i,1),r--);return o&&t.unshift(\"\"),(a===\".\"||a===\"..\")&&t.push(\"\"),t.join(\"/\")}function ie(n,e,t){if(n=Ue(n),n=n.replace(gt,\"\"),!(this instanceof ie))return new ie(n,e,t);var i,a,o,r,s,l,m=qe.slice(),h=typeof e,c=this,b=0;for(h!==\"object\"&&h!==\"string\"&&(t=e,e=null),t&&typeof t!=\"function\"&&(t=je.parse),e=bt(e),a=wt(n||\"\",e),i=!a.protocol&&!a.slashes,c.slashes=a.slashes||i&&e.slashes,c.protocol=a.protocol||e.protocol||\"\",n=a.rest,(a.protocol===\"file:\"&&(a.slashesCount!==2||wi.test(n))||!a.slashes&&(a.protocol||a.slashesCount<2||!te(c.protocol)))&&(m[3]=[/(.*)/,\"pathname\"]);b{\"use strict\";var ji=re&&re.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(re,\"__esModule\",{value:!0});re.URLExt=void 0;var Ci=ke(),Ce=ji(_t()),Oi;(function(n){function e(m){if(typeof document!=\"undefined\"&&document){let h=document.createElement(\"a\");return h.href=m,h}return(0,Ce.default)(m)}n.parse=e;function t(m){return(0,Ce.default)(m).hostname}n.getHostName=t;function i(m){return m&&e(m).toString()}n.normalize=i;function a(...m){let h=(0,Ce.default)(m[0],{}),c=h.protocol===\"\"&&h.slashes;c&&(h=(0,Ce.default)(m[0],\"https:\"+m[0]));let b=`${c?\"\":h.protocol}${h.slashes?\"//\":\"\"}${h.auth}${h.auth?\"@\":\"\"}${h.host}`,j=Ci.posix.join(`${b&&h.pathname[0]!==\"/\"?\"/\":\"\"}${h.pathname}`,...m.slice(1));return`${b}${j===\".\"?\"\":j}`}n.join=a;function o(m){return a(...m.split(\"/\").map(encodeURIComponent))}n.encodeParts=o;function r(m){let h=Object.keys(m).filter(c=>c.length>0);return h.length?\"?\"+h.map(c=>{let b=encodeURIComponent(String(m[c]));return c+(b?\"=\"+b:\"\")}).join(\"&\"):\"\"}n.objectToQueryString=r;function s(m){return m.replace(/^\\?/,\"\").split(\"&\").reduce((h,c)=>{let[b,j]=c.split(\"=\");return b.length>0&&(h[b]=decodeURIComponent(j||\"\")),h},{})}n.queryStringToObject=s;function l(m){let{protocol:h}=e(m);return(!h||m.toLowerCase().indexOf(h)!==0)&&m.indexOf(\"/\")!==0}n.isLocal=l})(Oi=re.URLExt||(re.URLExt={}))});var kt=F((exports,module)=>{\"use strict\";var __importDefault=exports&&exports.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(exports,\"__esModule\",{value:!0});exports.PageConfig=void 0;var coreutils_1=pe(),minimist_1=__importDefault(rt()),url_1=Ne(),PageConfig;(function(PageConfig){function getOption(name){if(configData)return configData[name]||getBodyData(name);configData=Object.create(null);let found=!1;if(typeof document!=\"undefined\"&&document){let n=document.getElementById(\"jupyter-config-data\");n&&(configData=JSON.parse(n.textContent||\"\"),found=!0)}if(!found&&typeof process!=\"undefined\"&&process.argv)try{let cli=(0,minimist_1.default)(process.argv.slice(2)),path=ke(),fullPath=\"\";\"jupyter-config-data\"in cli?fullPath=path.resolve(cli[\"jupyter-config-data\"]):\"JUPYTER_CONFIG_DATA\"in process.env&&(fullPath=path.resolve(process.env.JUPYTER_CONFIG_DATA)),fullPath&&(configData=eval(\"require\")(fullPath))}catch(n){console.error(n)}if(!coreutils_1.JSONExt.isObject(configData))configData=Object.create(null);else for(let n in configData)typeof configData[n]!=\"string\"&&(configData[n]=JSON.stringify(configData[n]));return configData[name]||getBodyData(name)}PageConfig.getOption=getOption;function setOption(n,e){let t=getOption(n);return configData[n]=e,t}PageConfig.setOption=setOption;function getBaseUrl(){return url_1.URLExt.normalize(getOption(\"baseUrl\")||\"/\")}PageConfig.getBaseUrl=getBaseUrl;function getTreeUrl(){return url_1.URLExt.join(getBaseUrl(),getOption(\"treeUrl\"))}PageConfig.getTreeUrl=getTreeUrl;function getShareUrl(){return url_1.URLExt.normalize(getOption(\"shareUrl\")||getBaseUrl())}PageConfig.getShareUrl=getShareUrl;function getTreeShareUrl(){return url_1.URLExt.normalize(url_1.URLExt.join(getShareUrl(),getOption(\"treeUrl\")))}PageConfig.getTreeShareUrl=getTreeShareUrl;function getUrl(n){var e,t,i,a;let o=n.toShare?getShareUrl():getBaseUrl(),r=(e=n.mode)!==null&&e!==void 0?e:getOption(\"mode\"),s=(t=n.workspace)!==null&&t!==void 0?t:getOption(\"workspace\"),l=r===\"single-document\"?\"doc\":\"lab\";o=url_1.URLExt.join(o,l),s!==PageConfig.defaultWorkspace&&(o=url_1.URLExt.join(o,\"workspaces\",encodeURIComponent((i=getOption(\"workspace\"))!==null&&i!==void 0?i:PageConfig.defaultWorkspace)));let m=(a=n.treePath)!==null&&a!==void 0?a:getOption(\"treePath\");return m&&(o=url_1.URLExt.join(o,\"tree\",url_1.URLExt.encodeParts(m))),o}PageConfig.getUrl=getUrl,PageConfig.defaultWorkspace=\"default\";function getWsUrl(n){let e=getOption(\"wsUrl\");if(!e){if(n=n?url_1.URLExt.normalize(n):getBaseUrl(),n.indexOf(\"http\")!==0)return\"\";e=\"ws\"+n.slice(4)}return url_1.URLExt.normalize(e)}PageConfig.getWsUrl=getWsUrl;function getNBConvertURL({path:n,format:e,download:t}){let i=url_1.URLExt.encodeParts(n),a=url_1.URLExt.join(getBaseUrl(),\"nbconvert\",e,i);return t?a+\"?download=true\":a}PageConfig.getNBConvertURL=getNBConvertURL;function getToken(){return getOption(\"token\")||getBodyData(\"jupyterApiToken\")}PageConfig.getToken=getToken;function getNotebookVersion(){let n=getOption(\"notebookVersion\");return n===\"\"?[0,0,0]:JSON.parse(n)}PageConfig.getNotebookVersion=getNotebookVersion;let configData=null;function getBodyData(n){if(typeof document==\"undefined\"||!document.body)return\"\";let e=document.body.dataset[n];return typeof e==\"undefined\"?\"\":decodeURIComponent(e)}let Extension;(function(n){function e(a){try{let o=getOption(a);if(o)return JSON.parse(o)}catch(o){console.warn(`Unable to parse ${a}.`,o)}return[]}n.deferred=e(\"deferredExtensions\"),n.disabled=e(\"disabledExtensions\");function t(a){let o=a.indexOf(\":\"),r=\"\";return o!==-1&&(r=a.slice(0,o)),n.deferred.some(s=>s===a||r&&s===r)}n.isDeferred=t;function i(a){let o=a.indexOf(\":\"),r=\"\";return o!==-1&&(r=a.slice(0,o)),n.disabled.some(s=>s===a||r&&s===r)}n.isDisabled=i})(Extension=PageConfig.Extension||(PageConfig.Extension={}))})(PageConfig=exports.PageConfig||(exports.PageConfig={}))});var jt=F(he=>{\"use strict\";Object.defineProperty(he,\"__esModule\",{value:!0});he.PathExt=void 0;var le=ke(),Pi;(function(n){function e(...h){let c=le.posix.join(...h);return c===\".\"?\"\":m(c)}n.join=e;function t(h,c){return le.posix.basename(h,c)}n.basename=t;function i(h){let c=m(le.posix.dirname(h));return c===\".\"?\"\":c}n.dirname=i;function a(h){return le.posix.extname(h)}n.extname=a;function o(h){return h===\"\"?\"\":m(le.posix.normalize(h))}n.normalize=o;function r(...h){return m(le.posix.resolve(...h))}n.resolve=r;function s(h,c){return m(le.posix.relative(h,c))}n.relative=s;function l(h){return h.length>0&&h.indexOf(\".\")!==0&&(h=`.${h}`),h}n.normalizeExtension=l;function m(h){return h.indexOf(\"/\")===0&&(h=h.slice(1)),h}n.removeSlash=m})(Pi=he.PathExt||(he.PathExt={}))});var Ct=F(Oe=>{\"use strict\";Object.defineProperty(Oe,\"__esModule\",{value:!0});Oe.signalToPromise=void 0;var Si=pe();function zi(n,e){let t=new Si.PromiseDelegate;function i(){n.disconnect(a)}function a(o,r){i(),t.resolve([o,r])}return n.connect(a),(e!=null?e:0)>0&&setTimeout(()=>{i(),t.reject(`Signal not emitted within ${e} ms.`)},e),t.promise}Oe.signalToPromise=zi});var Ot=F(ve=>{\"use strict\";Object.defineProperty(ve,\"__esModule\",{value:!0});ve.Text=void 0;var Ri;(function(n){let e=2>1;function t(r,s){if(e)return r;let l=r;for(let m=0;m+1=55296&&h<=56319){let c=s.charCodeAt(m+1);c>=56320&&c<=57343&&(l--,m++)}}return l}n.jsIndexToCharIndex=t;function i(r,s){if(e)return r;let l=r;for(let m=0;m+1=55296&&h<=56319){let c=s.charCodeAt(m+1);c>=56320&&c<=57343&&(l++,m++)}}return l}n.charIndexToJsIndex=i;function a(r,s=!1){return r.replace(/^(\\w)|[\\s-_:]+(\\w)/g,function(l,m,h){return h?h.toUpperCase():s?m.toUpperCase():m.toLowerCase()})}n.camelCase=a;function o(r){return(r||\"\").toLowerCase().split(\" \").map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(\" \")}n.titleCase=o})(Ri=ve.Text||(ve.Text={}))});var Pt=F(ge=>{\"use strict\";Object.defineProperty(ge,\"__esModule\",{value:!0});ge.Time=void 0;var Ei=[{name:\"years\",milliseconds:365*24*60*60*1e3},{name:\"months\",milliseconds:30*24*60*60*1e3},{name:\"days\",milliseconds:24*60*60*1e3},{name:\"hours\",milliseconds:60*60*1e3},{name:\"minutes\",milliseconds:60*1e3},{name:\"seconds\",milliseconds:1e3}],Ii;(function(n){function e(i){let a=document.documentElement.lang||\"en\",o=new Intl.RelativeTimeFormat(a,{numeric:\"auto\"}),r=new Date(i).getTime()-Date.now();for(let s of Ei){let l=Math.ceil(r/s.milliseconds);if(l!==0)return o.format(l,s.name)}return o.format(0,\"seconds\")}n.formatHuman=e;function t(i){let a=document.documentElement.lang||\"en\";return new Intl.DateTimeFormat(a,{dateStyle:\"short\",timeStyle:\"short\"}).format(new Date(i))}n.format=t})(Ii=ge.Time||(ge.Time={}))});var xe=F(J=>{\"use strict\";var Di=J&&J.__createBinding||(Object.create?function(n,e,t,i){i===void 0&&(i=t);var a=Object.getOwnPropertyDescriptor(e,t);(!a||(\"get\"in a?!e.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,i,a)}:function(n,e,t,i){i===void 0&&(i=t),n[i]=e[t]}),ae=J&&J.__exportStar||function(n,e){for(var t in n)t!==\"default\"&&!Object.prototype.hasOwnProperty.call(e,t)&&Di(e,n,t)};Object.defineProperty(J,\"__esModule\",{value:!0});ae(et(),J);ae(it(),J);ae(nt(),J);ae(kt(),J);ae(jt(),J);ae(Ct(),J);ae(Ot(),J);ae(Pt(),J);ae(Ne(),J)});var zt=F((nn,St)=>{\"use strict\";function Pe(){this._types=Object.create(null),this._extensions=Object.create(null);for(let n=0;n{Rt.exports={\"application/andrew-inset\":[\"ez\"],\"application/applixware\":[\"aw\"],\"application/atom+xml\":[\"atom\"],\"application/atomcat+xml\":[\"atomcat\"],\"application/atomdeleted+xml\":[\"atomdeleted\"],\"application/atomsvc+xml\":[\"atomsvc\"],\"application/atsc-dwd+xml\":[\"dwd\"],\"application/atsc-held+xml\":[\"held\"],\"application/atsc-rsat+xml\":[\"rsat\"],\"application/bdoc\":[\"bdoc\"],\"application/calendar+xml\":[\"xcs\"],\"application/ccxml+xml\":[\"ccxml\"],\"application/cdfx+xml\":[\"cdfx\"],\"application/cdmi-capability\":[\"cdmia\"],\"application/cdmi-container\":[\"cdmic\"],\"application/cdmi-domain\":[\"cdmid\"],\"application/cdmi-object\":[\"cdmio\"],\"application/cdmi-queue\":[\"cdmiq\"],\"application/cu-seeme\":[\"cu\"],\"application/dash+xml\":[\"mpd\"],\"application/davmount+xml\":[\"davmount\"],\"application/docbook+xml\":[\"dbk\"],\"application/dssc+der\":[\"dssc\"],\"application/dssc+xml\":[\"xdssc\"],\"application/ecmascript\":[\"es\",\"ecma\"],\"application/emma+xml\":[\"emma\"],\"application/emotionml+xml\":[\"emotionml\"],\"application/epub+zip\":[\"epub\"],\"application/exi\":[\"exi\"],\"application/express\":[\"exp\"],\"application/fdt+xml\":[\"fdt\"],\"application/font-tdpfr\":[\"pfr\"],\"application/geo+json\":[\"geojson\"],\"application/gml+xml\":[\"gml\"],\"application/gpx+xml\":[\"gpx\"],\"application/gxf\":[\"gxf\"],\"application/gzip\":[\"gz\"],\"application/hjson\":[\"hjson\"],\"application/hyperstudio\":[\"stk\"],\"application/inkml+xml\":[\"ink\",\"inkml\"],\"application/ipfix\":[\"ipfix\"],\"application/its+xml\":[\"its\"],\"application/java-archive\":[\"jar\",\"war\",\"ear\"],\"application/java-serialized-object\":[\"ser\"],\"application/java-vm\":[\"class\"],\"application/javascript\":[\"js\",\"mjs\"],\"application/json\":[\"json\",\"map\"],\"application/json5\":[\"json5\"],\"application/jsonml+json\":[\"jsonml\"],\"application/ld+json\":[\"jsonld\"],\"application/lgr+xml\":[\"lgr\"],\"application/lost+xml\":[\"lostxml\"],\"application/mac-binhex40\":[\"hqx\"],\"application/mac-compactpro\":[\"cpt\"],\"application/mads+xml\":[\"mads\"],\"application/manifest+json\":[\"webmanifest\"],\"application/marc\":[\"mrc\"],\"application/marcxml+xml\":[\"mrcx\"],\"application/mathematica\":[\"ma\",\"nb\",\"mb\"],\"application/mathml+xml\":[\"mathml\"],\"application/mbox\":[\"mbox\"],\"application/mediaservercontrol+xml\":[\"mscml\"],\"application/metalink+xml\":[\"metalink\"],\"application/metalink4+xml\":[\"meta4\"],\"application/mets+xml\":[\"mets\"],\"application/mmt-aei+xml\":[\"maei\"],\"application/mmt-usd+xml\":[\"musd\"],\"application/mods+xml\":[\"mods\"],\"application/mp21\":[\"m21\",\"mp21\"],\"application/mp4\":[\"mp4s\",\"m4p\"],\"application/msword\":[\"doc\",\"dot\"],\"application/mxf\":[\"mxf\"],\"application/n-quads\":[\"nq\"],\"application/n-triples\":[\"nt\"],\"application/node\":[\"cjs\"],\"application/octet-stream\":[\"bin\",\"dms\",\"lrf\",\"mar\",\"so\",\"dist\",\"distz\",\"pkg\",\"bpk\",\"dump\",\"elc\",\"deploy\",\"exe\",\"dll\",\"deb\",\"dmg\",\"iso\",\"img\",\"msi\",\"msp\",\"msm\",\"buffer\"],\"application/oda\":[\"oda\"],\"application/oebps-package+xml\":[\"opf\"],\"application/ogg\":[\"ogx\"],\"application/omdoc+xml\":[\"omdoc\"],\"application/onenote\":[\"onetoc\",\"onetoc2\",\"onetmp\",\"onepkg\"],\"application/oxps\":[\"oxps\"],\"application/p2p-overlay+xml\":[\"relo\"],\"application/patch-ops-error+xml\":[\"xer\"],\"application/pdf\":[\"pdf\"],\"application/pgp-encrypted\":[\"pgp\"],\"application/pgp-signature\":[\"asc\",\"sig\"],\"application/pics-rules\":[\"prf\"],\"application/pkcs10\":[\"p10\"],\"application/pkcs7-mime\":[\"p7m\",\"p7c\"],\"application/pkcs7-signature\":[\"p7s\"],\"application/pkcs8\":[\"p8\"],\"application/pkix-attr-cert\":[\"ac\"],\"application/pkix-cert\":[\"cer\"],\"application/pkix-crl\":[\"crl\"],\"application/pkix-pkipath\":[\"pkipath\"],\"application/pkixcmp\":[\"pki\"],\"application/pls+xml\":[\"pls\"],\"application/postscript\":[\"ai\",\"eps\",\"ps\"],\"application/provenance+xml\":[\"provx\"],\"application/pskc+xml\":[\"pskcxml\"],\"application/raml+yaml\":[\"raml\"],\"application/rdf+xml\":[\"rdf\",\"owl\"],\"application/reginfo+xml\":[\"rif\"],\"application/relax-ng-compact-syntax\":[\"rnc\"],\"application/resource-lists+xml\":[\"rl\"],\"application/resource-lists-diff+xml\":[\"rld\"],\"application/rls-services+xml\":[\"rs\"],\"application/route-apd+xml\":[\"rapd\"],\"application/route-s-tsid+xml\":[\"sls\"],\"application/route-usd+xml\":[\"rusd\"],\"application/rpki-ghostbusters\":[\"gbr\"],\"application/rpki-manifest\":[\"mft\"],\"application/rpki-roa\":[\"roa\"],\"application/rsd+xml\":[\"rsd\"],\"application/rss+xml\":[\"rss\"],\"application/rtf\":[\"rtf\"],\"application/sbml+xml\":[\"sbml\"],\"application/scvp-cv-request\":[\"scq\"],\"application/scvp-cv-response\":[\"scs\"],\"application/scvp-vp-request\":[\"spq\"],\"application/scvp-vp-response\":[\"spp\"],\"application/sdp\":[\"sdp\"],\"application/senml+xml\":[\"senmlx\"],\"application/sensml+xml\":[\"sensmlx\"],\"application/set-payment-initiation\":[\"setpay\"],\"application/set-registration-initiation\":[\"setreg\"],\"application/shf+xml\":[\"shf\"],\"application/sieve\":[\"siv\",\"sieve\"],\"application/smil+xml\":[\"smi\",\"smil\"],\"application/sparql-query\":[\"rq\"],\"application/sparql-results+xml\":[\"srx\"],\"application/srgs\":[\"gram\"],\"application/srgs+xml\":[\"grxml\"],\"application/sru+xml\":[\"sru\"],\"application/ssdl+xml\":[\"ssdl\"],\"application/ssml+xml\":[\"ssml\"],\"application/swid+xml\":[\"swidtag\"],\"application/tei+xml\":[\"tei\",\"teicorpus\"],\"application/thraud+xml\":[\"tfi\"],\"application/timestamped-data\":[\"tsd\"],\"application/toml\":[\"toml\"],\"application/trig\":[\"trig\"],\"application/ttml+xml\":[\"ttml\"],\"application/ubjson\":[\"ubj\"],\"application/urc-ressheet+xml\":[\"rsheet\"],\"application/urc-targetdesc+xml\":[\"td\"],\"application/voicexml+xml\":[\"vxml\"],\"application/wasm\":[\"wasm\"],\"application/widget\":[\"wgt\"],\"application/winhlp\":[\"hlp\"],\"application/wsdl+xml\":[\"wsdl\"],\"application/wspolicy+xml\":[\"wspolicy\"],\"application/xaml+xml\":[\"xaml\"],\"application/xcap-att+xml\":[\"xav\"],\"application/xcap-caps+xml\":[\"xca\"],\"application/xcap-diff+xml\":[\"xdf\"],\"application/xcap-el+xml\":[\"xel\"],\"application/xcap-ns+xml\":[\"xns\"],\"application/xenc+xml\":[\"xenc\"],\"application/xhtml+xml\":[\"xhtml\",\"xht\"],\"application/xliff+xml\":[\"xlf\"],\"application/xml\":[\"xml\",\"xsl\",\"xsd\",\"rng\"],\"application/xml-dtd\":[\"dtd\"],\"application/xop+xml\":[\"xop\"],\"application/xproc+xml\":[\"xpl\"],\"application/xslt+xml\":[\"*xsl\",\"xslt\"],\"application/xspf+xml\":[\"xspf\"],\"application/xv+xml\":[\"mxml\",\"xhvml\",\"xvml\",\"xvm\"],\"application/yang\":[\"yang\"],\"application/yin+xml\":[\"yin\"],\"application/zip\":[\"zip\"],\"audio/3gpp\":[\"*3gpp\"],\"audio/adpcm\":[\"adp\"],\"audio/amr\":[\"amr\"],\"audio/basic\":[\"au\",\"snd\"],\"audio/midi\":[\"mid\",\"midi\",\"kar\",\"rmi\"],\"audio/mobile-xmf\":[\"mxmf\"],\"audio/mp3\":[\"*mp3\"],\"audio/mp4\":[\"m4a\",\"mp4a\"],\"audio/mpeg\":[\"mpga\",\"mp2\",\"mp2a\",\"mp3\",\"m2a\",\"m3a\"],\"audio/ogg\":[\"oga\",\"ogg\",\"spx\",\"opus\"],\"audio/s3m\":[\"s3m\"],\"audio/silk\":[\"sil\"],\"audio/wav\":[\"wav\"],\"audio/wave\":[\"*wav\"],\"audio/webm\":[\"weba\"],\"audio/xm\":[\"xm\"],\"font/collection\":[\"ttc\"],\"font/otf\":[\"otf\"],\"font/ttf\":[\"ttf\"],\"font/woff\":[\"woff\"],\"font/woff2\":[\"woff2\"],\"image/aces\":[\"exr\"],\"image/apng\":[\"apng\"],\"image/avif\":[\"avif\"],\"image/bmp\":[\"bmp\"],\"image/cgm\":[\"cgm\"],\"image/dicom-rle\":[\"drle\"],\"image/emf\":[\"emf\"],\"image/fits\":[\"fits\"],\"image/g3fax\":[\"g3\"],\"image/gif\":[\"gif\"],\"image/heic\":[\"heic\"],\"image/heic-sequence\":[\"heics\"],\"image/heif\":[\"heif\"],\"image/heif-sequence\":[\"heifs\"],\"image/hej2k\":[\"hej2\"],\"image/hsj2\":[\"hsj2\"],\"image/ief\":[\"ief\"],\"image/jls\":[\"jls\"],\"image/jp2\":[\"jp2\",\"jpg2\"],\"image/jpeg\":[\"jpeg\",\"jpg\",\"jpe\"],\"image/jph\":[\"jph\"],\"image/jphc\":[\"jhc\"],\"image/jpm\":[\"jpm\"],\"image/jpx\":[\"jpx\",\"jpf\"],\"image/jxr\":[\"jxr\"],\"image/jxra\":[\"jxra\"],\"image/jxrs\":[\"jxrs\"],\"image/jxs\":[\"jxs\"],\"image/jxsc\":[\"jxsc\"],\"image/jxsi\":[\"jxsi\"],\"image/jxss\":[\"jxss\"],\"image/ktx\":[\"ktx\"],\"image/ktx2\":[\"ktx2\"],\"image/png\":[\"png\"],\"image/sgi\":[\"sgi\"],\"image/svg+xml\":[\"svg\",\"svgz\"],\"image/t38\":[\"t38\"],\"image/tiff\":[\"tif\",\"tiff\"],\"image/tiff-fx\":[\"tfx\"],\"image/webp\":[\"webp\"],\"image/wmf\":[\"wmf\"],\"message/disposition-notification\":[\"disposition-notification\"],\"message/global\":[\"u8msg\"],\"message/global-delivery-status\":[\"u8dsn\"],\"message/global-disposition-notification\":[\"u8mdn\"],\"message/global-headers\":[\"u8hdr\"],\"message/rfc822\":[\"eml\",\"mime\"],\"model/3mf\":[\"3mf\"],\"model/gltf+json\":[\"gltf\"],\"model/gltf-binary\":[\"glb\"],\"model/iges\":[\"igs\",\"iges\"],\"model/mesh\":[\"msh\",\"mesh\",\"silo\"],\"model/mtl\":[\"mtl\"],\"model/obj\":[\"obj\"],\"model/step+xml\":[\"stpx\"],\"model/step+zip\":[\"stpz\"],\"model/step-xml+zip\":[\"stpxz\"],\"model/stl\":[\"stl\"],\"model/vrml\":[\"wrl\",\"vrml\"],\"model/x3d+binary\":[\"*x3db\",\"x3dbz\"],\"model/x3d+fastinfoset\":[\"x3db\"],\"model/x3d+vrml\":[\"*x3dv\",\"x3dvz\"],\"model/x3d+xml\":[\"x3d\",\"x3dz\"],\"model/x3d-vrml\":[\"x3dv\"],\"text/cache-manifest\":[\"appcache\",\"manifest\"],\"text/calendar\":[\"ics\",\"ifb\"],\"text/coffeescript\":[\"coffee\",\"litcoffee\"],\"text/css\":[\"css\"],\"text/csv\":[\"csv\"],\"text/html\":[\"html\",\"htm\",\"shtml\"],\"text/jade\":[\"jade\"],\"text/jsx\":[\"jsx\"],\"text/less\":[\"less\"],\"text/markdown\":[\"markdown\",\"md\"],\"text/mathml\":[\"mml\"],\"text/mdx\":[\"mdx\"],\"text/n3\":[\"n3\"],\"text/plain\":[\"txt\",\"text\",\"conf\",\"def\",\"list\",\"log\",\"in\",\"ini\"],\"text/richtext\":[\"rtx\"],\"text/rtf\":[\"*rtf\"],\"text/sgml\":[\"sgml\",\"sgm\"],\"text/shex\":[\"shex\"],\"text/slim\":[\"slim\",\"slm\"],\"text/spdx\":[\"spdx\"],\"text/stylus\":[\"stylus\",\"styl\"],\"text/tab-separated-values\":[\"tsv\"],\"text/troff\":[\"t\",\"tr\",\"roff\",\"man\",\"me\",\"ms\"],\"text/turtle\":[\"ttl\"],\"text/uri-list\":[\"uri\",\"uris\",\"urls\"],\"text/vcard\":[\"vcard\"],\"text/vtt\":[\"vtt\"],\"text/xml\":[\"*xml\"],\"text/yaml\":[\"yaml\",\"yml\"],\"video/3gpp\":[\"3gp\",\"3gpp\"],\"video/3gpp2\":[\"3g2\"],\"video/h261\":[\"h261\"],\"video/h263\":[\"h263\"],\"video/h264\":[\"h264\"],\"video/iso.segment\":[\"m4s\"],\"video/jpeg\":[\"jpgv\"],\"video/jpm\":[\"*jpm\",\"jpgm\"],\"video/mj2\":[\"mj2\",\"mjp2\"],\"video/mp2t\":[\"ts\"],\"video/mp4\":[\"mp4\",\"mp4v\",\"mpg4\"],\"video/mpeg\":[\"mpeg\",\"mpg\",\"mpe\",\"m1v\",\"m2v\"],\"video/ogg\":[\"ogv\"],\"video/quicktime\":[\"qt\",\"mov\"],\"video/webm\":[\"webm\"]}});var Dt=F((on,It)=>{It.exports={\"application/prs.cww\":[\"cww\"],\"application/vnd.1000minds.decision-model+xml\":[\"1km\"],\"application/vnd.3gpp.pic-bw-large\":[\"plb\"],\"application/vnd.3gpp.pic-bw-small\":[\"psb\"],\"application/vnd.3gpp.pic-bw-var\":[\"pvb\"],\"application/vnd.3gpp2.tcap\":[\"tcap\"],\"application/vnd.3m.post-it-notes\":[\"pwn\"],\"application/vnd.accpac.simply.aso\":[\"aso\"],\"application/vnd.accpac.simply.imp\":[\"imp\"],\"application/vnd.acucobol\":[\"acu\"],\"application/vnd.acucorp\":[\"atc\",\"acutc\"],\"application/vnd.adobe.air-application-installer-package+zip\":[\"air\"],\"application/vnd.adobe.formscentral.fcdt\":[\"fcdt\"],\"application/vnd.adobe.fxp\":[\"fxp\",\"fxpl\"],\"application/vnd.adobe.xdp+xml\":[\"xdp\"],\"application/vnd.adobe.xfdf\":[\"xfdf\"],\"application/vnd.ahead.space\":[\"ahead\"],\"application/vnd.airzip.filesecure.azf\":[\"azf\"],\"application/vnd.airzip.filesecure.azs\":[\"azs\"],\"application/vnd.amazon.ebook\":[\"azw\"],\"application/vnd.americandynamics.acc\":[\"acc\"],\"application/vnd.amiga.ami\":[\"ami\"],\"application/vnd.android.package-archive\":[\"apk\"],\"application/vnd.anser-web-certificate-issue-initiation\":[\"cii\"],\"application/vnd.anser-web-funds-transfer-initiation\":[\"fti\"],\"application/vnd.antix.game-component\":[\"atx\"],\"application/vnd.apple.installer+xml\":[\"mpkg\"],\"application/vnd.apple.keynote\":[\"key\"],\"application/vnd.apple.mpegurl\":[\"m3u8\"],\"application/vnd.apple.numbers\":[\"numbers\"],\"application/vnd.apple.pages\":[\"pages\"],\"application/vnd.apple.pkpass\":[\"pkpass\"],\"application/vnd.aristanetworks.swi\":[\"swi\"],\"application/vnd.astraea-software.iota\":[\"iota\"],\"application/vnd.audiograph\":[\"aep\"],\"application/vnd.balsamiq.bmml+xml\":[\"bmml\"],\"application/vnd.blueice.multipass\":[\"mpm\"],\"application/vnd.bmi\":[\"bmi\"],\"application/vnd.businessobjects\":[\"rep\"],\"application/vnd.chemdraw+xml\":[\"cdxml\"],\"application/vnd.chipnuts.karaoke-mmd\":[\"mmd\"],\"application/vnd.cinderella\":[\"cdy\"],\"application/vnd.citationstyles.style+xml\":[\"csl\"],\"application/vnd.claymore\":[\"cla\"],\"application/vnd.cloanto.rp9\":[\"rp9\"],\"application/vnd.clonk.c4group\":[\"c4g\",\"c4d\",\"c4f\",\"c4p\",\"c4u\"],\"application/vnd.cluetrust.cartomobile-config\":[\"c11amc\"],\"application/vnd.cluetrust.cartomobile-config-pkg\":[\"c11amz\"],\"application/vnd.commonspace\":[\"csp\"],\"application/vnd.contact.cmsg\":[\"cdbcmsg\"],\"application/vnd.cosmocaller\":[\"cmc\"],\"application/vnd.crick.clicker\":[\"clkx\"],\"application/vnd.crick.clicker.keyboard\":[\"clkk\"],\"application/vnd.crick.clicker.palette\":[\"clkp\"],\"application/vnd.crick.clicker.template\":[\"clkt\"],\"application/vnd.crick.clicker.wordbank\":[\"clkw\"],\"application/vnd.criticaltools.wbs+xml\":[\"wbs\"],\"application/vnd.ctc-posml\":[\"pml\"],\"application/vnd.cups-ppd\":[\"ppd\"],\"application/vnd.curl.car\":[\"car\"],\"application/vnd.curl.pcurl\":[\"pcurl\"],\"application/vnd.dart\":[\"dart\"],\"application/vnd.data-vision.rdz\":[\"rdz\"],\"application/vnd.dbf\":[\"dbf\"],\"application/vnd.dece.data\":[\"uvf\",\"uvvf\",\"uvd\",\"uvvd\"],\"application/vnd.dece.ttml+xml\":[\"uvt\",\"uvvt\"],\"application/vnd.dece.unspecified\":[\"uvx\",\"uvvx\"],\"application/vnd.dece.zip\":[\"uvz\",\"uvvz\"],\"application/vnd.denovo.fcselayout-link\":[\"fe_launch\"],\"application/vnd.dna\":[\"dna\"],\"application/vnd.dolby.mlp\":[\"mlp\"],\"application/vnd.dpgraph\":[\"dpg\"],\"application/vnd.dreamfactory\":[\"dfac\"],\"application/vnd.ds-keypoint\":[\"kpxx\"],\"application/vnd.dvb.ait\":[\"ait\"],\"application/vnd.dvb.service\":[\"svc\"],\"application/vnd.dynageo\":[\"geo\"],\"application/vnd.ecowin.chart\":[\"mag\"],\"application/vnd.enliven\":[\"nml\"],\"application/vnd.epson.esf\":[\"esf\"],\"application/vnd.epson.msf\":[\"msf\"],\"application/vnd.epson.quickanime\":[\"qam\"],\"application/vnd.epson.salt\":[\"slt\"],\"application/vnd.epson.ssf\":[\"ssf\"],\"application/vnd.eszigno3+xml\":[\"es3\",\"et3\"],\"application/vnd.ezpix-album\":[\"ez2\"],\"application/vnd.ezpix-package\":[\"ez3\"],\"application/vnd.fdf\":[\"fdf\"],\"application/vnd.fdsn.mseed\":[\"mseed\"],\"application/vnd.fdsn.seed\":[\"seed\",\"dataless\"],\"application/vnd.flographit\":[\"gph\"],\"application/vnd.fluxtime.clip\":[\"ftc\"],\"application/vnd.framemaker\":[\"fm\",\"frame\",\"maker\",\"book\"],\"application/vnd.frogans.fnc\":[\"fnc\"],\"application/vnd.frogans.ltf\":[\"ltf\"],\"application/vnd.fsc.weblaunch\":[\"fsc\"],\"application/vnd.fujitsu.oasys\":[\"oas\"],\"application/vnd.fujitsu.oasys2\":[\"oa2\"],\"application/vnd.fujitsu.oasys3\":[\"oa3\"],\"application/vnd.fujitsu.oasysgp\":[\"fg5\"],\"application/vnd.fujitsu.oasysprs\":[\"bh2\"],\"application/vnd.fujixerox.ddd\":[\"ddd\"],\"application/vnd.fujixerox.docuworks\":[\"xdw\"],\"application/vnd.fujixerox.docuworks.binder\":[\"xbd\"],\"application/vnd.fuzzysheet\":[\"fzs\"],\"application/vnd.genomatix.tuxedo\":[\"txd\"],\"application/vnd.geogebra.file\":[\"ggb\"],\"application/vnd.geogebra.tool\":[\"ggt\"],\"application/vnd.geometry-explorer\":[\"gex\",\"gre\"],\"application/vnd.geonext\":[\"gxt\"],\"application/vnd.geoplan\":[\"g2w\"],\"application/vnd.geospace\":[\"g3w\"],\"application/vnd.gmx\":[\"gmx\"],\"application/vnd.google-apps.document\":[\"gdoc\"],\"application/vnd.google-apps.presentation\":[\"gslides\"],\"application/vnd.google-apps.spreadsheet\":[\"gsheet\"],\"application/vnd.google-earth.kml+xml\":[\"kml\"],\"application/vnd.google-earth.kmz\":[\"kmz\"],\"application/vnd.grafeq\":[\"gqf\",\"gqs\"],\"application/vnd.groove-account\":[\"gac\"],\"application/vnd.groove-help\":[\"ghf\"],\"application/vnd.groove-identity-message\":[\"gim\"],\"application/vnd.groove-injector\":[\"grv\"],\"application/vnd.groove-tool-message\":[\"gtm\"],\"application/vnd.groove-tool-template\":[\"tpl\"],\"application/vnd.groove-vcard\":[\"vcg\"],\"application/vnd.hal+xml\":[\"hal\"],\"application/vnd.handheld-entertainment+xml\":[\"zmm\"],\"application/vnd.hbci\":[\"hbci\"],\"application/vnd.hhe.lesson-player\":[\"les\"],\"application/vnd.hp-hpgl\":[\"hpgl\"],\"application/vnd.hp-hpid\":[\"hpid\"],\"application/vnd.hp-hps\":[\"hps\"],\"application/vnd.hp-jlyt\":[\"jlt\"],\"application/vnd.hp-pcl\":[\"pcl\"],\"application/vnd.hp-pclxl\":[\"pclxl\"],\"application/vnd.hydrostatix.sof-data\":[\"sfd-hdstx\"],\"application/vnd.ibm.minipay\":[\"mpy\"],\"application/vnd.ibm.modcap\":[\"afp\",\"listafp\",\"list3820\"],\"application/vnd.ibm.rights-management\":[\"irm\"],\"application/vnd.ibm.secure-container\":[\"sc\"],\"application/vnd.iccprofile\":[\"icc\",\"icm\"],\"application/vnd.igloader\":[\"igl\"],\"application/vnd.immervision-ivp\":[\"ivp\"],\"application/vnd.immervision-ivu\":[\"ivu\"],\"application/vnd.insors.igm\":[\"igm\"],\"application/vnd.intercon.formnet\":[\"xpw\",\"xpx\"],\"application/vnd.intergeo\":[\"i2g\"],\"application/vnd.intu.qbo\":[\"qbo\"],\"application/vnd.intu.qfx\":[\"qfx\"],\"application/vnd.ipunplugged.rcprofile\":[\"rcprofile\"],\"application/vnd.irepository.package+xml\":[\"irp\"],\"application/vnd.is-xpr\":[\"xpr\"],\"application/vnd.isac.fcs\":[\"fcs\"],\"application/vnd.jam\":[\"jam\"],\"application/vnd.jcp.javame.midlet-rms\":[\"rms\"],\"application/vnd.jisp\":[\"jisp\"],\"application/vnd.joost.joda-archive\":[\"joda\"],\"application/vnd.kahootz\":[\"ktz\",\"ktr\"],\"application/vnd.kde.karbon\":[\"karbon\"],\"application/vnd.kde.kchart\":[\"chrt\"],\"application/vnd.kde.kformula\":[\"kfo\"],\"application/vnd.kde.kivio\":[\"flw\"],\"application/vnd.kde.kontour\":[\"kon\"],\"application/vnd.kde.kpresenter\":[\"kpr\",\"kpt\"],\"application/vnd.kde.kspread\":[\"ksp\"],\"application/vnd.kde.kword\":[\"kwd\",\"kwt\"],\"application/vnd.kenameaapp\":[\"htke\"],\"application/vnd.kidspiration\":[\"kia\"],\"application/vnd.kinar\":[\"kne\",\"knp\"],\"application/vnd.koan\":[\"skp\",\"skd\",\"skt\",\"skm\"],\"application/vnd.kodak-descriptor\":[\"sse\"],\"application/vnd.las.las+xml\":[\"lasxml\"],\"application/vnd.llamagraphics.life-balance.desktop\":[\"lbd\"],\"application/vnd.llamagraphics.life-balance.exchange+xml\":[\"lbe\"],\"application/vnd.lotus-1-2-3\":[\"123\"],\"application/vnd.lotus-approach\":[\"apr\"],\"application/vnd.lotus-freelance\":[\"pre\"],\"application/vnd.lotus-notes\":[\"nsf\"],\"application/vnd.lotus-organizer\":[\"org\"],\"application/vnd.lotus-screencam\":[\"scm\"],\"application/vnd.lotus-wordpro\":[\"lwp\"],\"application/vnd.macports.portpkg\":[\"portpkg\"],\"application/vnd.mapbox-vector-tile\":[\"mvt\"],\"application/vnd.mcd\":[\"mcd\"],\"application/vnd.medcalcdata\":[\"mc1\"],\"application/vnd.mediastation.cdkey\":[\"cdkey\"],\"application/vnd.mfer\":[\"mwf\"],\"application/vnd.mfmp\":[\"mfm\"],\"application/vnd.micrografx.flo\":[\"flo\"],\"application/vnd.micrografx.igx\":[\"igx\"],\"application/vnd.mif\":[\"mif\"],\"application/vnd.mobius.daf\":[\"daf\"],\"application/vnd.mobius.dis\":[\"dis\"],\"application/vnd.mobius.mbk\":[\"mbk\"],\"application/vnd.mobius.mqy\":[\"mqy\"],\"application/vnd.mobius.msl\":[\"msl\"],\"application/vnd.mobius.plc\":[\"plc\"],\"application/vnd.mobius.txf\":[\"txf\"],\"application/vnd.mophun.application\":[\"mpn\"],\"application/vnd.mophun.certificate\":[\"mpc\"],\"application/vnd.mozilla.xul+xml\":[\"xul\"],\"application/vnd.ms-artgalry\":[\"cil\"],\"application/vnd.ms-cab-compressed\":[\"cab\"],\"application/vnd.ms-excel\":[\"xls\",\"xlm\",\"xla\",\"xlc\",\"xlt\",\"xlw\"],\"application/vnd.ms-excel.addin.macroenabled.12\":[\"xlam\"],\"application/vnd.ms-excel.sheet.binary.macroenabled.12\":[\"xlsb\"],\"application/vnd.ms-excel.sheet.macroenabled.12\":[\"xlsm\"],\"application/vnd.ms-excel.template.macroenabled.12\":[\"xltm\"],\"application/vnd.ms-fontobject\":[\"eot\"],\"application/vnd.ms-htmlhelp\":[\"chm\"],\"application/vnd.ms-ims\":[\"ims\"],\"application/vnd.ms-lrm\":[\"lrm\"],\"application/vnd.ms-officetheme\":[\"thmx\"],\"application/vnd.ms-outlook\":[\"msg\"],\"application/vnd.ms-pki.seccat\":[\"cat\"],\"application/vnd.ms-pki.stl\":[\"*stl\"],\"application/vnd.ms-powerpoint\":[\"ppt\",\"pps\",\"pot\"],\"application/vnd.ms-powerpoint.addin.macroenabled.12\":[\"ppam\"],\"application/vnd.ms-powerpoint.presentation.macroenabled.12\":[\"pptm\"],\"application/vnd.ms-powerpoint.slide.macroenabled.12\":[\"sldm\"],\"application/vnd.ms-powerpoint.slideshow.macroenabled.12\":[\"ppsm\"],\"application/vnd.ms-powerpoint.template.macroenabled.12\":[\"potm\"],\"application/vnd.ms-project\":[\"mpp\",\"mpt\"],\"application/vnd.ms-word.document.macroenabled.12\":[\"docm\"],\"application/vnd.ms-word.template.macroenabled.12\":[\"dotm\"],\"application/vnd.ms-works\":[\"wps\",\"wks\",\"wcm\",\"wdb\"],\"application/vnd.ms-wpl\":[\"wpl\"],\"application/vnd.ms-xpsdocument\":[\"xps\"],\"application/vnd.mseq\":[\"mseq\"],\"application/vnd.musician\":[\"mus\"],\"application/vnd.muvee.style\":[\"msty\"],\"application/vnd.mynfc\":[\"taglet\"],\"application/vnd.neurolanguage.nlu\":[\"nlu\"],\"application/vnd.nitf\":[\"ntf\",\"nitf\"],\"application/vnd.noblenet-directory\":[\"nnd\"],\"application/vnd.noblenet-sealer\":[\"nns\"],\"application/vnd.noblenet-web\":[\"nnw\"],\"application/vnd.nokia.n-gage.ac+xml\":[\"*ac\"],\"application/vnd.nokia.n-gage.data\":[\"ngdat\"],\"application/vnd.nokia.n-gage.symbian.install\":[\"n-gage\"],\"application/vnd.nokia.radio-preset\":[\"rpst\"],\"application/vnd.nokia.radio-presets\":[\"rpss\"],\"application/vnd.novadigm.edm\":[\"edm\"],\"application/vnd.novadigm.edx\":[\"edx\"],\"application/vnd.novadigm.ext\":[\"ext\"],\"application/vnd.oasis.opendocument.chart\":[\"odc\"],\"application/vnd.oasis.opendocument.chart-template\":[\"otc\"],\"application/vnd.oasis.opendocument.database\":[\"odb\"],\"application/vnd.oasis.opendocument.formula\":[\"odf\"],\"application/vnd.oasis.opendocument.formula-template\":[\"odft\"],\"application/vnd.oasis.opendocument.graphics\":[\"odg\"],\"application/vnd.oasis.opendocument.graphics-template\":[\"otg\"],\"application/vnd.oasis.opendocument.image\":[\"odi\"],\"application/vnd.oasis.opendocument.image-template\":[\"oti\"],\"application/vnd.oasis.opendocument.presentation\":[\"odp\"],\"application/vnd.oasis.opendocument.presentation-template\":[\"otp\"],\"application/vnd.oasis.opendocument.spreadsheet\":[\"ods\"],\"application/vnd.oasis.opendocument.spreadsheet-template\":[\"ots\"],\"application/vnd.oasis.opendocument.text\":[\"odt\"],\"application/vnd.oasis.opendocument.text-master\":[\"odm\"],\"application/vnd.oasis.opendocument.text-template\":[\"ott\"],\"application/vnd.oasis.opendocument.text-web\":[\"oth\"],\"application/vnd.olpc-sugar\":[\"xo\"],\"application/vnd.oma.dd2+xml\":[\"dd2\"],\"application/vnd.openblox.game+xml\":[\"obgx\"],\"application/vnd.openofficeorg.extension\":[\"oxt\"],\"application/vnd.openstreetmap.data+xml\":[\"osm\"],\"application/vnd.openxmlformats-officedocument.presentationml.presentation\":[\"pptx\"],\"application/vnd.openxmlformats-officedocument.presentationml.slide\":[\"sldx\"],\"application/vnd.openxmlformats-officedocument.presentationml.slideshow\":[\"ppsx\"],\"application/vnd.openxmlformats-officedocument.presentationml.template\":[\"potx\"],\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\":[\"xlsx\"],\"application/vnd.openxmlformats-officedocument.spreadsheetml.template\":[\"xltx\"],\"application/vnd.openxmlformats-officedocument.wordprocessingml.document\":[\"docx\"],\"application/vnd.openxmlformats-officedocument.wordprocessingml.template\":[\"dotx\"],\"application/vnd.osgeo.mapguide.package\":[\"mgp\"],\"application/vnd.osgi.dp\":[\"dp\"],\"application/vnd.osgi.subsystem\":[\"esa\"],\"application/vnd.palm\":[\"pdb\",\"pqa\",\"oprc\"],\"application/vnd.pawaafile\":[\"paw\"],\"application/vnd.pg.format\":[\"str\"],\"application/vnd.pg.osasli\":[\"ei6\"],\"application/vnd.picsel\":[\"efif\"],\"application/vnd.pmi.widget\":[\"wg\"],\"application/vnd.pocketlearn\":[\"plf\"],\"application/vnd.powerbuilder6\":[\"pbd\"],\"application/vnd.previewsystems.box\":[\"box\"],\"application/vnd.proteus.magazine\":[\"mgz\"],\"application/vnd.publishare-delta-tree\":[\"qps\"],\"application/vnd.pvi.ptid1\":[\"ptid\"],\"application/vnd.quark.quarkxpress\":[\"qxd\",\"qxt\",\"qwd\",\"qwt\",\"qxl\",\"qxb\"],\"application/vnd.rar\":[\"rar\"],\"application/vnd.realvnc.bed\":[\"bed\"],\"application/vnd.recordare.musicxml\":[\"mxl\"],\"application/vnd.recordare.musicxml+xml\":[\"musicxml\"],\"application/vnd.rig.cryptonote\":[\"cryptonote\"],\"application/vnd.rim.cod\":[\"cod\"],\"application/vnd.rn-realmedia\":[\"rm\"],\"application/vnd.rn-realmedia-vbr\":[\"rmvb\"],\"application/vnd.route66.link66+xml\":[\"link66\"],\"application/vnd.sailingtracker.track\":[\"st\"],\"application/vnd.seemail\":[\"see\"],\"application/vnd.sema\":[\"sema\"],\"application/vnd.semd\":[\"semd\"],\"application/vnd.semf\":[\"semf\"],\"application/vnd.shana.informed.formdata\":[\"ifm\"],\"application/vnd.shana.informed.formtemplate\":[\"itp\"],\"application/vnd.shana.informed.interchange\":[\"iif\"],\"application/vnd.shana.informed.package\":[\"ipk\"],\"application/vnd.simtech-mindmapper\":[\"twd\",\"twds\"],\"application/vnd.smaf\":[\"mmf\"],\"application/vnd.smart.teacher\":[\"teacher\"],\"application/vnd.software602.filler.form+xml\":[\"fo\"],\"application/vnd.solent.sdkm+xml\":[\"sdkm\",\"sdkd\"],\"application/vnd.spotfire.dxp\":[\"dxp\"],\"application/vnd.spotfire.sfs\":[\"sfs\"],\"application/vnd.stardivision.calc\":[\"sdc\"],\"application/vnd.stardivision.draw\":[\"sda\"],\"application/vnd.stardivision.impress\":[\"sdd\"],\"application/vnd.stardivision.math\":[\"smf\"],\"application/vnd.stardivision.writer\":[\"sdw\",\"vor\"],\"application/vnd.stardivision.writer-global\":[\"sgl\"],\"application/vnd.stepmania.package\":[\"smzip\"],\"application/vnd.stepmania.stepchart\":[\"sm\"],\"application/vnd.sun.wadl+xml\":[\"wadl\"],\"application/vnd.sun.xml.calc\":[\"sxc\"],\"application/vnd.sun.xml.calc.template\":[\"stc\"],\"application/vnd.sun.xml.draw\":[\"sxd\"],\"application/vnd.sun.xml.draw.template\":[\"std\"],\"application/vnd.sun.xml.impress\":[\"sxi\"],\"application/vnd.sun.xml.impress.template\":[\"sti\"],\"application/vnd.sun.xml.math\":[\"sxm\"],\"application/vnd.sun.xml.writer\":[\"sxw\"],\"application/vnd.sun.xml.writer.global\":[\"sxg\"],\"application/vnd.sun.xml.writer.template\":[\"stw\"],\"application/vnd.sus-calendar\":[\"sus\",\"susp\"],\"application/vnd.svd\":[\"svd\"],\"application/vnd.symbian.install\":[\"sis\",\"sisx\"],\"application/vnd.syncml+xml\":[\"xsm\"],\"application/vnd.syncml.dm+wbxml\":[\"bdm\"],\"application/vnd.syncml.dm+xml\":[\"xdm\"],\"application/vnd.syncml.dmddf+xml\":[\"ddf\"],\"application/vnd.tao.intent-module-archive\":[\"tao\"],\"application/vnd.tcpdump.pcap\":[\"pcap\",\"cap\",\"dmp\"],\"application/vnd.tmobile-livetv\":[\"tmo\"],\"application/vnd.trid.tpt\":[\"tpt\"],\"application/vnd.triscape.mxs\":[\"mxs\"],\"application/vnd.trueapp\":[\"tra\"],\"application/vnd.ufdl\":[\"ufd\",\"ufdl\"],\"application/vnd.uiq.theme\":[\"utz\"],\"application/vnd.umajin\":[\"umj\"],\"application/vnd.unity\":[\"unityweb\"],\"application/vnd.uoml+xml\":[\"uoml\"],\"application/vnd.vcx\":[\"vcx\"],\"application/vnd.visio\":[\"vsd\",\"vst\",\"vss\",\"vsw\"],\"application/vnd.visionary\":[\"vis\"],\"application/vnd.vsf\":[\"vsf\"],\"application/vnd.wap.wbxml\":[\"wbxml\"],\"application/vnd.wap.wmlc\":[\"wmlc\"],\"application/vnd.wap.wmlscriptc\":[\"wmlsc\"],\"application/vnd.webturbo\":[\"wtb\"],\"application/vnd.wolfram.player\":[\"nbp\"],\"application/vnd.wordperfect\":[\"wpd\"],\"application/vnd.wqd\":[\"wqd\"],\"application/vnd.wt.stf\":[\"stf\"],\"application/vnd.xara\":[\"xar\"],\"application/vnd.xfdl\":[\"xfdl\"],\"application/vnd.yamaha.hv-dic\":[\"hvd\"],\"application/vnd.yamaha.hv-script\":[\"hvs\"],\"application/vnd.yamaha.hv-voice\":[\"hvp\"],\"application/vnd.yamaha.openscoreformat\":[\"osf\"],\"application/vnd.yamaha.openscoreformat.osfpvg+xml\":[\"osfpvg\"],\"application/vnd.yamaha.smaf-audio\":[\"saf\"],\"application/vnd.yamaha.smaf-phrase\":[\"spf\"],\"application/vnd.yellowriver-custom-menu\":[\"cmp\"],\"application/vnd.zul\":[\"zir\",\"zirz\"],\"application/vnd.zzazz.deck+xml\":[\"zaz\"],\"application/x-7z-compressed\":[\"7z\"],\"application/x-abiword\":[\"abw\"],\"application/x-ace-compressed\":[\"ace\"],\"application/x-apple-diskimage\":[\"*dmg\"],\"application/x-arj\":[\"arj\"],\"application/x-authorware-bin\":[\"aab\",\"x32\",\"u32\",\"vox\"],\"application/x-authorware-map\":[\"aam\"],\"application/x-authorware-seg\":[\"aas\"],\"application/x-bcpio\":[\"bcpio\"],\"application/x-bdoc\":[\"*bdoc\"],\"application/x-bittorrent\":[\"torrent\"],\"application/x-blorb\":[\"blb\",\"blorb\"],\"application/x-bzip\":[\"bz\"],\"application/x-bzip2\":[\"bz2\",\"boz\"],\"application/x-cbr\":[\"cbr\",\"cba\",\"cbt\",\"cbz\",\"cb7\"],\"application/x-cdlink\":[\"vcd\"],\"application/x-cfs-compressed\":[\"cfs\"],\"application/x-chat\":[\"chat\"],\"application/x-chess-pgn\":[\"pgn\"],\"application/x-chrome-extension\":[\"crx\"],\"application/x-cocoa\":[\"cco\"],\"application/x-conference\":[\"nsc\"],\"application/x-cpio\":[\"cpio\"],\"application/x-csh\":[\"csh\"],\"application/x-debian-package\":[\"*deb\",\"udeb\"],\"application/x-dgc-compressed\":[\"dgc\"],\"application/x-director\":[\"dir\",\"dcr\",\"dxr\",\"cst\",\"cct\",\"cxt\",\"w3d\",\"fgd\",\"swa\"],\"application/x-doom\":[\"wad\"],\"application/x-dtbncx+xml\":[\"ncx\"],\"application/x-dtbook+xml\":[\"dtb\"],\"application/x-dtbresource+xml\":[\"res\"],\"application/x-dvi\":[\"dvi\"],\"application/x-envoy\":[\"evy\"],\"application/x-eva\":[\"eva\"],\"application/x-font-bdf\":[\"bdf\"],\"application/x-font-ghostscript\":[\"gsf\"],\"application/x-font-linux-psf\":[\"psf\"],\"application/x-font-pcf\":[\"pcf\"],\"application/x-font-snf\":[\"snf\"],\"application/x-font-type1\":[\"pfa\",\"pfb\",\"pfm\",\"afm\"],\"application/x-freearc\":[\"arc\"],\"application/x-futuresplash\":[\"spl\"],\"application/x-gca-compressed\":[\"gca\"],\"application/x-glulx\":[\"ulx\"],\"application/x-gnumeric\":[\"gnumeric\"],\"application/x-gramps-xml\":[\"gramps\"],\"application/x-gtar\":[\"gtar\"],\"application/x-hdf\":[\"hdf\"],\"application/x-httpd-php\":[\"php\"],\"application/x-install-instructions\":[\"install\"],\"application/x-iso9660-image\":[\"*iso\"],\"application/x-iwork-keynote-sffkey\":[\"*key\"],\"application/x-iwork-numbers-sffnumbers\":[\"*numbers\"],\"application/x-iwork-pages-sffpages\":[\"*pages\"],\"application/x-java-archive-diff\":[\"jardiff\"],\"application/x-java-jnlp-file\":[\"jnlp\"],\"application/x-keepass2\":[\"kdbx\"],\"application/x-latex\":[\"latex\"],\"application/x-lua-bytecode\":[\"luac\"],\"application/x-lzh-compressed\":[\"lzh\",\"lha\"],\"application/x-makeself\":[\"run\"],\"application/x-mie\":[\"mie\"],\"application/x-mobipocket-ebook\":[\"prc\",\"mobi\"],\"application/x-ms-application\":[\"application\"],\"application/x-ms-shortcut\":[\"lnk\"],\"application/x-ms-wmd\":[\"wmd\"],\"application/x-ms-wmz\":[\"wmz\"],\"application/x-ms-xbap\":[\"xbap\"],\"application/x-msaccess\":[\"mdb\"],\"application/x-msbinder\":[\"obd\"],\"application/x-mscardfile\":[\"crd\"],\"application/x-msclip\":[\"clp\"],\"application/x-msdos-program\":[\"*exe\"],\"application/x-msdownload\":[\"*exe\",\"*dll\",\"com\",\"bat\",\"*msi\"],\"application/x-msmediaview\":[\"mvb\",\"m13\",\"m14\"],\"application/x-msmetafile\":[\"*wmf\",\"*wmz\",\"*emf\",\"emz\"],\"application/x-msmoney\":[\"mny\"],\"application/x-mspublisher\":[\"pub\"],\"application/x-msschedule\":[\"scd\"],\"application/x-msterminal\":[\"trm\"],\"application/x-mswrite\":[\"wri\"],\"application/x-netcdf\":[\"nc\",\"cdf\"],\"application/x-ns-proxy-autoconfig\":[\"pac\"],\"application/x-nzb\":[\"nzb\"],\"application/x-perl\":[\"pl\",\"pm\"],\"application/x-pilot\":[\"*prc\",\"*pdb\"],\"application/x-pkcs12\":[\"p12\",\"pfx\"],\"application/x-pkcs7-certificates\":[\"p7b\",\"spc\"],\"application/x-pkcs7-certreqresp\":[\"p7r\"],\"application/x-rar-compressed\":[\"*rar\"],\"application/x-redhat-package-manager\":[\"rpm\"],\"application/x-research-info-systems\":[\"ris\"],\"application/x-sea\":[\"sea\"],\"application/x-sh\":[\"sh\"],\"application/x-shar\":[\"shar\"],\"application/x-shockwave-flash\":[\"swf\"],\"application/x-silverlight-app\":[\"xap\"],\"application/x-sql\":[\"sql\"],\"application/x-stuffit\":[\"sit\"],\"application/x-stuffitx\":[\"sitx\"],\"application/x-subrip\":[\"srt\"],\"application/x-sv4cpio\":[\"sv4cpio\"],\"application/x-sv4crc\":[\"sv4crc\"],\"application/x-t3vm-image\":[\"t3\"],\"application/x-tads\":[\"gam\"],\"application/x-tar\":[\"tar\"],\"application/x-tcl\":[\"tcl\",\"tk\"],\"application/x-tex\":[\"tex\"],\"application/x-tex-tfm\":[\"tfm\"],\"application/x-texinfo\":[\"texinfo\",\"texi\"],\"application/x-tgif\":[\"*obj\"],\"application/x-ustar\":[\"ustar\"],\"application/x-virtualbox-hdd\":[\"hdd\"],\"application/x-virtualbox-ova\":[\"ova\"],\"application/x-virtualbox-ovf\":[\"ovf\"],\"application/x-virtualbox-vbox\":[\"vbox\"],\"application/x-virtualbox-vbox-extpack\":[\"vbox-extpack\"],\"application/x-virtualbox-vdi\":[\"vdi\"],\"application/x-virtualbox-vhd\":[\"vhd\"],\"application/x-virtualbox-vmdk\":[\"vmdk\"],\"application/x-wais-source\":[\"src\"],\"application/x-web-app-manifest+json\":[\"webapp\"],\"application/x-x509-ca-cert\":[\"der\",\"crt\",\"pem\"],\"application/x-xfig\":[\"fig\"],\"application/x-xliff+xml\":[\"*xlf\"],\"application/x-xpinstall\":[\"xpi\"],\"application/x-xz\":[\"xz\"],\"application/x-zmachine\":[\"z1\",\"z2\",\"z3\",\"z4\",\"z5\",\"z6\",\"z7\",\"z8\"],\"audio/vnd.dece.audio\":[\"uva\",\"uvva\"],\"audio/vnd.digital-winds\":[\"eol\"],\"audio/vnd.dra\":[\"dra\"],\"audio/vnd.dts\":[\"dts\"],\"audio/vnd.dts.hd\":[\"dtshd\"],\"audio/vnd.lucent.voice\":[\"lvp\"],\"audio/vnd.ms-playready.media.pya\":[\"pya\"],\"audio/vnd.nuera.ecelp4800\":[\"ecelp4800\"],\"audio/vnd.nuera.ecelp7470\":[\"ecelp7470\"],\"audio/vnd.nuera.ecelp9600\":[\"ecelp9600\"],\"audio/vnd.rip\":[\"rip\"],\"audio/x-aac\":[\"aac\"],\"audio/x-aiff\":[\"aif\",\"aiff\",\"aifc\"],\"audio/x-caf\":[\"caf\"],\"audio/x-flac\":[\"flac\"],\"audio/x-m4a\":[\"*m4a\"],\"audio/x-matroska\":[\"mka\"],\"audio/x-mpegurl\":[\"m3u\"],\"audio/x-ms-wax\":[\"wax\"],\"audio/x-ms-wma\":[\"wma\"],\"audio/x-pn-realaudio\":[\"ram\",\"ra\"],\"audio/x-pn-realaudio-plugin\":[\"rmp\"],\"audio/x-realaudio\":[\"*ra\"],\"audio/x-wav\":[\"*wav\"],\"chemical/x-cdx\":[\"cdx\"],\"chemical/x-cif\":[\"cif\"],\"chemical/x-cmdf\":[\"cmdf\"],\"chemical/x-cml\":[\"cml\"],\"chemical/x-csml\":[\"csml\"],\"chemical/x-xyz\":[\"xyz\"],\"image/prs.btif\":[\"btif\"],\"image/prs.pti\":[\"pti\"],\"image/vnd.adobe.photoshop\":[\"psd\"],\"image/vnd.airzip.accelerator.azv\":[\"azv\"],\"image/vnd.dece.graphic\":[\"uvi\",\"uvvi\",\"uvg\",\"uvvg\"],\"image/vnd.djvu\":[\"djvu\",\"djv\"],\"image/vnd.dvb.subtitle\":[\"*sub\"],\"image/vnd.dwg\":[\"dwg\"],\"image/vnd.dxf\":[\"dxf\"],\"image/vnd.fastbidsheet\":[\"fbs\"],\"image/vnd.fpx\":[\"fpx\"],\"image/vnd.fst\":[\"fst\"],\"image/vnd.fujixerox.edmics-mmr\":[\"mmr\"],\"image/vnd.fujixerox.edmics-rlc\":[\"rlc\"],\"image/vnd.microsoft.icon\":[\"ico\"],\"image/vnd.ms-dds\":[\"dds\"],\"image/vnd.ms-modi\":[\"mdi\"],\"image/vnd.ms-photo\":[\"wdp\"],\"image/vnd.net-fpx\":[\"npx\"],\"image/vnd.pco.b16\":[\"b16\"],\"image/vnd.tencent.tap\":[\"tap\"],\"image/vnd.valve.source.texture\":[\"vtf\"],\"image/vnd.wap.wbmp\":[\"wbmp\"],\"image/vnd.xiff\":[\"xif\"],\"image/vnd.zbrush.pcx\":[\"pcx\"],\"image/x-3ds\":[\"3ds\"],\"image/x-cmu-raster\":[\"ras\"],\"image/x-cmx\":[\"cmx\"],\"image/x-freehand\":[\"fh\",\"fhc\",\"fh4\",\"fh5\",\"fh7\"],\"image/x-icon\":[\"*ico\"],\"image/x-jng\":[\"jng\"],\"image/x-mrsid-image\":[\"sid\"],\"image/x-ms-bmp\":[\"*bmp\"],\"image/x-pcx\":[\"*pcx\"],\"image/x-pict\":[\"pic\",\"pct\"],\"image/x-portable-anymap\":[\"pnm\"],\"image/x-portable-bitmap\":[\"pbm\"],\"image/x-portable-graymap\":[\"pgm\"],\"image/x-portable-pixmap\":[\"ppm\"],\"image/x-rgb\":[\"rgb\"],\"image/x-tga\":[\"tga\"],\"image/x-xbitmap\":[\"xbm\"],\"image/x-xpixmap\":[\"xpm\"],\"image/x-xwindowdump\":[\"xwd\"],\"message/vnd.wfa.wsc\":[\"wsc\"],\"model/vnd.collada+xml\":[\"dae\"],\"model/vnd.dwf\":[\"dwf\"],\"model/vnd.gdl\":[\"gdl\"],\"model/vnd.gtw\":[\"gtw\"],\"model/vnd.mts\":[\"mts\"],\"model/vnd.opengex\":[\"ogex\"],\"model/vnd.parasolid.transmit.binary\":[\"x_b\"],\"model/vnd.parasolid.transmit.text\":[\"x_t\"],\"model/vnd.sap.vds\":[\"vds\"],\"model/vnd.usdz+zip\":[\"usdz\"],\"model/vnd.valve.source.compiled-map\":[\"bsp\"],\"model/vnd.vtu\":[\"vtu\"],\"text/prs.lines.tag\":[\"dsc\"],\"text/vnd.curl\":[\"curl\"],\"text/vnd.curl.dcurl\":[\"dcurl\"],\"text/vnd.curl.mcurl\":[\"mcurl\"],\"text/vnd.curl.scurl\":[\"scurl\"],\"text/vnd.dvb.subtitle\":[\"sub\"],\"text/vnd.fly\":[\"fly\"],\"text/vnd.fmi.flexstor\":[\"flx\"],\"text/vnd.graphviz\":[\"gv\"],\"text/vnd.in3d.3dml\":[\"3dml\"],\"text/vnd.in3d.spot\":[\"spot\"],\"text/vnd.sun.j2me.app-descriptor\":[\"jad\"],\"text/vnd.wap.wml\":[\"wml\"],\"text/vnd.wap.wmlscript\":[\"wmls\"],\"text/x-asm\":[\"s\",\"asm\"],\"text/x-c\":[\"c\",\"cc\",\"cxx\",\"cpp\",\"h\",\"hh\",\"dic\"],\"text/x-component\":[\"htc\"],\"text/x-fortran\":[\"f\",\"for\",\"f77\",\"f90\"],\"text/x-handlebars-template\":[\"hbs\"],\"text/x-java-source\":[\"java\"],\"text/x-lua\":[\"lua\"],\"text/x-markdown\":[\"mkd\"],\"text/x-nfo\":[\"nfo\"],\"text/x-opml\":[\"opml\"],\"text/x-org\":[\"*org\"],\"text/x-pascal\":[\"p\",\"pas\"],\"text/x-processing\":[\"pde\"],\"text/x-sass\":[\"sass\"],\"text/x-scss\":[\"scss\"],\"text/x-setext\":[\"etx\"],\"text/x-sfv\":[\"sfv\"],\"text/x-suse-ymp\":[\"ymp\"],\"text/x-uuencode\":[\"uu\"],\"text/x-vcalendar\":[\"vcs\"],\"text/x-vcard\":[\"vcf\"],\"video/vnd.dece.hd\":[\"uvh\",\"uvvh\"],\"video/vnd.dece.mobile\":[\"uvm\",\"uvvm\"],\"video/vnd.dece.pd\":[\"uvp\",\"uvvp\"],\"video/vnd.dece.sd\":[\"uvs\",\"uvvs\"],\"video/vnd.dece.video\":[\"uvv\",\"uvvv\"],\"video/vnd.dvb.file\":[\"dvb\"],\"video/vnd.fvt\":[\"fvt\"],\"video/vnd.mpegurl\":[\"mxu\",\"m4u\"],\"video/vnd.ms-playready.media.pyv\":[\"pyv\"],\"video/vnd.uvvu.mp4\":[\"uvu\",\"uvvu\"],\"video/vnd.vivo\":[\"viv\"],\"video/x-f4v\":[\"f4v\"],\"video/x-fli\":[\"fli\"],\"video/x-flv\":[\"flv\"],\"video/x-m4v\":[\"m4v\"],\"video/x-matroska\":[\"mkv\",\"mk3d\",\"mks\"],\"video/x-mng\":[\"mng\"],\"video/x-ms-asf\":[\"asf\",\"asx\"],\"video/x-ms-vob\":[\"vob\"],\"video/x-ms-wm\":[\"wm\"],\"video/x-ms-wmv\":[\"wmv\"],\"video/x-ms-wmx\":[\"wmx\"],\"video/x-ms-wvx\":[\"wvx\"],\"video/x-msvideo\":[\"avi\"],\"video/x-sgi-movie\":[\"movie\"],\"video/x-smv\":[\"smv\"],\"x-conference/x-cooltalk\":[\"ice\"]}});var Tt=F((sn,Mt)=>{\"use strict\";var Mi=zt();Mt.exports=new Mi(Et(),Dt())});var At,qt,Le,Ti,Y,ne,Ai,Fe=ce(()=>{At=se(xe()),qt=se(Tt()),Le=se(pe()),Ti=new Le.Token(\"@jupyterlite/contents:IContents\");(function(n){n.JSON=\"application/json\",n.PLAIN_TEXT=\"text/plain\",n.OCTET_STREAM=\"octet/stream\"})(Y||(Y={}));(function(n){let e=JSON.parse(At.PageConfig.getOption(\"fileTypes\")||\"{}\");function t(a,o=null){a=a.toLowerCase();for(let r of Object.values(e))for(let s of r.extensions||[])if(s===a&&r.mimeTypes&&r.mimeTypes.length)return r.mimeTypes[0];return qt.default.getType(a)||o||Y.OCTET_STREAM}n.getType=t;function i(a,o){a=a.toLowerCase();for(let r of Object.values(e))if(r.fileFormat===o){for(let s of r.extensions||[])if(s===a)return!0}return!1}n.hasFormat=i})(ne||(ne={}));Ai=new Le.Token(\"@jupyterlite/contents:IBroadcastChannelWrapper\")});var oe,X,Lt,Ut,Nt,Be,Se,Ft=ce(()=>{oe=se(xe()),X=se(xe());Fe();Lt=se(pe()),Ut=\"JupyterLite Storage\",Nt=5,Be=class{constructor(e){this.reduceBytesToString=(t,i)=>t+String.fromCharCode(i),this._serverContents=new Map,this._storageName=Ut,this._storageDrivers=null,this._localforage=e.localforage,this._storageName=e.storageName||Ut,this._storageDrivers=e.storageDrivers||null,this._ready=new Lt.PromiseDelegate}async initialize(){await this.initStorage(),this._ready.resolve(void 0)}async initStorage(){this._storage=this.createDefaultStorage(),this._counters=this.createDefaultCounters(),this._checkpoints=this.createDefaultCheckpoints()}get ready(){return this._ready.promise}get storage(){return this.ready.then(()=>this._storage)}get counters(){return this.ready.then(()=>this._counters)}get checkpoints(){return this.ready.then(()=>this._checkpoints)}get defaultStorageOptions(){let e=this._storageDrivers&&this._storageDrivers.length?this._storageDrivers:null;return{version:1,name:this._storageName,...e?{driver:e}:{}}}createDefaultStorage(){return this._localforage.createInstance({description:\"Offline Storage for Notebooks and Files\",storeName:\"files\",...this.defaultStorageOptions})}createDefaultCounters(){return this._localforage.createInstance({description:\"Store the current file suffix counters\",storeName:\"counters\",...this.defaultStorageOptions})}createDefaultCheckpoints(){return this._localforage.createInstance({description:\"Offline Storage for Checkpoints\",storeName:\"checkpoints\",...this.defaultStorageOptions})}async newUntitled(e){var t,i,a;let o=(t=e==null?void 0:e.path)!==null&&t!==void 0?t:\"\",r=(i=e==null?void 0:e.type)!==null&&i!==void 0?i:\"notebook\",s=new Date().toISOString(),l=X.PathExt.dirname(o),m=X.PathExt.basename(o),h=X.PathExt.extname(o),c=await this.get(l),b=\"\";o&&!h&&c?(l=`${o}/`,b=\"\"):l&&m?(l=`${l}/`,b=m):(l=\"\",b=o);let j;switch(r){case\"directory\":{b=`Untitled Folder${await this._incrementCounter(\"directory\")||\"\"}`,j={name:b,path:`${l}${b}`,last_modified:s,created:s,format:\"json\",mimetype:\"\",content:null,size:0,writable:!0,type:\"directory\"};break}case\"notebook\":{let q=await this._incrementCounter(\"notebook\");b=b||`Untitled${q||\"\"}.ipynb`,j={name:b,path:`${l}${b}`,last_modified:s,created:s,format:\"json\",mimetype:Y.JSON,content:Se.EMPTY_NB,size:JSON.stringify(Se.EMPTY_NB).length,writable:!0,type:\"notebook\"};break}default:{let q=(a=e==null?void 0:e.ext)!==null&&a!==void 0?a:\".txt\",O=await this._incrementCounter(\"file\"),S=ne.getType(q)||Y.OCTET_STREAM,R;ne.hasFormat(q,\"text\")||S.indexOf(\"text\")!==-1?R=\"text\":q.indexOf(\"json\")!==-1||q.indexOf(\"ipynb\")!==-1?R=\"json\":R=\"base64\",b=b||`untitled${O||\"\"}${q}`,j={name:b,path:`${l}${b}`,last_modified:s,created:s,format:R,mimetype:S,content:\"\",size:0,writable:!0,type:\"file\"};break}}let C=j.path;return await(await this.storage).setItem(C,j),j}async copy(e,t){let i=X.PathExt.basename(e);for(t=t===\"\"?\"\":`${t.slice(1)}/`;await this.get(`${t}${i}`,{content:!0});){let r=X.PathExt.extname(i);i=`${i.replace(r,\"\")} (copy)${r}`}let a=`${t}${i}`,o=await this.get(e,{content:!0});if(!o)throw Error(`Could not find file with path ${e}`);return o={...o,name:i,path:a},await(await this.storage).setItem(a,o),o}async get(e,t){if(e=decodeURIComponent(e.replace(/^\\//,\"\")),e===\"\")return await this._getFolder(e);let i=await this.storage,a=await i.getItem(e),o=await this._getServerContents(e,t),r=a||o;if(!r)return null;if(!(t!=null&&t.content))return{size:0,...r,content:null};if(r.type===\"directory\"){let s=new Map;await i.iterate((h,c)=>{c===`${e}/${h.name}`&&s.set(h.name,h)});let l=o?o.content:Array.from((await this._getServerDirectory(e)).values());for(let h of l)s.has(h.name)||s.set(h.name,h);let m=[...s.values()];return{name:X.PathExt.basename(e),path:e,last_modified:r.last_modified,created:r.created,format:\"json\",mimetype:Y.JSON,content:m,size:0,writable:!0,type:\"directory\"}}return r}async rename(e,t){let i=decodeURIComponent(e),a=await this.get(i,{content:!0});if(!a)throw Error(`Could not find file with path ${i}`);let o=new Date().toISOString(),r=X.PathExt.basename(t),s={...a,name:r,path:t,last_modified:o},l=await this.storage;if(await l.setItem(t,s),await l.removeItem(i),await(await this.checkpoints).removeItem(i),a.type===\"directory\"){let m;for(m of a.content)await this.rename(oe.URLExt.join(e,m.name),oe.URLExt.join(t,m.name))}return s}async save(e,t={}){var i;e=decodeURIComponent(e);let a=X.PathExt.extname((i=t.name)!==null&&i!==void 0?i:\"\"),o=t.chunk,r=o?o>1||o===-1:!1,s=await this.get(e,{content:r});if(s||(s=await this.newUntitled({path:e,ext:a,type:\"file\"})),!s)return null;let l=s.content,m=new Date().toISOString();if(s={...s,...t,last_modified:m},t.content&&t.format===\"base64\"){let h=o?o===-1:!0;if(a===\".ipynb\"){let c=this._handleChunk(t.content,l,r);s={...s,content:h?JSON.parse(c):c,format:\"json\",type:\"notebook\",size:c.length}}else if(ne.hasFormat(a,\"json\")){let c=this._handleChunk(t.content,l,r);s={...s,content:h?JSON.parse(c):c,format:\"json\",type:\"file\",size:c.length}}else if(ne.hasFormat(a,\"text\")){let c=this._handleChunk(t.content,l,r);s={...s,content:c,format:\"text\",type:\"file\",size:c.length}}else{let c=t.content;s={...s,content:c,size:atob(c).length}}}return await(await this.storage).setItem(e,s),s}async delete(e){e=decodeURIComponent(e);let t=`${e}/`,i=(await(await this.storage).keys()).filter(a=>a===e||a.startsWith(t));await Promise.all(i.map(this.forgetPath,this))}async forgetPath(e){await Promise.all([(await this.storage).removeItem(e),(await this.checkpoints).removeItem(e)])}async createCheckpoint(e){var t;let i=await this.checkpoints;e=decodeURIComponent(e);let a=await this.get(e,{content:!0});if(!a)throw Error(`Could not find file with path ${e}`);let o=((t=await i.getItem(e))!==null&&t!==void 0?t:[]).filter(Boolean);return o.push(a),o.length>Nt&&o.splice(0,o.length-Nt),await i.setItem(e,o),{id:`${o.length-1}`,last_modified:a.last_modified}}async listCheckpoints(e){return(await(await this.checkpoints).getItem(e)||[]).filter(Boolean).map(this.normalizeCheckpoint,this)}normalizeCheckpoint(e,t){return{id:t.toString(),last_modified:e.last_modified}}async restoreCheckpoint(e,t){e=decodeURIComponent(e);let i=await(await this.checkpoints).getItem(e)||[],a=parseInt(t),o=i[a];await(await this.storage).setItem(e,o)}async deleteCheckpoint(e,t){e=decodeURIComponent(e);let i=await(await this.checkpoints).getItem(e)||[],a=parseInt(t);i.splice(a,1),await(await this.checkpoints).setItem(e,i)}_handleChunk(e,t,i){let a=decodeURIComponent(escape(atob(e)));return i?t+a:a}async _getFolder(e){let t=new Map;await(await this.storage).iterate((a,o)=>{o.includes(\"/\")||t.set(a.path,a)});for(let a of(await this._getServerDirectory(e)).values())t.has(a.path)||t.set(a.path,a);return e&&t.size===0?null:{name:\"\",path:e,last_modified:new Date(0).toISOString(),created:new Date(0).toISOString(),format:\"json\",mimetype:Y.JSON,content:Array.from(t.values()),size:0,writable:!0,type:\"directory\"}}async _getServerContents(e,t){let i=X.PathExt.basename(e),o=(await this._getServerDirectory(oe.URLExt.join(e,\"..\"))).get(i);if(!o)return null;if(o=o||{name:i,path:e,last_modified:new Date(0).toISOString(),created:new Date(0).toISOString(),format:\"text\",mimetype:Y.PLAIN_TEXT,type:\"file\",writable:!0,size:0,content:\"\"},t!=null&&t.content)if(o.type===\"directory\"){let r=await this._getServerDirectory(e);o={...o,content:Array.from(r.values())}}else{let r=oe.URLExt.join(oe.PageConfig.getBaseUrl(),\"files\",e),s=await fetch(r);if(!s.ok)return null;let l=o.mimetype||s.headers.get(\"Content-Type\"),m=X.PathExt.extname(i);if(o.type===\"notebook\"||ne.hasFormat(m,\"json\")||(l==null?void 0:l.indexOf(\"json\"))!==-1||e.match(/\\.(ipynb|[^/]*json[^/]*)$/)){let h=await s.text();o={...o,content:JSON.parse(h),format:\"json\",mimetype:o.mimetype||Y.JSON,size:h.length}}else if(ne.hasFormat(m,\"text\")||l.indexOf(\"text\")!==-1){let h=await s.text();o={...o,content:h,format:\"text\",mimetype:l||Y.PLAIN_TEXT,size:h.length}}else{let h=await s.arrayBuffer(),c=new Uint8Array(h);o={...o,content:btoa(c.reduce(this.reduceBytesToString,\"\")),format:\"base64\",mimetype:l||Y.OCTET_STREAM,size:c.length}}}return o}async _getServerDirectory(e){let t=this._serverContents.get(e)||new Map;if(!this._serverContents.has(e)){let i=oe.URLExt.join(oe.PageConfig.getBaseUrl(),\"api/contents\",e,\"all.json\");try{let a=await fetch(i),o=JSON.parse(await a.text());for(let r of o.content)t.set(r.name,r)}catch(a){console.warn(`don't worry, about ${a}... nothing's broken. If there had been a\n file at ${i}, you might see some more files.`)}this._serverContents.set(e,t)}return t}async _incrementCounter(e){var t;let i=await this.counters,o=((t=await i.getItem(e))!==null&&t!==void 0?t:-1)+1;return await i.setItem(e,o),o}};(function(n){n.EMPTY_NB={metadata:{orig_nbformat:4},nbformat_minor:4,nbformat:4,cells:[]}})(Se||(Se={}))});var ze,Bt,qi,Ui,$t=ce(()=>{ze=16895,Bt=33206,qi=1,Ui=2});var Wt,He,De,Ni,Li,Ht,Re,Ee,Ie,$e,We=ce(()=>{Wt=\":\",He=\"/api/drive.v1\",De=4096,Ni=new TextEncoder,Li=new TextDecoder(\"utf-8\"),Ht={0:!1,1:!0,2:!0,64:!0,65:!0,66:!0,129:!0,193:!0,514:!0,577:!0,578:!0,705:!0,706:!0,1024:!0,1025:!0,1026:!0,1089:!0,1090:!0,1153:!0,1154:!0,1217:!0,1218:!0,4096:!0,4098:!0},Re=class{constructor(e){this.fs=e}open(e){let t=this.fs.realPath(e.node);this.fs.FS.isFile(e.node.mode)&&(e.file=this.fs.API.get(t))}close(e){if(!this.fs.FS.isFile(e.node.mode)||!e.file)return;let t=this.fs.realPath(e.node),i=e.flags,a=typeof i==\"string\"?parseInt(i,10):i;a&=8191;let o=!0;a in Ht&&(o=Ht[a]),o&&this.fs.API.put(t,e.file),e.file=void 0}read(e,t,i,a,o){if(a<=0||e.file===void 0||o>=(e.file.data.length||0))return 0;let r=Math.min(e.file.data.length-o,a);return t.set(e.file.data.subarray(o,o+r),i),r}write(e,t,i,a,o){var r;if(a<=0||e.file===void 0)return 0;if(e.node.timestamp=Date.now(),o+a>(((r=e.file)===null||r===void 0?void 0:r.data.length)||0)){let s=e.file.data?e.file.data:new Uint8Array;e.file.data=new Uint8Array(o+a),e.file.data.set(s)}return e.file.data.set(t.subarray(i,i+a),o),a}llseek(e,t,i){let a=t;if(i===1)a+=e.position;else if(i===2&&this.fs.FS.isFile(e.node.mode))if(e.file!==void 0)a+=e.file.data.length;else throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES.EPERM);if(a<0)throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES.EINVAL);return a}},Ee=class{constructor(e){this.fs=e}getattr(e){return{...this.fs.API.getattr(this.fs.realPath(e)),mode:e.mode,ino:e.id}}setattr(e,t){for(let[i,a]of Object.entries(t))switch(i){case\"mode\":e.mode=a;break;case\"timestamp\":e.timestamp=a;break;default:console.warn(\"setattr\",i,\"of\",a,\"on\",e,\"not yet implemented\");break}}lookup(e,t){let i=this.fs.PATH.join2(this.fs.realPath(e),t),a=this.fs.API.lookup(i);if(!a.ok)throw this.fs.FS.genericErrors[this.fs.ERRNO_CODES.ENOENT];return this.fs.createNode(e,t,a.mode,0)}mknod(e,t,i,a){let o=this.fs.PATH.join2(this.fs.realPath(e),t);return this.fs.API.mknod(o,i),this.fs.createNode(e,t,i,a)}rename(e,t,i){this.fs.API.rename(e.parent?this.fs.PATH.join2(this.fs.realPath(e.parent),e.name):e.name,this.fs.PATH.join2(this.fs.realPath(t),i)),e.name=i,e.parent=t}unlink(e,t){this.fs.API.rmdir(this.fs.PATH.join2(this.fs.realPath(e),t))}rmdir(e,t){this.fs.API.rmdir(this.fs.PATH.join2(this.fs.realPath(e),t))}readdir(e){return this.fs.API.readdir(this.fs.realPath(e))}symlink(e,t,i){throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES.EPERM)}readlink(e){throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES.EPERM)}},Ie=class{constructor(e,t,i,a,o){this._baseUrl=e,this._driveName=t,this._mountpoint=i,this.FS=a,this.ERRNO_CODES=o}request(e){let t=new XMLHttpRequest;t.open(\"POST\",encodeURI(this.endpoint),!1);try{t.send(JSON.stringify(e))}catch(i){console.error(i)}if(t.status>=400)throw new this.FS.ErrnoError(this.ERRNO_CODES.EINVAL);return JSON.parse(t.responseText)}lookup(e){return this.request({method:\"lookup\",path:this.normalizePath(e)})}getmode(e){return Number.parseInt(this.request({method:\"getmode\",path:this.normalizePath(e)}))}mknod(e,t){return this.request({method:\"mknod\",path:this.normalizePath(e),data:{mode:t}})}rename(e,t){return this.request({method:\"rename\",path:this.normalizePath(e),data:{newPath:this.normalizePath(t)}})}readdir(e){let t=this.request({method:\"readdir\",path:this.normalizePath(e)});return t.push(\".\"),t.push(\"..\"),t}rmdir(e){return this.request({method:\"rmdir\",path:this.normalizePath(e)})}get(e){let t=this.request({method:\"get\",path:this.normalizePath(e)}),i=t.content,a=t.format;switch(a){case\"json\":case\"text\":return{data:Ni.encode(i),format:a};case\"base64\":{let o=atob(i),r=o.length,s=new Uint8Array(r);for(let l=0;l{Ke=se(xe());We();Je=class{constructor(e){this.isDisposed=!1,this._onMessage=async t=>{if(!this._channel)return;let{_contents:i}=this,a=t.data,o=a==null?void 0:a.path;if((a==null?void 0:a.receiver)!==\"broadcast.ts\")return;let s=null,l;switch(a==null?void 0:a.method){case\"readdir\":l=await i.get(o,{content:!0}),s=[],l.type===\"directory\"&&l.content&&(s=l.content.map(m=>m.name));break;case\"rmdir\":await i.delete(o);break;case\"rename\":await i.rename(o,a.data.newPath);break;case\"getmode\":l=await i.get(o),l.type===\"directory\"?s=16895:s=33206;break;case\"lookup\":try{l=await i.get(o),s={ok:!0,mode:l.type===\"directory\"?16895:33206}}catch{s={ok:!1}}break;case\"mknod\":l=await i.newUntitled({path:Ke.PathExt.dirname(o),type:Number.parseInt(a.data.mode)===16895?\"directory\":\"file\",ext:Ke.PathExt.extname(o)}),await i.rename(l.path,o);break;case\"getattr\":{l=await i.get(o);let m=new Date(0).toISOString();s={dev:1,nlink:1,uid:0,gid:0,rdev:0,size:l.size||0,blksize:De,blocks:Math.ceil(l.size||0/De),atime:l.last_modified||m,mtime:l.last_modified||m,ctime:l.created||m,timestamp:0};break}case\"get\":if(l=await i.get(o,{content:!0}),l.type===\"directory\")break;s={content:l.format===\"json\"?JSON.stringify(l.content):l.content,format:l.format};break;case\"put\":await i.save(o,{content:a.data.format===\"json\"?JSON.parse(a.data.data):a.data.data,type:\"file\",format:a.data.format});break;default:s=null;break}this._channel.postMessage(s)},this._channel=null,this._enabled=!1,this._contents=e.contents}get enabled(){return this._enabled}enable(){if(this._channel){console.warn(\"BroadcastChannel already created and enabled\");return}this._channel=new BroadcastChannel(He),this._channel.addEventListener(\"message\",this._onMessage),this._enabled=!0}disable(){this._channel&&(this._channel.removeEventListener(\"message\",this._onMessage),this._channel=null),this._enabled=!1}dispose(){this.isDisposed||(this.disable(),this.isDisposed=!0)}}});var Jt={};li(Jt,{BLOCK_SIZE:()=>De,BroadcastChannelWrapper:()=>Je,Contents:()=>Be,ContentsAPI:()=>Ie,DIR_MODE:()=>ze,DRIVE_API_PATH:()=>He,DRIVE_SEPARATOR:()=>Wt,DriveFS:()=>$e,DriveFSEmscriptenNodeOps:()=>Ee,DriveFSEmscriptenStreamOps:()=>Re,FILE:()=>ne,FILE_MODE:()=>Bt,IBroadcastChannelWrapper:()=>Ai,IContents:()=>Ti,MIME:()=>Y,SEEK_CUR:()=>qi,SEEK_END:()=>Ui});var Vt=ce(()=>{Ft();We();Fe();Kt();$t()});var Yt=class{constructor(){this._options=null;this._initializer=null;this._pyodide=null;this._localPath=\"\";this._driveName=\"\";this._driveFS=null;this._initialized=new Promise((e,t)=>{this._initializer={resolve:e,reject:t}})}async initialize(e){var t;if(this._options=e,e.location.includes(\":\")){let i=e.location.split(\":\");this._driveName=i[0],this._localPath=i[1]}else this._driveName=\"\",this._localPath=e.location;await this.initRuntime(e),await this.initFilesystem(e),await this.initPackageManager(e),await this.initKernel(e),await this.initGlobals(e),(t=this._initializer)==null||t.resolve()}async initRuntime(e){let{pyodideUrl:t,indexUrl:i}=e,a;t.endsWith(\".mjs\")?a=(await import(t)).loadPyodide:(importScripts(t),a=self.loadPyodide),this._pyodide=await a({indexURL:i})}async initPackageManager(e){if(!this._options)throw new Error(\"Uninitialized\");let{pipliteWheelUrl:t,disablePyPIFallback:i,pipliteUrls:a}=this._options;await this._pyodide.loadPackage([\"micropip\"]),await this._pyodide.runPythonAsync(`\n import micropip\n await micropip.install('${t}', keep_going=True)\n import piplite.piplite\n piplite.piplite._PIPLITE_DISABLE_PYPI = ${i?\"True\":\"False\"}\n piplite.piplite._PIPLITE_URLS = ${JSON.stringify(a)}\n `)}async initKernel(e){await this._pyodide.runPythonAsync(`\n await piplite.install(['sqlite3'], keep_going=True);\n await piplite.install(['ipykernel'], keep_going=True);\n await piplite.install(['comm'], keep_going=True);\n await piplite.install(['pyodide_kernel'], keep_going=True);\n await piplite.install(['ipython'], keep_going=True);\n import pyodide_kernel\n `),e.mountDrive&&this._localPath&&await this._pyodide.runPythonAsync(`\n import os;\n os.chdir(\"${this._localPath}\");\n `)}async initGlobals(e){let{globals:t}=this._pyodide;this._kernel=t.get(\"pyodide_kernel\").kernel_instance.copy(),this._stdout_stream=t.get(\"pyodide_kernel\").stdout_stream.copy(),this._stderr_stream=t.get(\"pyodide_kernel\").stderr_stream.copy(),this._interpreter=this._kernel.interpreter.copy(),this._interpreter.send_comm=this.sendComm.bind(this)}async initFilesystem(e){if(e.mountDrive){let t=\"/drive\",{FS:i,PATH:a,ERRNO_CODES:o}=this._pyodide,{baseUrl:r}=e,{DriveFS:s}=await Promise.resolve().then(()=>(Vt(),Jt)),l=new s({FS:i,PATH:a,ERRNO_CODES:o,baseUrl:r,driveName:this._driveName,mountpoint:t});i.mkdir(t),i.mount(l,{},t),i.chdir(t),this._driveFS=l}}mapToObject(e){let t=e instanceof Array?[]:{};return e.forEach((i,a)=>{t[a]=i instanceof Map||i instanceof Array?this.mapToObject(i):i}),t}formatResult(e){if(!(e instanceof this._pyodide.ffi.PyProxy))return e;let t=e.toJs();return this.mapToObject(t)}async setup(e){await this._initialized,this._kernel._parent_header=this._pyodide.toPy(e)}async execute(e,t){await this.setup(t);let i=(c,b,j)=>{let C={execution_count:c,data:this.formatResult(b),metadata:this.formatResult(j)};postMessage({parentHeader:this.formatResult(this._kernel._parent_header).header,bundle:C,type:\"execute_result\"})},a=(c,b,j)=>{let C={ename:c,evalue:b,traceback:j};postMessage({parentHeader:this.formatResult(this._kernel._parent_header).header,bundle:C,type:\"execute_error\"})},o=c=>{let b={wait:this.formatResult(c)};postMessage({parentHeader:this.formatResult(this._kernel._parent_header).header,bundle:b,type:\"clear_output\"})},r=(c,b,j)=>{let C={data:this.formatResult(c),metadata:this.formatResult(b),transient:this.formatResult(j)};postMessage({parentHeader:this.formatResult(this._kernel._parent_header).header,bundle:C,type:\"display_data\"})},s=(c,b,j)=>{let C={data:this.formatResult(c),metadata:this.formatResult(b),transient:this.formatResult(j)};postMessage({parentHeader:this.formatResult(this._kernel._parent_header).header,bundle:C,type:\"update_display_data\"})},l=(c,b)=>{let j={name:this.formatResult(c),text:this.formatResult(b)};postMessage({parentHeader:this.formatResult(this._kernel._parent_header).header,bundle:j,type:\"stream\"})};this._stdout_stream.publish_stream_callback=l,this._stderr_stream.publish_stream_callback=l,this._interpreter.display_pub.clear_output_callback=o,this._interpreter.display_pub.display_data_callback=r,this._interpreter.display_pub.update_display_data_callback=s,this._interpreter.displayhook.publish_execution_result=i,this._interpreter.input=this.input.bind(this),this._interpreter.getpass=this.getpass.bind(this);let m=await this._kernel.run(e.code),h=this.formatResult(m);return h.status===\"error\"&&a(h.ename,h.evalue,h.traceback),h}async complete(e,t){await this.setup(t);let i=this._kernel.complete(e.code,e.cursor_pos);return this.formatResult(i)}async inspect(e,t){await this.setup(t);let i=this._kernel.inspect(e.code,e.cursor_pos,e.detail_level);return this.formatResult(i)}async isComplete(e,t){await this.setup(t);let i=this._kernel.is_complete(e.code);return this.formatResult(i)}async commInfo(e,t){await this.setup(t);let i=this._kernel.comm_info(e.target_name);return{comms:this.formatResult(i),status:\"ok\"}}async commOpen(e,t){await this.setup(t);let i=this._kernel.comm_manager.comm_open(this._pyodide.toPy(null),this._pyodide.toPy(null),this._pyodide.toPy(e));return this.formatResult(i)}async commMsg(e,t){await this.setup(t);let i=this._kernel.comm_manager.comm_msg(this._pyodide.toPy(null),this._pyodide.toPy(null),this._pyodide.toPy(e));return this.formatResult(i)}async commClose(e,t){await this.setup(t);let i=this._kernel.comm_manager.comm_close(this._pyodide.toPy(null),this._pyodide.toPy(null),this._pyodide.toPy(e));return this.formatResult(i)}async inputReply(e,t){await this.setup(t),this._resolveInputReply(e)}async sendInputRequest(e,t){let i={prompt:e,password:t};postMessage({type:\"input_request\",parentHeader:this.formatResult(this._kernel._parent_header).header,content:i})}async getpass(e){return e=typeof e==\"undefined\"?\"\":e,await this.sendInputRequest(e,!0),(await new Promise(a=>{this._resolveInputReply=a})).value}async input(e){return e=typeof e==\"undefined\"?\"\":e,await this.sendInputRequest(e,!1),(await new Promise(a=>{this._resolveInputReply=a})).value}async sendComm(e,t,i,a,o){postMessage({type:e,content:this.formatResult(t),metadata:this.formatResult(i),ident:this.formatResult(a),buffers:this.formatResult(o),parentHeader:this.formatResult(this._kernel._parent_header).header})}};export{Yt as PyodideRemoteKernel};\n//# sourceMappingURL=worker.js.map\n"],"names":["ni","Object","create","Me","defineProperty","ai","getOwnPropertyDescriptor","oi","getOwnPropertyNames","si","getPrototypeOf","ri","prototype","hasOwnProperty","ce","n","e","F","exports","li","t","get","enumerable","ci","i","a","call","se","__esModule","value","Ye","be","Ve","j","u","v","x","y","S","ArrayExt","g","w","d","p","_","f","length","Math","max","min","k","U","M","K","me","firstIndexOf","lastIndexOf","findFirstIndex","findLastIndex","findFirstValue","findLastValue","lowerBound","Z","fe","upperBound","shallowEqual","slice","start","stop","step","Error","floor","move","reverse","rotate","fill","insert","removeAt","removeFirstOf","removeLastOf","removeAllOf","removeFirstWhere","index","removeLastWhere","removeAllWhere","rangeLength","ceil","StringExt","T","A","H","L","Array","W","$","indexOf","findIndices","matchSumOfSquares","G","score","indices","matchSumOfDeltas","Q","highlight","push","cmp","chain","each","empty","enumerate","every","filter","find","findIndex","map","minmax","B","once","range","reduce","Symbol","iterator","next","done","TypeError","repeat","retro","some","stride","take","toArray","from","toObject","topologicSort","Set","Map","set","has","add","zip","define","globalThis","self","lumino_algorithm","pe","we","Ze","r","s","l","m","random","JSONExt","O","isArray","emptyObject","freeze","emptyArray","isPrimitive","isObject","deepEqual","h","R","I","b","P","deepCopy","c","C","q","Random","getRandomValues","window","crypto","msCrypto","UUID","uuid4","Uint8Array","toString","o","MimeData","constructor","this","_types","_values","types","hasData","getData","setData","clearData","splice","clear","PromiseDelegate","promise","Promise","_resolve","_reject","resolve","reject","Token","name","description","_tokenStructuralPropertyT","lumino_coreutils","Xe","ye","Ge","sender","connect","disconnect","emit","disconnectBetween","disconnectSender","disconnectReceiver","disconnectAll","getExceptionHandler","exceptionHandler","setExceptionHandler","super","arguments","_pending","async","asyncIterator","args","catch","z","E","signal","thisArg","slot","console","error","WeakMap","requestAnimationFrame","setImmediate","size","N","forEach","V","D","Signal","Stream","lumino_signaling","et","_e","ActivityMonitor","Qe","_timer","_timeout","_isDisposed","_activityStopped","_onSignalFired","timeout","activityStopped","isDisposed","dispose","clearTimeout","_sender","_args","setTimeout","Te","it","tt","nt","ue","MarkdownCodeBlocks","CODE_BLOCK_MARKER","startLine","code","endLine","MarkdownCodeBlock","isMarkdown","findMarkdownCodeBlocks","split","substring","rt","Wi","st","at","test","ot","bools","strings","unknownFn","unknown","boolean","allBools","concat","Boolean","keys","alias","string","default","Number","String","match","stopEarly","apply","di","ke","Ki","ct","ee","JSON","stringify","lt","charCodeAt","de","process","cwd","normalize","isAbsolute","join","relative","_makeLong","dirname","basename","extname","format","dir","root","base","ext","mi","parse","sep","delimiter","win32","posix","dt","Ji","pt","ut","Ae","fi","mt","decodeURIComponent","replace","ft","encodeURIComponent","isNaN","exec","hi","_t","Yi","yt","vt","je","gi","gt","xi","xt","bi","wi","Ue","qe","te","protocol","NaN","ht","hash","query","bt","location","ie","unescape","pathname","slashes","href","wt","toLowerCase","slashesCount","rest","charAt","unshift","yi","port","host","hostname","username","password","auth","origin","pop","extractProtocol","trimLeft","qs","Ne","re","ji","__importDefault","URLExt","Ci","Ce","document","createElement","getHostName","encodeParts","objectToQueryString","queryStringToObject","isLocal","kt","module","PageConfig","coreutils_1","minimist_1","url_1","getOption","configData","getBodyData","found","getElementById","textContent","argv","cli","path","fullPath","JUPYTER_CONFIG_DATA","eval","setOption","getBaseUrl","getTreeUrl","getShareUrl","getTreeShareUrl","getUrl","toShare","mode","workspace","defaultWorkspace","treePath","getWsUrl","getNBConvertURL","download","getToken","getNotebookVersion","Extension","body","dataset","warn","deferred","disabled","isDeferred","isDisabled","jt","he","PathExt","le","normalizeExtension","removeSlash","Ct","Oe","signalToPromise","Si","zi","Ot","ve","Text","jsIndexToCharIndex","charIndexToJsIndex","camelCase","toUpperCase","titleCase","Pt","ge","Time","Ei","milliseconds","formatHuman","documentElement","lang","Intl","RelativeTimeFormat","numeric","Date","getTime","now","DateTimeFormat","dateStyle","timeStyle","xe","J","Di","__createBinding","writable","configurable","ae","__exportStar","zt","nn","St","Pe","_extensions","bind","getType","getExtension","substr","RegExp","$1","Et","an","Rt","Dt","on","It","Tt","sn","Mt","Mi","At","qt","Le","Ti","Y","ne","Ai","Fe","PLAIN_TEXT","OCTET_STREAM","values","extensions","mimeTypes","hasFormat","fileFormat","oe","X","Lt","Ut","Nt","Be","Se","Ft","reduceBytesToString","fromCharCode","_serverContents","_storageName","_storageDrivers","_localforage","localforage","storageName","storageDrivers","_ready","initStorage","_storage","createDefaultStorage","_counters","createDefaultCounters","_checkpoints","createDefaultCheckpoints","ready","storage","then","counters","checkpoints","defaultStorageOptions","version","driver","createInstance","storeName","type","toISOString","_incrementCounter","last_modified","created","mimetype","content","EMPTY_NB","setItem","_getFolder","getItem","_getServerContents","iterate","_getServerDirectory","removeItem","rename","chunk","newUntitled","_handleChunk","atob","startsWith","all","forgetPath","id","normalizeCheckpoint","parseInt","escape","includes","fetch","ok","headers","text","arrayBuffer","btoa","metadata","orig_nbformat","nbformat_minor","nbformat","cells","ze","Bt","qi","Ui","$t","Wt","He","De","Ni","Li","Ht","Re","Ee","Ie","$e","We","TextEncoder","TextDecoder","fs","open","realPath","node","FS","isFile","file","API","close","flags","put","read","data","subarray","write","timestamp","llseek","position","ErrnoError","ERRNO_CODES","EPERM","EINVAL","getattr","ino","setattr","entries","lookup","PATH","join2","genericErrors","ENOENT","createNode","mknod","parent","unlink","rmdir","readdir","symlink","readlink","_baseUrl","_driveName","_mountpoint","request","XMLHttpRequest","encodeURI","endpoint","send","status","responseText","method","normalizePath","getmode","newPath","encode","decode","byteLength","atime","mtime","ctime","baseUrl","driveName","mountpoint","node_ops","stream_ops","mount","isDir","getMode","Ke","Je","Kt","_onMessage","_channel","_contents","receiver","delete","dev","nlink","uid","gid","rdev","blksize","blocks","save","postMessage","_enabled","contents","enabled","enable","BroadcastChannel","addEventListener","disable","removeEventListener","Jt","BLOCK_SIZE","BroadcastChannelWrapper","Contents","ContentsAPI","DIR_MODE","DRIVE_API_PATH","DRIVE_SEPARATOR","DriveFS","DriveFSEmscriptenNodeOps","DriveFSEmscriptenStreamOps","FILE","FILE_MODE","IBroadcastChannelWrapper","IContents","MIME","SEEK_CUR","SEEK_END","Vt","Yt","_options","_initializer","_pyodide","_localPath","_driveFS","_initialized","initRuntime","initFilesystem","initPackageManager","initKernel","initGlobals","pyodideUrl","indexUrl","endsWith","loadPyodide","importScripts","indexURL","pipliteWheelUrl","disablePyPIFallback","pipliteUrls","loadPackage","runPythonAsync","mountDrive","globals","_kernel","kernel_instance","copy","_stdout_stream","stdout_stream","_stderr_stream","stderr_stream","_interpreter","interpreter","send_comm","sendComm","mkdir","chdir","mapToObject","formatResult","ffi","PyProxy","toJs","_parent_header","toPy","setup","parentHeader","header","bundle","publish_stream_callback","display_pub","clear_output_callback","wait","display_data_callback","transient","update_display_data_callback","displayhook","publish_execution_result","execution_count","input","getpass","run","ename","evalue","traceback","complete","cursor_pos","inspect","detail_level","is_complete","comm_info","target_name","comms","comm_manager","comm_open","comm_msg","comm_close","_resolveInputReply","prompt","sendInputRequest","ident","buffers"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/3217.index.js b/book/_build/html/_static/3217.index.js new file mode 100644 index 0000000..0fa3cf0 --- /dev/null +++ b/book/_build/html/_static/3217.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[3217],{3217:(e,t,n)=>{n.r(t),n.d(t,{go:()=>s});var r,i={break:!0,case:!0,chan:!0,const:!0,continue:!0,default:!0,defer:!0,else:!0,fallthrough:!0,for:!0,func:!0,go:!0,goto:!0,if:!0,import:!0,interface:!0,map:!0,package:!0,range:!0,return:!0,select:!0,struct:!0,switch:!0,type:!0,var:!0,bool:!0,byte:!0,complex64:!0,complex128:!0,float32:!0,float64:!0,int8:!0,int16:!0,int32:!0,int64:!0,string:!0,uint8:!0,uint16:!0,uint32:!0,uint64:!0,int:!0,uint:!0,uintptr:!0,error:!0,rune:!0,any:!0,comparable:!0},a={true:!0,false:!0,iota:!0,nil:!0,append:!0,cap:!0,close:!0,complex:!0,copy:!0,delete:!0,imag:!0,len:!0,make:!0,new:!0,panic:!0,print:!0,println:!0,real:!0,recover:!0},o=/[+\-*&^%:=<>!|\/]/;function u(e,t){var n,l=e.next();if('"'==l||"'"==l||"`"==l)return t.tokenize=(n=l,function(e,t){for(var r,i=!1,a=!1;null!=(r=e.next());){if(r==n&&!i){a=!0;break}i=!i&&"`"!=n&&"\\"==r}return(a||!i&&"`"!=n)&&(t.tokenize=u),"string"}),t.tokenize(e,t);if(/[\d\.]/.test(l))return"."==l?e.match(/^[0-9]+([eE][\-+]?[0-9]+)?/):"0"==l?e.match(/^[xX][0-9a-fA-F]+/)||e.match(/^0[0-7]+/):e.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/),"number";if(/[\[\]{}\(\),;\:\.]/.test(l))return r=l,null;if("/"==l){if(e.eat("*"))return t.tokenize=c,c(e,t);if(e.eat("/"))return e.skipToEnd(),"comment"}if(o.test(l))return e.eatWhile(o),"operator";e.eatWhile(/[\w\$_\xa1-\uffff]/);var f=e.current();return i.propertyIsEnumerable(f)?("case"!=f&&"default"!=f||(r="case"),"keyword"):a.propertyIsEnumerable(f)?"atom":"variable"}function c(e,t){for(var n,r=!1;n=e.next();){if("/"==n&&r){t.tokenize=u;break}r="*"==n}return"comment"}function l(e,t,n,r,i){this.indented=e,this.column=t,this.type=n,this.align=r,this.prev=i}function f(e,t,n){return e.context=new l(e.indented,t,n,null,e.context)}const s={name:"go",startState:function(e){return{tokenize:null,context:new l(-e,0,"top",!1),indented:0,startOfLine:!0}},token:function(e,t){var n=t.context;if(e.sol()&&(null==n.align&&(n.align=!1),t.indented=e.indentation(),t.startOfLine=!0,"case"==n.type&&(n.type="}")),e.eatSpace())return null;r=null;var i=(t.tokenize||u)(e,t);return"comment"==i||(null==n.align&&(n.align=!0),"{"==r?f(t,e.column(),"}"):"["==r?f(t,e.column(),"]"):"("==r?f(t,e.column(),")"):"case"==r?n.type="case":("}"==r&&"}"==n.type||r==n.type)&&function(e){if(e.context.prev){var t=e.context.type;")"!=t&&"]"!=t&&"}"!=t||(e.indented=e.context.indented),e.context=e.context.prev}}(t),t.startOfLine=!1),i},indent:function(e,t,n){if(e.tokenize!=u&&null!=e.tokenize)return null;var r=e.context,i=t&&t.charAt(0);if("case"==r.type&&/^(?:case|default)\b/.test(t))return r.indented;var a=i==r.type;return r.align?r.column+(a?0:1):r.indented+(a?0:n.unit)},languageData:{indentOnInput:/^\s([{}]|case |default\s*:)$/,commentTokens:{line:"//",block:{open:"/*",close:"*/"}}}}}}]); +//# sourceMappingURL=3217.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/3217.index.js.map b/book/_build/html/_static/3217.index.js.map new file mode 100644 index 0000000..da03e85 --- /dev/null +++ b/book/_build/html/_static/3217.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3217.index.js","mappings":"uHAAA,IAsBIA,EAtBAC,EAAW,CACb,OAAQ,EAAM,MAAO,EAAM,MAAO,EAAM,OAAQ,EAAM,UAAW,EACjE,SAAU,EAAM,OAAQ,EAAM,MAAO,EAAM,aAAc,EAAM,KAAM,EACrE,MAAO,EAAM,IAAK,EAAM,MA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,cAAe,+BACfC,cAAe,CAACC,KAAM,KAAMC,MAAO,CAACC,KAAM,KAAMC,MAAO,Q","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/go.js"],"sourcesContent":["var keywords = {\n \"break\":true, \"case\":true, \"chan\":true, \"const\":true, \"continue\":true,\n \"default\":true, \"defer\":true, \"else\":true, \"fallthrough\":true, \"for\":true,\n \"func\":true, \"go\":true, \"goto\":true, \"if\":true, \"import\":true,\n \"interface\":true, \"map\":true, \"package\":true, \"range\":true, \"return\":true,\n \"select\":true, \"struct\":true, \"switch\":true, \"type\":true, \"var\":true,\n \"bool\":true, \"byte\":true, \"complex64\":true, \"complex128\":true,\n \"float32\":true, \"float64\":true, \"int8\":true, \"int16\":true, \"int32\":true,\n \"int64\":true, \"string\":true, \"uint8\":true, \"uint16\":true, \"uint32\":true,\n \"uint64\":true, \"int\":true, \"uint\":true, \"uintptr\":true, \"error\": true,\n \"rune\":true, \"any\":true, \"comparable\":true\n};\n\nvar atoms = {\n \"true\":true, \"false\":true, \"iota\":true, \"nil\":true, \"append\":true,\n \"cap\":true, \"close\":true, \"complex\":true, \"copy\":true, \"delete\":true, \"imag\":true,\n \"len\":true, \"make\":true, \"new\":true, \"panic\":true, \"print\":true,\n \"println\":true, \"real\":true, \"recover\":true\n};\n\nvar isOperatorChar = /[+\\-*&^%:=<>!|\\/]/;\n\nvar curPunc;\n\nfunction tokenBase(stream, state) {\n var ch = stream.next();\n if (ch == '\"' || ch == \"'\" || ch == \"`\") {\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n }\n if (/[\\d\\.]/.test(ch)) {\n if (ch == \".\") {\n stream.match(/^[0-9]+([eE][\\-+]?[0-9]+)?/);\n } else if (ch == \"0\") {\n stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/);\n } else {\n stream.match(/^[0-9]*\\.?[0-9]*([eE][\\-+]?[0-9]+)?/);\n }\n return \"number\";\n }\n if (/[\\[\\]{}\\(\\),;\\:\\.]/.test(ch)) {\n curPunc = ch;\n return null;\n }\n if (ch == \"/\") {\n if (stream.eat(\"*\")) {\n state.tokenize = tokenComment;\n return tokenComment(stream, state);\n }\n if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return \"comment\";\n }\n }\n if (isOperatorChar.test(ch)) {\n stream.eatWhile(isOperatorChar);\n return \"operator\";\n }\n stream.eatWhile(/[\\w\\$_\\xa1-\\uffff]/);\n var cur = stream.current();\n if (keywords.propertyIsEnumerable(cur)) {\n if (cur == \"case\" || cur == \"default\") curPunc = \"case\";\n return \"keyword\";\n }\n if (atoms.propertyIsEnumerable(cur)) return \"atom\";\n return \"variable\";\n}\n\nfunction tokenString(quote) {\n return function(stream, state) {\n var escaped = false, next, end = false;\n while ((next = stream.next()) != null) {\n if (next == quote && !escaped) {end = true; break;}\n escaped = !escaped && quote != \"`\" && next == \"\\\\\";\n }\n if (end || !(escaped || quote == \"`\"))\n state.tokenize = tokenBase;\n return \"string\";\n };\n}\n\nfunction tokenComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if (ch == \"/\" && maybeEnd) {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return \"comment\";\n}\n\nfunction Context(indented, column, type, align, prev) {\n this.indented = indented;\n this.column = column;\n this.type = type;\n this.align = align;\n this.prev = prev;\n}\nfunction pushContext(state, col, type) {\n return state.context = new Context(state.indented, col, type, null, state.context);\n}\nfunction popContext(state) {\n if (!state.context.prev) return;\n var t = state.context.type;\n if (t == \")\" || t == \"]\" || t == \"}\")\n state.indented = state.context.indented;\n return state.context = state.context.prev;\n}\n\n// Interface\n\nexport const go = {\n name: \"go\",\n startState: function(indentUnit) {\n return {\n tokenize: null,\n context: new Context(-indentUnit, 0, \"top\", false),\n indented: 0,\n startOfLine: true\n };\n },\n\n token: function(stream, state) {\n var ctx = state.context;\n if (stream.sol()) {\n if (ctx.align == null) ctx.align = false;\n state.indented = stream.indentation();\n state.startOfLine = true;\n if (ctx.type == \"case\") ctx.type = \"}\";\n }\n if (stream.eatSpace()) return null;\n curPunc = null;\n var style = (state.tokenize || tokenBase)(stream, state);\n if (style == \"comment\") return style;\n if (ctx.align == null) ctx.align = true;\n\n if (curPunc == \"{\") pushContext(state, stream.column(), \"}\");\n else if (curPunc == \"[\") pushContext(state, stream.column(), \"]\");\n else if (curPunc == \"(\") pushContext(state, stream.column(), \")\");\n else if (curPunc == \"case\") ctx.type = \"case\";\n else if (curPunc == \"}\" && ctx.type == \"}\") popContext(state);\n else if (curPunc == ctx.type) popContext(state);\n state.startOfLine = false;\n return style;\n },\n\n indent: function(state, textAfter, cx) {\n if (state.tokenize != tokenBase && state.tokenize != null) return null;\n var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);\n if (ctx.type == \"case\" && /^(?:case|default)\\b/.test(textAfter)) return ctx.indented;\n var closing = firstChar == ctx.type;\n if (ctx.align) return ctx.column + (closing ? 0 : 1);\n else return ctx.indented + (closing ? 0 : cx.unit);\n },\n\n languageData: {\n indentOnInput: /^\\s([{}]|case |default\\s*:)$/,\n commentTokens: {line: \"//\", block: {open: \"/*\", close: \"*/\"}}\n }\n};\n\n"],"names":["curPunc","keywords","atoms","isOperatorChar","tokenBase","stream","state","quote","ch","next","tokenize","escaped","end","test","match","eat","tokenComment","skipToEnd","eatWhile","cur","current","propertyIsEnumerable","maybeEnd","Context","indented","column","type","align","prev","this","pushContext","col","context","go","name","startState","indentUnit","startOfLine","token","ctx","sol","indentation","eatSpace","style","t","popContext","indent","textAfter","cx","firstChar","charAt","closing","unit","languageData","indentOnInput","commentTokens","line","block","open","close"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/3443.index.js b/book/_build/html/_static/3443.index.js new file mode 100644 index 0000000..b2e49d0 --- /dev/null +++ b/book/_build/html/_static/3443.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[3443],{23443:(e,r,t)=>{function n(e){for(var r={},t=e.split(" "),n=0;nu});var a=n("Tcl safe after append array auto_execok auto_import auto_load auto_mkindex auto_mkindex_old auto_qualify auto_reset bgerror binary break catch cd close concat continue dde eof encoding error eval exec exit expr fblocked fconfigure fcopy file fileevent filename filename flush for foreach format gets glob global history http if incr info interp join lappend lindex linsert list llength load lrange lreplace lsearch lset lsort memory msgcat namespace open package parray pid pkg::create pkg_mkIndex proc puts pwd re_syntax read regex regexp registry regsub rename resource return scan seek set socket source split string subst switch tcl_endOfWord tcl_findLibrary tcl_startOfNextWord tcl_wordBreakAfter tcl_startOfPreviousWord tcl_wordBreakBefore tcltest tclvars tell time trace unknown unset update uplevel upvar variable vwait"),o=n("if elseif else and not or eq ne in ni for foreach while switch"),i=/[+\-*&%=<>!?^\/\|]/;function l(e,r,t){return r.tokenize=t,t(e,r)}function s(e,r){var t=r.beforeParams;r.beforeParams=!1;var n,u=e.next();if('"'!=u&&"'"!=u||!r.inParams){if(/[\[\]{}\(\),;\.]/.test(u))return"("==u&&t?r.inParams=!0:")"==u&&(r.inParams=!1),null;if(/\d/.test(u))return e.eatWhile(/[\w\.]/),"number";if("#"==u)return e.eat("*")?l(e,r,c):"#"==u&&e.match(/ *\[ *\[/)?l(e,r,f):(e.skipToEnd(),"comment");if('"'==u)return e.skipTo(/"/),"comment";if("$"==u)return e.eatWhile(/[$_a-z0-9A-Z\.{:]/),e.eatWhile(/}/),r.beforeParams=!0,"builtin";if(i.test(u))return e.eatWhile(i),"comment";e.eatWhile(/[\w\$_{}\xa1-\uffff]/);var m=e.current().toLowerCase();return a&&a.propertyIsEnumerable(m)?"keyword":o&&o.propertyIsEnumerable(m)?(r.beforeParams=!0,"keyword"):null}return l(e,r,(n=u,function(e,r){for(var t,a=!1,o=!1;null!=(t=e.next());){if(t==n&&!a){o=!0;break}a=!a&&"\\"==t}return o&&(r.tokenize=s),"string"}))}function c(e,r){for(var t,n=!1;t=e.next();){if("#"==t&&n){r.tokenize=s;break}n="*"==t}return"comment"}function f(e,r){for(var t,n=0;t=e.next();){if("#"==t&&2==n){r.tokenize=s;break}"]"==t?n++:" "!=t&&(n=0)}return"meta"}const u={name:"tcl",startState:function(){return{tokenize:s,beforeParams:!1,inParams:!1}},token:function(e,r){return e.eatSpace()?null:r.tokenize(e,r)},languageData:{commentTokens:{line:"#"}}}}}]); +//# sourceMappingURL=3443.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/3443.index.js.map b/book/_build/html/_static/3443.index.js.map new file mode 100644 index 0000000..2aca852 --- /dev/null +++ b/book/_build/html/_static/3443.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3443.index.js","mappings":"+FAAA,SAASA,EAAWC,GAElB,IADA,IAAIC,EAAM,CAAC,EAAGC,EAAQF,EAAIG,MAAM,KACvBC,EAAI,EAAGA,EAAIF,EAAMG,SAAUD,EAAGH,EAAIC,EAAME,KAAM,EACvD,OAAOH,CACT,C,0BACA,IAAIK,EAAWP,EAAW,+zBAatBQ,EAAYR,EAAW,kEACvBS,EAAiB,qBACrB,SAASC,EAAMC,EAAQC,EAAOC,GAE5B,OADAD,EAAME,SAAWD,EACVA,EAAEF,EAAQC,EACnB,CACA,SAASG,EAAUJ,EAAQC,GACzB,IAAII,EAAeJ,EAAMI,aACzBJ,EAAMI,cAAe,EACrB,IAwCmBC,EAxCfC,EAAKP,EAAOQ,OAChB,GAAW,KAAND,GAAmB,KAANA,IAAcN,EAAMQ,SAE/B,IAAI,mBAAmBC,KAAKH,GAGjC,MAFU,KAANA,GAAaF,EAAcJ,EAAMQ,UAAW,EACjC,KAANF,IAAWN,EAAMQ,UAAW,GAC9B,KACF,GAAI,KAAKC,KAAKH,GAEnB,OADAP,EAAOW,SAAS,UACT,SACF,GAAU,KAANJ,EACT,OAAIP,EAAOY,IAAI,KACNb,EAAMC,EAAQC,EAAOY,GACpB,KAANN,GAAaP,EAAOc,MAAM,YACrBf,EAAMC,EAAQC,EAAOc,IAC9Bf,EAAOgB,YACA,WACF,GAAU,KAANT,EAET,OADAP,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SAASH,EAAQC,EAChC,EACA6B,aAAc,CACZC,cAAe,CAACC,KAAM,M","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/tcl.js"],"sourcesContent":["function parseWords(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n}\nvar keywords = parseWords(\"Tcl safe after append array auto_execok auto_import auto_load \" +\n \"auto_mkindex auto_mkindex_old auto_qualify auto_reset bgerror \" +\n \"binary break catch cd close concat continue dde eof encoding error \" +\n \"eval exec exit expr fblocked fconfigure fcopy file fileevent filename \" +\n \"filename flush for foreach format gets glob global history http if \" +\n \"incr info interp join lappend lindex linsert list llength load lrange \" +\n \"lreplace lsearch lset lsort memory msgcat namespace open package parray \" +\n \"pid pkg::create pkg_mkIndex proc puts pwd re_syntax read regex regexp \" +\n \"registry regsub rename resource return scan seek set socket source split \" +\n \"string subst switch tcl_endOfWord tcl_findLibrary tcl_startOfNextWord \" +\n \"tcl_wordBreakAfter tcl_startOfPreviousWord tcl_wordBreakBefore tcltest \" +\n \"tclvars tell time trace unknown unset update uplevel upvar variable \" +\n \"vwait\");\nvar functions = parseWords(\"if elseif else and not or eq ne in ni for foreach while switch\");\nvar isOperatorChar = /[+\\-*&%=<>!?^\\/\\|]/;\nfunction chain(stream, state, f) {\n state.tokenize = f;\n return f(stream, state);\n}\nfunction tokenBase(stream, state) {\n var beforeParams = state.beforeParams;\n state.beforeParams = false;\n var ch = stream.next();\n if ((ch == '\"' || ch == \"'\") && state.inParams) {\n return chain(stream, state, tokenString(ch));\n } else if (/[\\[\\]{}\\(\\),;\\.]/.test(ch)) {\n if (ch == \"(\" && beforeParams) state.inParams = true;\n else if (ch == \")\") state.inParams = false;\n return null;\n } else if (/\\d/.test(ch)) {\n stream.eatWhile(/[\\w\\.]/);\n return \"number\";\n } else if (ch == \"#\") {\n if (stream.eat(\"*\"))\n return chain(stream, state, tokenComment);\n if (ch == \"#\" && stream.match(/ *\\[ *\\[/))\n return chain(stream, state, tokenUnparsed);\n stream.skipToEnd();\n return \"comment\";\n } else if (ch == '\"') {\n stream.skipTo(/\"/);\n return \"comment\";\n } else if (ch == \"$\") {\n stream.eatWhile(/[$_a-z0-9A-Z\\.{:]/);\n stream.eatWhile(/}/);\n state.beforeParams = true;\n return \"builtin\";\n } else if (isOperatorChar.test(ch)) {\n stream.eatWhile(isOperatorChar);\n return \"comment\";\n } else {\n stream.eatWhile(/[\\w\\$_{}\\xa1-\\uffff]/);\n var word = stream.current().toLowerCase();\n if (keywords && keywords.propertyIsEnumerable(word))\n return \"keyword\";\n if (functions && functions.propertyIsEnumerable(word)) {\n state.beforeParams = true;\n return \"keyword\";\n }\n return null;\n }\n}\nfunction tokenString(quote) {\n return function(stream, state) {\n var escaped = false, next, end = false;\n while ((next = stream.next()) != null) {\n if (next == quote && !escaped) {\n end = true;\n break;\n }\n escaped = !escaped && next == \"\\\\\";\n }\n if (end) state.tokenize = tokenBase;\n return \"string\";\n };\n}\nfunction tokenComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if (ch == \"#\" && maybeEnd) {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return \"comment\";\n}\nfunction tokenUnparsed(stream, state) {\n var maybeEnd = 0, ch;\n while (ch = stream.next()) {\n if (ch == \"#\" && maybeEnd == 2) {\n state.tokenize = tokenBase;\n break;\n }\n if (ch == \"]\")\n maybeEnd++;\n else if (ch != \" \")\n maybeEnd = 0;\n }\n return \"meta\";\n}\nexport const tcl = {\n name: \"tcl\",\n startState: function() {\n return {\n tokenize: tokenBase,\n beforeParams: false,\n inParams: false\n };\n },\n token: function(stream, state) {\n if (stream.eatSpace()) return null;\n return state.tokenize(stream, state);\n },\n languageData: {\n commentTokens: {line: \"#\"}\n }\n};\n"],"names":["parseWords","str","obj","words","split","i","length","keywords","functions","isOperatorChar","chain","stream","state","f","tokenize","tokenBase","beforeParams","quote","ch","next","inParams","test","eatWhile","eat","tokenComment","match","tokenUnparsed","skipToEnd","skipTo","word","current","toLowerCase","propertyIsEnumerable","escaped","end","maybeEnd","tcl","name","startState","token","eatSpace","languageData","commentTokens","line"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/3506.index.js b/book/_build/html/_static/3506.index.js new file mode 100644 index 0000000..a24ea14 --- /dev/null +++ b/book/_build/html/_static/3506.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[3506],{3506:(e,r,t)=>{t.r(r),t.d(r,{diff:()=>s});var n={"+":"inserted","-":"deleted","@":"meta"};const s={name:"diff",token:function(e){var r=e.string.search(/[\t ]+?$/);if(!e.sol()||0===r)return e.skipToEnd(),("error "+(n[e.string.charAt(0)]||"")).replace(/ $/,"");var t=n[e.peek()]||e.skipToEnd();return-1===r?e.skipToEnd():e.pos=r,t}}}}]); +//# sourceMappingURL=3506.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/3506.index.js.map b/book/_build/html/_static/3506.index.js.map new file mode 100644 index 0000000..6d4c1b6 --- /dev/null +++ b/book/_build/html/_static/3506.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3506.index.js","mappings":"yHAAA,IAAIA,EAAc,CAChB,IAAK,WACL,IAAK,UACL,IAAK,QAGA,MAAMC,EAAO,CAClBC,KAAM,OACNC,MAAO,SAASC,GACd,IAAIC,EAASD,EAAOE,OAAOC,OAAO,YAElC,IAAKH,EAAOI,OAAoB,IAAXH,EAEnB,OADAD,EAAOK,aACC,UACNT,EAAYI,EAAOE,OAAOI,OAAO,KAAO,KAAKC,QAAQ,KAAM,IAG/D,IAAIC,EAAaZ,EAAYI,EAAOS,SAAWT,EAAOK,YAQtD,OANgB,IAAZJ,EACFD,EAAOK,YAEPL,EAAOU,IAAMT,EAGRO,CACT,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/diff.js"],"sourcesContent":["var TOKEN_NAMES = {\n '+': 'inserted',\n '-': 'deleted',\n '@': 'meta'\n};\n\nexport const diff = {\n name: \"diff\",\n token: function(stream) {\n var tw_pos = stream.string.search(/[\\t ]+?$/);\n\n if (!stream.sol() || tw_pos === 0) {\n stream.skipToEnd();\n return (\"error \" + (\n TOKEN_NAMES[stream.string.charAt(0)] || '')).replace(/ $/, '');\n }\n\n var token_name = TOKEN_NAMES[stream.peek()] || stream.skipToEnd();\n\n if (tw_pos === -1) {\n stream.skipToEnd();\n } else {\n stream.pos = tw_pos;\n }\n\n return token_name;\n }\n};\n\n"],"names":["TOKEN_NAMES","diff","name","token","stream","tw_pos","string","search","sol","skipToEnd","charAt","replace","token_name","peek","pos"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/3560.index.js b/book/_build/html/_static/3560.index.js new file mode 100644 index 0000000..22682cc --- /dev/null +++ b/book/_build/html/_static/3560.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[3560],{33560:(e,t,n)=>{n.r(t),n.d(t,{erlang:()=>C});var r=["-type","-spec","-export_type","-opaque"],i=["after","begin","catch","case","cond","end","fun","if","let","of","query","receive","try","when"],o=/[\->,;]/,a=["->",";",","],c=["and","andalso","band","bnot","bor","bsl","bsr","bxor","div","not","or","orelse","rem","xor"],u=/[\+\-\*\/<>=\|:!]/,s=["=","+","-","*","/",">",">=","<","=<","=:=","==","=/=","/=","||","<-","!"],l=/[<\(\[\{]/,_=["<<","(","[","{"],f=/[>\)\]\}]/,p=["}","]",")",">>"],m=["is_atom","is_binary","is_bitstring","is_boolean","is_float","is_function","is_integer","is_list","is_number","is_pid","is_port","is_record","is_reference","is_tuple","atom","binary","bitstring","boolean","function","integer","list","number","pid","port","record","reference","tuple"],b=["abs","adler32","adler32_combine","alive","apply","atom_to_binary","atom_to_list","binary_to_atom","binary_to_existing_atom","binary_to_list","binary_to_term","bit_size","bitstring_to_list","byte_size","check_process_code","contact_binary","crc32","crc32_combine","date","decode_packet","delete_module","disconnect_node","element","erase","exit","float","float_to_list","garbage_collect","get","get_keys","group_leader","halt","hd","integer_to_list","internal_bif","iolist_size","iolist_to_binary","is_alive","is_atom","is_binary","is_bitstring","is_boolean","is_float","is_function","is_integer","is_list","is_number","is_pid","is_port","is_process_alive","is_record","is_reference","is_tuple","length","link","list_to_atom","list_to_binary","list_to_bitstring","list_to_existing_atom","list_to_float","list_to_integer","list_to_pid","list_to_tuple","load_module","make_ref","module_loaded","monitor_node","node","node_link","node_unlink","nodes","notalive","now","open_port","pid_to_list","port_close","port_command","port_connect","port_control","pre_loaded","process_flag","process_info","processes","purge_module","put","register","registered","round","self","setelement","size","spawn","spawn_link","spawn_monitor","spawn_opt","split_binary","statistics","term_to_binary","time","throw","tl","trunc","tuple_size","tuple_to_list","unlink","unregister","whereis"],d=/[\w@Ø-ÞÀ-Öß-öø-ÿ]/,k=/[0-7]{1,3}|[bdefnrstv\\"']|\^[a-zA-Z]|x[0-9a-zA-Z]{2}|x{[0-9a-zA-Z]+}/;function g(e,t,n){if(1==e.current().length&&t.test(e.current())){for(e.backUp(1);t.test(e.peek());)if(e.next(),x(e.current(),n))return!0;e.backUp(e.current().length-1)}return!1}function h(e,t,n){if(1==e.current().length&&t.test(e.current())){for(;t.test(e.peek());)e.next();for(;01&&"fun"===e[t].type&&"fun"===e[t-1].token)return e.slice(0,t-1);switch(e[t].token){case"}":return A(e,{g:["{"]});case"]":return A(e,{i:["["]});case")":return A(e,{i:["("]});case">>":return A(e,{i:["<<"]});case"end":return A(e,{i:["begin","case","fun","if","receive","try"]});case",":return A(e,{e:["begin","try","when","->",",","(","[","{","<<"]});case"->":return A(e,{r:["when"],m:["try","if","case","receive"]});case";":return A(e,{E:["case","fun","if","receive","try","when"]});case"catch":return A(e,{e:["try"]});case"of":return A(e,{e:["case"]});case"after":return A(e,{e:["receive","try"]});default:return e}}(e.tokenStack))}(e,function(e,t){return z(t.current(),t.column(),t.indentation(),e)}(n,t)),n){case"atom":case"boolean":return"atom";case"attribute":return"attribute";case"builtin":return"builtin";case"close_paren":case"colon":case"dot":case"open_paren":case"separator":default:return null;case"comment":return"comment";case"error":return"error";case"fun":return"meta";case"function":return"tag";case"guard":return"property";case"keyword":return"keyword";case"macro":return"macroName";case"number":return"number";case"operator":return"operator";case"record":return"bracket";case"string":return"string";case"type":return"def";case"variable":return"variable"}}function z(e,t,n,r){return{token:e,column:t,indent:n,type:r}}function W(e){return z(e,0,0,e)}function U(e,t){var n=e.tokenStack.length,r=t||1;return!(n({tokenStack:[],in_string:!1,in_atom:!1}),token:function(e,t){if(t.in_string)return t.in_string=!y(e),S(t,e,"string");if(t.in_atom)return t.in_atom=!v(e),S(t,e,"atom");if(e.eatSpace())return S(t,e,"whitespace");if(!U(t)&&e.match(/-\s*[a-zß-öø-ÿ][\wØ-ÞÀ-Öß-öø-ÿ]*/))return x(e.current(),r)?S(t,e,"type"):S(t,e,"attribute");var n=e.next();if("%"==n)return e.skipToEnd(),S(t,e,"comment");if(":"==n)return S(t,e,"colon");if("?"==n)return e.eatSpace(),e.eatWhile(d),S(t,e,"macro");if("#"==n)return e.eatSpace(),e.eatWhile(d),S(t,e,"record");if("$"==n)return"\\"!=e.next()||e.match(k)?S(t,e,"number"):S(t,e,"error");if("."==n)return S(t,e,"dot");if("'"==n){if(!(t.in_atom=!v(e))){if(e.match(/\s*\/\s*[0-9]/,!1))return e.match(/\s*\/\s*[0-9]/,!0),S(t,e,"fun");if(e.match(/\s*\(/,!1)||e.match(/\s*:/,!1))return S(t,e,"function")}return S(t,e,"atom")}if('"'==n)return t.in_string=!y(e),S(t,e,"string");if(/[A-Z_Ø-ÞÀ-Ö]/.test(n))return e.eatWhile(d),S(t,e,"variable");if(/[a-z_ß-öø-ÿ]/.test(n)){if(e.eatWhile(d),e.match(/\s*\/\s*[0-9]/,!1))return e.match(/\s*\/\s*[0-9]/,!0),S(t,e,"fun");var w=e.current();return x(w,i)?S(t,e,"keyword"):x(w,c)?S(t,e,"operator"):e.match(/\s*\(/,!1)?!x(w,b)||":"==U(t).token&&"erlang"!=U(t,2).token?x(w,m)?S(t,e,"guard"):S(t,e,"function"):S(t,e,"builtin"):":"==function(e){var t=e.match(/^\s*([^\s%])/,!1);return t?t[1]:""}(e)?S(t,e,"erlang"==w?"builtin":"function"):x(w,["true","false"])?S(t,e,"boolean"):S(t,e,"atom")}var z=/[0-9]/;return z.test(n)?(e.eatWhile(z),e.eat("#")?e.eatWhile(/[0-9a-zA-Z]/)||e.backUp(1):e.eat(".")&&(e.eatWhile(z)?e.eat(/[eE]/)&&(e.eat(/[-+]/)?e.eatWhile(z)||e.backUp(2):e.eatWhile(z)||e.backUp(1)):e.backUp(1)),S(t,e,"number")):g(e,l,_)?S(t,e,"open_paren"):g(e,f,p)?S(t,e,"close_paren"):h(e,o,a)?S(t,e,"separator"):h(e,u,s)?S(t,e,"operator"):S(t,e,null)},indent:function(e,t,n){var r,i,o=q(i=t.match(/,|[a-z]+|\}|\]|\)|>>|\|+|\(/))&&0===i.index?i[0]:"",a=U(e,1),c=U(e,2);return e.in_string||e.in_atom?null:c?"when"==a.token?a.column+n.unit:"when"===o&&"function"===c.type?c.indent+n.unit:"("===o&&"fun"===a.token?a.column+3:"catch"===o&&(r=E(e,["try"]))?r.column:x(o,["end","after","of"])?(r=E(e,["begin","case","fun","if","receive","try"]))?r.column:null:x(o,p)?(r=E(e,_))?r.column:null:x(a.token,[",","|","||"])||x(o,[",","|","||"])?(r=function(e){var t=e.tokenStack.slice(0,-1),n=Z(t,"type",["open_paren"]);return!!q(t[n])&&t[n]}(e))?r.column+r.token.length:n.unit:"->"==a.token?x(c.token,["receive","case","if","try"])?c.column+n.unit+n.unit:c.column+n.unit:x(a.token,_)?a.column+a.token.length:(r=function(e){var t=e.tokenStack,n=Z(t,"type",["open_paren","separator","keyword"]),r=Z(t,"type",["operator"]);return q(n)&&q(r)&&n,;]/;\nvar separatorWords = [\n \"->\",\";\",\",\"];\n\nvar operatorAtomWords = [\n \"and\",\"andalso\",\"band\",\"bnot\",\"bor\",\"bsl\",\"bsr\",\"bxor\",\n \"div\",\"not\",\"or\",\"orelse\",\"rem\",\"xor\"];\n\nvar operatorSymbolRE = /[\\+\\-\\*\\/<>=\\|:!]/;\nvar operatorSymbolWords = [\n \"=\",\"+\",\"-\",\"*\",\"/\",\">\",\">=\",\"<\",\"=<\",\"=:=\",\"==\",\"=/=\",\"/=\",\"||\",\"<-\",\"!\"];\n\nvar openParenRE = /[<\\(\\[\\{]/;\nvar openParenWords = [\n \"<<\",\"(\",\"[\",\"{\"];\n\nvar closeParenRE = /[>\\)\\]\\}]/;\nvar closeParenWords = [\n \"}\",\"]\",\")\",\">>\"];\n\nvar guardWords = [\n \"is_atom\",\"is_binary\",\"is_bitstring\",\"is_boolean\",\"is_float\",\n \"is_function\",\"is_integer\",\"is_list\",\"is_number\",\"is_pid\",\n \"is_port\",\"is_record\",\"is_reference\",\"is_tuple\",\n \"atom\",\"binary\",\"bitstring\",\"boolean\",\"function\",\"integer\",\"list\",\n \"number\",\"pid\",\"port\",\"record\",\"reference\",\"tuple\"];\n\nvar bifWords = [\n \"abs\",\"adler32\",\"adler32_combine\",\"alive\",\"apply\",\"atom_to_binary\",\n \"atom_to_list\",\"binary_to_atom\",\"binary_to_existing_atom\",\n \"binary_to_list\",\"binary_to_term\",\"bit_size\",\"bitstring_to_list\",\n \"byte_size\",\"check_process_code\",\"contact_binary\",\"crc32\",\n \"crc32_combine\",\"date\",\"decode_packet\",\"delete_module\",\n \"disconnect_node\",\"element\",\"erase\",\"exit\",\"float\",\"float_to_list\",\n \"garbage_collect\",\"get\",\"get_keys\",\"group_leader\",\"halt\",\"hd\",\n \"integer_to_list\",\"internal_bif\",\"iolist_size\",\"iolist_to_binary\",\n \"is_alive\",\"is_atom\",\"is_binary\",\"is_bitstring\",\"is_boolean\",\n \"is_float\",\"is_function\",\"is_integer\",\"is_list\",\"is_number\",\"is_pid\",\n \"is_port\",\"is_process_alive\",\"is_record\",\"is_reference\",\"is_tuple\",\n \"length\",\"link\",\"list_to_atom\",\"list_to_binary\",\"list_to_bitstring\",\n \"list_to_existing_atom\",\"list_to_float\",\"list_to_integer\",\n \"list_to_pid\",\"list_to_tuple\",\"load_module\",\"make_ref\",\"module_loaded\",\n \"monitor_node\",\"node\",\"node_link\",\"node_unlink\",\"nodes\",\"notalive\",\n \"now\",\"open_port\",\"pid_to_list\",\"port_close\",\"port_command\",\n \"port_connect\",\"port_control\",\"pre_loaded\",\"process_flag\",\n \"process_info\",\"processes\",\"purge_module\",\"put\",\"register\",\n \"registered\",\"round\",\"self\",\"setelement\",\"size\",\"spawn\",\"spawn_link\",\n \"spawn_monitor\",\"spawn_opt\",\"split_binary\",\"statistics\",\n \"term_to_binary\",\"time\",\"throw\",\"tl\",\"trunc\",\"tuple_size\",\n \"tuple_to_list\",\"unlink\",\"unregister\",\"whereis\"];\n\n// upper case: [A-Z] [Ø-Þ] [À-Ö]\n// lower case: [a-z] [ß-ö] [ø-ÿ]\nvar anumRE = /[\\w@Ø-ÞÀ-Öß-öø-ÿ]/;\nvar escapesRE =\n /[0-7]{1,3}|[bdefnrstv\\\\\"']|\\^[a-zA-Z]|x[0-9a-zA-Z]{2}|x{[0-9a-zA-Z]+}/;\n\n/////////////////////////////////////////////////////////////////////////////\n// tokenizer\n\nfunction tokenizer(stream,state) {\n // in multi-line string\n if (state.in_string) {\n state.in_string = (!doubleQuote(stream));\n return rval(state,stream,\"string\");\n }\n\n // in multi-line atom\n if (state.in_atom) {\n state.in_atom = (!singleQuote(stream));\n return rval(state,stream,\"atom\");\n }\n\n // whitespace\n if (stream.eatSpace()) {\n return rval(state,stream,\"whitespace\");\n }\n\n // attributes and type specs\n if (!peekToken(state) &&\n stream.match(/-\\s*[a-zß-öø-ÿ][\\wØ-ÞÀ-Öß-öø-ÿ]*/)) {\n if (is_member(stream.current(),typeWords)) {\n return rval(state,stream,\"type\");\n }else{\n return rval(state,stream,\"attribute\");\n }\n }\n\n var ch = stream.next();\n\n // comment\n if (ch == '%') {\n stream.skipToEnd();\n return rval(state,stream,\"comment\");\n }\n\n // colon\n if (ch == \":\") {\n return rval(state,stream,\"colon\");\n }\n\n // macro\n if (ch == '?') {\n stream.eatSpace();\n stream.eatWhile(anumRE);\n return rval(state,stream,\"macro\");\n }\n\n // record\n if (ch == \"#\") {\n stream.eatSpace();\n stream.eatWhile(anumRE);\n return rval(state,stream,\"record\");\n }\n\n // dollar escape\n if (ch == \"$\") {\n if (stream.next() == \"\\\\\" && !stream.match(escapesRE)) {\n return rval(state,stream,\"error\");\n }\n return rval(state,stream,\"number\");\n }\n\n // dot\n if (ch == \".\") {\n return rval(state,stream,\"dot\");\n }\n\n // quoted atom\n if (ch == '\\'') {\n if (!(state.in_atom = (!singleQuote(stream)))) {\n if (stream.match(/\\s*\\/\\s*[0-9]/,false)) {\n stream.match(/\\s*\\/\\s*[0-9]/,true);\n return rval(state,stream,\"fun\"); // 'f'/0 style fun\n }\n if (stream.match(/\\s*\\(/,false) || stream.match(/\\s*:/,false)) {\n return rval(state,stream,\"function\");\n }\n }\n return rval(state,stream,\"atom\");\n }\n\n // string\n if (ch == '\"') {\n state.in_string = (!doubleQuote(stream));\n return rval(state,stream,\"string\");\n }\n\n // variable\n if (/[A-Z_Ø-ÞÀ-Ö]/.test(ch)) {\n stream.eatWhile(anumRE);\n return rval(state,stream,\"variable\");\n }\n\n // atom/keyword/BIF/function\n if (/[a-z_ß-öø-ÿ]/.test(ch)) {\n stream.eatWhile(anumRE);\n\n if (stream.match(/\\s*\\/\\s*[0-9]/,false)) {\n stream.match(/\\s*\\/\\s*[0-9]/,true);\n return rval(state,stream,\"fun\"); // f/0 style fun\n }\n\n var w = stream.current();\n\n if (is_member(w,keywordWords)) {\n return rval(state,stream,\"keyword\");\n }else if (is_member(w,operatorAtomWords)) {\n return rval(state,stream,\"operator\");\n }else if (stream.match(/\\s*\\(/,false)) {\n // 'put' and 'erlang:put' are bifs, 'foo:put' is not\n if (is_member(w,bifWords) &&\n ((peekToken(state).token != \":\") ||\n (peekToken(state,2).token == \"erlang\"))) {\n return rval(state,stream,\"builtin\");\n }else if (is_member(w,guardWords)) {\n return rval(state,stream,\"guard\");\n }else{\n return rval(state,stream,\"function\");\n }\n }else if (lookahead(stream) == \":\") {\n if (w == \"erlang\") {\n return rval(state,stream,\"builtin\");\n } else {\n return rval(state,stream,\"function\");\n }\n }else if (is_member(w,[\"true\",\"false\"])) {\n return rval(state,stream,\"boolean\");\n }else{\n return rval(state,stream,\"atom\");\n }\n }\n\n // number\n var digitRE = /[0-9]/;\n var radixRE = /[0-9a-zA-Z]/; // 36#zZ style int\n if (digitRE.test(ch)) {\n stream.eatWhile(digitRE);\n if (stream.eat('#')) { // 36#aZ style integer\n if (!stream.eatWhile(radixRE)) {\n stream.backUp(1); //\"36#\" - syntax error\n }\n } else if (stream.eat('.')) { // float\n if (!stream.eatWhile(digitRE)) {\n stream.backUp(1); // \"3.\" - probably end of function\n } else {\n if (stream.eat(/[eE]/)) { // float with exponent\n if (stream.eat(/[-+]/)) {\n if (!stream.eatWhile(digitRE)) {\n stream.backUp(2); // \"2e-\" - syntax error\n }\n } else {\n if (!stream.eatWhile(digitRE)) {\n stream.backUp(1); // \"2e\" - syntax error\n }\n }\n }\n }\n }\n return rval(state,stream,\"number\"); // normal integer\n }\n\n // open parens\n if (nongreedy(stream,openParenRE,openParenWords)) {\n return rval(state,stream,\"open_paren\");\n }\n\n // close parens\n if (nongreedy(stream,closeParenRE,closeParenWords)) {\n return rval(state,stream,\"close_paren\");\n }\n\n // separators\n if (greedy(stream,separatorRE,separatorWords)) {\n return rval(state,stream,\"separator\");\n }\n\n // operators\n if (greedy(stream,operatorSymbolRE,operatorSymbolWords)) {\n return rval(state,stream,\"operator\");\n }\n\n return rval(state,stream,null);\n}\n\n/////////////////////////////////////////////////////////////////////////////\n// utilities\nfunction nongreedy(stream,re,words) {\n if (stream.current().length == 1 && re.test(stream.current())) {\n stream.backUp(1);\n while (re.test(stream.peek())) {\n stream.next();\n if (is_member(stream.current(),words)) {\n return true;\n }\n }\n stream.backUp(stream.current().length-1);\n }\n return false;\n}\n\nfunction greedy(stream,re,words) {\n if (stream.current().length == 1 && re.test(stream.current())) {\n while (re.test(stream.peek())) {\n stream.next();\n }\n while (0 < stream.current().length) {\n if (is_member(stream.current(),words)) {\n return true;\n }else{\n stream.backUp(1);\n }\n }\n stream.next();\n }\n return false;\n}\n\nfunction doubleQuote(stream) {\n return quote(stream, '\"', '\\\\');\n}\n\nfunction singleQuote(stream) {\n return quote(stream,'\\'','\\\\');\n}\n\nfunction quote(stream,quoteChar,escapeChar) {\n while (!stream.eol()) {\n var ch = stream.next();\n if (ch == quoteChar) {\n return true;\n }else if (ch == escapeChar) {\n stream.next();\n }\n }\n return false;\n}\n\nfunction lookahead(stream) {\n var m = stream.match(/^\\s*([^\\s%])/, false)\n return m ? m[1] : \"\";\n}\n\nfunction is_member(element,list) {\n return (-1 < list.indexOf(element));\n}\n\nfunction rval(state,stream,type) {\n\n // parse stack\n pushToken(state,realToken(type,stream));\n\n // map erlang token type to CodeMirror style class\n // erlang -> CodeMirror tag\n switch (type) {\n case \"atom\": return \"atom\";\n case \"attribute\": return \"attribute\";\n case \"boolean\": return \"atom\";\n case \"builtin\": return \"builtin\";\n case \"close_paren\": return null;\n case \"colon\": return null;\n case \"comment\": return \"comment\";\n case \"dot\": return null;\n case \"error\": return \"error\";\n case \"fun\": return \"meta\";\n case \"function\": return \"tag\";\n case \"guard\": return \"property\";\n case \"keyword\": return \"keyword\";\n case \"macro\": return \"macroName\";\n case \"number\": return \"number\";\n case \"open_paren\": return null;\n case \"operator\": return \"operator\";\n case \"record\": return \"bracket\";\n case \"separator\": return null;\n case \"string\": return \"string\";\n case \"type\": return \"def\";\n case \"variable\": return \"variable\";\n default: return null;\n }\n}\n\nfunction aToken(tok,col,ind,typ) {\n return {token: tok,\n column: col,\n indent: ind,\n type: typ};\n}\n\nfunction realToken(type,stream) {\n return aToken(stream.current(),\n stream.column(),\n stream.indentation(),\n type);\n}\n\nfunction fakeToken(type) {\n return aToken(type,0,0,type);\n}\n\nfunction peekToken(state,depth) {\n var len = state.tokenStack.length;\n var dep = (depth ? depth : 1);\n\n if (len < dep) {\n return false;\n }else{\n return state.tokenStack[len-dep];\n }\n}\n\nfunction pushToken(state,token) {\n\n if (!(token.type == \"comment\" || token.type == \"whitespace\")) {\n state.tokenStack = maybe_drop_pre(state.tokenStack,token);\n state.tokenStack = maybe_drop_post(state.tokenStack);\n }\n}\n\nfunction maybe_drop_pre(s,token) {\n var last = s.length-1;\n\n if (0 < last && s[last].type === \"record\" && token.type === \"dot\") {\n s.pop();\n }else if (0 < last && s[last].type === \"group\") {\n s.pop();\n s.push(token);\n }else{\n s.push(token);\n }\n return s;\n}\n\nfunction maybe_drop_post(s) {\n if (!s.length) return s\n var last = s.length-1;\n\n if (s[last].type === \"dot\") {\n return [];\n }\n if (last > 1 && s[last].type === \"fun\" && s[last-1].token === \"fun\") {\n return s.slice(0,last-1);\n }\n switch (s[last].token) {\n case \"}\": return d(s,{g:[\"{\"]});\n case \"]\": return d(s,{i:[\"[\"]});\n case \")\": return d(s,{i:[\"(\"]});\n case \">>\": return d(s,{i:[\"<<\"]});\n case \"end\": return d(s,{i:[\"begin\",\"case\",\"fun\",\"if\",\"receive\",\"try\"]});\n case \",\": return d(s,{e:[\"begin\",\"try\",\"when\",\"->\",\n \",\",\"(\",\"[\",\"{\",\"<<\"]});\n case \"->\": return d(s,{r:[\"when\"],\n m:[\"try\",\"if\",\"case\",\"receive\"]});\n case \";\": return d(s,{E:[\"case\",\"fun\",\"if\",\"receive\",\"try\",\"when\"]});\n case \"catch\":return d(s,{e:[\"try\"]});\n case \"of\": return d(s,{e:[\"case\"]});\n case \"after\":return d(s,{e:[\"receive\",\"try\"]});\n default: return s;\n }\n}\n\nfunction d(stack,tt) {\n // stack is a stack of Token objects.\n // tt is an object; {type:tokens}\n // type is a char, tokens is a list of token strings.\n // The function returns (possibly truncated) stack.\n // It will descend the stack, looking for a Token such that Token.token\n // is a member of tokens. If it does not find that, it will normally (but\n // see \"E\" below) return stack. If it does find a match, it will remove\n // all the Tokens between the top and the matched Token.\n // If type is \"m\", that is all it does.\n // If type is \"i\", it will also remove the matched Token and the top Token.\n // If type is \"g\", like \"i\", but add a fake \"group\" token at the top.\n // If type is \"r\", it will remove the matched Token, but not the top Token.\n // If type is \"e\", it will keep the matched Token but not the top Token.\n // If type is \"E\", it behaves as for type \"e\", except if there is no match,\n // in which case it will return an empty stack.\n\n for (var type in tt) {\n var len = stack.length-1;\n var tokens = tt[type];\n for (var i = len-1; -1 < i ; i--) {\n if (is_member(stack[i].token,tokens)) {\n var ss = stack.slice(0,i);\n switch (type) {\n case \"m\": return ss.concat(stack[i]).concat(stack[len]);\n case \"r\": return ss.concat(stack[len]);\n case \"i\": return ss;\n case \"g\": return ss.concat(fakeToken(\"group\"));\n case \"E\": return ss.concat(stack[i]);\n case \"e\": return ss.concat(stack[i]);\n }\n }\n }\n }\n return (type == \"E\" ? [] : stack);\n}\n\n/////////////////////////////////////////////////////////////////////////////\n// indenter\n\nfunction indenter(state, textAfter, cx) {\n var t;\n var wordAfter = wordafter(textAfter);\n var currT = peekToken(state,1);\n var prevT = peekToken(state,2);\n\n if (state.in_string || state.in_atom) {\n return null;\n }else if (!prevT) {\n return 0;\n }else if (currT.token == \"when\") {\n return currT.column + cx.unit;\n }else if (wordAfter === \"when\" && prevT.type === \"function\") {\n return prevT.indent+cx.unit;\n }else if (wordAfter === \"(\" && currT.token === \"fun\") {\n return currT.column+3;\n }else if (wordAfter === \"catch\" && (t = getToken(state,[\"try\"]))) {\n return t.column;\n }else if (is_member(wordAfter,[\"end\",\"after\",\"of\"])) {\n t = getToken(state,[\"begin\",\"case\",\"fun\",\"if\",\"receive\",\"try\"]);\n return t ? t.column : null;\n }else if (is_member(wordAfter,closeParenWords)) {\n t = getToken(state,openParenWords);\n return t ? t.column : null;\n }else if (is_member(currT.token,[\",\",\"|\",\"||\"]) ||\n is_member(wordAfter,[\",\",\"|\",\"||\"])) {\n t = postcommaToken(state);\n return t ? t.column+t.token.length : cx.unit;\n }else if (currT.token == \"->\") {\n if (is_member(prevT.token, [\"receive\",\"case\",\"if\",\"try\"])) {\n return prevT.column+cx.unit+cx.unit;\n }else{\n return prevT.column+cx.unit;\n }\n }else if (is_member(currT.token,openParenWords)) {\n return currT.column+currT.token.length;\n }else{\n t = defaultToken(state);\n return truthy(t) ? t.column+cx.unit : 0;\n }\n}\n\nfunction wordafter(str) {\n var m = str.match(/,|[a-z]+|\\}|\\]|\\)|>>|\\|+|\\(/);\n\n return truthy(m) && (m.index === 0) ? m[0] : \"\";\n}\n\nfunction postcommaToken(state) {\n var objs = state.tokenStack.slice(0,-1);\n var i = getTokenIndex(objs,\"type\",[\"open_paren\"]);\n\n return truthy(objs[i]) ? objs[i] : false;\n}\n\nfunction defaultToken(state) {\n var objs = state.tokenStack;\n var stop = getTokenIndex(objs,\"type\",[\"open_paren\",\"separator\",\"keyword\"]);\n var oper = getTokenIndex(objs,\"type\",[\"operator\"]);\n\n if (truthy(stop) && truthy(oper) && stop < oper) {\n return objs[stop+1];\n } else if (truthy(stop)) {\n return objs[stop];\n } else {\n return false;\n }\n}\n\nfunction getToken(state,tokens) {\n var objs = state.tokenStack;\n var i = getTokenIndex(objs,\"token\",tokens);\n\n return truthy(objs[i]) ? objs[i] : false;\n}\n\nfunction getTokenIndex(objs,propname,propvals) {\n\n for (var i = objs.length-1; -1 < i ; i--) {\n if (is_member(objs[i][propname],propvals)) {\n return i;\n }\n }\n return false;\n}\n\nfunction truthy(x) {\n return (x !== false) && (x != null);\n}\n\n/////////////////////////////////////////////////////////////////////////////\n// this object defines the mode\n\nexport const erlang = {\n name: \"erlang\",\n startState() {\n return {tokenStack: [],\n in_string: false,\n in_atom: false};\n },\n\n token: tokenizer,\n\n indent: indenter,\n\n languageData: {\n commentTokens: {line: \"%\"}\n }\n};\n\n"],"names":["typeWords","keywordWords","separatorRE","separatorWords","operatorAtomWords","operatorSymbolRE","operatorSymbolWords","openParenRE","openParenWords","closeParenRE","closeParenWords","guardWords","bifWords","anumRE","escapesRE","nongreedy","stream","re","words","current","length","test","backUp","peek","next","is_member","greedy","doubleQuote","quote","singleQuote","quoteChar","escapeChar","eol","ch","element","list","indexOf","rval","state","type","token","tokenStack","s","last","pop","push","maybe_drop_pre","slice","d","g","i","e","r","m","E","maybe_drop_post","pushToken","aToken","column","indentation","realToken","tok","col","ind","typ","indent","fakeToken","peekToken","depth","len","dep","stack","tt","tokens","ss","concat","getToken","objs","getTokenIndex","truthy","propname","propvals","x","erlang","name","startState","in_string","in_atom","eatSpace","match","skipToEnd","eatWhile","w","lookahead","digitRE","eat","textAfter","cx","t","wordAfter","index","currT","prevT","unit","postcommaToken","stop","oper","defaultToken","languageData","commentTokens","line"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/3747.index.js b/book/_build/html/_static/3747.index.js new file mode 100644 index 0000000..ccc68da --- /dev/null +++ b/book/_build/html/_static/3747.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[3747],{3747:(e,t,r)=>{function n(e){var t,r,n=e.statementIndent,a=e.jsonld,i=e.json||a,o=e.typescript,u=e.wordCharacters||/[\w$\xa1-\uffff]/,s=function(){function e(e){return{type:e,style:"keyword"}}var t=e("keyword a"),r=e("keyword b"),n=e("keyword c"),a=e("keyword d"),i=e("operator"),o={type:"atom",style:"atom"};return{if:e("if"),while:t,with:t,else:r,do:r,try:r,finally:r,return:a,break:a,continue:a,new:e("new"),delete:n,void:n,throw:n,debugger:e("debugger"),var:e("var"),const:e("var"),let:e("var"),function:e("function"),catch:e("catch"),for:e("for"),switch:e("switch"),case:e("case"),default:e("default"),in:i,typeof:i,instanceof:i,true:o,false:o,null:o,undefined:o,NaN:o,Infinity:o,this:e("this"),class:e("class"),super:e("atom"),yield:n,export:e("export"),import:e("import"),extends:n,await:n}}(),c=/[+\-*&%=<>!?|~^@]/,l=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;function f(e,n,a){return t=e,r=a,n}function d(e,t){var r,n=e.next();if('"'==n||"'"==n)return t.tokenize=(r=n,function(e,t){var n,i=!1;if(a&&"@"==e.peek()&&e.match(l))return t.tokenize=d,f("jsonld-keyword","meta");for(;null!=(n=e.next())&&(n!=r||i);)i=!i&&"\\"==n;return i||(t.tokenize=d),f("string","string")}),t.tokenize(e,t);if("."==n&&e.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/))return f("number","number");if("."==n&&e.match(".."))return f("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(n))return f(n);if("="==n&&e.eat(">"))return f("=>","operator");if("0"==n&&e.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/))return f("number","number");if(/\d/.test(n))return e.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/),f("number","number");if("/"==n)return e.eat("*")?(t.tokenize=m,m(e,t)):e.eat("/")?(e.skipToEnd(),f("comment","comment")):function(e,t,r){return t.tokenize==d&&/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(t.lastType)||"quasi"==t.lastType&&/\{\s*$/.test(e.string.slice(0,e.pos-1))}(e,t)?(function(e){for(var t,r=!1,n=!1;null!=(t=e.next());){if(!r){if("/"==t&&!n)return;"["==t?n=!0:n&&"]"==t&&(n=!1)}r=!r&&"\\"==t}}(e),e.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/),f("regexp","string.special")):(e.eat("="),f("operator","operator",e.current()));if("`"==n)return t.tokenize=p,p(e,t);if("#"==n&&"!"==e.peek())return e.skipToEnd(),f("meta","meta");if("#"==n&&e.eatWhile(u))return f("variable","property");if("<"==n&&e.match("!--")||"-"==n&&e.match("->")&&!/\S/.test(e.string.slice(0,e.start)))return e.skipToEnd(),f("comment","comment");if(c.test(n))return">"==n&&t.lexical&&">"==t.lexical.type||(e.eat("=")?"!"!=n&&"="!=n||e.eat("="):/[<>*+\-|&?]/.test(n)&&(e.eat(n),">"==n&&e.eat(n))),"?"==n&&e.eat(".")?f("."):f("operator","operator",e.current());if(u.test(n)){e.eatWhile(u);var i=e.current();if("."!=t.lastType){if(s.propertyIsEnumerable(i)){var o=s[i];return f(o.type,o.style,i)}if("async"==i&&e.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/,!1))return f("async","keyword",i)}return f("variable","variable",i)}}function m(e,t){for(var r,n=!1;r=e.next();){if("/"==r&&n){t.tokenize=d;break}n="*"==r}return f("comment","comment")}function p(e,t){for(var r,n=!1;null!=(r=e.next());){if(!n&&("`"==r||"$"==r&&e.eat("{"))){t.tokenize=d;break}n=!n&&"\\"==r}return f("quasi","string.special",e.current())}var k="([{}])";function v(e,t){t.fatArrowAt&&(t.fatArrowAt=null);var r=e.string.indexOf("=>",e.start);if(!(r<0)){if(o){var n=/:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(e.string.slice(e.start,r));n&&(r=n.index)}for(var a=0,i=!1,s=r-1;s>=0;--s){var c=e.string.charAt(s),l=k.indexOf(c);if(l>=0&&l<3){if(!a){++s;break}if(0==--a){"("==c&&(i=!0);break}}else if(l>=3&&l<6)++a;else if(u.test(c))i=!0;else if(/["'\/`]/.test(c))for(;;--s){if(0==s)return;if(e.string.charAt(s-1)==c&&"\\"!=e.string.charAt(s-2)){s--;break}}else if(i&&!a){++s;break}}i&&!a&&(t.fatArrowAt=s)}}var y={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,this:!0,import:!0,"jsonld-keyword":!0};function w(e,t,r,n,a,i){this.indented=e,this.column=t,this.type=r,this.prev=a,this.info=i,null!=n&&(this.align=n)}function b(e,t){for(var r=e.localVars;r;r=r.next)if(r.name==t)return!0;for(var n=e.context;n;n=n.prev)for(r=n.vars;r;r=r.next)if(r.name==t)return!0}var h={state:null,column:null,marked:null,cc:null};function x(){for(var e=arguments.length-1;e>=0;e--)h.cc.push(arguments[e])}function g(){return x.apply(null,arguments),!0}function V(e,t){for(var r=t;r;r=r.next)if(r.name==e)return!0;return!1}function A(t){var r=h.state;if(h.marked="def",r.context)if("var"==r.lexical.info&&r.context&&r.context.block){var n=z(t,r.context);if(null!=n)return void(r.context=n)}else if(!V(t,r.localVars))return void(r.localVars=new $(t,r.localVars));e.globalVars&&!V(t,r.globalVars)&&(r.globalVars=new $(t,r.globalVars))}function z(e,t){if(t){if(t.block){var r=z(e,t.prev);return r?r==t.prev?t:new T(r,t.vars,!0):null}return V(e,t.vars)?t:new T(t.prev,new $(e,t.vars),!1)}return null}function j(e){return"public"==e||"private"==e||"protected"==e||"abstract"==e||"readonly"==e}function T(e,t,r){this.prev=e,this.vars=t,this.block=r}function $(e,t){this.name=e,this.next=t}var O=new $("this",new $("arguments",null));function _(){h.state.context=new T(h.state.context,h.state.localVars,!1),h.state.localVars=O}function q(){h.state.context=new T(h.state.context,h.state.localVars,!0),h.state.localVars=null}function E(){h.state.localVars=h.state.context.vars,h.state.context=h.state.context.prev}function I(e,t){var r=function(){var r=h.state,n=r.indented;if("stat"==r.lexical.type)n=r.lexical.indented;else for(var a=r.lexical;a&&")"==a.type&&a.align;a=a.prev)n=a.indented;r.lexical=new w(n,h.stream.column(),e,null,r.lexical,t)};return r.lex=!0,r}function C(){var e=h.state;e.lexical.prev&&(")"==e.lexical.type&&(e.indented=e.lexical.indented),e.lexical=e.lexical.prev)}function S(e){return function t(r){return r==e?g():";"==e||"}"==r||")"==r||"]"==r?x():g(t)}}function N(e,t){return"var"==e?g(I("vardef",t),he,S(";"),C):"keyword a"==e?g(I("form"),D,N,C):"keyword b"==e?g(I("form"),N,C):"keyword d"==e?h.stream.match(/^\s*$/,!1)?g():g(I("stat"),U,S(";"),C):"debugger"==e?g(S(";")):"{"==e?g(I("}"),q,ae,C,E):";"==e?g():"if"==e?("else"==h.state.lexical.info&&h.state.cc[h.state.cc.length-1]==C&&h.state.cc.pop()(),g(I("form"),D,N,C,je)):"function"==e?g(_e):"for"==e?g(I("form"),q,Te,N,E,C):"class"==e||o&&"interface"==t?(h.marked="keyword",g(I("form","class"==e?e:t),Se,C)):"variable"==e?o&&"declare"==t?(h.marked="keyword",g(N)):o&&("module"==t||"enum"==t||"type"==t)&&h.stream.match(/^\s*\w/,!1)?(h.marked="keyword","enum"==t?g(Le):"type"==t?g(Ee,S("operator"),ce,S(";")):g(I("form"),xe,S("{"),I("}"),ae,C,C)):o&&"namespace"==t?(h.marked="keyword",g(I("form"),W,N,C)):o&&"abstract"==t?(h.marked="keyword",g(N)):g(I("stat"),X):"switch"==e?g(I("form"),D,S("{"),I("}","switch"),q,ae,C,C,E):"case"==e?g(W,S(":")):"default"==e?g(S(":")):"catch"==e?g(I("form"),_,P,N,C,E):"export"==e?g(I("stat"),Be,C):"import"==e?g(I("stat"),Fe,C):"async"==e?g(N):"@"==t?g(W,N):x(I("stat"),W,S(";"),C)}function P(e){if("("==e)return g(Ie,S(")"))}function W(e,t){return F(e,t,!1)}function B(e,t){return F(e,t,!0)}function D(e){return"("!=e?x():g(I(")"),U,S(")"),C)}function F(e,t,r){if(h.state.fatArrowAt==h.stream.start){var n=r?M:L;if("("==e)return g(_,I(")"),re(Ie,")"),C,S("=>"),n,E);if("variable"==e)return x(_,xe,S("=>"),n,E)}var a=r?H:G;return y.hasOwnProperty(e)?g(a):"function"==e?g(_e,a):"class"==e||o&&"interface"==t?(h.marked="keyword",g(I("form"),Ce,C)):"keyword c"==e||"async"==e?g(r?B:W):"("==e?g(I(")"),U,S(")"),C,a):"operator"==e||"spread"==e?g(r?B:W):"["==e?g(I("]"),Ke,C,a):"{"==e?ne(Z,"}",null,a):"quasi"==e?x(J,a):"new"==e?g(function(e){return function(t){return"."==t?g(e?R:Q):"variable"==t&&o?g(ye,e?H:G):x(e?B:W)}}(r)):g()}function U(e){return e.match(/[;\}\)\],]/)?x():x(W)}function G(e,t){return","==e?g(U):H(e,t,!1)}function H(e,t,r){var n=0==r?G:H,a=0==r?W:B;return"=>"==e?g(_,r?M:L,E):"operator"==e?/\+\+|--/.test(t)||o&&"!"==t?g(n):o&&"<"==t&&h.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/,!1)?g(I(">"),re(ce,">"),C,n):"?"==t?g(W,S(":"),a):g(a):"quasi"==e?x(J,n):";"!=e?"("==e?ne(B,")","call",n):"."==e?g(Y,n):"["==e?g(I("]"),U,S("]"),C,n):o&&"as"==t?(h.marked="keyword",g(ce,n)):"regexp"==e?(h.state.lastType=h.marked="operator",h.stream.backUp(h.stream.pos-h.stream.start-1),g(a)):void 0:void 0}function J(e,t){return"quasi"!=e?x():"${"!=t.slice(t.length-2)?g(J):g(U,K)}function K(e){if("}"==e)return h.marked="string.special",h.state.tokenize=p,g(J)}function L(e){return v(h.stream,h.state),x("{"==e?N:W)}function M(e){return v(h.stream,h.state),x("{"==e?N:B)}function Q(e,t){if("target"==t)return h.marked="keyword",g(G)}function R(e,t){if("target"==t)return h.marked="keyword",g(H)}function X(e){return":"==e?g(C,N):x(G,S(";"),C)}function Y(e){if("variable"==e)return h.marked="property",g()}function Z(e,t){return"async"==e?(h.marked="property",g(Z)):"variable"==e||"keyword"==h.style?(h.marked="property","get"==t||"set"==t?g(ee):(o&&h.state.fatArrowAt==h.stream.start&&(r=h.stream.match(/^\s*:\s*/,!1))&&(h.state.fatArrowAt=h.stream.pos+r[0].length),g(te))):"number"==e||"string"==e?(h.marked=a?"property":h.style+" property",g(te)):"jsonld-keyword"==e?g(te):o&&j(t)?(h.marked="keyword",g(Z)):"["==e?g(W,ie,S("]"),te):"spread"==e?g(B,te):"*"==t?(h.marked="keyword",g(Z)):":"==e?x(te):void 0;var r}function ee(e){return"variable"!=e?x(te):(h.marked="property",g(_e))}function te(e){return":"==e?g(B):"("==e?x(_e):void 0}function re(e,t,r){function n(a,i){if(r?r.indexOf(a)>-1:","==a){var o=h.state.lexical;return"call"==o.info&&(o.pos=(o.pos||0)+1),g((function(r,n){return r==t||n==t?x():x(e)}),n)}return a==t||i==t?g():r&&r.indexOf(";")>-1?x(e):g(S(t))}return function(r,a){return r==t||a==t?g():x(e,n)}}function ne(e,t,r){for(var n=3;n"),ce):"quasi"==e?x(me,ve):void 0}function le(e){if("=>"==e)return g(ce)}function fe(e){return e.match(/[\}\)\]]/)?g():","==e||";"==e?g(fe):x(de,fe)}function de(e,t){return"variable"==e||"keyword"==h.style?(h.marked="property",g(de)):"?"==t||"number"==e||"string"==e?g(de):":"==e?g(ce):"["==e?g(S("variable"),oe,S("]"),de):"("==e?x(qe,de):e.match(/[;\}\)\],]/)?void 0:g()}function me(e,t){return"quasi"!=e?x():"${"!=t.slice(t.length-2)?g(me):g(ce,pe)}function pe(e){if("}"==e)return h.marked="string.special",h.state.tokenize=p,g(me)}function ke(e,t){return"variable"==e&&h.stream.match(/^\s*[?:]/,!1)||"?"==t?g(ke):":"==e?g(ce):"spread"==e?g(ke):x(ce)}function ve(e,t){return"<"==t?g(I(">"),re(ce,">"),C,ve):"|"==t||"."==e||"&"==t?g(ce):"["==e?g(ce,S("]"),ve):"extends"==t||"implements"==t?(h.marked="keyword",g(ce)):"?"==t?g(ce,S(":"),ce):void 0}function ye(e,t){if("<"==t)return g(I(">"),re(ce,">"),C,ve)}function we(){return x(ce,be)}function be(e,t){if("="==t)return g(ce)}function he(e,t){return"enum"==t?(h.marked="keyword",g(Le)):x(xe,ie,Ae,ze)}function xe(e,t){return o&&j(t)?(h.marked="keyword",g(xe)):"variable"==e?(A(t),g()):"spread"==e?g(xe):"["==e?ne(Ve,"]"):"{"==e?ne(ge,"}"):void 0}function ge(e,t){return"variable"!=e||h.stream.match(/^\s*:/,!1)?("variable"==e&&(h.marked="property"),"spread"==e?g(xe):"}"==e?x():"["==e?g(W,S("]"),S(":"),ge):g(S(":"),xe,Ae)):(A(t),g(Ae))}function Ve(){return x(xe,Ae)}function Ae(e,t){if("="==t)return g(B)}function ze(e){if(","==e)return g(he)}function je(e,t){if("keyword b"==e&&"else"==t)return g(I("form","else"),N,C)}function Te(e,t){return"await"==t?g(Te):"("==e?g(I(")"),$e,C):void 0}function $e(e){return"var"==e?g(he,Oe):"variable"==e?g(Oe):x(Oe)}function Oe(e,t){return")"==e?g():";"==e?g(Oe):"in"==t||"of"==t?(h.marked="keyword",g(W,Oe)):x(W,Oe)}function _e(e,t){return"*"==t?(h.marked="keyword",g(_e)):"variable"==e?(A(t),g(_e)):"("==e?g(_,I(")"),re(Ie,")"),C,ue,N,E):o&&"<"==t?g(I(">"),re(we,">"),C,_e):void 0}function qe(e,t){return"*"==t?(h.marked="keyword",g(qe)):"variable"==e?(A(t),g(qe)):"("==e?g(_,I(")"),re(Ie,")"),C,ue,E):o&&"<"==t?g(I(">"),re(we,">"),C,qe):void 0}function Ee(e,t){return"keyword"==e||"variable"==e?(h.marked="type",g(Ee)):"<"==t?g(I(">"),re(we,">"),C):void 0}function Ie(e,t){return"@"==t&&g(W,Ie),"spread"==e?g(Ie):o&&j(t)?(h.marked="keyword",g(Ie)):o&&"this"==e?g(ie,Ae):x(xe,ie,Ae)}function Ce(e,t){return"variable"==e?Se(e,t):Ne(e,t)}function Se(e,t){if("variable"==e)return A(t),g(Ne)}function Ne(e,t){return"<"==t?g(I(">"),re(we,">"),C,Ne):"extends"==t||"implements"==t||o&&","==e?("implements"==t&&(h.marked="keyword"),g(o?ce:W,Ne)):"{"==e?g(I("}"),Pe,C):void 0}function Pe(e,t){return"async"==e||"variable"==e&&("static"==t||"get"==t||"set"==t||o&&j(t))&&h.stream.match(/^\s+#?[\w$\xa1-\uffff]/,!1)?(h.marked="keyword",g(Pe)):"variable"==e||"keyword"==h.style?(h.marked="property",g(We,Pe)):"number"==e||"string"==e?g(We,Pe):"["==e?g(W,ie,S("]"),We,Pe):"*"==t?(h.marked="keyword",g(Pe)):o&&"("==e?x(qe,Pe):";"==e||","==e?g(Pe):"}"==e?g():"@"==t?g(W,Pe):void 0}function We(e,t){if("!"==t||"?"==t)return g(We);if(":"==e)return g(ce,Ae);if("="==t)return g(B);var r=h.state.lexical.prev;return x(r&&"interface"==r.info?qe:_e)}function Be(e,t){return"*"==t?(h.marked="keyword",g(Je,S(";"))):"default"==t?(h.marked="keyword",g(W,S(";"))):"{"==e?g(re(De,"}"),Je,S(";")):x(N)}function De(e,t){return"as"==t?(h.marked="keyword",g(S("variable"))):"variable"==e?x(B,De):void 0}function Fe(e){return"string"==e?g():"("==e?x(W):"."==e?x(G):x(Ue,Ge,Je)}function Ue(e,t){return"{"==e?ne(Ue,"}"):("variable"==e&&A(t),"*"==t&&(h.marked="keyword"),g(He))}function Ge(e){if(","==e)return g(Ue,Ge)}function He(e,t){if("as"==t)return h.marked="keyword",g(Ue)}function Je(e,t){if("from"==t)return h.marked="keyword",g(W)}function Ke(e){return"]"==e?g():x(re(B,"]"))}function Le(){return x(I("form"),xe,S("{"),I("}"),re(Me,"}"),C,C)}function Me(){return x(xe,Ae)}return _.lex=q.lex=!0,E.lex=!0,C.lex=!0,{name:e.name,startState:function(t){var r={tokenize:d,lastType:"sof",cc:[],lexical:new w(-t,0,"block",!1),localVars:e.localVars,context:e.localVars&&new T(null,null,!1),indented:0};return e.globalVars&&"object"==typeof e.globalVars&&(r.globalVars=e.globalVars),r},token:function(e,n){if(e.sol()&&(n.lexical.hasOwnProperty("align")||(n.lexical.align=!1),n.indented=e.indentation(),v(e,n)),n.tokenize!=m&&e.eatSpace())return null;var a=n.tokenize(e,n);return"comment"==t?a:(n.lastType="operator"!=t||"++"!=r&&"--"!=r?t:"incdec",function(e,t,r,n,a){var o=e.cc;for(h.state=e,h.stream=a,h.marked=null,h.cc=o,h.style=t,e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);;)if((o.length?o.pop():i?W:N)(r,n)){for(;o.length&&o[o.length-1].lex;)o.pop()();return h.marked?h.marked:"variable"==r&&b(e,n)?"variableName.local":t}}(n,a,t,r,e))},indent:function(t,r,a){if(t.tokenize==m||t.tokenize==p)return null;if(t.tokenize!=d)return 0;var i,o=r&&r.charAt(0),u=t.lexical;if(!/^\s*else\b/.test(r))for(var s=t.cc.length-1;s>=0;--s){var l=t.cc[s];if(l==C)u=u.prev;else if(l!=je&&l!=E)break}for(;("stat"==u.type||"form"==u.type)&&("}"==o||(i=t.cc[t.cc.length-1])&&(i==G||i==H)&&!/^[,\.=+\-*:?[\(]/.test(r));)u=u.prev;n&&")"==u.type&&"stat"==u.prev.type&&(u=u.prev);var f=u.type,k=o==f;return"vardef"==f?u.indented+("operator"==t.lastType||","==t.lastType?u.info.length+1:0):"form"==f&&"{"==o?u.indented:"form"==f?u.indented+a.unit:"stat"==f?u.indented+(function(e,t){return"operator"==e.lastType||","==e.lastType||c.test(t.charAt(0))||/[,.]/.test(t.charAt(0))}(t,r)?n||a.unit:0):"switch"!=u.info||k||0==e.doubleIndentSwitch?u.align?u.column+(k?0:1):u.indented+(k?0:a.unit):u.indented+(/^(?:case|default)\b/.test(r)?a.unit:2*a.unit)},languageData:{indentOnInput:/^\s*(?:case .*?:|default:|\{|\})$/,commentTokens:i?void 0:{line:"//",block:{open:"/*",close:"*/"}},closeBrackets:{brackets:["(","[","{","'",'"',"`"]},wordChars:"$"}}}r.r(t),r.d(t,{javascript:()=>a,json:()=>i,jsonld:()=>o,typescript:()=>u});const a=n({name:"javascript"}),i=n({name:"json",json:!0}),o=n({name:"json",jsonld:!0}),u=n({name:"typescript",typescript:!0})}}]); +//# sourceMappingURL=3747.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/3747.index.js.map b/book/_build/html/_static/3747.index.js.map new file mode 100644 index 0000000..5072a4a --- /dev/null +++ b/book/_build/html/_static/3747.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"3747.index.js","mappings":"8FAAA,SAASA,EAAaC,GACpB,IA4CIC,EAAMC,EA5CNC,EAAkBH,EAAaG,gBAC/BC,EAAaJ,EAAaK,OAC1BC,EAAWN,EAAaO,MAAQH,EAChCI,EAAOR,EAAaS,WACpBC,EAASV,EAAaW,gBAAkB,mBAIxCC,EAAW,WACb,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,IAAK,IAAK,IAAK,IAAK,IAAK,MACpDoK,UAAW,KAGjB,C,0EAEO,MAAMC,EAAa9N,EAAa,CAACiF,KAAM,eACjCzE,EAAOR,EAAa,CAACiF,KAAM,OAAQzE,MAAM,IACzCF,EAASN,EAAa,CAACiF,KAAM,OAAQ3E,QAAQ,IAC7CI,EAAaV,EAAa,CAACiF,KAAM,aAAcvE,YAAY,G","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/javascript.js"],"sourcesContent":["function mkJavaScript(parserConfig) {\n var statementIndent = parserConfig.statementIndent;\n var jsonldMode = parserConfig.jsonld;\n var jsonMode = parserConfig.json || jsonldMode;\n var isTS = parserConfig.typescript;\n var wordRE = parserConfig.wordCharacters || /[\\w$\\xa1-\\uffff]/;\n\n // Tokenizer\n\n var keywords = function(){\n function kw(type) {return {type: type, style: \"keyword\"};}\n var A = kw(\"keyword a\"), B = kw(\"keyword b\"), C = kw(\"keyword c\"), D = kw(\"keyword d\");\n var operator = kw(\"operator\"), atom = {type: \"atom\", style: \"atom\"};\n\n return {\n \"if\": kw(\"if\"), \"while\": A, \"with\": A, \"else\": B, \"do\": B, \"try\": B, \"finally\": B,\n \"return\": D, \"break\": D, \"continue\": D, \"new\": kw(\"new\"), \"delete\": C, \"void\": C, \"throw\": C,\n \"debugger\": kw(\"debugger\"), \"var\": kw(\"var\"), \"const\": kw(\"var\"), \"let\": kw(\"var\"),\n \"function\": kw(\"function\"), \"catch\": kw(\"catch\"),\n \"for\": kw(\"for\"), \"switch\": kw(\"switch\"), \"case\": kw(\"case\"), \"default\": kw(\"default\"),\n \"in\": operator, \"typeof\": operator, \"instanceof\": operator,\n \"true\": atom, \"false\": atom, \"null\": atom, \"undefined\": atom, \"NaN\": atom, \"Infinity\": atom,\n \"this\": kw(\"this\"), \"class\": kw(\"class\"), \"super\": kw(\"atom\"),\n \"yield\": C, \"export\": kw(\"export\"), \"import\": kw(\"import\"), \"extends\": C,\n \"await\": C\n };\n }();\n\n var isOperatorChar = /[+\\-*&%=<>!?|~^@]/;\n var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)\"/;\n\n function readRegexp(stream) {\n var escaped = false, next, inSet = false;\n while ((next = stream.next()) != null) {\n if (!escaped) {\n if (next == \"/\" && !inSet) return;\n if (next == \"[\") inSet = true;\n else if (inSet && next == \"]\") inSet = false;\n }\n escaped = !escaped && next == \"\\\\\";\n }\n }\n\n // Used as scratch variables to communicate multiple values without\n // consing up tons of objects.\n var type, content;\n function ret(tp, style, cont) {\n type = tp; content = cont;\n return style;\n }\n function tokenBase(stream, state) {\n var ch = stream.next();\n if (ch == '\"' || ch == \"'\") {\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n } else if (ch == \".\" && stream.match(/^\\d[\\d_]*(?:[eE][+\\-]?[\\d_]+)?/)) {\n return ret(\"number\", \"number\");\n } else if (ch == \".\" && stream.match(\"..\")) {\n return ret(\"spread\", \"meta\");\n } else if (/[\\[\\]{}\\(\\),;\\:\\.]/.test(ch)) {\n return ret(ch);\n } else if (ch == \"=\" && stream.eat(\">\")) {\n return ret(\"=>\", \"operator\");\n } else if (ch == \"0\" && stream.match(/^(?:x[\\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) {\n return ret(\"number\", \"number\");\n } else if (/\\d/.test(ch)) {\n stream.match(/^[\\d_]*(?:n|(?:\\.[\\d_]*)?(?:[eE][+\\-]?[\\d_]+)?)?/);\n return ret(\"number\", \"number\");\n } else if (ch == \"/\") {\n if (stream.eat(\"*\")) {\n state.tokenize = tokenComment;\n return tokenComment(stream, state);\n } else if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return ret(\"comment\", \"comment\");\n } else if (expressionAllowed(stream, state, 1)) {\n readRegexp(stream);\n stream.match(/^\\b(([gimyus])(?![gimyus]*\\2))+\\b/);\n return ret(\"regexp\", \"string.special\");\n } else {\n stream.eat(\"=\");\n return ret(\"operator\", \"operator\", stream.current());\n }\n } else if (ch == \"`\") {\n state.tokenize = tokenQuasi;\n return tokenQuasi(stream, state);\n } else if (ch == \"#\" && stream.peek() == \"!\") {\n stream.skipToEnd();\n return ret(\"meta\", \"meta\");\n } else if (ch == \"#\" && stream.eatWhile(wordRE)) {\n return ret(\"variable\", \"property\")\n } else if (ch == \"<\" && stream.match(\"!--\") ||\n (ch == \"-\" && stream.match(\"->\") && !/\\S/.test(stream.string.slice(0, stream.start)))) {\n stream.skipToEnd()\n return ret(\"comment\", \"comment\")\n } else if (isOperatorChar.test(ch)) {\n if (ch != \">\" || !state.lexical || state.lexical.type != \">\") {\n if (stream.eat(\"=\")) {\n if (ch == \"!\" || ch == \"=\") stream.eat(\"=\")\n } else if (/[<>*+\\-|&?]/.test(ch)) {\n stream.eat(ch)\n if (ch == \">\") stream.eat(ch)\n }\n }\n if (ch == \"?\" && stream.eat(\".\")) return ret(\".\")\n return ret(\"operator\", \"operator\", stream.current());\n } else if (wordRE.test(ch)) {\n stream.eatWhile(wordRE);\n var word = stream.current()\n if (state.lastType != \".\") {\n if (keywords.propertyIsEnumerable(word)) {\n var kw = keywords[word]\n return ret(kw.type, kw.style, word)\n }\n if (word == \"async\" && stream.match(/^(\\s|\\/\\*([^*]|\\*(?!\\/))*?\\*\\/)*[\\[\\(\\w]/, false))\n return ret(\"async\", \"keyword\", word)\n }\n return ret(\"variable\", \"variable\", word)\n }\n }\n\n function tokenString(quote) {\n return function(stream, state) {\n var escaped = false, next;\n if (jsonldMode && stream.peek() == \"@\" && stream.match(isJsonldKeyword)){\n state.tokenize = tokenBase;\n return ret(\"jsonld-keyword\", \"meta\");\n }\n while ((next = stream.next()) != null) {\n if (next == quote && !escaped) break;\n escaped = !escaped && next == \"\\\\\";\n }\n if (!escaped) state.tokenize = tokenBase;\n return ret(\"string\", \"string\");\n };\n }\n\n function tokenComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if (ch == \"/\" && maybeEnd) {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return ret(\"comment\", \"comment\");\n }\n\n function tokenQuasi(stream, state) {\n var escaped = false, next;\n while ((next = stream.next()) != null) {\n if (!escaped && (next == \"`\" || next == \"$\" && stream.eat(\"{\"))) {\n state.tokenize = tokenBase;\n break;\n }\n escaped = !escaped && next == \"\\\\\";\n }\n return ret(\"quasi\", \"string.special\", stream.current());\n }\n\n var brackets = \"([{}])\";\n // This is a crude lookahead trick to try and notice that we're\n // parsing the argument patterns for a fat-arrow function before we\n // actually hit the arrow token. It only works if the arrow is on\n // the same line as the arguments and there's no strange noise\n // (comments) in between. Fallback is to only notice when we hit the\n // arrow, and not declare the arguments as locals for the arrow\n // body.\n function findFatArrow(stream, state) {\n if (state.fatArrowAt) state.fatArrowAt = null;\n var arrow = stream.string.indexOf(\"=>\", stream.start);\n if (arrow < 0) return;\n\n if (isTS) { // Try to skip TypeScript return type declarations after the arguments\n var m = /:\\s*(?:\\w+(?:<[^>]*>|\\[\\])?|\\{[^}]*\\})\\s*$/.exec(stream.string.slice(stream.start, arrow))\n if (m) arrow = m.index\n }\n\n var depth = 0, sawSomething = false;\n for (var pos = arrow - 1; pos >= 0; --pos) {\n var ch = stream.string.charAt(pos);\n var bracket = brackets.indexOf(ch);\n if (bracket >= 0 && bracket < 3) {\n if (!depth) { ++pos; break; }\n if (--depth == 0) { if (ch == \"(\") sawSomething = true; break; }\n } else if (bracket >= 3 && bracket < 6) {\n ++depth;\n } else if (wordRE.test(ch)) {\n sawSomething = true;\n } else if (/[\"'\\/`]/.test(ch)) {\n for (;; --pos) {\n if (pos == 0) return\n var next = stream.string.charAt(pos - 1)\n if (next == ch && stream.string.charAt(pos - 2) != \"\\\\\") { pos--; break }\n }\n } else if (sawSomething && !depth) {\n ++pos;\n break;\n }\n }\n if (sawSomething && !depth) state.fatArrowAt = pos;\n }\n\n // Parser\n\n var atomicTypes = {\"atom\": true, \"number\": true, \"variable\": true, \"string\": true,\n \"regexp\": true, \"this\": true, \"import\": true, \"jsonld-keyword\": true};\n\n function JSLexical(indented, column, type, align, prev, info) {\n this.indented = indented;\n this.column = column;\n this.type = type;\n this.prev = prev;\n this.info = info;\n if (align != null) this.align = align;\n }\n\n function inScope(state, varname) {\n for (var v = state.localVars; v; v = v.next)\n if (v.name == varname) return true;\n for (var cx = state.context; cx; cx = cx.prev) {\n for (var v = cx.vars; v; v = v.next)\n if (v.name == varname) return true;\n }\n }\n\n function parseJS(state, style, type, content, stream) {\n var cc = state.cc;\n // Communicate our context to the combinators.\n // (Less wasteful than consing up a hundred closures on every call.)\n cx.state = state; cx.stream = stream; cx.marked = null; cx.cc = cc; cx.style = style;\n\n if (!state.lexical.hasOwnProperty(\"align\"))\n state.lexical.align = true;\n\n while(true) {\n var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;\n if (combinator(type, content)) {\n while(cc.length && cc[cc.length - 1].lex)\n cc.pop()();\n if (cx.marked) return cx.marked;\n if (type == \"variable\" && inScope(state, content)) return \"variableName.local\";\n return style;\n }\n }\n }\n\n // Combinator utils\n\n var cx = {state: null, column: null, marked: null, cc: null};\n function pass() {\n for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);\n }\n function cont() {\n pass.apply(null, arguments);\n return true;\n }\n function inList(name, list) {\n for (var v = list; v; v = v.next) if (v.name == name) return true\n return false;\n }\n function register(varname) {\n var state = cx.state;\n cx.marked = \"def\";\n if (state.context) {\n if (state.lexical.info == \"var\" && state.context && state.context.block) {\n // FIXME function decls are also not block scoped\n var newContext = registerVarScoped(varname, state.context)\n if (newContext != null) {\n state.context = newContext\n return\n }\n } else if (!inList(varname, state.localVars)) {\n state.localVars = new Var(varname, state.localVars)\n return\n }\n }\n // Fall through means this is global\n if (parserConfig.globalVars && !inList(varname, state.globalVars))\n state.globalVars = new Var(varname, state.globalVars)\n }\n function registerVarScoped(varname, context) {\n if (!context) {\n return null\n } else if (context.block) {\n var inner = registerVarScoped(varname, context.prev)\n if (!inner) return null\n if (inner == context.prev) return context\n return new Context(inner, context.vars, true)\n } else if (inList(varname, context.vars)) {\n return context\n } else {\n return new Context(context.prev, new Var(varname, context.vars), false)\n }\n }\n\n function isModifier(name) {\n return name == \"public\" || name == \"private\" || name == \"protected\" || name == \"abstract\" || name == \"readonly\"\n }\n\n // Combinators\n\n function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block }\n function Var(name, next) { this.name = name; this.next = next }\n\n var defaultVars = new Var(\"this\", new Var(\"arguments\", null))\n function pushcontext() {\n cx.state.context = new Context(cx.state.context, cx.state.localVars, false)\n cx.state.localVars = defaultVars\n }\n function pushblockcontext() {\n cx.state.context = new Context(cx.state.context, cx.state.localVars, true)\n cx.state.localVars = null\n }\n pushcontext.lex = pushblockcontext.lex = true\n function popcontext() {\n cx.state.localVars = cx.state.context.vars\n cx.state.context = cx.state.context.prev\n }\n popcontext.lex = true\n function pushlex(type, info) {\n var result = function() {\n var state = cx.state, indent = state.indented;\n if (state.lexical.type == \"stat\") indent = state.lexical.indented;\n else for (var outer = state.lexical; outer && outer.type == \")\" && outer.align; outer = outer.prev)\n indent = outer.indented;\n state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);\n };\n result.lex = true;\n return result;\n }\n function poplex() {\n var state = cx.state;\n if (state.lexical.prev) {\n if (state.lexical.type == \")\")\n state.indented = state.lexical.indented;\n state.lexical = state.lexical.prev;\n }\n }\n poplex.lex = true;\n\n function expect(wanted) {\n function exp(type) {\n if (type == wanted) return cont();\n else if (wanted == \";\" || type == \"}\" || type == \")\" || type == \"]\") return pass();\n else return cont(exp);\n };\n return exp;\n }\n\n function statement(type, value) {\n if (type == \"var\") return cont(pushlex(\"vardef\", value), vardef, expect(\";\"), poplex);\n if (type == \"keyword a\") return cont(pushlex(\"form\"), parenExpr, statement, poplex);\n if (type == \"keyword b\") return cont(pushlex(\"form\"), statement, poplex);\n if (type == \"keyword d\") return cx.stream.match(/^\\s*$/, false) ? cont() : cont(pushlex(\"stat\"), maybeexpression, expect(\";\"), poplex);\n if (type == \"debugger\") return cont(expect(\";\"));\n if (type == \"{\") return cont(pushlex(\"}\"), pushblockcontext, block, poplex, popcontext);\n if (type == \";\") return cont();\n if (type == \"if\") {\n if (cx.state.lexical.info == \"else\" && cx.state.cc[cx.state.cc.length - 1] == poplex)\n cx.state.cc.pop()();\n return cont(pushlex(\"form\"), parenExpr, statement, poplex, maybeelse);\n }\n if (type == \"function\") return cont(functiondef);\n if (type == \"for\") return cont(pushlex(\"form\"), pushblockcontext, forspec, statement, popcontext, poplex);\n if (type == \"class\" || (isTS && value == \"interface\")) {\n cx.marked = \"keyword\"\n return cont(pushlex(\"form\", type == \"class\" ? type : value), className, poplex)\n }\n if (type == \"variable\") {\n if (isTS && value == \"declare\") {\n cx.marked = \"keyword\"\n return cont(statement)\n } else if (isTS && (value == \"module\" || value == \"enum\" || value == \"type\") && cx.stream.match(/^\\s*\\w/, false)) {\n cx.marked = \"keyword\"\n if (value == \"enum\") return cont(enumdef);\n else if (value == \"type\") return cont(typename, expect(\"operator\"), typeexpr, expect(\";\"));\n else return cont(pushlex(\"form\"), pattern, expect(\"{\"), pushlex(\"}\"), block, poplex, poplex)\n } else if (isTS && value == \"namespace\") {\n cx.marked = \"keyword\"\n return cont(pushlex(\"form\"), expression, statement, poplex)\n } else if (isTS && value == \"abstract\") {\n cx.marked = \"keyword\"\n return cont(statement)\n } else {\n return cont(pushlex(\"stat\"), maybelabel);\n }\n }\n if (type == \"switch\") return cont(pushlex(\"form\"), parenExpr, expect(\"{\"), pushlex(\"}\", \"switch\"), pushblockcontext,\n block, poplex, poplex, popcontext);\n if (type == \"case\") return cont(expression, expect(\":\"));\n if (type == \"default\") return cont(expect(\":\"));\n if (type == \"catch\") return cont(pushlex(\"form\"), pushcontext, maybeCatchBinding, statement, poplex, popcontext);\n if (type == \"export\") return cont(pushlex(\"stat\"), afterExport, poplex);\n if (type == \"import\") return cont(pushlex(\"stat\"), afterImport, poplex);\n if (type == \"async\") return cont(statement)\n if (value == \"@\") return cont(expression, statement)\n return pass(pushlex(\"stat\"), expression, expect(\";\"), poplex);\n }\n function maybeCatchBinding(type) {\n if (type == \"(\") return cont(funarg, expect(\")\"))\n }\n function expression(type, value) {\n return expressionInner(type, value, false);\n }\n function expressionNoComma(type, value) {\n return expressionInner(type, value, true);\n }\n function parenExpr(type) {\n if (type != \"(\") return pass()\n return cont(pushlex(\")\"), maybeexpression, expect(\")\"), poplex)\n }\n function expressionInner(type, value, noComma) {\n if (cx.state.fatArrowAt == cx.stream.start) {\n var body = noComma ? arrowBodyNoComma : arrowBody;\n if (type == \"(\") return cont(pushcontext, pushlex(\")\"), commasep(funarg, \")\"), poplex, expect(\"=>\"), body, popcontext);\n else if (type == \"variable\") return pass(pushcontext, pattern, expect(\"=>\"), body, popcontext);\n }\n\n var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;\n if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);\n if (type == \"function\") return cont(functiondef, maybeop);\n if (type == \"class\" || (isTS && value == \"interface\")) { cx.marked = \"keyword\"; return cont(pushlex(\"form\"), classExpression, poplex); }\n if (type == \"keyword c\" || type == \"async\") return cont(noComma ? expressionNoComma : expression);\n if (type == \"(\") return cont(pushlex(\")\"), maybeexpression, expect(\")\"), poplex, maybeop);\n if (type == \"operator\" || type == \"spread\") return cont(noComma ? expressionNoComma : expression);\n if (type == \"[\") return cont(pushlex(\"]\"), arrayLiteral, poplex, maybeop);\n if (type == \"{\") return contCommasep(objprop, \"}\", null, maybeop);\n if (type == \"quasi\") return pass(quasi, maybeop);\n if (type == \"new\") return cont(maybeTarget(noComma));\n return cont();\n }\n function maybeexpression(type) {\n if (type.match(/[;\\}\\)\\],]/)) return pass();\n return pass(expression);\n }\n\n function maybeoperatorComma(type, value) {\n if (type == \",\") return cont(maybeexpression);\n return maybeoperatorNoComma(type, value, false);\n }\n function maybeoperatorNoComma(type, value, noComma) {\n var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;\n var expr = noComma == false ? expression : expressionNoComma;\n if (type == \"=>\") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);\n if (type == \"operator\") {\n if (/\\+\\+|--/.test(value) || isTS && value == \"!\") return cont(me);\n if (isTS && value == \"<\" && cx.stream.match(/^([^<>]|<[^<>]*>)*>\\s*\\(/, false))\n return cont(pushlex(\">\"), commasep(typeexpr, \">\"), poplex, me);\n if (value == \"?\") return cont(expression, expect(\":\"), expr);\n return cont(expr);\n }\n if (type == \"quasi\") { return pass(quasi, me); }\n if (type == \";\") return;\n if (type == \"(\") return contCommasep(expressionNoComma, \")\", \"call\", me);\n if (type == \".\") return cont(property, me);\n if (type == \"[\") return cont(pushlex(\"]\"), maybeexpression, expect(\"]\"), poplex, me);\n if (isTS && value == \"as\") { cx.marked = \"keyword\"; return cont(typeexpr, me) }\n if (type == \"regexp\") {\n cx.state.lastType = cx.marked = \"operator\"\n cx.stream.backUp(cx.stream.pos - cx.stream.start - 1)\n return cont(expr)\n }\n }\n function quasi(type, value) {\n if (type != \"quasi\") return pass();\n if (value.slice(value.length - 2) != \"${\") return cont(quasi);\n return cont(maybeexpression, continueQuasi);\n }\n function continueQuasi(type) {\n if (type == \"}\") {\n cx.marked = \"string.special\";\n cx.state.tokenize = tokenQuasi;\n return cont(quasi);\n }\n }\n function arrowBody(type) {\n findFatArrow(cx.stream, cx.state);\n return pass(type == \"{\" ? statement : expression);\n }\n function arrowBodyNoComma(type) {\n findFatArrow(cx.stream, cx.state);\n return pass(type == \"{\" ? statement : expressionNoComma);\n }\n function maybeTarget(noComma) {\n return function(type) {\n if (type == \".\") return cont(noComma ? targetNoComma : target);\n else if (type == \"variable\" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma)\n else return pass(noComma ? expressionNoComma : expression);\n };\n }\n function target(_, value) {\n if (value == \"target\") { cx.marked = \"keyword\"; return cont(maybeoperatorComma); }\n }\n function targetNoComma(_, value) {\n if (value == \"target\") { cx.marked = \"keyword\"; return cont(maybeoperatorNoComma); }\n }\n function maybelabel(type) {\n if (type == \":\") return cont(poplex, statement);\n return pass(maybeoperatorComma, expect(\";\"), poplex);\n }\n function property(type) {\n if (type == \"variable\") {cx.marked = \"property\"; return cont();}\n }\n function objprop(type, value) {\n if (type == \"async\") {\n cx.marked = \"property\";\n return cont(objprop);\n } else if (type == \"variable\" || cx.style == \"keyword\") {\n cx.marked = \"property\";\n if (value == \"get\" || value == \"set\") return cont(getterSetter);\n var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params\n if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\\s*:\\s*/, false)))\n cx.state.fatArrowAt = cx.stream.pos + m[0].length\n return cont(afterprop);\n } else if (type == \"number\" || type == \"string\") {\n cx.marked = jsonldMode ? \"property\" : (cx.style + \" property\");\n return cont(afterprop);\n } else if (type == \"jsonld-keyword\") {\n return cont(afterprop);\n } else if (isTS && isModifier(value)) {\n cx.marked = \"keyword\"\n return cont(objprop)\n } else if (type == \"[\") {\n return cont(expression, maybetype, expect(\"]\"), afterprop);\n } else if (type == \"spread\") {\n return cont(expressionNoComma, afterprop);\n } else if (value == \"*\") {\n cx.marked = \"keyword\";\n return cont(objprop);\n } else if (type == \":\") {\n return pass(afterprop)\n }\n }\n function getterSetter(type) {\n if (type != \"variable\") return pass(afterprop);\n cx.marked = \"property\";\n return cont(functiondef);\n }\n function afterprop(type) {\n if (type == \":\") return cont(expressionNoComma);\n if (type == \"(\") return pass(functiondef);\n }\n function commasep(what, end, sep) {\n function proceed(type, value) {\n if (sep ? sep.indexOf(type) > -1 : type == \",\") {\n var lex = cx.state.lexical;\n if (lex.info == \"call\") lex.pos = (lex.pos || 0) + 1;\n return cont(function(type, value) {\n if (type == end || value == end) return pass()\n return pass(what)\n }, proceed);\n }\n if (type == end || value == end) return cont();\n if (sep && sep.indexOf(\";\") > -1) return pass(what)\n return cont(expect(end));\n }\n return function(type, value) {\n if (type == end || value == end) return cont();\n return pass(what, proceed);\n };\n }\n function contCommasep(what, end, info) {\n for (var i = 3; i < arguments.length; i++)\n cx.cc.push(arguments[i]);\n return cont(pushlex(end, info), commasep(what, end), poplex);\n }\n function block(type) {\n if (type == \"}\") return cont();\n return pass(statement, block);\n }\n function maybetype(type, value) {\n if (isTS) {\n if (type == \":\") return cont(typeexpr);\n if (value == \"?\") return cont(maybetype);\n }\n }\n function maybetypeOrIn(type, value) {\n if (isTS && (type == \":\" || value == \"in\")) return cont(typeexpr)\n }\n function mayberettype(type) {\n if (isTS && type == \":\") {\n if (cx.stream.match(/^\\s*\\w+\\s+is\\b/, false)) return cont(expression, isKW, typeexpr)\n else return cont(typeexpr)\n }\n }\n function isKW(_, value) {\n if (value == \"is\") {\n cx.marked = \"keyword\"\n return cont()\n }\n }\n function typeexpr(type, value) {\n if (value == \"keyof\" || value == \"typeof\" || value == \"infer\" || value == \"readonly\") {\n cx.marked = \"keyword\"\n return cont(value == \"typeof\" ? expressionNoComma : typeexpr)\n }\n if (type == \"variable\" || value == \"void\") {\n cx.marked = \"type\"\n return cont(afterType)\n }\n if (value == \"|\" || value == \"&\") return cont(typeexpr)\n if (type == \"string\" || type == \"number\" || type == \"atom\") return cont(afterType);\n if (type == \"[\") return cont(pushlex(\"]\"), commasep(typeexpr, \"]\", \",\"), poplex, afterType)\n if (type == \"{\") return cont(pushlex(\"}\"), typeprops, poplex, afterType)\n if (type == \"(\") return cont(commasep(typearg, \")\"), maybeReturnType, afterType)\n if (type == \"<\") return cont(commasep(typeexpr, \">\"), typeexpr)\n if (type == \"quasi\") return pass(quasiType, afterType)\n }\n function maybeReturnType(type) {\n if (type == \"=>\") return cont(typeexpr)\n }\n function typeprops(type) {\n if (type.match(/[\\}\\)\\]]/)) return cont()\n if (type == \",\" || type == \";\") return cont(typeprops)\n return pass(typeprop, typeprops)\n }\n function typeprop(type, value) {\n if (type == \"variable\" || cx.style == \"keyword\") {\n cx.marked = \"property\"\n return cont(typeprop)\n } else if (value == \"?\" || type == \"number\" || type == \"string\") {\n return cont(typeprop)\n } else if (type == \":\") {\n return cont(typeexpr)\n } else if (type == \"[\") {\n return cont(expect(\"variable\"), maybetypeOrIn, expect(\"]\"), typeprop)\n } else if (type == \"(\") {\n return pass(functiondecl, typeprop)\n } else if (!type.match(/[;\\}\\)\\],]/)) {\n return cont()\n }\n }\n function quasiType(type, value) {\n if (type != \"quasi\") return pass();\n if (value.slice(value.length - 2) != \"${\") return cont(quasiType);\n return cont(typeexpr, continueQuasiType);\n }\n function continueQuasiType(type) {\n if (type == \"}\") {\n cx.marked = \"string.special\";\n cx.state.tokenize = tokenQuasi;\n return cont(quasiType);\n }\n }\n function typearg(type, value) {\n if (type == \"variable\" && cx.stream.match(/^\\s*[?:]/, false) || value == \"?\") return cont(typearg)\n if (type == \":\") return cont(typeexpr)\n if (type == \"spread\") return cont(typearg)\n return pass(typeexpr)\n }\n function afterType(type, value) {\n if (value == \"<\") return cont(pushlex(\">\"), commasep(typeexpr, \">\"), poplex, afterType)\n if (value == \"|\" || type == \".\" || value == \"&\") return cont(typeexpr)\n if (type == \"[\") return cont(typeexpr, expect(\"]\"), afterType)\n if (value == \"extends\" || value == \"implements\") { cx.marked = \"keyword\"; return cont(typeexpr) }\n if (value == \"?\") return cont(typeexpr, expect(\":\"), typeexpr)\n }\n function maybeTypeArgs(_, value) {\n if (value == \"<\") return cont(pushlex(\">\"), commasep(typeexpr, \">\"), poplex, afterType)\n }\n function typeparam() {\n return pass(typeexpr, maybeTypeDefault)\n }\n function maybeTypeDefault(_, value) {\n if (value == \"=\") return cont(typeexpr)\n }\n function vardef(_, value) {\n if (value == \"enum\") {cx.marked = \"keyword\"; return cont(enumdef)}\n return pass(pattern, maybetype, maybeAssign, vardefCont);\n }\n function pattern(type, value) {\n if (isTS && isModifier(value)) { cx.marked = \"keyword\"; return cont(pattern) }\n if (type == \"variable\") { register(value); return cont(); }\n if (type == \"spread\") return cont(pattern);\n if (type == \"[\") return contCommasep(eltpattern, \"]\");\n if (type == \"{\") return contCommasep(proppattern, \"}\");\n }\n function proppattern(type, value) {\n if (type == \"variable\" && !cx.stream.match(/^\\s*:/, false)) {\n register(value);\n return cont(maybeAssign);\n }\n if (type == \"variable\") cx.marked = \"property\";\n if (type == \"spread\") return cont(pattern);\n if (type == \"}\") return pass();\n if (type == \"[\") return cont(expression, expect(']'), expect(':'), proppattern);\n return cont(expect(\":\"), pattern, maybeAssign);\n }\n function eltpattern() {\n return pass(pattern, maybeAssign)\n }\n function maybeAssign(_type, value) {\n if (value == \"=\") return cont(expressionNoComma);\n }\n function vardefCont(type) {\n if (type == \",\") return cont(vardef);\n }\n function maybeelse(type, value) {\n if (type == \"keyword b\" && value == \"else\") return cont(pushlex(\"form\", \"else\"), statement, poplex);\n }\n function forspec(type, value) {\n if (value == \"await\") return cont(forspec);\n if (type == \"(\") return cont(pushlex(\")\"), forspec1, poplex);\n }\n function forspec1(type) {\n if (type == \"var\") return cont(vardef, forspec2);\n if (type == \"variable\") return cont(forspec2);\n return pass(forspec2)\n }\n function forspec2(type, value) {\n if (type == \")\") return cont()\n if (type == \";\") return cont(forspec2)\n if (value == \"in\" || value == \"of\") { cx.marked = \"keyword\"; return cont(expression, forspec2) }\n return pass(expression, forspec2)\n }\n function functiondef(type, value) {\n if (value == \"*\") {cx.marked = \"keyword\"; return cont(functiondef);}\n if (type == \"variable\") {register(value); return cont(functiondef);}\n if (type == \"(\") return cont(pushcontext, pushlex(\")\"), commasep(funarg, \")\"), poplex, mayberettype, statement, popcontext);\n if (isTS && value == \"<\") return cont(pushlex(\">\"), commasep(typeparam, \">\"), poplex, functiondef)\n }\n function functiondecl(type, value) {\n if (value == \"*\") {cx.marked = \"keyword\"; return cont(functiondecl);}\n if (type == \"variable\") {register(value); return cont(functiondecl);}\n if (type == \"(\") return cont(pushcontext, pushlex(\")\"), commasep(funarg, \")\"), poplex, mayberettype, popcontext);\n if (isTS && value == \"<\") return cont(pushlex(\">\"), commasep(typeparam, \">\"), poplex, functiondecl)\n }\n function typename(type, value) {\n if (type == \"keyword\" || type == \"variable\") {\n cx.marked = \"type\"\n return cont(typename)\n } else if (value == \"<\") {\n return cont(pushlex(\">\"), commasep(typeparam, \">\"), poplex)\n }\n }\n function funarg(type, value) {\n if (value == \"@\") cont(expression, funarg)\n if (type == \"spread\") return cont(funarg);\n if (isTS && isModifier(value)) { cx.marked = \"keyword\"; return cont(funarg); }\n if (isTS && type == \"this\") return cont(maybetype, maybeAssign)\n return pass(pattern, maybetype, maybeAssign);\n }\n function classExpression(type, value) {\n // Class expressions may have an optional name.\n if (type == \"variable\") return className(type, value);\n return classNameAfter(type, value);\n }\n function className(type, value) {\n if (type == \"variable\") {register(value); return cont(classNameAfter);}\n }\n function classNameAfter(type, value) {\n if (value == \"<\") return cont(pushlex(\">\"), commasep(typeparam, \">\"), poplex, classNameAfter)\n if (value == \"extends\" || value == \"implements\" || (isTS && type == \",\")) {\n if (value == \"implements\") cx.marked = \"keyword\";\n return cont(isTS ? typeexpr : expression, classNameAfter);\n }\n if (type == \"{\") return cont(pushlex(\"}\"), classBody, poplex);\n }\n function classBody(type, value) {\n if (type == \"async\" ||\n (type == \"variable\" &&\n (value == \"static\" || value == \"get\" || value == \"set\" || (isTS && isModifier(value))) &&\n cx.stream.match(/^\\s+#?[\\w$\\xa1-\\uffff]/, false))) {\n cx.marked = \"keyword\";\n return cont(classBody);\n }\n if (type == \"variable\" || cx.style == \"keyword\") {\n cx.marked = \"property\";\n return cont(classfield, classBody);\n }\n if (type == \"number\" || type == \"string\") return cont(classfield, classBody);\n if (type == \"[\")\n return cont(expression, maybetype, expect(\"]\"), classfield, classBody)\n if (value == \"*\") {\n cx.marked = \"keyword\";\n return cont(classBody);\n }\n if (isTS && type == \"(\") return pass(functiondecl, classBody)\n if (type == \";\" || type == \",\") return cont(classBody);\n if (type == \"}\") return cont();\n if (value == \"@\") return cont(expression, classBody)\n }\n function classfield(type, value) {\n if (value == \"!\" || value == \"?\") return cont(classfield)\n if (type == \":\") return cont(typeexpr, maybeAssign)\n if (value == \"=\") return cont(expressionNoComma)\n var context = cx.state.lexical.prev, isInterface = context && context.info == \"interface\"\n return pass(isInterface ? functiondecl : functiondef)\n }\n function afterExport(type, value) {\n if (value == \"*\") { cx.marked = \"keyword\"; return cont(maybeFrom, expect(\";\")); }\n if (value == \"default\") { cx.marked = \"keyword\"; return cont(expression, expect(\";\")); }\n if (type == \"{\") return cont(commasep(exportField, \"}\"), maybeFrom, expect(\";\"));\n return pass(statement);\n }\n function exportField(type, value) {\n if (value == \"as\") { cx.marked = \"keyword\"; return cont(expect(\"variable\")); }\n if (type == \"variable\") return pass(expressionNoComma, exportField);\n }\n function afterImport(type) {\n if (type == \"string\") return cont();\n if (type == \"(\") return pass(expression);\n if (type == \".\") return pass(maybeoperatorComma);\n return pass(importSpec, maybeMoreImports, maybeFrom);\n }\n function importSpec(type, value) {\n if (type == \"{\") return contCommasep(importSpec, \"}\");\n if (type == \"variable\") register(value);\n if (value == \"*\") cx.marked = \"keyword\";\n return cont(maybeAs);\n }\n function maybeMoreImports(type) {\n if (type == \",\") return cont(importSpec, maybeMoreImports)\n }\n function maybeAs(_type, value) {\n if (value == \"as\") { cx.marked = \"keyword\"; return cont(importSpec); }\n }\n function maybeFrom(_type, value) {\n if (value == \"from\") { cx.marked = \"keyword\"; return cont(expression); }\n }\n function arrayLiteral(type) {\n if (type == \"]\") return cont();\n return pass(commasep(expressionNoComma, \"]\"));\n }\n function enumdef() {\n return pass(pushlex(\"form\"), pattern, expect(\"{\"), pushlex(\"}\"), commasep(enummember, \"}\"), poplex, poplex)\n }\n function enummember() {\n return pass(pattern, maybeAssign);\n }\n\n function isContinuedStatement(state, textAfter) {\n return state.lastType == \"operator\" || state.lastType == \",\" ||\n isOperatorChar.test(textAfter.charAt(0)) ||\n /[,.]/.test(textAfter.charAt(0));\n }\n\n function expressionAllowed(stream, state, backUp) {\n return state.tokenize == tokenBase &&\n /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\\[{}\\(,;:]|=>)$/.test(state.lastType) ||\n (state.lastType == \"quasi\" && /\\{\\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))\n }\n\n // Interface\n\n return {\n name: parserConfig.name,\n\n startState: function(indentUnit) {\n var state = {\n tokenize: tokenBase,\n lastType: \"sof\",\n cc: [],\n lexical: new JSLexical(-indentUnit, 0, \"block\", false),\n localVars: parserConfig.localVars,\n context: parserConfig.localVars && new Context(null, null, false),\n indented: 0\n };\n if (parserConfig.globalVars && typeof parserConfig.globalVars == \"object\")\n state.globalVars = parserConfig.globalVars;\n return state;\n },\n\n token: function(stream, state) {\n if (stream.sol()) {\n if (!state.lexical.hasOwnProperty(\"align\"))\n state.lexical.align = false;\n state.indented = stream.indentation();\n findFatArrow(stream, state);\n }\n if (state.tokenize != tokenComment && stream.eatSpace()) return null;\n var style = state.tokenize(stream, state);\n if (type == \"comment\") return style;\n state.lastType = type == \"operator\" && (content == \"++\" || content == \"--\") ? \"incdec\" : type;\n return parseJS(state, style, type, content, stream);\n },\n\n indent: function(state, textAfter, cx) {\n if (state.tokenize == tokenComment || state.tokenize == tokenQuasi) return null;\n if (state.tokenize != tokenBase) return 0;\n var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top\n // Kludge to prevent 'maybelse' from blocking lexical scope pops\n if (!/^\\s*else\\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {\n var c = state.cc[i];\n if (c == poplex) lexical = lexical.prev;\n else if (c != maybeelse && c != popcontext) break;\n }\n while ((lexical.type == \"stat\" || lexical.type == \"form\") &&\n (firstChar == \"}\" || ((top = state.cc[state.cc.length - 1]) &&\n (top == maybeoperatorComma || top == maybeoperatorNoComma) &&\n !/^[,\\.=+\\-*:?[\\(]/.test(textAfter))))\n lexical = lexical.prev;\n if (statementIndent && lexical.type == \")\" && lexical.prev.type == \"stat\")\n lexical = lexical.prev;\n var type = lexical.type, closing = firstChar == type;\n\n if (type == \"vardef\") return lexical.indented + (state.lastType == \"operator\" || state.lastType == \",\" ? lexical.info.length + 1 : 0);\n else if (type == \"form\" && firstChar == \"{\") return lexical.indented;\n else if (type == \"form\") return lexical.indented + cx.unit;\n else if (type == \"stat\")\n return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || cx.unit : 0);\n else if (lexical.info == \"switch\" && !closing && parserConfig.doubleIndentSwitch != false)\n return lexical.indented + (/^(?:case|default)\\b/.test(textAfter) ? cx.unit : 2 * cx.unit);\n else if (lexical.align) return lexical.column + (closing ? 0 : 1);\n else return lexical.indented + (closing ? 0 : cx.unit);\n },\n\n languageData: {\n indentOnInput: /^\\s*(?:case .*?:|default:|\\{|\\})$/,\n commentTokens: jsonMode ? undefined : {line: \"//\", block: {open: \"/*\", close: \"*/\"}},\n closeBrackets: {brackets: [\"(\", \"[\", \"{\", \"'\", '\"', \"`\"]},\n wordChars: \"$\"\n }\n };\n};\n\nexport const javascript = mkJavaScript({name: \"javascript\"})\nexport const json = mkJavaScript({name: \"json\", json: true})\nexport const jsonld = mkJavaScript({name: \"json\", jsonld: true})\nexport const typescript = mkJavaScript({name: \"typescript\", typescript: true})\n"],"names":["mkJavaScript","parserConfig","type","content","statementIndent","jsonldMode","jsonld","jsonMode","json","isTS","typescript","wordRE","wordCharacters","keywords","kw","style","A","B","C","D","operator","atom","isOperatorChar","isJsonldKeyword","ret","tp","cont","tokenBase","stream","state","quote","ch","next","tokenize","escaped","peek","match","test","eat","tokenComment","skipToEnd","backUp","lastType","string","slice","pos","expressionAllowed","inSet","readRegexp","current","tokenQuasi","eatWhile","start","lexical","word","propertyIsEnumerable","maybeEnd","brackets","findFatArrow","fatArrowAt","arrow","indexOf","m","exec","index","depth","sawSomething","charAt","bracket","atomicTypes","JSLexical","indented","column","align","prev","info","this","inScope","varname","v","localVars","name","cx","context","vars","marked","cc","pass","i","arguments","length","push","apply","inList","list","register","block","newContext","registerVarScoped","Var","globalVars","inner","Context","isModifier","defaultVars","pushcontext","pushblockcontext","popcontext","pushlex","result","indent","outer","lex","poplex","expect","wanted","exp","statement","value","vardef","parenExpr","maybeexpression","pop","maybeelse","functiondef","forspec","className","enumdef","typename","typeexpr","pattern","expression","maybelabel","maybeCatchBinding","afterExport","afterImport","funarg","expressionInner","expressionNoComma","noComma","body","arrowBodyNoComma","arrowBody","commasep","maybeop","maybeoperatorNoComma","maybeoperatorComma","hasOwnProperty","classExpression","arrayLiteral","contCommasep","objprop","quasi","targetNoComma","target","maybeTypeArgs","maybeTarget","me","expr","property","continueQuasi","_","getterSetter","afterprop","maybetype","what","end","sep","proceed","maybetypeOrIn","mayberettype","isKW","afterType","typeprops","typearg","maybeReturnType","quasiType","typeprop","functiondecl","continueQuasiType","typeparam","maybeTypeDefault","maybeAssign","vardefCont","eltpattern","proppattern","_type","forspec1","forspec2","classNameAfter","classBody","classfield","maybeFrom","exportField","importSpec","maybeMoreImports","maybeAs","enummember","startState","indentUnit","token","sol","indentation","eatSpace","parseJS","textAfter","top","firstChar","c","closing","unit","isContinuedStatement","doubleIndentSwitch","languageData","indentOnInput","commentTokens","undefined","line","open","close","closeBrackets","wordChars","javascript"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/386.index.js b/book/_build/html/_static/386.index.js new file mode 100644 index 0000000..a097d58 --- /dev/null +++ b/book/_build/html/_static/386.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[386],{386:(t,e,n)=>{n.r(e),n.d(e,{commonLisp:()=>d});var r,o=/^(block|let*|return-from|catch|load-time-value|setq|eval-when|locally|symbol-macrolet|flet|macrolet|tagbody|function|multiple-value-call|the|go|multiple-value-prog1|throw|if|progn|unwind-protect|labels|progv|let|quote)$/,a=/^with|^def|^do|^prog|case$|^cond$|bind$|when$|unless$/,l=/^(?:[+\-]?(?:\d+|\d*\.\d+)(?:[efd][+\-]?\d+)?|[+\-]?\d+(?:\/[+\-]?\d+)?|#b[+\-]?[01]+|#o[+\-]?[0-7]+|#x[+\-]?[\da-f]+)/,c=/[^\s'`,@()\[\]";]/;function i(t){for(var e;e=t.next();)if("\\"==e)t.next();else if(!c.test(e)){t.backUp(1);break}return t.current()}function u(t,e){if(t.eatSpace())return r="ws",null;if(t.match(l))return"number";var n;if("\\"==(n=t.next())&&(n=t.next()),'"'==n)return(e.tokenize=s)(t,e);if("("==n)return r="open","bracket";if(")"==n||"]"==n)return r="close","bracket";if(";"==n)return t.skipToEnd(),r="ws","comment";if(/['`,@]/.test(n))return null;if("|"==n)return t.skipTo("|")?(t.next(),"variableName"):(t.skipToEnd(),"error");if("#"==n)return"("==(n=t.next())?(r="open","bracket"):/[+\-=\.']/.test(n)||/\d/.test(n)&&t.match(/^\d*#/)?null:"|"==n?(e.tokenize=f)(t,e):":"==n?(i(t),"meta"):"\\"==n?(t.next(),i(t),"string.special"):"error";var c=i(t);return"."==c?null:(r="symbol","nil"==c||"t"==c||":"==c.charAt(0)?"atom":"open"==e.lastType&&(o.test(c)||a.test(c))?"keyword":"&"==c.charAt(0)?"variableName.special":"variableName")}function s(t,e){for(var n,r=!1;n=t.next();){if('"'==n&&!r){e.tokenize=u;break}r=!r&&"\\"==n}return"string"}function f(t,e){for(var n,o;n=t.next();){if("#"==n&&"|"==o){e.tokenize=u;break}o=n}return r="ws","comment"}const d={name:"commonlisp",startState:function(){return{ctx:{prev:null,start:0,indentTo:0},lastType:null,tokenize:u}},token:function(t,e){t.sol()&&"number"!=typeof e.ctx.indentTo&&(e.ctx.indentTo=e.ctx.start+1),r=null;var n=e.tokenize(t,e);return"ws"!=r&&(null==e.ctx.indentTo?"symbol"==r&&a.test(t.current())?e.ctx.indentTo=e.ctx.start+t.indentUnit:e.ctx.indentTo="next":"next"==e.ctx.indentTo&&(e.ctx.indentTo=t.column()),e.lastType=r),"open"==r?e.ctx={prev:e.ctx,start:t.column(),indentTo:null}:"close"==r&&(e.ctx=e.ctx.prev||e.ctx),n},indent:function(t){var e=t.ctx.indentTo;return"number"==typeof e?e:t.ctx.start+1},languageData:{commentTokens:{line:";;",block:{open:"#|",close:"|#"}},closeBrackets:{brackets:["(","[","{",'"']}}}}}]); +//# sourceMappingURL=386.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/386.index.js.map b/book/_build/html/_static/386.index.js.map new file mode 100644 index 0000000..484dd28 --- /dev/null +++ b/book/_build/html/_static/386.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"386.index.js","mappings":"6HAAA,IAIIA,EAJAC,EAAc,8NACdC,EAAa,wDACbC,EAAa,yHACbC,EAAS,oBAGb,SAASC,EAAQC,GAEf,IADA,IAAIC,EACGA,EAAKD,EAAOE,QACjB,GAAU,MAAND,EAAYD,EAAOE,YAClB,IAAKJ,EAAOK,KAAKF,GAAK,CAAED,EAAOI,OAAO,GAAI,KAAO,CAExD,OAAOJ,EAAOK,SAChB,CAEA,SAASC,EAAKN,EAAQO,GACpB,GAAIP,EAAOQ,WAA0B,OAAbd,EAAO,KAAa,KAC5C,GAAIM,EAAOS,MAAMZ,GAAa,MAAO,SACrC,IAYMI,EATN,GAFU,OADNA,EAAKD,EAAOE,UACAD,EAAKD,EAAOE,QAElB,KAAND,EAAW,OAAQM,EAAMG,SAAWC,GAAUX,EAAQO,GACrD,GAAU,KAANN,EAA4B,OAAfP,EAAO,OAAe,UACvC,GAAU,KAANO,GAAmB,KAANA,EAA6B,OAAhBP,EAAO,QAAgB,UACrD,GAAU,KAANO,EAA8C,OAAjCD,EAAOY,YAAalB,EAAO,KAAa,UACzD,GAAI,SAASS,KAAKF,GAAK,OAAO,KAC9B,GAAU,KAANA,EACP,OAAID,EAAOa,OAAO,MAAQb,EAAOE,OAAe,iBACzCF,EAAOY,YAAoB,SAC7B,GAAU,KAANX,EAET,MAAU,MADNA,EAAKD,EAAOE,SACCR,EAAO,OAAe,WAC9B,YAAYS,KAAKF,IACjB,KAAKE,KAAKF,IAAOD,EAAOS,MAAM,SADD,KAEvB,KAANR,GAAmBM,EAAMG,SAAWI,GAAWd,EAAQO,GACjD,KAANN,GAAaF,EAAQC,GAAgB,QAC/B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,SAAW,OACQ,QAAtBlB,EAAMe,IAAIG,WACnBlB,EAAMe,IAAIG,SAAWzB,EAAO8B,UAE9BvB,EAAMU,SAAWvB,GAEP,QAARA,EAAgBa,EAAMe,IAAM,CAACC,KAAMhB,EAAMe,IAAKE,MAAOxB,EAAO8B,SAAUL,SAAU,MACnE,SAAR/B,IAAiBa,EAAMe,IAAMf,EAAMe,IAAIC,MAAQhB,EAAMe,KACvDM,CACT,EAEAG,OAAQ,SAAUxB,GAChB,IAAIyB,EAAIzB,EAAMe,IAAIG,SAClB,MAAmB,iBAALO,EAAgBA,EAAIzB,EAAMe,IAAIE,MAAQ,CACtD,EAEAS,aAAc,CACZC,cAAe,CAACC,KAAM,KAAMC,MAAO,CAACC,KAAM,KAAMC,MAAO,OACvDC,cAAe,CAACC,SAAU,CAAC,IAAK,IAAK,IAAK,O","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/commonlisp.js"],"sourcesContent":["var specialForm = /^(block|let*|return-from|catch|load-time-value|setq|eval-when|locally|symbol-macrolet|flet|macrolet|tagbody|function|multiple-value-call|the|go|multiple-value-prog1|throw|if|progn|unwind-protect|labels|progv|let|quote)$/;\nvar assumeBody = /^with|^def|^do|^prog|case$|^cond$|bind$|when$|unless$/;\nvar numLiteral = /^(?:[+\\-]?(?:\\d+|\\d*\\.\\d+)(?:[efd][+\\-]?\\d+)?|[+\\-]?\\d+(?:\\/[+\\-]?\\d+)?|#b[+\\-]?[01]+|#o[+\\-]?[0-7]+|#x[+\\-]?[\\da-f]+)/;\nvar symbol = /[^\\s'`,@()\\[\\]\";]/;\nvar type;\n\nfunction readSym(stream) {\n var ch;\n while (ch = stream.next()) {\n if (ch == \"\\\\\") stream.next();\n else if (!symbol.test(ch)) { stream.backUp(1); break; }\n }\n return stream.current();\n}\n\nfunction base(stream, state) {\n if (stream.eatSpace()) {type = \"ws\"; return null;}\n if (stream.match(numLiteral)) return \"number\";\n var ch = stream.next();\n if (ch == \"\\\\\") ch = stream.next();\n\n if (ch == '\"') return (state.tokenize = inString)(stream, state);\n else if (ch == \"(\") { type = \"open\"; return \"bracket\"; }\n else if (ch == \")\" || ch == \"]\") { type = \"close\"; return \"bracket\"; }\n else if (ch == \";\") { stream.skipToEnd(); type = \"ws\"; return \"comment\"; }\n else if (/['`,@]/.test(ch)) return null;\n else if (ch == \"|\") {\n if (stream.skipTo(\"|\")) { stream.next(); return \"variableName\"; }\n else { stream.skipToEnd(); return \"error\"; }\n } else if (ch == \"#\") {\n var ch = stream.next();\n if (ch == \"(\") { type = \"open\"; return \"bracket\"; }\n else if (/[+\\-=\\.']/.test(ch)) return null;\n else if (/\\d/.test(ch) && stream.match(/^\\d*#/)) return null;\n else if (ch == \"|\") return (state.tokenize = inComment)(stream, state);\n else if (ch == \":\") { readSym(stream); return \"meta\"; }\n else if (ch == \"\\\\\") { stream.next(); readSym(stream); return \"string.special\" }\n else return \"error\";\n } else {\n var name = readSym(stream);\n if (name == \".\") return null;\n type = \"symbol\";\n if (name == \"nil\" || name == \"t\" || name.charAt(0) == \":\") return \"atom\";\n if (state.lastType == \"open\" && (specialForm.test(name) || assumeBody.test(name))) return \"keyword\";\n if (name.charAt(0) == \"&\") return \"variableName.special\";\n return \"variableName\";\n }\n}\n\nfunction inString(stream, state) {\n var escaped = false, next;\n while (next = stream.next()) {\n if (next == '\"' && !escaped) { state.tokenize = base; break; }\n escaped = !escaped && next == \"\\\\\";\n }\n return \"string\";\n}\n\nfunction inComment(stream, state) {\n var next, last;\n while (next = stream.next()) {\n if (next == \"#\" && last == \"|\") { state.tokenize = base; break; }\n last = next;\n }\n type = \"ws\";\n return \"comment\";\n}\n\nexport const commonLisp = {\n name: \"commonlisp\",\n startState: function () {\n return {ctx: {prev: null, start: 0, indentTo: 0}, lastType: null, tokenize: base};\n },\n\n token: function (stream, state) {\n if (stream.sol() && typeof state.ctx.indentTo != \"number\")\n state.ctx.indentTo = state.ctx.start + 1;\n\n type = null;\n var style = state.tokenize(stream, state);\n if (type != \"ws\") {\n if (state.ctx.indentTo == null) {\n if (type == \"symbol\" && assumeBody.test(stream.current()))\n state.ctx.indentTo = state.ctx.start + stream.indentUnit;\n else\n state.ctx.indentTo = \"next\";\n } else if (state.ctx.indentTo == \"next\") {\n state.ctx.indentTo = stream.column();\n }\n state.lastType = type;\n }\n if (type == \"open\") state.ctx = {prev: state.ctx, start: stream.column(), indentTo: null};\n else if (type == \"close\") state.ctx = state.ctx.prev || state.ctx;\n return style;\n },\n\n indent: function (state) {\n var i = state.ctx.indentTo;\n return typeof i == \"number\" ? i : state.ctx.start + 1;\n },\n\n languageData: {\n commentTokens: {line: \";;\", block: {open: \"#|\", close: \"|#\"}},\n closeBrackets: {brackets: [\"(\", \"[\", \"{\", '\"']}\n }\n};\n\n"],"names":["type","specialForm","assumeBody","numLiteral","symbol","readSym","stream","ch","next","test","backUp","current","base","state","eatSpace","match","tokenize","inString","skipToEnd","skipTo","inComment","name","charAt","lastType","escaped","last","commonLisp","startState","ctx","prev","start","indentTo","token","sol","style","indentUnit","column","indent","i","languageData","commentTokens","line","block","open","close","closeBrackets","brackets"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/4127.index.js b/book/_build/html/_static/4127.index.js new file mode 100644 index 0000000..5c38cc4 --- /dev/null +++ b/book/_build/html/_static/4127.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[4127],{14127:(e,n,t)=>{function r(e){return new RegExp("^(("+e.join(")|(")+"))\\b")}t.r(n),t.d(n,{octave:()=>k});var i=new RegExp("^[\\+\\-\\*/&|\\^~<>!@'\\\\]"),a=new RegExp("^[\\(\\[\\{\\},:=;\\.]"),o=new RegExp("^((==)|(~=)|(<=)|(>=)|(<<)|(>>)|(\\.[\\+\\-\\*/\\^\\\\]))"),c=new RegExp("^((!=)|(\\+=)|(\\-=)|(\\*=)|(/=)|(&=)|(\\|=)|(\\^=))"),m=new RegExp("^((>>=)|(<<=))"),s=new RegExp("^[\\]\\)]"),u=new RegExp("^[_A-Za-z¡-￿][_A-Za-z0-9¡-￿]*"),l=r(["error","eval","function","abs","acos","atan","asin","cos","cosh","exp","log","prod","sum","log10","max","min","sign","sin","sinh","sqrt","tan","reshape","break","zeros","default","margin","round","ones","rand","syn","ceil","floor","size","clear","zeros","eye","mean","std","cov","det","eig","inv","norm","rank","trace","expm","logm","sqrtm","linspace","plot","title","xlabel","ylabel","legend","text","grid","meshgrid","mesh","num2str","fft","ifft","arrayfun","cellfun","input","fliplr","flipud","ismember"]),f=r(["return","case","switch","else","elseif","end","endif","endfunction","if","otherwise","do","for","while","try","catch","classdef","properties","events","methods","global","persistent","endfor","endwhile","printf","sprintf","disp","until","continue","pkg"]);function h(e,n){return e.sol()||"'"!==e.peek()?(n.tokenize=d,d(e,n)):(e.next(),n.tokenize=d,"operator")}function p(e,n){return e.match(/^.*%}/)?(n.tokenize=d,"comment"):(e.skipToEnd(),"comment")}function d(e,n){if(e.eatSpace())return null;if(e.match("%{"))return n.tokenize=p,e.skipToEnd(),"comment";if(e.match(/^[%#]/))return e.skipToEnd(),"comment";if(e.match(/^[0-9\.+-]/,!1)){if(e.match(/^[+-]?0x[0-9a-fA-F]+[ij]?/))return e.tokenize=d,"number";if(e.match(/^[+-]?\d*\.\d+([EeDd][+-]?\d+)?[ij]?/))return"number";if(e.match(/^[+-]?\d+([EeDd][+-]?\d+)?[ij]?/))return"number"}if(e.match(r(["nan","NaN","inf","Inf"])))return"number";var t=e.match(/^"(?:[^"]|"")*("|$)/)||e.match(/^'(?:[^']|'')*('|$)/);return t?t[1]?"string":"error":e.match(f)?"keyword":e.match(l)?"builtin":e.match(u)?"variable":e.match(i)||e.match(o)?"operator":e.match(a)||e.match(c)||e.match(m)?null:e.match(s)?(n.tokenize=h,null):(e.next(),"error")}const k={name:"octave",startState:function(){return{tokenize:d}},token:function(e,n){var t=n.tokenize(e,n);return"number"!==t&&"variable"!==t||(n.tokenize=h),t},languageData:{commentTokens:{line:"%"}}}}}]); +//# sourceMappingURL=4127.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/4127.index.js.map b/book/_build/html/_static/4127.index.js.map new file mode 100644 index 0000000..170f681 --- /dev/null +++ b/book/_build/html/_static/4127.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"4127.index.js","mappings":"+FAAA,SAASA,EAAWC,GAClB,OAAO,IAAIC,OAAO,MAAQD,EAAME,KAAK,OAAS,QAChD,C,6BAEA,IAAIC,EAAkB,IAAIF,OAAO,gCAC7BG,EAAmB,IAAIH,OAAO,0BAC9BI,EAAkB,IAAIJ,OAAO,6DAC7BK,EAAmB,IAAIL,OAAO,wDAC9BM,EAAmB,IAAIN,OAAO,kBAC9BO,EAAgB,IAAIP,OAAO,aAC3BQ,EAAc,IAAIR,OAAO,iCAEzBS,EAAWX,EAAW,CACxB,QAAS,OAAQ,WAAY,MAAO,OAAQ,OAAQ,OAAQ,MAC5D,OAAQ,MAAO,MAAO,OAAQ,MAAO,QAAS,MAAO,MAAO,OAAQ,MAAO,OAC3E,OAAQ,MAAO,UAAW,QAAS,QAAS,UAAW,SAAU,QAAS,OAC1E,OAAQ,MAAO,OAAQ,QAAS,OAAQ,QAAS,QAAS,MAAO,OAAQ,MAAO,MAChF,MAAO,MAAO,MAAO,OAAQ,OAAQ,QAAS,OAAQ,OAAQ,QAAS,WAAY,OACnF,QAAS,SAAU,SAAU,SAAU,OAAQ,OAAQ,WAAY,OAAQ,UAC3E,MAAO,OAAQ,WAAY,UAAW,QAAS,SAAU,SAAU,aAGjEY,EAAWZ,EAAW,CACxB,SAAU,OAAQ,SAAU,OAAQ,SAAU,MAAO,QAAS,cAC9D,KAAM,YAAa,KAAM,MAAO,QAAS,MAAO,QAAS,WAAY,aAAc,SACnF,UAAW,SAAU,aAAc,SAAU,WAAY,SAAU,UAAW,OAAQ,QACtF,WAAY,QAKd,SAASa,EAAeC,EAAQC,GAC9B,OAAKD,EAAOE,OAA2B,MAAlBF,EAAOG,QAK5BF,EAAMG,SA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iB,CACT,EAEAC,aAAc,CACZC,cAAe,CAACC,KAAM,M","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/octave.js"],"sourcesContent":["function wordRegexp(words) {\n return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\");\n}\n\nvar singleOperators = new RegExp(\"^[\\\\+\\\\-\\\\*/&|\\\\^~<>!@'\\\\\\\\]\");\nvar singleDelimiters = new RegExp('^[\\\\(\\\\[\\\\{\\\\},:=;\\\\.]');\nvar doubleOperators = new RegExp(\"^((==)|(~=)|(<=)|(>=)|(<<)|(>>)|(\\\\.[\\\\+\\\\-\\\\*/\\\\^\\\\\\\\]))\");\nvar doubleDelimiters = new RegExp(\"^((!=)|(\\\\+=)|(\\\\-=)|(\\\\*=)|(/=)|(&=)|(\\\\|=)|(\\\\^=))\");\nvar tripleDelimiters = new RegExp(\"^((>>=)|(<<=))\");\nvar expressionEnd = new RegExp(\"^[\\\\]\\\\)]\");\nvar identifiers = new RegExp(\"^[_A-Za-z\\xa1-\\uffff][_A-Za-z0-9\\xa1-\\uffff]*\");\n\nvar builtins = wordRegexp([\n 'error', 'eval', 'function', 'abs', 'acos', 'atan', 'asin', 'cos',\n 'cosh', 'exp', 'log', 'prod', 'sum', 'log10', 'max', 'min', 'sign', 'sin', 'sinh',\n 'sqrt', 'tan', 'reshape', 'break', 'zeros', 'default', 'margin', 'round', 'ones',\n 'rand', 'syn', 'ceil', 'floor', 'size', 'clear', 'zeros', 'eye', 'mean', 'std', 'cov',\n 'det', 'eig', 'inv', 'norm', 'rank', 'trace', 'expm', 'logm', 'sqrtm', 'linspace', 'plot',\n 'title', 'xlabel', 'ylabel', 'legend', 'text', 'grid', 'meshgrid', 'mesh', 'num2str',\n 'fft', 'ifft', 'arrayfun', 'cellfun', 'input', 'fliplr', 'flipud', 'ismember'\n]);\n\nvar keywords = wordRegexp([\n 'return', 'case', 'switch', 'else', 'elseif', 'end', 'endif', 'endfunction',\n 'if', 'otherwise', 'do', 'for', 'while', 'try', 'catch', 'classdef', 'properties', 'events',\n 'methods', 'global', 'persistent', 'endfor', 'endwhile', 'printf', 'sprintf', 'disp', 'until',\n 'continue', 'pkg'\n]);\n\n\n// tokenizers\nfunction tokenTranspose(stream, state) {\n if (!stream.sol() && stream.peek() === '\\'') {\n stream.next();\n state.tokenize = tokenBase;\n return 'operator';\n }\n state.tokenize = tokenBase;\n return tokenBase(stream, state);\n}\n\n\nfunction tokenComment(stream, state) {\n if (stream.match(/^.*%}/)) {\n state.tokenize = tokenBase;\n return 'comment';\n };\n stream.skipToEnd();\n return 'comment';\n}\n\nfunction tokenBase(stream, state) {\n // whitespaces\n if (stream.eatSpace()) return null;\n\n // Handle one line Comments\n if (stream.match('%{')){\n state.tokenize = tokenComment;\n stream.skipToEnd();\n return 'comment';\n }\n\n if (stream.match(/^[%#]/)){\n stream.skipToEnd();\n return 'comment';\n }\n\n // Handle Number Literals\n if (stream.match(/^[0-9\\.+-]/, false)) {\n if (stream.match(/^[+-]?0x[0-9a-fA-F]+[ij]?/)) {\n stream.tokenize = tokenBase;\n return 'number'; };\n if (stream.match(/^[+-]?\\d*\\.\\d+([EeDd][+-]?\\d+)?[ij]?/)) { return 'number'; };\n if (stream.match(/^[+-]?\\d+([EeDd][+-]?\\d+)?[ij]?/)) { return 'number'; };\n }\n if (stream.match(wordRegexp(['nan','NaN','inf','Inf']))) { return 'number'; };\n\n // Handle Strings\n var m = stream.match(/^\"(?:[^\"]|\"\")*(\"|$)/) || stream.match(/^'(?:[^']|'')*('|$)/)\n if (m) { return m[1] ? 'string' : \"error\"; }\n\n // Handle words\n if (stream.match(keywords)) { return 'keyword'; } ;\n if (stream.match(builtins)) { return 'builtin'; } ;\n if (stream.match(identifiers)) { return 'variable'; } ;\n\n if (stream.match(singleOperators) || stream.match(doubleOperators)) { return 'operator'; };\n if (stream.match(singleDelimiters) || stream.match(doubleDelimiters) || stream.match(tripleDelimiters)) { return null; };\n\n if (stream.match(expressionEnd)) {\n state.tokenize = tokenTranspose;\n return null;\n };\n\n\n // Handle non-detected items\n stream.next();\n return 'error';\n};\n\n\nexport const octave = {\n name: \"octave\",\n\n startState: function() {\n return {\n tokenize: tokenBase\n };\n },\n\n token: function(stream, state) {\n var style = state.tokenize(stream, state);\n if (style === 'number' || style === 'variable'){\n state.tokenize = tokenTranspose;\n }\n return style;\n },\n\n languageData: {\n commentTokens: {line: \"%\"}\n }\n};\n\n"],"names":["wordRegexp","words","RegExp","join","singleOperators","singleDelimiters","doubleOperators","doubleDelimiters","tripleDelimiters","expressionEnd","identifiers","builtins","keywords","tokenTranspose","stream","state","sol","peek","tokenize","tokenBase","next","tokenComment","match","skipToEnd","eatSpace","m","octave","name","startState","token","style","languageData","commentTokens","line"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/4140.index.js b/book/_build/html/_static/4140.index.js new file mode 100644 index 0000000..c8a9b19 --- /dev/null +++ b/book/_build/html/_static/4140.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[4140],{84140:(e,t,n)=>{n.r(t),n.d(t,{yacas:()=>k});var r=function(e){for(var t={},n="Assert BackQuote D Defun Deriv For ForEach FromFile FromString Function Integrate InverseTaylor Limit LocalSymbols Macro MacroRule MacroRulePattern NIntegrate Rule RulePattern Subst TD TExplicitSum TSum Taylor Taylor1 Taylor2 Taylor3 ToFile ToStdout ToString TraceRule Until While".split(" "),r=0;r|<|&|\||_|`|'|\^|\?|!|%|#)/,!0,!1)?"operator":"error"}function s(e,t){for(var n,r=!1,o=!1;null!=(n=e.next());){if('"'===n&&!o){r=!0;break}o=!o&&"\\"===n}return r&&!o&&(t.tokenize=l),"string"}function p(e,t){for(var n,r;null!=(r=e.next());){if("*"===n&&"/"===r){t.tokenize=l;break}n=r}return"comment"}function f(e){var t=null;return e.scopes.length>0&&(t=e.scopes[e.scopes.length-1]),t}const k={name:"yacas",startState:function(){return{tokenize:l,scopes:[]}},token:function(e,t){return e.eatSpace()?null:t.tokenize(e,t)},indent:function(e,t,n){if(e.tokenize!==l&&null!==e.tokenize)return null;var r=0;return"]"!==t&&"];"!==t&&"}"!==t&&"};"!==t&&");"!==t||(r=-1),(e.scopes.length+r)*n.unit},languageData:{electricInput:/[{}\[\]()\;]/,commentTokens:{line:"//",block:{open:"/*",close:"*/"}}}}}}]); +//# sourceMappingURL=4140.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/4140.index.js.map b/book/_build/html/_static/4140.index.js.map new file mode 100644 index 0000000..77a8178 --- /dev/null +++ b/book/_build/html/_static/4140.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"4140.index.js","mappings":"2HAMA,IAAIA,EANJ,SAAeC,GAEb,IADA,IAAIC,EAAM,CAAC,EAAGC,EAKM,2RALMC,MAAM,KACvBC,EAAI,EAAGA,EAAIF,EAAMG,SAAUD,EAAGH,EAAIC,EAAME,KAAM,EACvD,OAAOH,CACT,CAEgBC,GASZI,EAAc,mCAGdC,EAAiB,IAAIC,OAJP,sDAKdC,EAAiB,IAAID,OAAOF,GAC5BI,EAAiB,IAAIF,OAAOF,EAAc,KAAOA,GACjDK,EAAiB,IAAIH,OAAOF,EAAc,WAE9C,SAASM,EAAUC,EAAQC,GACzB,IAAIC,EAMJ,GAAW,OAHXA,EAAKF,EAAOG,QAKV,OADAF,EAAMG,SAAWC,EACVJ,EAAMG,SAASJ,EAAQC,GAIhC,GAAW,MAAPC,EAAY,CACd,GAAIF,EAAOM,IAAI,KAEb,OADAL,EAAMG,SAAWG,EACVN,EAAMG,SAASJ,EAAQC,GAEhC,GAAID,EAAOM,IAAI,KAEb,OADAN,EAAOQ,YACA,SAEX,CAGAR,EAAOS,OAAO,GAGd,IAAIC,EAAIV,EAAOW,MAAM,eAAe,GAC1B,OAAND,GAAcxB,EAAU0B,eAAeF,EAAE,KAC3CT,EAAMY,OAAOC,KAAK,UAEpB,IAAIC,EAAQC,EAAaf,GAezB,GAbc,WAAVc,GAA6B,MAAPb,GACxBD,EAAM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V,MAAO,CACLnB,SAAUL,EACVc,OAAQ,GAEZ,EACAW,MAAO,SAASxB,EAAQC,GACtB,OAAID,EAAOyB,WAAmB,KACvBxB,EAAMG,SAASJ,EAAQC,EAChC,EACAyB,OAAQ,SAASzB,EAAO0B,EAAWC,GACjC,GAAI3B,EAAMG,WAAaL,GAAgC,OAAnBE,EAAMG,SACxC,OAAO,KAET,IAAIyB,EAAQ,EAMZ,MALkB,MAAdF,GAAmC,OAAdA,GACP,MAAdA,GAAmC,OAAdA,GACP,OAAdA,IACFE,GAAS,IAEH5B,EAAMY,OAAOrB,OAASqC,GAASD,EAAGE,IAC5C,EAEAC,aAAc,CACZC,cAAe,eACfC,cAAe,CAACC,KAAM,KAAMC,MAAO,CAACC,KAAM,KAAMC,MAAO,Q","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/yacas.js"],"sourcesContent":["function words(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n}\n\nvar bodiedOps = words(\"Assert BackQuote D Defun Deriv For ForEach FromFile \" +\n \"FromString Function Integrate InverseTaylor Limit \" +\n \"LocalSymbols Macro MacroRule MacroRulePattern \" +\n \"NIntegrate Rule RulePattern Subst TD TExplicitSum \" +\n \"TSum Taylor Taylor1 Taylor2 Taylor3 ToFile \" +\n \"ToStdout ToString TraceRule Until While\");\n\n// patterns\nvar pFloatForm = \"(?:(?:\\\\.\\\\d+|\\\\d+\\\\.\\\\d*|\\\\d+)(?:[eE][+-]?\\\\d+)?)\";\nvar pIdentifier = \"(?:[a-zA-Z\\\\$'][a-zA-Z0-9\\\\$']*)\";\n\n// regular expressions\nvar reFloatForm = new RegExp(pFloatForm);\nvar reIdentifier = new RegExp(pIdentifier);\nvar rePattern = new RegExp(pIdentifier + \"?_\" + pIdentifier);\nvar reFunctionLike = new RegExp(pIdentifier + \"\\\\s*\\\\(\");\n\nfunction tokenBase(stream, state) {\n var ch;\n\n // get next character\n ch = stream.next();\n\n // string\n if (ch === '\"') {\n state.tokenize = tokenString;\n return state.tokenize(stream, state);\n }\n\n // comment\n if (ch === '/') {\n if (stream.eat('*')) {\n state.tokenize = tokenComment;\n return state.tokenize(stream, state);\n }\n if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return \"comment\";\n }\n }\n\n // go back one character\n stream.backUp(1);\n\n // update scope info\n var m = stream.match(/^(\\w+)\\s*\\(/, false);\n if (m !== null && bodiedOps.hasOwnProperty(m[1]))\n state.scopes.push('bodied');\n\n var scope = currentScope(state);\n\n if (scope === 'bodied' && ch === '[')\n state.scopes.pop();\n\n if (ch === '[' || ch === '{' || ch === '(')\n state.scopes.push(ch);\n\n scope = currentScope(state);\n\n if (scope === '[' && ch === ']' ||\n scope === '{' && ch === '}' ||\n scope === '(' && ch === ')')\n state.scopes.pop();\n\n if (ch === ';') {\n while (scope === 'bodied') {\n state.scopes.pop();\n scope = currentScope(state);\n }\n }\n\n // look for ordered rules\n if (stream.match(/\\d+ *#/, true, false)) {\n return 'qualifier';\n }\n\n // look for numbers\n if (stream.match(reFloatForm, true, false)) {\n return 'number';\n }\n\n // look for placeholders\n if (stream.match(rePattern, true, false)) {\n return 'variableName.special';\n }\n\n // match all braces separately\n if (stream.match(/(?:\\[|\\]|{|}|\\(|\\))/, true, false)) {\n return 'bracket';\n }\n\n // literals looking like function calls\n if (stream.match(reFunctionLike, true, false)) {\n stream.backUp(1);\n return 'variableName.function';\n }\n\n // all other identifiers\n if (stream.match(reIdentifier, true, false)) {\n return 'variable';\n }\n\n // operators; note that operators like @@ or /; are matched separately for each symbol.\n if (stream.match(/(?:\\\\|\\+|\\-|\\*|\\/|,|;|\\.|:|@|~|=|>|<|&|\\||_|`|'|\\^|\\?|!|%|#)/, true, false)) {\n return 'operator';\n }\n\n // everything else is an error\n return 'error';\n}\n\nfunction tokenString(stream, state) {\n var next, end = false, escaped = false;\n while ((next = stream.next()) != null) {\n if (next === '\"' && !escaped) {\n end = true;\n break;\n }\n escaped = !escaped && next === '\\\\';\n }\n if (end && !escaped) {\n state.tokenize = tokenBase;\n }\n return 'string';\n};\n\nfunction tokenComment(stream, state) {\n var prev, next;\n while((next = stream.next()) != null) {\n if (prev === '*' && next === '/') {\n state.tokenize = tokenBase;\n break;\n }\n prev = next;\n }\n return 'comment';\n}\n\nfunction currentScope(state) {\n var scope = null;\n if (state.scopes.length > 0)\n scope = state.scopes[state.scopes.length - 1];\n return scope;\n}\n\nexport const yacas = {\n name: \"yacas\",\n startState: function() {\n return {\n tokenize: tokenBase,\n scopes: []\n };\n },\n token: function(stream, state) {\n if (stream.eatSpace()) return null;\n return state.tokenize(stream, state);\n },\n indent: function(state, textAfter, cx) {\n if (state.tokenize !== tokenBase && state.tokenize !== null)\n return null;\n\n var delta = 0;\n if (textAfter === ']' || textAfter === '];' ||\n textAfter === '}' || textAfter === '};' ||\n textAfter === ');')\n delta = -1;\n\n return (state.scopes.length + delta) * cx.unit;\n },\n\n languageData: {\n electricInput: /[{}\\[\\]()\\;]/,\n commentTokens: {line: \"//\", block: {open: \"/*\", close: \"*/\"}}\n }\n};\n"],"names":["bodiedOps","str","obj","words","split","i","length","pIdentifier","reFloatForm","RegExp","reIdentifier","rePattern","reFunctionLike","tokenBase","stream","state","ch","next","tokenize","tokenString","eat","tokenComment","skipToEnd","backUp","m","match","hasOwnProperty","scopes","push","scope","currentScope","pop","end","escaped","prev","yacas","name","startState","token","eatSpace","indent","textAfter","cx","delta","unit","languageData","electricInput","commentTokens","line","block","open","close"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/4211.index.js b/book/_build/html/_static/4211.index.js new file mode 100644 index 0000000..8b2eebe --- /dev/null +++ b/book/_build/html/_static/4211.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[4211],{4211:(e,O,a)=>{a.r(O),a.d(O,{css:()=>x,cssCompletionSource:()=>W,cssLanguage:()=>X,defineCSSCompletionSource:()=>R});var t=a(51392),o=a(86253);const r=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288];function l(e){return e>=65&&e<=90||e>=97&&e<=122||e>=161}const i=new t.Jq(((e,O)=>{for(let t=!1,o=0,r=0;;r++){let{next:i}=e;if(l(i)||45==i||95==i||t&&(a=i)>=48&&a<=57)!t&&(45!=i||r>0)&&(t=!0),o===r&&45==i&&o++,e.advance();else{if(92!=i||10==e.peek(1)){t&&e.acceptToken(40==i?97:2==o&&O.canShift(2)?2:98);break}e.advance(),e.next>-1&&e.advance(),t=!0}}var a})),n=new t.Jq((e=>{if(r.includes(e.peek(-1))){let{next:O}=e;(l(O)||95==O||35==O||46==O||91==O||58==O||45==O||38==O)&&e.acceptToken(96)}})),s=new t.Jq((e=>{if(!r.includes(e.peek(-1))){let{next:O}=e;if(37==O&&(e.advance(),e.acceptToken(1)),l(O)){do{e.advance()}while(l(e.next));e.acceptToken(1)}}})),d=(0,o.Gv)({"AtKeyword import charset namespace keyframes media supports":o.pJ.definitionKeyword,"from to selector":o.pJ.keyword,NamespaceName:o.pJ.namespace,KeyframeName:o.pJ.labelName,KeyframeRangeName:o.pJ.operatorKeyword,TagName:o.pJ.tagName,ClassName:o.pJ.className,PseudoClassName:o.pJ.constant(o.pJ.className),IdName:o.pJ.labelName,"FeatureName PropertyName":o.pJ.propertyName,AttributeName:o.pJ.attributeName,NumberLiteral:o.pJ.number,KeywordQuery:o.pJ.keyword,UnaryQueryOp:o.pJ.operatorKeyword,"CallTag ValueName":o.pJ.atom,VariableName:o.pJ.variableName,Callee:o.pJ.operatorKeyword,Unit:o.pJ.unit,"UniversalSelector NestingSelector":o.pJ.definitionOperator,MatchOp:o.pJ.compareOperator,"ChildOp SiblingOp, LogicOp":o.pJ.logicOperator,BinOp:o.pJ.arithmeticOperator,Important:o.pJ.modifier,Comment:o.pJ.blockComment,ColorLiteral:o.pJ.color,"ParenthesizedContent StringLiteral":o.pJ.string,":":o.pJ.punctuation,"PseudoOp #":o.pJ.derefOperator,"; ,":o.pJ.separator,"( )":o.pJ.paren,"[ ]":o.pJ.squareBracket,"{ }":o.pJ.brace}),c={__proto__:null,lang:32,"nth-child":32,"nth-last-child":32,"nth-of-type":32,"nth-last-of-type":32,dir:32,"host-context":32,url:60,"url-prefix":60,domain:60,regexp:60,selector:134},p={__proto__:null,"@import":114,"@media":138,"@charset":142,"@namespace":146,"@keyframes":152,"@supports":164},Q={__proto__:null,not:128,only:128},u=t.WQ.deserialize({version:14,states:"9bQYQ[OOO#_Q[OOP#fOWOOOOQP'#Cd'#CdOOQP'#Cc'#CcO#kQ[O'#CfO$_QXO'#CaO$fQ[O'#ChO$qQ[O'#DPO$vQ[O'#DTOOQP'#Ej'#EjO${QdO'#DeO%gQ[O'#DrO${QdO'#DtO%xQ[O'#DvO&TQ[O'#DyO&]Q[O'#EPO&kQ[O'#EROOQS'#Ei'#EiOOQS'#EU'#EUQYQ[OOO&rQXO'#CdO'gQWO'#DaO'lQWO'#EpO'wQ[O'#EpQOQWOOP(RO#tO'#C_POOO)C@X)C@XOOQP'#Cg'#CgOOQP,59Q,59QO#kQ[O,59QO(^Q[O'#EXO(xQWO,58{O)QQ[O,59SO$qQ[O,59kO$vQ[O,59oO(^Q[O,59sO(^Q[O,59uO(^Q[O,59vO)]Q[O'#D`OOQS,58{,58{OOQP'#Ck'#CkOOQO'#C}'#C}OOQP,59S,59SO)dQWO,59SO)iQWO,59SOOQP'#DR'#DROOQP,59k,59kOOQO'#DV'#DVO)nQ`O,59oOOQS'#Cp'#CpO${QdO'#CqO)vQvO'#CsO+TQtO,5:POOQO'#Cx'#CxO)iQWO'#CwO+iQWO'#CyOOQS'#Em'#EmOOQO'#Dh'#DhO+nQ[O'#DoO+|QWO'#EqO&]Q[O'#DmO,[QWO'#DpOOQO'#Er'#ErO({QWO,5:^O,aQpO,5:`OOQS'#Dx'#DxO,iQWO,5:bO,nQ[O,5:bOOQO'#D{'#D{O,vQWO,5:eO,{QWO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o<%lO%^nIcS!Q^Oy%^z;'S%^;'S;=`%o<%lO%^fItU!PQOy%^z!_%^!_!`6y!`;'S%^;'S;=`%o<%lO%^`JZP;=`<%l$}",tokenizers:[n,s,i,1,2,3,4,new t.RA("m~RRYZ[z{a~~g~aO#Z~~dP!P!Qg~lO#[~~",28,102)],topRules:{StyleSheet:[0,4],Styles:[1,84]},specialized:[{term:97,get:e=>c[e]||-1},{term:56,get:e=>p[e]||-1},{term:98,get:e=>Q[e]||-1}],tokenPrec:1169});var m=a(77120),S=a(21649);let b=null;function g(){if(!b&&"object"==typeof document&&document.body){let{style:e}=document.body,O=[],a=new Set;for(let t in e)"cssText"!=t&&"cssFloat"!=t&&"string"==typeof e[t]&&(/[A-Z]/.test(t)&&(t=t.replace(/[A-Z]/g,(e=>"-"+e.toLowerCase()))),a.has(t)||(O.push(t),a.add(t)));b=O.sort().map((e=>({type:"property",label:e})))}return b||[]}const h=["active","after","any-link","autofill","backdrop","before","checked","cue","default","defined","disabled","empty","enabled","file-selector-button","first","first-child","first-letter","first-line","first-of-type","focus","focus-visible","focus-within","fullscreen","has","host","host-context","hover","in-range","indeterminate","invalid","is","lang","last-child","last-of-type","left","link","marker","modal","not","nth-child","nth-last-child","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","part","placeholder","placeholder-shown","read-only","read-write","required","right","root","scope","selection","slotted","target","target-text","valid","visited","where"].map((e=>({type:"class",label:e}))),y=["above","absolute","activeborder","additive","activecaption","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","antialiased","appworkspace","asterisks","attr","auto","auto-flow","avoid","avoid-column","avoid-page","avoid-region","axis-pan","background","backwards","baseline","below","bidi-override","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","contents","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","difference","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic-abegede-gez","ethiopic-halehame-aa-er","ethiopic-halehame-gez","ew-resize","exclusion","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fill-box","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","graytext","grid","groove","hand","hard-light","help","hidden","hide","higher","highlight","highlighttext","horizontal","hsl","hsla","hue","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-grid","inline-table","inset","inside","intrinsic","invert","italic","justify","keep-all","landscape","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-hexadecimal","lower-latin","lower-norwegian","lowercase","ltr","luminosity","manipulation","match","matrix","matrix3d","medium","menu","menutext","message-box","middle","min-intrinsic","mix","monospace","move","multiple","multiple_mask_images","multiply","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","opacity","open-quote","optimizeLegibility","optimizeSpeed","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","perspective","pinch-zoom","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","scroll-position","se-resize","self-start","self-end","semi-condensed","semi-expanded","separate","serif","show","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","source-atop","source-in","source-out","source-over","space","space-around","space-between","space-evenly","spell-out","square","start","static","status-bar","stretch","stroke","stroke-box","sub","subpixel-antialiased","svg_masks","super","sw-resize","symbolic","symbols","system-ui","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","text","text-bottom","text-top","textarea","textfield","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","to","top","transform","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","unidirectional-pan","unset","up","upper-latin","uppercase","url","var","vertical","vertical-text","view-box","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"].map((e=>({type:"keyword",label:e}))).concat(["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"].map((e=>({type:"constant",label:e})))),$=["a","abbr","address","article","aside","b","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","dd","del","details","dfn","dialog","div","dl","dt","em","figcaption","figure","footer","form","header","hgroup","h1","h2","h3","h4","h5","h6","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","main","meter","nav","ol","output","p","pre","ruby","section","select","small","source","span","strong","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","tr","u","ul"].map((e=>({type:"type",label:e}))),f=/^(\w[\w-]*|-\w[\w-]*|)$/,P=/^-(-[\w-]*)?$/,w=new S.hr,k=["Declaration"];function v(e){for(let O=e;;){if(O.type.isTop)return O;if(!(O=O.parent))return e}}function z(e,O,a){if(O.to-O.from>4096){let t=w.get(O);if(t)return t;let o=[],r=new Set,l=O.cursor(S.vj.IncludeAnonymous);if(l.firstChild())do{for(let O of z(e,l.node,a))r.has(O.label)||(r.add(O.label),o.push(O))}while(l.nextSibling());return w.set(O,o),o}{let t=[],o=new Set;return O.cursor().iterate((O=>{var r;if(a(O)&&O.matchContext(k)&&":"==(null===(r=O.node.nextSibling)||void 0===r?void 0:r.name)){let a=e.sliceString(O.from,O.to);o.has(a)||(o.add(a),t.push({label:a,type:"variable"}))}})),t}}const R=e=>O=>{let{state:a,pos:t}=O,o=(0,m.qz)(a).resolveInner(t,-1),r=o.type.isError&&o.from==o.to-1&&"-"==a.doc.sliceString(o.from,o.to);if("PropertyName"==o.name||(r||"TagName"==o.name)&&/^(Block|Styles)$/.test(o.resolve(o.to).name))return{from:o.from,options:g(),validFor:f};if("ValueName"==o.name)return{from:o.from,options:y,validFor:f};if("PseudoClassName"==o.name)return{from:o.from,options:h,validFor:f};if(e(o)||(O.explicit||r)&&function(e,O){var a;if(("("==e.name||e.type.isError)&&(e=e.parent||e),"ArgList"!=e.name)return!1;let t=null===(a=e.parent)||void 0===a?void 0:a.firstChild;return"Callee"==(null==t?void 0:t.name)&&"var"==O.sliceString(t.from,t.to)}(o,a.doc))return{from:e(o)||r?o.from:t,options:z(a.doc,v(o),e),validFor:P};if("TagName"==o.name){for(let{parent:e}=o;e;e=e.parent)if("Block"==e.name)return{from:o.from,options:g(),validFor:f};return{from:o.from,options:$,validFor:f}}if(!O.explicit)return null;let l=o.resolve(t),i=l.childBefore(t);return i&&":"==i.name&&"PseudoClassSelector"==l.name?{from:t,options:h,validFor:f}:i&&":"==i.name&&"Declaration"==l.name||"ArgList"==l.name?{from:t,options:y,validFor:f}:"Block"==l.name||"Styles"==l.name?{from:t,options:g(),validFor:f}:null},W=R((e=>"VariableName"==e.name)),X=m.qp.define({name:"css",parser:u.configure({props:[m.uj.add({Declaration:(0,m.tC)()}),m.x0.add({"Block KeyframeList":m.Dv})]}),languageData:{commentTokens:{block:{open:"/*",close:"*/"}},indentOnInput:/^\s*\}$/,wordChars:"-"}});function x(){return new m.ri(X,X.data.of({autocomplete:W}))}}}]); +//# sourceMappingURL=4211.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/4211.index.js.map b/book/_build/html/_static/4211.index.js.map new file mode 100644 index 0000000..60c354a --- /dev/null +++ b/book/_build/html/_static/4211.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"4211.index.js","mappings":"8NAIA,MASMA,EAAQ,CAAC,EAAG,GAAI,GAAI,GAAI,GAAI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,YAAkB,CAC/CjD,KAAM,MACNpC,OAAqBA,EAAOsF,UAAU,CAClCC,MAAO,CACU,SAAmB,CAC5BC,aAA0B,YAEjB,SAAiB,CAC1B,qBAAsB,UAIlCC,aAAc,CACVC,cAAe,CAAEC,MAAO,CAAEC,KAAM,KAAMC,MAAO,OAC7CC,cAAe,UACfC,UAAW,OAMnB,SAASC,IACL,OAAO,IAAI,KAAgBX,EAAaA,EAAYY,KAAKC,GAAG,CAAEC,aAAchB,IAChF,C","sources":["webpack://thebe/../../node_modules/@lezer/css/dist/index.js","webpack://thebe/../../node_modules/@codemirror/lang-css/dist/index.js"],"sourcesContent":["import { ExternalTokenizer, LRParser, LocalTokenGroup } from '@lezer/lr';\nimport { styleTags, tags } from '@lezer/highlight';\n\n// This file was generated by lezer-generator. You probably shouldn't edit it.\nconst descendantOp = 96,\n Unit = 1,\n callee = 97,\n identifier = 98,\n VariableName = 2;\n\n/* Hand-written tokenizers for CSS tokens that can't be\n expressed by Lezer's built-in tokenizer. */\n\nconst space = [9, 10, 11, 12, 13, 32, 133, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197,\n 8198, 8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288];\nconst colon = 58, parenL = 40, underscore = 95, bracketL = 91, dash = 45, period = 46,\n hash = 35, percent = 37, ampersand = 38, backslash = 92, newline = 10;\n\nfunction isAlpha(ch) { return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || ch >= 161 }\n\nfunction isDigit(ch) { return ch >= 48 && ch <= 57 }\n\nconst identifiers = new ExternalTokenizer((input, stack) => {\n for (let inside = false, dashes = 0, i = 0;; i++) {\n let {next} = input;\n if (isAlpha(next) || next == dash || next == underscore || (inside && isDigit(next))) {\n if (!inside && (next != dash || i > 0)) inside = true;\n if (dashes === i && next == dash) dashes++;\n input.advance();\n } else if (next == backslash && input.peek(1) != newline) {\n input.advance();\n if (input.next > -1) input.advance();\n inside = true;\n } else {\n if (inside)\n input.acceptToken(next == parenL ? callee : dashes == 2 && stack.canShift(VariableName) ? VariableName : identifier);\n break\n }\n }\n});\n\nconst descendant = new ExternalTokenizer(input => {\n if (space.includes(input.peek(-1))) {\n let {next} = input;\n if (isAlpha(next) || next == underscore || next == hash || next == period ||\n next == bracketL || next == colon || next == dash || next == ampersand)\n input.acceptToken(descendantOp);\n }\n});\n\nconst unitToken = new ExternalTokenizer(input => {\n if (!space.includes(input.peek(-1))) {\n let {next} = input;\n if (next == percent) { input.advance(); input.acceptToken(Unit); }\n if (isAlpha(next)) {\n do { input.advance(); } while (isAlpha(input.next))\n input.acceptToken(Unit);\n }\n }\n});\n\nconst cssHighlighting = styleTags({\n \"AtKeyword import charset namespace keyframes media supports\": tags.definitionKeyword,\n \"from to selector\": tags.keyword,\n NamespaceName: tags.namespace,\n KeyframeName: tags.labelName,\n KeyframeRangeName: tags.operatorKeyword,\n TagName: tags.tagName,\n ClassName: tags.className,\n PseudoClassName: tags.constant(tags.className),\n IdName: tags.labelName,\n \"FeatureName PropertyName\": tags.propertyName,\n AttributeName: tags.attributeName,\n NumberLiteral: tags.number,\n KeywordQuery: tags.keyword,\n UnaryQueryOp: tags.operatorKeyword,\n \"CallTag ValueName\": tags.atom,\n VariableName: tags.variableName,\n Callee: tags.operatorKeyword,\n Unit: tags.unit,\n \"UniversalSelector NestingSelector\": tags.definitionOperator,\n MatchOp: tags.compareOperator,\n \"ChildOp SiblingOp, LogicOp\": tags.logicOperator,\n BinOp: tags.arithmeticOperator,\n Important: tags.modifier,\n Comment: tags.blockComment,\n ColorLiteral: tags.color,\n \"ParenthesizedContent StringLiteral\": tags.string,\n \":\": tags.punctuation,\n \"PseudoOp #\": tags.derefOperator,\n \"; ,\": tags.separator,\n \"( )\": tags.paren,\n \"[ ]\": tags.squareBracket,\n \"{ }\": tags.brace\n});\n\n// This file was generated by lezer-generator. You probably shouldn't edit it.\nconst spec_callee = {__proto__:null,lang:32, \"nth-child\":32, \"nth-last-child\":32, \"nth-of-type\":32, \"nth-last-of-type\":32, dir:32, \"host-context\":32, url:60, \"url-prefix\":60, domain:60, regexp:60, selector:134};\nconst spec_AtKeyword = {__proto__:null,\"@import\":114, \"@media\":138, \"@charset\":142, \"@namespace\":146, \"@keyframes\":152, \"@supports\":164};\nconst spec_identifier = {__proto__:null,not:128, only:128};\nconst parser = LRParser.deserialize({\n version: 14,\n states: \"9bQYQ[OOO#_Q[OOP#fOWOOOOQP'#Cd'#CdOOQP'#Cc'#CcO#kQ[O'#CfO$_QXO'#CaO$fQ[O'#ChO$qQ[O'#DPO$vQ[O'#DTOOQP'#Ej'#EjO${QdO'#DeO%gQ[O'#DrO${QdO'#DtO%xQ[O'#DvO&TQ[O'#DyO&]Q[O'#EPO&kQ[O'#EROOQS'#Ei'#EiOOQS'#EU'#EUQYQ[OOO&rQXO'#CdO'gQWO'#DaO'lQWO'#EpO'wQ[O'#EpQOQWOOP(RO#tO'#C_POOO)C@X)C@XOOQP'#Cg'#CgOOQP,59Q,59QO#kQ[O,59QO(^Q[O'#EXO(xQWO,58{O)QQ[O,59SO$qQ[O,59kO$vQ[O,59oO(^Q[O,59sO(^Q[O,59uO(^Q[O,59vO)]Q[O'#D`OOQS,58{,58{OOQP'#Ck'#CkOOQO'#C}'#C}OOQP,59S,59SO)dQWO,59SO)iQWO,59SOOQP'#DR'#DROOQP,59k,59kOOQO'#DV'#DVO)nQ`O,59oOOQS'#Cp'#CpO${QdO'#CqO)vQvO'#CsO+TQtO,5:POOQO'#Cx'#CxO)iQWO'#CwO+iQWO'#CyOOQS'#Em'#EmOOQO'#Dh'#DhO+nQ[O'#DoO+|QWO'#EqO&]Q[O'#DmO,[QWO'#DpOOQO'#Er'#ErO({QWO,5:^O,aQpO,5:`OOQS'#Dx'#DxO,iQWO,5:bO,nQ[O,5:bOOQO'#D{'#D{O,vQWO,5:eO,{QWO,5:kO-TQWO,5:mOOQS-E8S-E8SO${QdO,59{O-]Q[O'#EZO-jQWO,5;[O-jQWO,5;[POOO'#ET'#ETP-uO#tO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JZP;=`<%l$}\",\n tokenizers: [descendant, unitToken, identifiers, 1, 2, 3, 4, new LocalTokenGroup(\"m~RRYZ[z{a~~g~aO#Z~~dP!P!Qg~lO#[~~\", 28, 102)],\n topRules: {\"StyleSheet\":[0,4],\"Styles\":[1,84]},\n specialized: [{term: 97, get: (value) => spec_callee[value] || -1},{term: 56, get: (value) => spec_AtKeyword[value] || -1},{term: 98, get: (value) => spec_identifier[value] || -1}],\n tokenPrec: 1169\n});\n\nexport { parser };\n","import { parser } from '@lezer/css';\nimport { syntaxTree, LRLanguage, indentNodeProp, continuedIndent, foldNodeProp, foldInside, LanguageSupport } from '@codemirror/language';\nimport { NodeWeakMap, IterMode } from '@lezer/common';\n\nlet _properties = null;\nfunction properties() {\n if (!_properties && typeof document == \"object\" && document.body) {\n let { style } = document.body, names = [], seen = new Set;\n for (let prop in style)\n if (prop != \"cssText\" && prop != \"cssFloat\") {\n if (typeof style[prop] == \"string\") {\n if (/[A-Z]/.test(prop))\n prop = prop.replace(/[A-Z]/g, ch => \"-\" + ch.toLowerCase());\n if (!seen.has(prop)) {\n names.push(prop);\n seen.add(prop);\n }\n }\n }\n _properties = names.sort().map(name => ({ type: \"property\", label: name }));\n }\n return _properties || [];\n}\nconst pseudoClasses = /*@__PURE__*/[\n \"active\", \"after\", \"any-link\", \"autofill\", \"backdrop\", \"before\",\n \"checked\", \"cue\", \"default\", \"defined\", \"disabled\", \"empty\",\n \"enabled\", \"file-selector-button\", \"first\", \"first-child\",\n \"first-letter\", \"first-line\", \"first-of-type\", \"focus\",\n \"focus-visible\", \"focus-within\", \"fullscreen\", \"has\", \"host\",\n \"host-context\", \"hover\", \"in-range\", \"indeterminate\", \"invalid\",\n \"is\", \"lang\", \"last-child\", \"last-of-type\", \"left\", \"link\", \"marker\",\n \"modal\", \"not\", \"nth-child\", \"nth-last-child\", \"nth-last-of-type\",\n \"nth-of-type\", \"only-child\", \"only-of-type\", \"optional\", \"out-of-range\",\n \"part\", \"placeholder\", \"placeholder-shown\", \"read-only\", \"read-write\",\n \"required\", \"right\", \"root\", \"scope\", \"selection\", \"slotted\", \"target\",\n \"target-text\", \"valid\", \"visited\", \"where\"\n].map(name => ({ type: \"class\", label: name }));\nconst values = /*@__PURE__*/[\n \"above\", \"absolute\", \"activeborder\", \"additive\", \"activecaption\", \"after-white-space\",\n \"ahead\", \"alias\", \"all\", \"all-scroll\", \"alphabetic\", \"alternate\", \"always\",\n \"antialiased\", \"appworkspace\", \"asterisks\", \"attr\", \"auto\", \"auto-flow\", \"avoid\", \"avoid-column\",\n \"avoid-page\", \"avoid-region\", \"axis-pan\", \"background\", \"backwards\", \"baseline\", \"below\",\n \"bidi-override\", \"blink\", \"block\", \"block-axis\", \"bold\", \"bolder\", \"border\", \"border-box\",\n \"both\", \"bottom\", \"break\", \"break-all\", \"break-word\", \"bullets\", \"button\", \"button-bevel\",\n \"buttonface\", \"buttonhighlight\", \"buttonshadow\", \"buttontext\", \"calc\", \"capitalize\",\n \"caps-lock-indicator\", \"caption\", \"captiontext\", \"caret\", \"cell\", \"center\", \"checkbox\", \"circle\",\n \"cjk-decimal\", \"clear\", \"clip\", \"close-quote\", \"col-resize\", \"collapse\", \"color\", \"color-burn\",\n \"color-dodge\", \"column\", \"column-reverse\", \"compact\", \"condensed\", \"contain\", \"content\",\n \"contents\", \"content-box\", \"context-menu\", \"continuous\", \"copy\", \"counter\", \"counters\", \"cover\",\n \"crop\", \"cross\", \"crosshair\", \"currentcolor\", \"cursive\", \"cyclic\", \"darken\", \"dashed\", \"decimal\",\n \"decimal-leading-zero\", \"default\", \"default-button\", \"dense\", \"destination-atop\", \"destination-in\",\n \"destination-out\", \"destination-over\", \"difference\", \"disc\", \"discard\", \"disclosure-closed\",\n \"disclosure-open\", \"document\", \"dot-dash\", \"dot-dot-dash\", \"dotted\", \"double\", \"down\", \"e-resize\",\n \"ease\", \"ease-in\", \"ease-in-out\", \"ease-out\", \"element\", \"ellipse\", \"ellipsis\", \"embed\", \"end\",\n \"ethiopic-abegede-gez\", \"ethiopic-halehame-aa-er\", \"ethiopic-halehame-gez\", \"ew-resize\", \"exclusion\",\n \"expanded\", \"extends\", \"extra-condensed\", \"extra-expanded\", \"fantasy\", \"fast\", \"fill\", \"fill-box\",\n \"fixed\", \"flat\", \"flex\", \"flex-end\", \"flex-start\", \"footnotes\", \"forwards\", \"from\",\n \"geometricPrecision\", \"graytext\", \"grid\", \"groove\", \"hand\", \"hard-light\", \"help\", \"hidden\", \"hide\",\n \"higher\", \"highlight\", \"highlighttext\", \"horizontal\", \"hsl\", \"hsla\", \"hue\", \"icon\", \"ignore\",\n \"inactiveborder\", \"inactivecaption\", \"inactivecaptiontext\", \"infinite\", \"infobackground\", \"infotext\",\n \"inherit\", \"initial\", \"inline\", \"inline-axis\", \"inline-block\", \"inline-flex\", \"inline-grid\",\n \"inline-table\", \"inset\", \"inside\", \"intrinsic\", \"invert\", \"italic\", \"justify\", \"keep-all\",\n \"landscape\", \"large\", \"larger\", \"left\", \"level\", \"lighter\", \"lighten\", \"line-through\", \"linear\",\n \"linear-gradient\", \"lines\", \"list-item\", \"listbox\", \"listitem\", \"local\", \"logical\", \"loud\", \"lower\",\n \"lower-hexadecimal\", \"lower-latin\", \"lower-norwegian\", \"lowercase\", \"ltr\", \"luminosity\", \"manipulation\",\n \"match\", \"matrix\", \"matrix3d\", \"medium\", \"menu\", \"menutext\", \"message-box\", \"middle\", \"min-intrinsic\",\n \"mix\", \"monospace\", \"move\", \"multiple\", \"multiple_mask_images\", \"multiply\", \"n-resize\", \"narrower\",\n \"ne-resize\", \"nesw-resize\", \"no-close-quote\", \"no-drop\", \"no-open-quote\", \"no-repeat\", \"none\",\n \"normal\", \"not-allowed\", \"nowrap\", \"ns-resize\", \"numbers\", \"numeric\", \"nw-resize\", \"nwse-resize\",\n \"oblique\", \"opacity\", \"open-quote\", \"optimizeLegibility\", \"optimizeSpeed\", \"outset\", \"outside\",\n \"outside-shape\", \"overlay\", \"overline\", \"padding\", \"padding-box\", \"painted\", \"page\", \"paused\",\n \"perspective\", \"pinch-zoom\", \"plus-darker\", \"plus-lighter\", \"pointer\", \"polygon\", \"portrait\",\n \"pre\", \"pre-line\", \"pre-wrap\", \"preserve-3d\", \"progress\", \"push-button\", \"radial-gradient\", \"radio\",\n \"read-only\", \"read-write\", \"read-write-plaintext-only\", \"rectangle\", \"region\", \"relative\", \"repeat\",\n \"repeating-linear-gradient\", \"repeating-radial-gradient\", \"repeat-x\", \"repeat-y\", \"reset\", \"reverse\",\n \"rgb\", \"rgba\", \"ridge\", \"right\", \"rotate\", \"rotate3d\", \"rotateX\", \"rotateY\", \"rotateZ\", \"round\",\n \"row\", \"row-resize\", \"row-reverse\", \"rtl\", \"run-in\", \"running\", \"s-resize\", \"sans-serif\", \"saturation\",\n \"scale\", \"scale3d\", \"scaleX\", \"scaleY\", \"scaleZ\", \"screen\", \"scroll\", \"scrollbar\", \"scroll-position\",\n \"se-resize\", \"self-start\", \"self-end\", \"semi-condensed\", \"semi-expanded\", \"separate\", \"serif\", \"show\",\n \"single\", \"skew\", \"skewX\", \"skewY\", \"skip-white-space\", \"slide\", \"slider-horizontal\",\n \"slider-vertical\", \"sliderthumb-horizontal\", \"sliderthumb-vertical\", \"slow\", \"small\", \"small-caps\",\n \"small-caption\", \"smaller\", \"soft-light\", \"solid\", \"source-atop\", \"source-in\", \"source-out\",\n \"source-over\", \"space\", \"space-around\", \"space-between\", \"space-evenly\", \"spell-out\", \"square\", \"start\",\n \"static\", \"status-bar\", \"stretch\", \"stroke\", \"stroke-box\", \"sub\", \"subpixel-antialiased\", \"svg_masks\",\n \"super\", \"sw-resize\", \"symbolic\", \"symbols\", \"system-ui\", \"table\", \"table-caption\", \"table-cell\",\n \"table-column\", \"table-column-group\", \"table-footer-group\", \"table-header-group\", \"table-row\",\n \"table-row-group\", \"text\", \"text-bottom\", \"text-top\", \"textarea\", \"textfield\", \"thick\", \"thin\",\n \"threeddarkshadow\", \"threedface\", \"threedhighlight\", \"threedlightshadow\", \"threedshadow\", \"to\", \"top\",\n \"transform\", \"translate\", \"translate3d\", \"translateX\", \"translateY\", \"translateZ\", \"transparent\",\n \"ultra-condensed\", \"ultra-expanded\", \"underline\", \"unidirectional-pan\", \"unset\", \"up\", \"upper-latin\",\n \"uppercase\", \"url\", \"var\", \"vertical\", \"vertical-text\", \"view-box\", \"visible\", \"visibleFill\",\n \"visiblePainted\", \"visibleStroke\", \"visual\", \"w-resize\", \"wait\", \"wave\", \"wider\", \"window\", \"windowframe\",\n \"windowtext\", \"words\", \"wrap\", \"wrap-reverse\", \"x-large\", \"x-small\", \"xor\", \"xx-large\", \"xx-small\"\n].map(name => ({ type: \"keyword\", label: name })).concat(/*@__PURE__*/[\n \"aliceblue\", \"antiquewhite\", \"aqua\", \"aquamarine\", \"azure\", \"beige\",\n \"bisque\", \"black\", \"blanchedalmond\", \"blue\", \"blueviolet\", \"brown\",\n \"burlywood\", \"cadetblue\", \"chartreuse\", \"chocolate\", \"coral\", \"cornflowerblue\",\n \"cornsilk\", \"crimson\", \"cyan\", \"darkblue\", \"darkcyan\", \"darkgoldenrod\",\n \"darkgray\", \"darkgreen\", \"darkkhaki\", \"darkmagenta\", \"darkolivegreen\",\n \"darkorange\", \"darkorchid\", \"darkred\", \"darksalmon\", \"darkseagreen\",\n \"darkslateblue\", \"darkslategray\", \"darkturquoise\", \"darkviolet\",\n \"deeppink\", \"deepskyblue\", \"dimgray\", \"dodgerblue\", \"firebrick\",\n \"floralwhite\", \"forestgreen\", \"fuchsia\", \"gainsboro\", \"ghostwhite\",\n \"gold\", \"goldenrod\", \"gray\", \"grey\", \"green\", \"greenyellow\", \"honeydew\",\n \"hotpink\", \"indianred\", \"indigo\", \"ivory\", \"khaki\", \"lavender\",\n \"lavenderblush\", \"lawngreen\", \"lemonchiffon\", \"lightblue\", \"lightcoral\",\n \"lightcyan\", \"lightgoldenrodyellow\", \"lightgray\", \"lightgreen\", \"lightpink\",\n \"lightsalmon\", \"lightseagreen\", \"lightskyblue\", \"lightslategray\",\n \"lightsteelblue\", \"lightyellow\", \"lime\", \"limegreen\", \"linen\", \"magenta\",\n \"maroon\", \"mediumaquamarine\", \"mediumblue\", \"mediumorchid\", \"mediumpurple\",\n \"mediumseagreen\", \"mediumslateblue\", \"mediumspringgreen\", \"mediumturquoise\",\n \"mediumvioletred\", \"midnightblue\", \"mintcream\", \"mistyrose\", \"moccasin\",\n \"navajowhite\", \"navy\", \"oldlace\", \"olive\", \"olivedrab\", \"orange\", \"orangered\",\n \"orchid\", \"palegoldenrod\", \"palegreen\", \"paleturquoise\", \"palevioletred\",\n \"papayawhip\", \"peachpuff\", \"peru\", \"pink\", \"plum\", \"powderblue\",\n \"purple\", \"rebeccapurple\", \"red\", \"rosybrown\", \"royalblue\", \"saddlebrown\",\n \"salmon\", \"sandybrown\", \"seagreen\", \"seashell\", \"sienna\", \"silver\", \"skyblue\",\n \"slateblue\", \"slategray\", \"snow\", \"springgreen\", \"steelblue\", \"tan\",\n \"teal\", \"thistle\", \"tomato\", \"turquoise\", \"violet\", \"wheat\", \"white\",\n \"whitesmoke\", \"yellow\", \"yellowgreen\"\n].map(name => ({ type: \"constant\", label: name })));\nconst tags = /*@__PURE__*/[\n \"a\", \"abbr\", \"address\", \"article\", \"aside\", \"b\", \"bdi\", \"bdo\", \"blockquote\", \"body\",\n \"br\", \"button\", \"canvas\", \"caption\", \"cite\", \"code\", \"col\", \"colgroup\", \"dd\", \"del\",\n \"details\", \"dfn\", \"dialog\", \"div\", \"dl\", \"dt\", \"em\", \"figcaption\", \"figure\", \"footer\",\n \"form\", \"header\", \"hgroup\", \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\", \"hr\", \"html\", \"i\", \"iframe\",\n \"img\", \"input\", \"ins\", \"kbd\", \"label\", \"legend\", \"li\", \"main\", \"meter\", \"nav\", \"ol\", \"output\",\n \"p\", \"pre\", \"ruby\", \"section\", \"select\", \"small\", \"source\", \"span\", \"strong\", \"sub\", \"summary\",\n \"sup\", \"table\", \"tbody\", \"td\", \"template\", \"textarea\", \"tfoot\", \"th\", \"thead\", \"tr\", \"u\", \"ul\"\n].map(name => ({ type: \"type\", label: name }));\nconst identifier = /^(\\w[\\w-]*|-\\w[\\w-]*|)$/, variable = /^-(-[\\w-]*)?$/;\nfunction isVarArg(node, doc) {\n var _a;\n if (node.name == \"(\" || node.type.isError)\n node = node.parent || node;\n if (node.name != \"ArgList\")\n return false;\n let callee = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.firstChild;\n if ((callee === null || callee === void 0 ? void 0 : callee.name) != \"Callee\")\n return false;\n return doc.sliceString(callee.from, callee.to) == \"var\";\n}\nconst VariablesByNode = /*@__PURE__*/new NodeWeakMap();\nconst declSelector = [\"Declaration\"];\nfunction astTop(node) {\n for (let cur = node;;) {\n if (cur.type.isTop)\n return cur;\n if (!(cur = cur.parent))\n return node;\n }\n}\nfunction variableNames(doc, node, isVariable) {\n if (node.to - node.from > 4096) {\n let known = VariablesByNode.get(node);\n if (known)\n return known;\n let result = [], seen = new Set, cursor = node.cursor(IterMode.IncludeAnonymous);\n if (cursor.firstChild())\n do {\n for (let option of variableNames(doc, cursor.node, isVariable))\n if (!seen.has(option.label)) {\n seen.add(option.label);\n result.push(option);\n }\n } while (cursor.nextSibling());\n VariablesByNode.set(node, result);\n return result;\n }\n else {\n let result = [], seen = new Set;\n node.cursor().iterate(node => {\n var _a;\n if (isVariable(node) && node.matchContext(declSelector) && ((_a = node.node.nextSibling) === null || _a === void 0 ? void 0 : _a.name) == \":\") {\n let name = doc.sliceString(node.from, node.to);\n if (!seen.has(name)) {\n seen.add(name);\n result.push({ label: name, type: \"variable\" });\n }\n }\n });\n return result;\n }\n}\n/**\nCreate a completion source for a CSS dialect, providing a\npredicate for determining what kind of syntax node can act as a\ncompletable variable. This is used by language modes like Sass and\nLess to reuse this package's completion logic.\n*/\nconst defineCSSCompletionSource = (isVariable) => context => {\n let { state, pos } = context, node = syntaxTree(state).resolveInner(pos, -1);\n let isDash = node.type.isError && node.from == node.to - 1 && state.doc.sliceString(node.from, node.to) == \"-\";\n if (node.name == \"PropertyName\" ||\n (isDash || node.name == \"TagName\") && /^(Block|Styles)$/.test(node.resolve(node.to).name))\n return { from: node.from, options: properties(), validFor: identifier };\n if (node.name == \"ValueName\")\n return { from: node.from, options: values, validFor: identifier };\n if (node.name == \"PseudoClassName\")\n return { from: node.from, options: pseudoClasses, validFor: identifier };\n if (isVariable(node) || (context.explicit || isDash) && isVarArg(node, state.doc))\n return { from: isVariable(node) || isDash ? node.from : pos,\n options: variableNames(state.doc, astTop(node), isVariable),\n validFor: variable };\n if (node.name == \"TagName\") {\n for (let { parent } = node; parent; parent = parent.parent)\n if (parent.name == \"Block\")\n return { from: node.from, options: properties(), validFor: identifier };\n return { from: node.from, options: tags, validFor: identifier };\n }\n if (!context.explicit)\n return null;\n let above = node.resolve(pos), before = above.childBefore(pos);\n if (before && before.name == \":\" && above.name == \"PseudoClassSelector\")\n return { from: pos, options: pseudoClasses, validFor: identifier };\n if (before && before.name == \":\" && above.name == \"Declaration\" || above.name == \"ArgList\")\n return { from: pos, options: values, validFor: identifier };\n if (above.name == \"Block\" || above.name == \"Styles\")\n return { from: pos, options: properties(), validFor: identifier };\n return null;\n};\n/**\nCSS property, variable, and value keyword completion source.\n*/\nconst cssCompletionSource = /*@__PURE__*/defineCSSCompletionSource(n => n.name == \"VariableName\");\n\n/**\nA language provider based on the [Lezer CSS\nparser](https://github.com/lezer-parser/css), extended with\nhighlighting and indentation information.\n*/\nconst cssLanguage = /*@__PURE__*/LRLanguage.define({\n name: \"css\",\n parser: /*@__PURE__*/parser.configure({\n props: [\n /*@__PURE__*/indentNodeProp.add({\n Declaration: /*@__PURE__*/continuedIndent()\n }),\n /*@__PURE__*/foldNodeProp.add({\n \"Block KeyframeList\": foldInside\n })\n ]\n }),\n languageData: {\n commentTokens: { block: { open: \"/*\", close: \"*/\" } },\n indentOnInput: /^\\s*\\}$/,\n wordChars: \"-\"\n }\n});\n/**\nLanguage support for CSS.\n*/\nfunction css() {\n return new LanguageSupport(cssLanguage, cssLanguage.data.of({ autocomplete: cssCompletionSource }));\n}\n\nexport { css, cssCompletionSource, cssLanguage, defineCSSCompletionSource };\n"],"names":["space","isAlpha","ch","identifiers","input","stack","inside","dashes","i","next","advance","peek","acceptToken","canShift","descendant","includes","unitToken","cssHighlighting","NamespaceName","KeyframeName","KeyframeRangeName","TagName","ClassName","PseudoClassName","IdName","AttributeName","NumberLiteral","KeywordQuery","UnaryQueryOp","VariableName","Callee","Unit","MatchOp","BinOp","Important","Comment","ColorLiteral","spec_callee","__proto__","lang","dir","url","domain","regexp","selector","spec_AtKeyword","spec_identifier","not","only","parser","version","states","stateData","goto","nodeNames","maxTerm","nodeProps","propSources","skippedNodes","repeatNodeCount","tokenData","tokenizers","topRules","specialized","term","get","value","tokenPrec","_properties","properties","document","body","style","names","seen","Set","prop","test","replace","toLowerCase","has","push","add","sort","map","name","type","label","pseudoClasses","values","concat","tags","variable","VariablesByNode","declSelector","astTop","node","cur","isTop","parent","variableNames","doc","isVariable","to","from","known","result","cursor","firstChild","option","nextSibling","set","iterate","_a","matchContext","sliceString","defineCSSCompletionSource","context","state","pos","resolveInner","isDash","isError","resolve","options","validFor","explicit","callee","isVarArg","above","before","childBefore","cssCompletionSource","n","cssLanguage","configure","props","Declaration","languageData","commentTokens","block","open","close","indentOnInput","wordChars","css","data","of","autocomplete"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/432.index.js b/book/_build/html/_static/432.index.js new file mode 100644 index 0000000..05150f6 --- /dev/null +++ b/book/_build/html/_static/432.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[432],{90432:(E,T,I)=>{I.r(T),I.d(T,{cobol:()=>S});var N="string",R="atom";function A(E){for(var T={},I=E.split(" "),N=0;N >= "),D={digit:/\d/,digit_or_colon:/[\d:]/,hex:/[0-9a-f]/i,sign:/[+-]/,exponent:/e/i,keyword_char:/[^\s\(\[\;\)\]]/,symbol:/[\w*+\-]/};const S={name:"cobol",startState:function(){return{indentStack:null,indentation:0,mode:!1}},token:function(E,T){if(null==T.indentStack&&E.sol()&&(T.indentation=6),E.eatSpace())return null;var I=null;if("string"===T.mode){for(var A=!1;null!=(A=E.next());)if(('"'==A||"'"==A)&&!E.match(/['"]/,!1)){T.mode=!1;break}I=N}else{var S=E.next(),U=E.column();if(U>=0&&U<=5)I="def";else if(U>=72&&U<=79)E.skipToEnd(),I="header";else if("*"==S&&6==U)E.skipToEnd(),I="comment";else if('"'==S||"'"==S)T.mode="string",I=N;else if("'"!=S||D.digit_or_colon.test(E.peek()))if("."==S)I="link";else if(function(E,T){return"0"===E&&T.eat(/x/i)?(T.eatWhile(D.hex),!0):("+"!=E&&"-"!=E||!D.digit.test(T.peek())||(T.eat(D.sign),E=T.next()),!!D.digit.test(E)&&(T.eat(E),T.eatWhile(D.digit),"."==T.peek()&&(T.eat("."),T.eatWhile(D.digit)),T.eat(D.exponent)&&(T.eat(D.sign),T.eatWhile(D.digit)),!0))}(S,E))I="number";else{if(E.current().match(D.symbol))for(;U<71&&void 0!==E.eat(D.symbol);)U++;I=C&&C.propertyIsEnumerable(E.current().toUpperCase())?"keyword":L&&L.propertyIsEnumerable(E.current().toUpperCase())?"builtin":O&&O.propertyIsEnumerable(E.current().toUpperCase())?R:null}else I=R}return I},indent:function(E){return null==E.indentStack?E.indentation:E.indentStack.indent}}}}]); +//# sourceMappingURL=432.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/432.index.js.map b/book/_build/html/_static/432.index.js.map new file mode 100644 index 0000000..ae06632 --- /dev/null +++ b/book/_build/html/_static/432.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"432.index.js","mappings":"0HAAA,IAA8CA,EAAS,SACnDC,EAAO,OAEX,SAASC,EAAaC,GAEpB,IADA,IAAIC,EAAM,CAAC,EAAGC,EAAQF,EAAIG,MAAM,KACvBC,EAAI,EAAGA,EAAIF,EAAMG,SAAUD,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I5B,EAAMI,MACjBkB,EAAKP,EAAOK,UAETpB,EAAMC,MAAMyB,KAAKJ,KACpBP,EAAOa,IAAIN,GACXP,EAAOc,SAAS7B,EAAMC,OACjB,KAAOc,EAAOY,SACjBZ,EAAOa,IAAI,KACXb,EAAOc,SAAS7B,EAAMC,QAEnBc,EAAOa,IAAI5B,EAAMK,YACpBU,EAAOa,IAAI5B,EAAMI,MACjBW,EAAOc,SAAS7B,EAAMC,SAEjB,GAGX,CAiDiB6B,CAASR,EAAGP,GACrBI,EA7MoB,aA8Mf,CACL,GAAIJ,EAAOgB,UAAUV,MAAMrB,EAAMO,QAC/B,KAAOgB,EAAM,SACsBS,IAA7BjB,EAAOa,IAAI5B,EAAMO,SAGnBgB,IAKJJ,EADErB,GAAYA,EAASmC,qBAAqBlB,EAAOgB,UAAUG,eAxNvB,UA0N7BnC,GAAYA,EAASkC,qBAAqBlB,EAAOgB,UAAUG,eA3NhE,UA6NKrC,GAASA,EAAMoC,qBAAqBlB,EAAOgB,UAAUG,eACjD7C,EACK,IACtB,MAtBE8B,EAAa9B,CAsBf,CAEF,OAAO8B,CACT,EACAgB,OAAQ,SAAUnB,GAChB,OAAyB,MAArBA,EAAML,YAA4BK,EAAMJ,YACrCI,EAAML,YAAYwB,MAC3B,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/cobol.js"],"sourcesContent":["var BUILTIN = \"builtin\", COMMENT = \"comment\", STRING = \"string\",\n ATOM = \"atom\", NUMBER = \"number\", KEYWORD = \"keyword\", MODTAG = \"header\",\n COBOLLINENUM = \"def\", PERIOD = \"link\";\nfunction makeKeywords(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n}\nvar atoms = makeKeywords(\"TRUE FALSE ZEROES ZEROS ZERO SPACES SPACE LOW-VALUE LOW-VALUES \");\nvar keywords = makeKeywords(\n \"ACCEPT ACCESS ACQUIRE ADD ADDRESS \" +\n \"ADVANCING AFTER ALIAS ALL ALPHABET \" +\n \"ALPHABETIC ALPHABETIC-LOWER ALPHABETIC-UPPER ALPHANUMERIC ALPHANUMERIC-EDITED \" +\n \"ALSO ALTER ALTERNATE AND ANY \" +\n \"ARE AREA AREAS ARITHMETIC ASCENDING \" +\n \"ASSIGN AT ATTRIBUTE AUTHOR AUTO \" +\n \"AUTO-SKIP AUTOMATIC B-AND B-EXOR B-LESS \" +\n \"B-NOT B-OR BACKGROUND-COLOR BACKGROUND-COLOUR BEEP \" +\n \"BEFORE BELL BINARY BIT BITS \" +\n \"BLANK BLINK BLOCK BOOLEAN BOTTOM \" +\n \"BY CALL CANCEL CD CF \" +\n \"CH CHARACTER CHARACTERS CLASS CLOCK-UNITS \" +\n \"CLOSE COBOL CODE CODE-SET COL \" +\n \"COLLATING COLUMN COMMA COMMIT COMMITMENT \" +\n \"COMMON COMMUNICATION COMP COMP-0 COMP-1 \" +\n \"COMP-2 COMP-3 COMP-4 COMP-5 COMP-6 \" +\n \"COMP-7 COMP-8 COMP-9 COMPUTATIONAL COMPUTATIONAL-0 \" +\n \"COMPUTATIONAL-1 COMPUTATIONAL-2 COMPUTATIONAL-3 COMPUTATIONAL-4 COMPUTATIONAL-5 \" +\n \"COMPUTATIONAL-6 COMPUTATIONAL-7 COMPUTATIONAL-8 COMPUTATIONAL-9 COMPUTE \" +\n \"CONFIGURATION CONNECT CONSOLE CONTAINED CONTAINS \" +\n \"CONTENT CONTINUE CONTROL CONTROL-AREA CONTROLS \" +\n \"CONVERTING COPY CORR CORRESPONDING COUNT \" +\n \"CRT CRT-UNDER CURRENCY CURRENT CURSOR \" +\n \"DATA DATE DATE-COMPILED DATE-WRITTEN DAY \" +\n \"DAY-OF-WEEK DB DB-ACCESS-CONTROL-KEY DB-DATA-NAME DB-EXCEPTION \" +\n \"DB-FORMAT-NAME DB-RECORD-NAME DB-SET-NAME DB-STATUS DBCS \" +\n \"DBCS-EDITED DE DEBUG-CONTENTS DEBUG-ITEM DEBUG-LINE \" +\n \"DEBUG-NAME DEBUG-SUB-1 DEBUG-SUB-2 DEBUG-SUB-3 DEBUGGING \" +\n \"DECIMAL-POINT DECLARATIVES DEFAULT DELETE DELIMITED \" +\n \"DELIMITER DEPENDING DESCENDING DESCRIBED DESTINATION \" +\n \"DETAIL DISABLE DISCONNECT DISPLAY DISPLAY-1 \" +\n \"DISPLAY-2 DISPLAY-3 DISPLAY-4 DISPLAY-5 DISPLAY-6 \" +\n \"DISPLAY-7 DISPLAY-8 DISPLAY-9 DIVIDE DIVISION \" +\n \"DOWN DROP DUPLICATE DUPLICATES DYNAMIC \" +\n \"EBCDIC EGI EJECT ELSE EMI \" +\n \"EMPTY EMPTY-CHECK ENABLE END END. END-ACCEPT END-ACCEPT. \" +\n \"END-ADD END-CALL END-COMPUTE END-DELETE END-DISPLAY \" +\n \"END-DIVIDE END-EVALUATE END-IF END-INVOKE END-MULTIPLY \" +\n \"END-OF-PAGE END-PERFORM END-READ END-RECEIVE END-RETURN \" +\n \"END-REWRITE END-SEARCH END-START END-STRING END-SUBTRACT \" +\n \"END-UNSTRING END-WRITE END-XML ENTER ENTRY \" +\n \"ENVIRONMENT EOP EQUAL EQUALS ERASE \" +\n \"ERROR ESI EVALUATE EVERY EXCEEDS \" +\n \"EXCEPTION EXCLUSIVE EXIT EXTEND EXTERNAL \" +\n \"EXTERNALLY-DESCRIBED-KEY FD FETCH FILE FILE-CONTROL \" +\n \"FILE-STREAM FILES FILLER FINAL FIND \" +\n \"FINISH FIRST FOOTING FOR FOREGROUND-COLOR \" +\n \"FOREGROUND-COLOUR FORMAT FREE FROM FULL \" +\n \"FUNCTION GENERATE GET GIVING GLOBAL \" +\n \"GO GOBACK GREATER GROUP HEADING \" +\n \"HIGH-VALUE HIGH-VALUES HIGHLIGHT I-O I-O-CONTROL \" +\n \"ID IDENTIFICATION IF IN INDEX \" +\n \"INDEX-1 INDEX-2 INDEX-3 INDEX-4 INDEX-5 \" +\n \"INDEX-6 INDEX-7 INDEX-8 INDEX-9 INDEXED \" +\n \"INDIC INDICATE INDICATOR INDICATORS INITIAL \" +\n \"INITIALIZE INITIATE INPUT INPUT-OUTPUT INSPECT \" +\n \"INSTALLATION INTO INVALID INVOKE IS \" +\n \"JUST JUSTIFIED KANJI KEEP KEY \" +\n \"LABEL LAST LD LEADING LEFT \" +\n \"LEFT-JUSTIFY LENGTH LENGTH-CHECK LESS LIBRARY \" +\n \"LIKE LIMIT LIMITS LINAGE LINAGE-COUNTER \" +\n \"LINE LINE-COUNTER LINES LINKAGE LOCAL-STORAGE \" +\n \"LOCALE LOCALLY LOCK \" +\n \"MEMBER MEMORY MERGE MESSAGE METACLASS \" +\n \"MODE MODIFIED MODIFY MODULES MOVE \" +\n \"MULTIPLE MULTIPLY NATIONAL NATIVE NEGATIVE \" +\n \"NEXT NO NO-ECHO NONE NOT \" +\n \"NULL NULL-KEY-MAP NULL-MAP NULLS NUMBER \" +\n \"NUMERIC NUMERIC-EDITED OBJECT OBJECT-COMPUTER OCCURS \" +\n \"OF OFF OMITTED ON ONLY \" +\n \"OPEN OPTIONAL OR ORDER ORGANIZATION \" +\n \"OTHER OUTPUT OVERFLOW OWNER PACKED-DECIMAL \" +\n \"PADDING PAGE PAGE-COUNTER PARSE PERFORM \" +\n \"PF PH PIC PICTURE PLUS \" +\n \"POINTER POSITION POSITIVE PREFIX PRESENT \" +\n \"PRINTING PRIOR PROCEDURE PROCEDURE-POINTER PROCEDURES \" +\n \"PROCEED PROCESS PROCESSING PROGRAM PROGRAM-ID \" +\n \"PROMPT PROTECTED PURGE QUEUE QUOTE \" +\n \"QUOTES RANDOM RD READ READY \" +\n \"REALM RECEIVE RECONNECT RECORD RECORD-NAME \" +\n \"RECORDS RECURSIVE REDEFINES REEL REFERENCE \" +\n \"REFERENCE-MONITOR REFERENCES RELATION RELATIVE RELEASE \" +\n \"REMAINDER REMOVAL RENAMES REPEATED REPLACE \" +\n \"REPLACING REPORT REPORTING REPORTS REPOSITORY \" +\n \"REQUIRED RERUN RESERVE RESET RETAINING \" +\n \"RETRIEVAL RETURN RETURN-CODE RETURNING REVERSE-VIDEO \" +\n \"REVERSED REWIND REWRITE RF RH \" +\n \"RIGHT RIGHT-JUSTIFY ROLLBACK ROLLING ROUNDED \" +\n \"RUN SAME SCREEN SD SEARCH \" +\n \"SECTION SECURE SECURITY SEGMENT SEGMENT-LIMIT \" +\n \"SELECT SEND SENTENCE SEPARATE SEQUENCE \" +\n \"SEQUENTIAL SET SHARED SIGN SIZE \" +\n \"SKIP1 SKIP2 SKIP3 SORT SORT-MERGE \" +\n \"SORT-RETURN SOURCE SOURCE-COMPUTER SPACE-FILL \" +\n \"SPECIAL-NAMES STANDARD STANDARD-1 STANDARD-2 \" +\n \"START STARTING STATUS STOP STORE \" +\n \"STRING SUB-QUEUE-1 SUB-QUEUE-2 SUB-QUEUE-3 SUB-SCHEMA \" +\n \"SUBFILE SUBSTITUTE SUBTRACT SUM SUPPRESS \" +\n \"SYMBOLIC SYNC SYNCHRONIZED SYSIN SYSOUT \" +\n \"TABLE TALLYING TAPE TENANT TERMINAL \" +\n \"TERMINATE TEST TEXT THAN THEN \" +\n \"THROUGH THRU TIME TIMES TITLE \" +\n \"TO TOP TRAILING TRAILING-SIGN TRANSACTION \" +\n \"TYPE TYPEDEF UNDERLINE UNEQUAL UNIT \" +\n \"UNSTRING UNTIL UP UPDATE UPON \" +\n \"USAGE USAGE-MODE USE USING VALID \" +\n \"VALIDATE VALUE VALUES VARYING VLR \" +\n \"WAIT WHEN WHEN-COMPILED WITH WITHIN \" +\n \"WORDS WORKING-STORAGE WRITE XML XML-CODE \" +\n \"XML-EVENT XML-NTEXT XML-TEXT ZERO ZERO-FILL \" );\n\nvar builtins = makeKeywords(\"- * ** / + < <= = > >= \");\nvar tests = {\n digit: /\\d/,\n digit_or_colon: /[\\d:]/,\n hex: /[0-9a-f]/i,\n sign: /[+-]/,\n exponent: /e/i,\n keyword_char: /[^\\s\\(\\[\\;\\)\\]]/,\n symbol: /[\\w*+\\-]/\n};\nfunction isNumber(ch, stream){\n // hex\n if ( ch === '0' && stream.eat(/x/i) ) {\n stream.eatWhile(tests.hex);\n return true;\n }\n // leading sign\n if ( ( ch == '+' || ch == '-' ) && ( tests.digit.test(stream.peek()) ) ) {\n stream.eat(tests.sign);\n ch = stream.next();\n }\n if ( tests.digit.test(ch) ) {\n stream.eat(ch);\n stream.eatWhile(tests.digit);\n if ( '.' == stream.peek()) {\n stream.eat('.');\n stream.eatWhile(tests.digit);\n }\n if ( stream.eat(tests.exponent) ) {\n stream.eat(tests.sign);\n stream.eatWhile(tests.digit);\n }\n return true;\n }\n return false;\n}\nexport const cobol = {\n name: \"cobol\",\n startState: function () {\n return {\n indentStack: null,\n indentation: 0,\n mode: false\n };\n },\n token: function (stream, state) {\n if (state.indentStack == null && stream.sol()) {\n // update indentation, but only if indentStack is empty\n state.indentation = 6 ; //stream.indentation();\n }\n // skip spaces\n if (stream.eatSpace()) {\n return null;\n }\n var returnType = null;\n switch(state.mode){\n case \"string\": // multi-line string parsing mode\n var next = false;\n while ((next = stream.next()) != null) {\n if ((next == \"\\\"\" || next == \"\\'\") && !stream.match(/['\"]/, false)) {\n state.mode = false;\n break;\n }\n }\n returnType = STRING; // continue on in string mode\n break;\n default: // default parsing mode\n var ch = stream.next();\n var col = stream.column();\n if (col >= 0 && col <= 5) {\n returnType = COBOLLINENUM;\n } else if (col >= 72 && col <= 79) {\n stream.skipToEnd();\n returnType = MODTAG;\n } else if (ch == \"*\" && col == 6) { // comment\n stream.skipToEnd(); // rest of the line is a comment\n returnType = COMMENT;\n } else if (ch == \"\\\"\" || ch == \"\\'\") {\n state.mode = \"string\";\n returnType = STRING;\n } else if (ch == \"'\" && !( tests.digit_or_colon.test(stream.peek()) )) {\n returnType = ATOM;\n } else if (ch == \".\") {\n returnType = PERIOD;\n } else if (isNumber(ch,stream)){\n returnType = NUMBER;\n } else {\n if (stream.current().match(tests.symbol)) {\n while (col < 71) {\n if (stream.eat(tests.symbol) === undefined) {\n break;\n } else {\n col++;\n }\n }\n }\n if (keywords && keywords.propertyIsEnumerable(stream.current().toUpperCase())) {\n returnType = KEYWORD;\n } else if (builtins && builtins.propertyIsEnumerable(stream.current().toUpperCase())) {\n returnType = BUILTIN;\n } else if (atoms && atoms.propertyIsEnumerable(stream.current().toUpperCase())) {\n returnType = ATOM;\n } else returnType = null;\n }\n }\n return returnType;\n },\n indent: function (state) {\n if (state.indentStack == null) return state.indentation;\n return state.indentStack.indent;\n }\n};\n\n"],"names":["STRING","ATOM","makeKeywords","str","obj","words","split","i","length","atoms","keywords","builtins","tests","digit","digit_or_colon","hex","sign","exponent","keyword_char","symbol","cobol","name","startState","indentStack","indentation","mode","token","stream","state","sol","eatSpace","returnType","next","match","ch","col","column","skipToEnd","test","peek","eat","eatWhile","isNumber","current","undefined","propertyIsEnumerable","toUpperCase","indent"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/4393.index.js b/book/_build/html/_static/4393.index.js new file mode 100644 index 0000000..fe02fb5 --- /dev/null +++ b/book/_build/html/_static/4393.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[4393],{84393:(e,t,i)=>{i.r(t),i.d(t,{properties:()=>n});const n={name:"properties",token:function(e,t){var i=e.sol()||t.afterSection,n=e.eol();if(t.afterSection=!1,i&&(t.nextMultiline?(t.inMultiline=!0,t.nextMultiline=!1):t.position="def"),n&&!t.nextMultiline&&(t.inMultiline=!1,t.position="def"),i)for(;e.eatSpace(););var o=e.next();return!i||"#"!==o&&"!"!==o&&";"!==o?i&&"["===o?(t.afterSection=!0,e.skipTo("]"),e.eat("]"),"header"):"="===o||":"===o?(t.position="quote",null):("\\"===o&&"quote"===t.position&&e.eol()&&(t.nextMultiline=!0),t.position):(t.position="comment",e.skipToEnd(),"comment")},startState:function(){return{position:"def",nextMultiline:!1,inMultiline:!1,afterSection:!1}}}}}]); +//# sourceMappingURL=4393.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/4393.index.js.map b/book/_build/html/_static/4393.index.js.map new file mode 100644 index 0000000..f217c59 --- /dev/null +++ b/book/_build/html/_static/4393.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"4393.index.js","mappings":"gIAAO,MAAMA,EAAa,CACxBC,KAAM,aAENC,MAAO,SAASC,EAAQC,GACtB,IAAIC,EAAMF,EAAOE,OAASD,EAAME,aAC5BC,EAAMJ,EAAOI,MAkBjB,GAhBAH,EAAME,cAAe,EAEjBD,IACED,EAAMI,eACRJ,EAAMK,aAAc,EACpBL,EAAMI,eAAgB,GAEtBJ,EAAMM,SAAW,OAIjBH,IAASH,EAAMI,gBACjBJ,EAAMK,aAAc,EACpBL,EAAMM,SAAW,OAGfL,EACF,KAAMF,EAAOQ,aAGf,IAAIC,EAAKT,EAAOU,OAEhB,OAAIR,GAAe,MAAPO,GAAqB,MAAPA,GAAqB,MAAPA,EAI7BP,GAAc,MAAPO,GAChBR,EAAME,cAAe,EACrBH,EAAOW,OAAO,KAAMX,EAAOY,IAAI,KACxB,UACS,MAAPH,GAAqB,MAAPA,GACvBR,EAAMM,SAAW,QACV,OACS,OAAPE,GAAkC,UAAnBR,EAAMM,UAC1BP,EAAOI,QAETH,EAAMI,eAAgB,GAInBJ,EAAMM,WAjBXN,EAAMM,SAAW,UACjBP,EAAOa,YACA,UAgBX,EAEAC,WAAY,WACV,MAAO,CACLP,SAAW,MACXF,eAAgB,EAChBC,aAAc,EACdH,cAAe,EAEnB,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/properties.js"],"sourcesContent":["export const properties = {\n name: \"properties\",\n\n token: function(stream, state) {\n var sol = stream.sol() || state.afterSection;\n var eol = stream.eol();\n\n state.afterSection = false;\n\n if (sol) {\n if (state.nextMultiline) {\n state.inMultiline = true;\n state.nextMultiline = false;\n } else {\n state.position = \"def\";\n }\n }\n\n if (eol && ! state.nextMultiline) {\n state.inMultiline = false;\n state.position = \"def\";\n }\n\n if (sol) {\n while(stream.eatSpace()) {}\n }\n\n var ch = stream.next();\n\n if (sol && (ch === \"#\" || ch === \"!\" || ch === \";\")) {\n state.position = \"comment\";\n stream.skipToEnd();\n return \"comment\";\n } else if (sol && ch === \"[\") {\n state.afterSection = true;\n stream.skipTo(\"]\"); stream.eat(\"]\");\n return \"header\";\n } else if (ch === \"=\" || ch === \":\") {\n state.position = \"quote\";\n return null;\n } else if (ch === \"\\\\\" && state.position === \"quote\") {\n if (stream.eol()) { // end of line?\n // Multiline value\n state.nextMultiline = true;\n }\n }\n\n return state.position;\n },\n\n startState: function() {\n return {\n position : \"def\", // Current position, \"def\", \"quote\" or \"comment\"\n nextMultiline : false, // Is the next line multiline value\n inMultiline : false, // Is the current line a multiline value\n afterSection : false // Did we just open a section\n };\n }\n\n};\n"],"names":["properties","name","token","stream","state","sol","afterSection","eol","nextMultiline","inMultiline","position","eatSpace","ch","next","skipTo","eat","skipToEnd","startState"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/4537.index.js b/book/_build/html/_static/4537.index.js new file mode 100644 index 0000000..42f4071 --- /dev/null +++ b/book/_build/html/_static/4537.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[4537],{94537:(e,t,n)=>{function r(e,t){return new RegExp((t?"":"^")+"(?:"+e.join("|")+")"+(t?"$":"\\b"))}function a(e,t,n){return n.tokenize.push(e),e(t,n)}n.r(t),n.d(t,{crystal:()=>S});var u=/^(?:[-+/%|&^]|\*\*?|[<>]{2})/,i=/^(?:[=!]~|===|<=>|[<>=!]=?|[|&]{2}|~)/,c=/^(?:\[\][?=]?)/,o=/^(?:\.(?:\.{2})?|->|[?:])/,s=/^[a-z_\u009F-\uFFFF][a-zA-Z0-9_\u009F-\uFFFF]*/,l=/^[A-Z_\u009F-\uFFFF][a-zA-Z0-9_\u009F-\uFFFF]*/,f=r(["abstract","alias","as","asm","begin","break","case","class","def","do","else","elsif","end","ensure","enum","extend","for","fun","if","include","instance_sizeof","lib","macro","module","next","of","out","pointerof","private","protected","rescue","return","require","select","sizeof","struct","super","then","type","typeof","uninitialized","union","unless","until","when","while","with","yield","__DIR__","__END_LINE__","__FILE__","__LINE__"]),m=r(["true","false","nil","self"]),h=r(["def","fun","macro","class","module","struct","lib","enum","union","do","for"]),p=r(["if","unless","case","while","until","begin","then"]),k=["end","else","elsif","rescue","ensure"],d=r(k),F=["\\)","\\}","\\]"],z=new RegExp("^(?:"+F.join("|")+")$"),_={def:y,fun:y,macro:function(e,t){if(e.eatSpace())return null;var n;if(n=e.match(s)){if("def"==n)return"keyword";e.eat(/[?!]/)}return t.tokenize.pop(),"def"},class:I,module:I,struct:I,lib:I,enum:I,union:I},b={"[":"]","{":"}","(":")","<":">"};function g(e,t){if(e.eatSpace())return null;if("\\"!=t.lastToken&&e.match("{%",!1))return a(x("%","%"),e,t);if("\\"!=t.lastToken&&e.match("{{",!1))return a(x("{","}"),e,t);if("#"==e.peek())return e.skipToEnd(),"comment";var n;if(e.match(s))return e.eat(/[?!]/),n=e.current(),e.eat(":")?"atom":"."==t.lastToken?"property":f.test(n)?(h.test(n)?"fun"==n&&t.blocks.indexOf("lib")>=0||"def"==n&&"abstract"==t.lastToken||(t.blocks.push(n),t.currentIndent+=1):"operator"!=t.lastStyle&&t.lastStyle||!p.test(n)?"end"==n&&(t.blocks.pop(),t.currentIndent-=1):(t.blocks.push(n),t.currentIndent+=1),_.hasOwnProperty(n)&&t.tokenize.push(_[n]),"keyword"):m.test(n)?"atom":"variable";if(e.eat("@"))return"["==e.peek()?a(w("[","]","meta"),e,t):(e.eat("@"),e.match(s)||e.match(l),"propertyName");if(e.match(l))return"tag";if(e.eat(":"))return e.eat('"')?a(v('"',"atom",!1),e,t):e.match(s)||e.match(l)||e.match(u)||e.match(i)||e.match(c)?"atom":(e.eat(":"),"operator");if(e.eat('"'))return a(v('"',"string",!0),e,t);if("%"==e.peek()){var r,k="string",d=!0;if(e.match("%r"))k="string.special",r=e.next();else if(e.match("%w"))d=!1,r=e.next();else if(e.match("%q"))d=!1,r=e.next();else if(r=e.match(/^%([^\w\s=])/))r=r[1];else{if(e.match(/^%[a-zA-Z_\u009F-\uFFFF][\w\u009F-\uFFFF]*/))return"meta";if(e.eat("%"))return"operator"}return b.hasOwnProperty(r)&&(r=b[r]),a(v(r,k,d),e,t)}return(n=e.match(/^<<-('?)([A-Z]\w*)\1/))?a(function(e,t){return function(n,r){if(n.sol()&&(n.eatSpace(),n.match(e)))return r.tokenize.pop(),"string";for(var a=!1;n.peek();)if(a)n.next(),a=!1;else{if(n.match("{%",!1))return r.tokenize.push(x("%","%")),"string";if(n.match("{{",!1))return r.tokenize.push(x("{","}")),"string";if(t&&n.match("#{",!1))return r.tokenize.push(w("#{","}","meta")),"string";a=t&&"\\"==n.next()}return"string"}}(n[2],!n[1]),e,t):e.eat("'")?(e.match(/^(?:[^']|\\(?:[befnrtv0'"]|[0-7]{3}|u(?:[0-9a-fA-F]{4}|\{[0-9a-fA-F]{1,6}\})))/),e.eat("'"),"atom"):e.eat("0")?(e.eat("x")?e.match(/^[0-9a-fA-F_]+/):e.eat("o")?e.match(/^[0-7_]+/):e.eat("b")&&e.match(/^[01_]+/),"number"):e.eat(/^\d/)?(e.match(/^[\d_]*(?:\.[\d_]+)?(?:[eE][+-]?\d+)?/),"number"):e.match(u)?(e.eat("="),"operator"):e.match(i)||e.match(o)?"operator":(n=e.match(/[({[]/,!1))?a(w(n=n[0],b[n],null),e,t):e.eat("\\")?(e.next(),"meta"):(e.next(),null)}function w(e,t,n,r){return function(a,u){if(!r&&a.match(e))return u.tokenize[u.tokenize.length-1]=w(e,t,n,!0),u.currentIndent+=1,n;var i=g(a,u);return a.current()===t&&(u.tokenize.pop(),u.currentIndent-=1,i=n),i}}function x(e,t,n){return function(r,a){return!n&&r.match("{"+e)?(a.currentIndent+=1,a.tokenize[a.tokenize.length-1]=x(e,t,!0),"meta"):r.match(t+"}")?(a.currentIndent-=1,a.tokenize.pop(),"meta"):g(r,a)}}function y(e,t){return e.eatSpace()?null:(e.match(s)?e.eat(/[!?]/):e.match(u)||e.match(i)||e.match(c),t.tokenize.pop(),"def")}function I(e,t){return e.eatSpace()?null:(e.match(l),t.tokenize.pop(),"def")}function v(e,t,n){return function(r,a){for(var u=!1;r.peek();)if(u)r.next(),u=!1;else{if(r.match("{%",!1))return a.tokenize.push(x("%","%")),t;if(r.match("{{",!1))return a.tokenize.push(x("{","}")),t;if(n&&r.match("#{",!1))return a.tokenize.push(w("#{","}","meta")),t;var i=r.next();if(i==e)return a.tokenize.pop(),t;u=n&&"\\"==i}return t}}const S={name:"crystal",startState:function(){return{tokenize:[g],currentIndent:0,lastToken:null,lastStyle:null,blocks:[]}},token:function(e,t){var n=t.tokenize[t.tokenize.length-1](e,t),r=e.current();return n&&"comment"!=n&&(t.lastToken=r,t.lastStyle=n),n},indent:function(e,t,n){return t=t.replace(/^\s*(?:\{%)?\s*|\s*(?:%\})?\s*$/g,""),d.test(t)||z.test(t)?n.unit*(e.currentIndent-1):n.unit*e.currentIndent},languageData:{indentOnInput:r(F.concat(k),!0),commentTokens:{line:"#"}}}}}]); +//# sourceMappingURL=4537.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/4537.index.js.map b/book/_build/html/_static/4537.index.js.map new file mode 100644 index 0000000..73e570d --- /dev/null +++ b/book/_build/html/_static/4537.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"4537.index.js","mappings":"+FAAA,SAASA,EAAWC,EAAOC,GACzB,OAAO,IAAIC,QAAQD,EAAM,GAAK,KAAO,MAAQD,EAAMG,KAAK,KAAO,KAAOF,EAAM,IAAM,OACpF,CAEA,SAASG,EAAMC,EAAUC,EAAQC,GAE/B,OADAA,EAAMF,SAASG,KAAKH,GACbA,EAASC,EAAQC,EAC1B,C,8BAEA,IAAIE,EAAY,+BACZC,EAAuB,wCACvBC,EAAoB,iBACpBC,EAAmB,4BACnBC,EAAS,iDACTC,EAAQ,iDACRC,EAAWhB,EAAW,CACxB,WAAY,Q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OAAQ,GAEZ,EAEAuB,MAAO,SAAUxD,EAAQC,GACvB,IAAIwC,EAAQxC,EAAMF,SAASE,EAAMF,SAASmD,OAAS,GAAGlD,EAAQC,GAC1DuD,EAAQxD,EAAO+B,UAOnB,OALIU,GAAkB,WAATA,IACXxC,EAAM0B,UAAY6B,EAClBvD,EAAMmC,UAAYK,GAGbA,CACT,EAEAgB,OAAQ,SAAUxD,EAAOyD,EAAWC,GAGlC,OAFAD,EAAYA,EAAUE,QAAQ,mCAAoC,IAE9D9C,EAAekB,KAAK0B,IAAc1C,EAAgBgB,KAAK0B,GAClDC,EAAGE,MAAQ5D,EAAMkC,cAAgB,GAGnCwB,EAAGE,KAAO5D,EAAMkC,aACzB,EAEA2B,aAAc,CACZC,cAAetE,EAAWsB,EAAqBiD,OAAOnD,IAAsB,GAC5EoD,cAAe,CAACC,KAAM,M","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/crystal.js"],"sourcesContent":["function wordRegExp(words, end) {\n return new RegExp((end ? \"\" : \"^\") + \"(?:\" + words.join(\"|\") + \")\" + (end ? \"$\" : \"\\\\b\"));\n}\n\nfunction chain(tokenize, stream, state) {\n state.tokenize.push(tokenize);\n return tokenize(stream, state);\n}\n\nvar operators = /^(?:[-+/%|&^]|\\*\\*?|[<>]{2})/;\nvar conditionalOperators = /^(?:[=!]~|===|<=>|[<>=!]=?|[|&]{2}|~)/;\nvar indexingOperators = /^(?:\\[\\][?=]?)/;\nvar anotherOperators = /^(?:\\.(?:\\.{2})?|->|[?:])/;\nvar idents = /^[a-z_\\u009F-\\uFFFF][a-zA-Z0-9_\\u009F-\\uFFFF]*/;\nvar types = /^[A-Z_\\u009F-\\uFFFF][a-zA-Z0-9_\\u009F-\\uFFFF]*/;\nvar keywords = wordRegExp([\n \"abstract\", \"alias\", \"as\", \"asm\", \"begin\", \"break\", \"case\", \"class\", \"def\", \"do\",\n \"else\", \"elsif\", \"end\", \"ensure\", \"enum\", \"extend\", \"for\", \"fun\", \"if\",\n \"include\", \"instance_sizeof\", \"lib\", \"macro\", \"module\", \"next\", \"of\", \"out\", \"pointerof\",\n \"private\", \"protected\", \"rescue\", \"return\", \"require\", \"select\", \"sizeof\", \"struct\",\n \"super\", \"then\", \"type\", \"typeof\", \"uninitialized\", \"union\", \"unless\", \"until\", \"when\", \"while\", \"with\",\n \"yield\", \"__DIR__\", \"__END_LINE__\", \"__FILE__\", \"__LINE__\"\n]);\nvar atomWords = wordRegExp([\"true\", \"false\", \"nil\", \"self\"]);\nvar indentKeywordsArray = [\n \"def\", \"fun\", \"macro\",\n \"class\", \"module\", \"struct\", \"lib\", \"enum\", \"union\",\n \"do\", \"for\"\n];\nvar indentKeywords = wordRegExp(indentKeywordsArray);\nvar indentExpressionKeywordsArray = [\"if\", \"unless\", \"case\", \"while\", \"until\", \"begin\", \"then\"];\nvar indentExpressionKeywords = wordRegExp(indentExpressionKeywordsArray);\nvar dedentKeywordsArray = [\"end\", \"else\", \"elsif\", \"rescue\", \"ensure\"];\nvar dedentKeywords = wordRegExp(dedentKeywordsArray);\nvar dedentPunctualsArray = [\"\\\\)\", \"\\\\}\", \"\\\\]\"];\nvar dedentPunctuals = new RegExp(\"^(?:\" + dedentPunctualsArray.join(\"|\") + \")$\");\nvar nextTokenizer = {\n \"def\": tokenFollowIdent, \"fun\": tokenFollowIdent, \"macro\": tokenMacroDef,\n \"class\": tokenFollowType, \"module\": tokenFollowType, \"struct\": tokenFollowType,\n \"lib\": tokenFollowType, \"enum\": tokenFollowType, \"union\": tokenFollowType\n};\nvar matching = {\"[\": \"]\", \"{\": \"}\", \"(\": \")\", \"<\": \">\"};\n\nfunction tokenBase(stream, state) {\n if (stream.eatSpace()) {\n return null;\n }\n\n // Macros\n if (state.lastToken != \"\\\\\" && stream.match(\"{%\", false)) {\n return chain(tokenMacro(\"%\", \"%\"), stream, state);\n }\n\n if (state.lastToken != \"\\\\\" && stream.match(\"{{\", false)) {\n return chain(tokenMacro(\"{\", \"}\"), stream, state);\n }\n\n // Comments\n if (stream.peek() == \"#\") {\n stream.skipToEnd();\n return \"comment\";\n }\n\n // Variables and keywords\n var matched;\n if (stream.match(idents)) {\n stream.eat(/[?!]/);\n\n matched = stream.current();\n if (stream.eat(\":\")) {\n return \"atom\";\n } else if (state.lastToken == \".\") {\n return \"property\";\n } else if (keywords.test(matched)) {\n if (indentKeywords.test(matched)) {\n if (!(matched == \"fun\" && state.blocks.indexOf(\"lib\") >= 0) && !(matched == \"def\" && state.lastToken == \"abstract\")) {\n state.blocks.push(matched);\n state.currentIndent += 1;\n }\n } else if ((state.lastStyle == \"operator\" || !state.lastStyle) && indentExpressionKeywords.test(matched)) {\n state.blocks.push(matched);\n state.currentIndent += 1;\n } else if (matched == \"end\") {\n state.blocks.pop();\n state.currentIndent -= 1;\n }\n\n if (nextTokenizer.hasOwnProperty(matched)) {\n state.tokenize.push(nextTokenizer[matched]);\n }\n\n return \"keyword\";\n } else if (atomWords.test(matched)) {\n return \"atom\";\n }\n\n return \"variable\";\n }\n\n // Class variables and instance variables\n // or attributes\n if (stream.eat(\"@\")) {\n if (stream.peek() == \"[\") {\n return chain(tokenNest(\"[\", \"]\", \"meta\"), stream, state);\n }\n\n stream.eat(\"@\");\n stream.match(idents) || stream.match(types);\n return \"propertyName\";\n }\n\n // Constants and types\n if (stream.match(types)) {\n return \"tag\";\n }\n\n // Symbols or ':' operator\n if (stream.eat(\":\")) {\n if (stream.eat(\"\\\"\")) {\n return chain(tokenQuote(\"\\\"\", \"atom\", false), stream, state);\n } else if (stream.match(idents) || stream.match(types) ||\n stream.match(operators) || stream.match(conditionalOperators) || stream.match(indexingOperators)) {\n return \"atom\";\n }\n stream.eat(\":\");\n return \"operator\";\n }\n\n // Strings\n if (stream.eat(\"\\\"\")) {\n return chain(tokenQuote(\"\\\"\", \"string\", true), stream, state);\n }\n\n // Strings or regexps or macro variables or '%' operator\n if (stream.peek() == \"%\") {\n var style = \"string\";\n var embed = true;\n var delim;\n\n if (stream.match(\"%r\")) {\n // Regexps\n style = \"string.special\";\n delim = stream.next();\n } else if (stream.match(\"%w\")) {\n embed = false;\n delim = stream.next();\n } else if (stream.match(\"%q\")) {\n embed = false;\n delim = stream.next();\n } else {\n if(delim = stream.match(/^%([^\\w\\s=])/)) {\n delim = delim[1];\n } else if (stream.match(/^%[a-zA-Z_\\u009F-\\uFFFF][\\w\\u009F-\\uFFFF]*/)) {\n // Macro variables\n return \"meta\";\n } else if (stream.eat('%')) {\n // '%' operator\n return \"operator\";\n }\n }\n\n if (matching.hasOwnProperty(delim)) {\n delim = matching[delim];\n }\n return chain(tokenQuote(delim, style, embed), stream, state);\n }\n\n // Here Docs\n if (matched = stream.match(/^<<-('?)([A-Z]\\w*)\\1/)) {\n return chain(tokenHereDoc(matched[2], !matched[1]), stream, state)\n }\n\n // Characters\n if (stream.eat(\"'\")) {\n stream.match(/^(?:[^']|\\\\(?:[befnrtv0'\"]|[0-7]{3}|u(?:[0-9a-fA-F]{4}|\\{[0-9a-fA-F]{1,6}\\})))/);\n stream.eat(\"'\");\n return \"atom\";\n }\n\n // Numbers\n if (stream.eat(\"0\")) {\n if (stream.eat(\"x\")) {\n stream.match(/^[0-9a-fA-F_]+/);\n } else if (stream.eat(\"o\")) {\n stream.match(/^[0-7_]+/);\n } else if (stream.eat(\"b\")) {\n stream.match(/^[01_]+/);\n }\n return \"number\";\n }\n\n if (stream.eat(/^\\d/)) {\n stream.match(/^[\\d_]*(?:\\.[\\d_]+)?(?:[eE][+-]?\\d+)?/);\n return \"number\";\n }\n\n // Operators\n if (stream.match(operators)) {\n stream.eat(\"=\"); // Operators can follow assign symbol.\n return \"operator\";\n }\n\n if (stream.match(conditionalOperators) || stream.match(anotherOperators)) {\n return \"operator\";\n }\n\n // Parens and braces\n if (matched = stream.match(/[({[]/, false)) {\n matched = matched[0];\n return chain(tokenNest(matched, matching[matched], null), stream, state);\n }\n\n // Escapes\n if (stream.eat(\"\\\\\")) {\n stream.next();\n return \"meta\";\n }\n\n stream.next();\n return null;\n}\n\nfunction tokenNest(begin, end, style, started) {\n return function (stream, state) {\n if (!started && stream.match(begin)) {\n state.tokenize[state.tokenize.length - 1] = tokenNest(begin, end, style, true);\n state.currentIndent += 1;\n return style;\n }\n\n var nextStyle = tokenBase(stream, state);\n if (stream.current() === end) {\n state.tokenize.pop();\n state.currentIndent -= 1;\n nextStyle = style;\n }\n\n return nextStyle;\n };\n}\n\nfunction tokenMacro(begin, end, started) {\n return function (stream, state) {\n if (!started && stream.match(\"{\" + begin)) {\n state.currentIndent += 1;\n state.tokenize[state.tokenize.length - 1] = tokenMacro(begin, end, true);\n return \"meta\";\n }\n\n if (stream.match(end + \"}\")) {\n state.currentIndent -= 1;\n state.tokenize.pop();\n return \"meta\";\n }\n\n return tokenBase(stream, state);\n };\n}\n\nfunction tokenMacroDef(stream, state) {\n if (stream.eatSpace()) {\n return null;\n }\n\n var matched;\n if (matched = stream.match(idents)) {\n if (matched == \"def\") {\n return \"keyword\";\n }\n stream.eat(/[?!]/);\n }\n\n state.tokenize.pop();\n return \"def\";\n}\n\nfunction tokenFollowIdent(stream, state) {\n if (stream.eatSpace()) {\n return null;\n }\n\n if (stream.match(idents)) {\n stream.eat(/[!?]/);\n } else {\n stream.match(operators) || stream.match(conditionalOperators) || stream.match(indexingOperators);\n }\n state.tokenize.pop();\n return \"def\";\n}\n\nfunction tokenFollowType(stream, state) {\n if (stream.eatSpace()) {\n return null;\n }\n\n stream.match(types);\n state.tokenize.pop();\n return \"def\";\n}\n\nfunction tokenQuote(end, style, embed) {\n return function (stream, state) {\n var escaped = false;\n\n while (stream.peek()) {\n if (!escaped) {\n if (stream.match(\"{%\", false)) {\n state.tokenize.push(tokenMacro(\"%\", \"%\"));\n return style;\n }\n\n if (stream.match(\"{{\", false)) {\n state.tokenize.push(tokenMacro(\"{\", \"}\"));\n return style;\n }\n\n if (embed && stream.match(\"#{\", false)) {\n state.tokenize.push(tokenNest(\"#{\", \"}\", \"meta\"));\n return style;\n }\n\n var ch = stream.next();\n\n if (ch == end) {\n state.tokenize.pop();\n return style;\n }\n\n escaped = embed && ch == \"\\\\\";\n } else {\n stream.next();\n escaped = false;\n }\n }\n\n return style;\n };\n}\n\nfunction tokenHereDoc(phrase, embed) {\n return function (stream, state) {\n if (stream.sol()) {\n stream.eatSpace()\n if (stream.match(phrase)) {\n state.tokenize.pop();\n return \"string\";\n }\n }\n\n var escaped = false;\n while (stream.peek()) {\n if (!escaped) {\n if (stream.match(\"{%\", false)) {\n state.tokenize.push(tokenMacro(\"%\", \"%\"));\n return \"string\";\n }\n\n if (stream.match(\"{{\", false)) {\n state.tokenize.push(tokenMacro(\"{\", \"}\"));\n return \"string\";\n }\n\n if (embed && stream.match(\"#{\", false)) {\n state.tokenize.push(tokenNest(\"#{\", \"}\", \"meta\"));\n return \"string\";\n }\n\n escaped = embed && stream.next() == \"\\\\\";\n } else {\n stream.next();\n escaped = false;\n }\n }\n\n return \"string\";\n }\n}\n\nexport const crystal = {\n name: \"crystal\",\n startState: function () {\n return {\n tokenize: [tokenBase],\n currentIndent: 0,\n lastToken: null,\n lastStyle: null,\n blocks: []\n };\n },\n\n token: function (stream, state) {\n var style = state.tokenize[state.tokenize.length - 1](stream, state);\n var token = stream.current();\n\n if (style && style != \"comment\") {\n state.lastToken = token;\n state.lastStyle = style;\n }\n\n return style;\n },\n\n indent: function (state, textAfter, cx) {\n textAfter = textAfter.replace(/^\\s*(?:\\{%)?\\s*|\\s*(?:%\\})?\\s*$/g, \"\");\n\n if (dedentKeywords.test(textAfter) || dedentPunctuals.test(textAfter)) {\n return cx.unit * (state.currentIndent - 1);\n }\n\n return cx.unit * state.currentIndent;\n },\n\n languageData: {\n indentOnInput: wordRegExp(dedentPunctualsArray.concat(dedentKeywordsArray), true),\n commentTokens: {line: \"#\"}\n }\n};\n"],"names":["wordRegExp","words","end","RegExp","join","chain","tokenize","stream","state","push","operators","conditionalOperators","indexingOperators","anotherOperators","idents","types","keywords","atomWords","indentKeywords","indentExpressionKeywords","dedentKeywordsArray","dedentKeywords","dedentPunctualsArray","dedentPunctuals","nextTokenizer","tokenFollowIdent","eatSpace","matched","match","eat","pop","tokenFollowType","matching","tokenBase","lastToken","tokenMacro","peek","skipToEnd","current","test","blocks","indexOf","currentIndent","lastStyle","hasOwnProperty","tokenNest","tokenQuote","delim","style","embed","next","phrase","sol","escaped","tokenHereDoc","begin","started","length","nextStyle","ch","crystal","name","startState","token","indent","textAfter","cx","replace","unit","languageData","indentOnInput","concat","commentTokens","line"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/4651.index.js b/book/_build/html/_static/4651.index.js new file mode 100644 index 0000000..efe94f0 --- /dev/null +++ b/book/_build/html/_static/4651.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[4651],{54651:(t,e,n)=>{var r;function a(t){return new RegExp("^(?:"+t.join("|")+")$","i")}n.r(e),n.d(e,{sparql:()=>F});var u=a(["str","lang","langmatches","datatype","bound","sameterm","isiri","isuri","iri","uri","bnode","count","sum","min","max","avg","sample","group_concat","rand","abs","ceil","floor","round","concat","substr","strlen","replace","ucase","lcase","encode_for_uri","contains","strstarts","strends","strbefore","strafter","year","month","day","hours","minutes","seconds","timezone","tz","now","uuid","struuid","md5","sha1","sha256","sha384","sha512","coalesce","if","strlang","strdt","isnumeric","regex","exists","isblank","isliteral","a","bind"]),o=a(["base","prefix","select","distinct","reduced","construct","describe","ask","from","named","where","order","limit","offset","filter","optional","graph","by","asc","desc","as","having","undef","values","group","minus","in","not","service","silent","using","insert","delete","union","true","false","with","data","copy","to","move","add","create","drop","clear","load","into"]),i=/[*+\-<>=&|\^\/!\?]/,c="[A-Za-z_\\-0-9]",s=new RegExp("[A-Za-z]"),l=new RegExp("(("+c+"|\\.)*("+c+"))?:");function d(t,e){var n,a=t.next();if(r=null,"$"==a||"?"==a)return"?"==a&&t.match(/\s/,!1)?"operator":(t.match(/^[A-Za-z0-9_\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][A-Za-z0-9_\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]*/),"variableName.local");if("<"==a&&!t.match(/^[\s\u00a0=]/,!1))return t.match(/^[^\s\u00a0>]*>?/),"atom";if('"'==a||"'"==a)return e.tokenize=(n=a,function(t,e){for(var r,a=!1;null!=(r=t.next());){if(r==n&&!a){e.tokenize=d;break}a=!a&&"\\"==r}return"string"}),e.tokenize(t,e);if(/[{}\(\),\.;\[\]]/.test(a))return r=a,"bracket";if("#"==a)return t.skipToEnd(),"comment";if(i.test(a))return"operator";if(":"==a)return f(t),"atom";if("@"==a)return t.eatWhile(/[a-z\d\-]/i),"meta";if(s.test(a)&&t.match(l))return f(t),"atom";t.eatWhile(/[_\w\d]/);var c=t.current();return u.test(c)?"builtin":o.test(c)?"keyword":"variable"}function f(t){t.match(/(\.(?=[\w_\-\\%])|[:\w_-]|\\[-\\_~.!$&'()*+,;=/?#@%]|%[a-f\d][a-f\d])+/i)}function p(t,e,n){t.context={prev:t.context,indent:t.indent,col:n,type:e}}function m(t){t.indent=t.context.indent,t.context=t.context.prev}const F={name:"sparql",startState:function(){return{tokenize:d,context:null,indent:0,col:0}},token:function(t,e){if(t.sol()&&(e.context&&null==e.context.align&&(e.context.align=!1),e.indent=t.indentation()),t.eatSpace())return null;var n=e.tokenize(t,e);if("comment"!=n&&e.context&&null==e.context.align&&"pattern"!=e.context.type&&(e.context.align=!0),"("==r)p(e,")",t.column());else if("["==r)p(e,"]",t.column());else if("{"==r)p(e,"}",t.column());else if(/[\]\}\)]/.test(r)){for(;e.context&&"pattern"==e.context.type;)m(e);e.context&&r==e.context.type&&(m(e),"}"==r&&e.context&&"pattern"==e.context.type&&m(e))}else"."==r&&e.context&&"pattern"==e.context.type?m(e):/atom|string|variable/.test(n)&&e.context&&(/[\}\]]/.test(e.context.type)?p(e,"pattern",t.column()):"pattern"!=e.context.type||e.context.align||(e.context.align=!0,e.context.col=t.column()));return n},indent:function(t,e,n){var r=e&&e.charAt(0),a=t.context;if(/[\]\}]/.test(r))for(;a&&"pattern"==a.type;)a=a.prev;var u=a&&r==a.type;return a?"pattern"==a.type?a.col:a.align?a.col+(u?0:1):a.indent+(u?0:n.unit):0},languageData:{commentTokens:{line:"#"}}}}}]); +//# sourceMappingURL=4651.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/4651.index.js.map b/book/_build/html/_static/4651.index.js.map new file mode 100644 index 0000000..31f823e --- /dev/null +++ b/book/_build/html/_static/4651.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"4651.index.js","mappings":"+FAAA,IAAIA,EAEJ,SAASC,EAAWC,GAClB,OAAO,IAAIC,OAAO,OAASD,EAAME,KAAK,KAAO,KAAM,IACrD,C,6BACA,IAAIC,EAAMJ,EAAW,CAAC,MAAO,OAAQ,cAAe,WAAY,QAAS,WAAY,QAAS,QACxE,MAAO,MAAO,QAAS,QAAS,MAAO,MAAO,MAAO,MAAO,SAC5D,eAAgB,OAAQ,MAAO,OAAQ,QAAS,QAAS,SAAU,SAAU,SAC7E,UAAW,QAAS,QAAS,iBAAkB,WAAY,YAAa,UACxE,YAAa,WAAY,OAAQ,QAAS,MAAO,QAAS,UAAW,UACrE,WAAY,KAAM,MAAO,OAAQ,UAAW,MAAO,OAAQ,SAAU,SACrE,SAAU,WAAY,KAAM,UAAW,QAAS,YAAa,QAAS,SACtE,UAAW,YAAa,IAAK,SAC/CK,EAAWL,EAAW,CAAC,OAAQ,SAAU,SAAU,WAAY,UAAW,YAAa,WAChE,MAAO,OAAQ,QAAS,QAAS,QAAS,QAAS,SAAU,SAAU,WACvE,QAAS,KAAM,MAAO,OAAQ,KAAM,SA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GAEjB,KACoB,KAAXb,GAAkBa,EAAMgB,SAAiC,WAAtBhB,EAAMgB,QAAQF,KAAmBK,EAAWnB,GAC/E,uBAAuBO,KAAKqB,IAAU5B,EAAMgB,UAC/C,SAAST,KAAKP,EAAMgB,QAAQF,MAC9BD,EAAYb,EAAO,UAAWD,EAAO8B,UACR,WAAtB7B,EAAMgB,QAAQF,MAAsBd,EAAMgB,QAAQS,QACzDzB,EAAMgB,QAAQS,OAAQ,EACtBzB,EAAMgB,QAAQD,IAAMhB,EAAO8B,WAI/B,OAAOD,CACT,EAEAV,OAAQ,SAASlB,EAAO8B,EAAWC,GACjC,IAAIC,EAAYF,GAAaA,EAAUG,OAAO,GAC1CjB,EAAUhB,EAAMgB,QACpB,GAAI,SAAST,KAAKyB,GAChB,KAAOhB,GAA2B,WAAhBA,EAAQF,MAAmBE,EAAUA,EAAQC,KAEjE,IAAIiB,EAAUlB,GAAWgB,GAAahB,EAAQF,KAC9C,OAAKE,EAEoB,WAAhBA,EAAQF,KACRE,EAAQD,IACRC,EAAQS,MACRT,EAAQD,KAAOmB,EAAU,EAAI,GAE7BlB,EAAQE,QAAUgB,EAAU,EAAIH,EAAGI,MANnC,CAOX,EAEAC,aAAc,CACZC,cAAe,CAACC,KAAM,M","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/sparql.js"],"sourcesContent":["var curPunc;\n\nfunction wordRegexp(words) {\n return new RegExp(\"^(?:\" + words.join(\"|\") + \")$\", \"i\");\n}\nvar ops = wordRegexp([\"str\", \"lang\", \"langmatches\", \"datatype\", \"bound\", \"sameterm\", \"isiri\", \"isuri\",\n \"iri\", \"uri\", \"bnode\", \"count\", \"sum\", \"min\", \"max\", \"avg\", \"sample\",\n \"group_concat\", \"rand\", \"abs\", \"ceil\", \"floor\", \"round\", \"concat\", \"substr\", \"strlen\",\n \"replace\", \"ucase\", \"lcase\", \"encode_for_uri\", \"contains\", \"strstarts\", \"strends\",\n \"strbefore\", \"strafter\", \"year\", \"month\", \"day\", \"hours\", \"minutes\", \"seconds\",\n \"timezone\", \"tz\", \"now\", \"uuid\", \"struuid\", \"md5\", \"sha1\", \"sha256\", \"sha384\",\n \"sha512\", \"coalesce\", \"if\", \"strlang\", \"strdt\", \"isnumeric\", \"regex\", \"exists\",\n \"isblank\", \"isliteral\", \"a\", \"bind\"]);\nvar keywords = wordRegexp([\"base\", \"prefix\", \"select\", \"distinct\", \"reduced\", \"construct\", \"describe\",\n \"ask\", \"from\", \"named\", \"where\", \"order\", \"limit\", \"offset\", \"filter\", \"optional\",\n \"graph\", \"by\", \"asc\", \"desc\", \"as\", \"having\", \"undef\", \"values\", \"group\",\n \"minus\", \"in\", \"not\", \"service\", \"silent\", \"using\", \"insert\", \"delete\", \"union\",\n \"true\", \"false\", \"with\",\n \"data\", \"copy\", \"to\", \"move\", \"add\", \"create\", \"drop\", \"clear\", \"load\", \"into\"]);\nvar operatorChars = /[*+\\-<>=&|\\^\\/!\\?]/;\nvar PN_CHARS = \"[A-Za-z_\\\\-0-9]\";\nvar PREFIX_START = new RegExp(\"[A-Za-z]\");\nvar PREFIX_REMAINDER = new RegExp(\"((\" + PN_CHARS + \"|\\\\.)*(\" + PN_CHARS + \"))?:\");\n\nfunction tokenBase(stream, state) {\n var ch = stream.next();\n curPunc = null;\n if (ch == \"$\" || ch == \"?\") {\n if(ch == \"?\" && stream.match(/\\s/, false)){\n return \"operator\";\n }\n stream.match(/^[A-Za-z0-9_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][A-Za-z0-9_\\u00B7\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u203F-\\u2040\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]*/);\n return \"variableName.local\";\n }\n else if (ch == \"<\" && !stream.match(/^[\\s\\u00a0=]/, false)) {\n stream.match(/^[^\\s\\u00a0>]*>?/);\n return \"atom\";\n }\n else if (ch == \"\\\"\" || ch == \"'\") {\n state.tokenize = tokenLiteral(ch);\n return state.tokenize(stream, state);\n }\n else if (/[{}\\(\\),\\.;\\[\\]]/.test(ch)) {\n curPunc = ch;\n return \"bracket\";\n }\n else if (ch == \"#\") {\n stream.skipToEnd();\n return \"comment\";\n }\n else if (operatorChars.test(ch)) {\n return \"operator\";\n }\n else if (ch == \":\") {\n eatPnLocal(stream);\n return \"atom\";\n }\n else if (ch == \"@\") {\n stream.eatWhile(/[a-z\\d\\-]/i);\n return \"meta\";\n }\n else if (PREFIX_START.test(ch) && stream.match(PREFIX_REMAINDER)) {\n eatPnLocal(stream);\n return \"atom\";\n }\n stream.eatWhile(/[_\\w\\d]/);\n var word = stream.current();\n if (ops.test(word))\n return \"builtin\";\n else if (keywords.test(word))\n return \"keyword\";\n else\n return \"variable\";\n}\n\nfunction eatPnLocal(stream) {\n stream.match(/(\\.(?=[\\w_\\-\\\\%])|[:\\w_-]|\\\\[-\\\\_~.!$&'()*+,;=/?#@%]|%[a-f\\d][a-f\\d])+/i);\n}\n\nfunction tokenLiteral(quote) {\n return function(stream, state) {\n var escaped = false, ch;\n while ((ch = stream.next()) != null) {\n if (ch == quote && !escaped) {\n state.tokenize = tokenBase;\n break;\n }\n escaped = !escaped && ch == \"\\\\\";\n }\n return \"string\";\n };\n}\n\nfunction pushContext(state, type, col) {\n state.context = {prev: state.context, indent: state.indent, col: col, type: type};\n}\nfunction popContext(state) {\n state.indent = state.context.indent;\n state.context = state.context.prev;\n}\n\nexport const sparql = {\n name: \"sparql\",\n\n startState: function() {\n return {tokenize: tokenBase,\n context: null,\n indent: 0,\n col: 0};\n },\n\n token: function(stream, state) {\n if (stream.sol()) {\n if (state.context && state.context.align == null) state.context.align = false;\n state.indent = stream.indentation();\n }\n if (stream.eatSpace()) return null;\n var style = state.tokenize(stream, state);\n\n if (style != \"comment\" && state.context && state.context.align == null && state.context.type != \"pattern\") {\n state.context.align = true;\n }\n\n if (curPunc == \"(\") pushContext(state, \")\", stream.column());\n else if (curPunc == \"[\") pushContext(state, \"]\", stream.column());\n else if (curPunc == \"{\") pushContext(state, \"}\", stream.column());\n else if (/[\\]\\}\\)]/.test(curPunc)) {\n while (state.context && state.context.type == \"pattern\") popContext(state);\n if (state.context && curPunc == state.context.type) {\n popContext(state);\n if (curPunc == \"}\" && state.context && state.context.type == \"pattern\")\n popContext(state);\n }\n }\n else if (curPunc == \".\" && state.context && state.context.type == \"pattern\") popContext(state);\n else if (/atom|string|variable/.test(style) && state.context) {\n if (/[\\}\\]]/.test(state.context.type))\n pushContext(state, \"pattern\", stream.column());\n else if (state.context.type == \"pattern\" && !state.context.align) {\n state.context.align = true;\n state.context.col = stream.column();\n }\n }\n\n return style;\n },\n\n indent: function(state, textAfter, cx) {\n var firstChar = textAfter && textAfter.charAt(0);\n var context = state.context;\n if (/[\\]\\}]/.test(firstChar))\n while (context && context.type == \"pattern\") context = context.prev;\n\n var closing = context && firstChar == context.type;\n if (!context)\n return 0;\n else if (context.type == \"pattern\")\n return context.col;\n else if (context.align)\n return context.col + (closing ? 0 : 1);\n else\n return context.indent + (closing ? 0 : cx.unit);\n },\n\n languageData: {\n commentTokens: {line: \"#\"}\n }\n};\n\n"],"names":["curPunc","wordRegexp","words","RegExp","join","ops","keywords","operatorChars","PN_CHARS","PREFIX_START","PREFIX_REMAINDER","tokenBase","stream","state","quote","ch","next","match","tokenize","escaped","test","skipToEnd","eatPnLocal","eatWhile","word","current","pushContext","type","col","context","prev","indent","popContext","sparql","name","startState","token","sol","align","indentation","eatSpace","style","column","textAfter","cx","firstChar","charAt","closing","unit","languageData","commentTokens","line"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/4745.index.js b/book/_build/html/_static/4745.index.js new file mode 100644 index 0000000..6e568fe --- /dev/null +++ b/book/_build/html/_static/4745.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[4745],{74745:(e,t,r)=>{function n(e){return new RegExp("^(("+e.join(")|(")+"))\\b")}r.r(t),r.d(t,{webIDL:()=>E});var a=["Clamp","Constructor","EnforceRange","Exposed","ImplicitThis","Global","PrimaryGlobal","LegacyArrayClass","LegacyUnenumerableNamedProperties","LenientThis","NamedConstructor","NewObject","NoInterfaceObject","OverrideBuiltins","PutForwards","Replaceable","SameObject","TreatNonObjectAsNull","TreatNullAs","EmptyString","Unforgeable","Unscopeable"],i=n(a),c=["unsigned","short","long","unrestricted","float","double","boolean","byte","octet","Promise","ArrayBuffer","DataView","Int8Array","Int16Array","Int32Array","Uint8Array","Uint16Array","Uint32Array","Uint8ClampedArray","Float32Array","Float64Array","ByteString","DOMString","USVString","sequence","object","RegExp","Error","DOMException","FrozenArray","any","void"],o=n(c),l=["attribute","callback","const","deleter","dictionary","enum","getter","implements","inherit","interface","iterable","legacycaller","maplike","partial","required","serializer","setlike","setter","static","stringifier","typedef","optional","readonly","or"],m=n(l),s=["true","false","Infinity","NaN","null"],u=n(s),f=n(["callback","dictionary","enum","interface"]),b=n(["typedef"]),d=/^[:<=>?]/,y=/^-?([1-9][0-9]*|0[Xx][0-9A-Fa-f]+|0[0-7]*)/,p=/^-?(([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([Ee][+-]?[0-9]+)?|[0-9]+[Ee][+-]?[0-9]+)/,h=/^_?[A-Za-z][0-9A-Z_a-z-]*/,A=/^_?[A-Za-z][0-9A-Z_a-z-]*(?=\s*;)/,g=/^"[^"]*"/,k=/^\/\*.*?\*\//,D=/^\/\*.*/,C=/^.*?\*\//;const E={name:"webidl",startState:function(){return{inComment:!1,lastToken:"",startDef:!1,endDef:!1}},token:function(e,t){var r=function(e,t){if(e.eatSpace())return null;if(t.inComment)return e.match(C)?(t.inComment=!1,"comment"):(e.skipToEnd(),"comment");if(e.match("//"))return e.skipToEnd(),"comment";if(e.match(k))return"comment";if(e.match(D))return t.inComment=!0,"comment";if(e.match(/^-?[0-9\.]/,!1)&&(e.match(y)||e.match(p)))return"number";if(e.match(g))return"string";if(t.startDef&&e.match(h))return"def";if(t.endDef&&e.match(A))return t.endDef=!1,"def";if(e.match(m))return"keyword";if(e.match(o)){var r=t.lastToken,n=(e.match(/^\s*(.+?)\b/,!1)||[])[1];return":"===r||"implements"===r||"implements"===n||"="===n?"builtin":"type"}return e.match(i)?"builtin":e.match(u)?"atom":e.match(h)?"variable":e.match(d)?"operator":(e.next(),null)}(e,t);if(r){var n=e.current();t.lastToken=n,"keyword"===r?(t.startDef=f.test(n),t.endDef=t.endDef||b.test(n)):t.startDef=!1}return r},languageData:{autocomplete:a.concat(c).concat(l).concat(s)}}}}]); +//# sourceMappingURL=4745.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/4745.index.js.map b/book/_build/html/_static/4745.index.js.map new file mode 100644 index 0000000..fd584f1 --- /dev/null +++ b/book/_build/html/_static/4745.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"4745.index.js","mappings":"+FAAA,SAASA,EAAWC,GAClB,OAAO,IAAIC,OAAO,MAAQD,EAAME,KAAK,OAAS,QAChD,C,6BAEA,IAAIC,EAAe,CACjB,QACA,cACA,eACA,UACA,eACA,SAAU,gBACV,mBACA,oCACA,cACA,mBACA,YACA,oBACA,mBACA,cACA,cACA,aACA,uBACA,cACE,cACF,cACA,eAEEC,EAAWL,EAAWI,GAEtBE,EAAY,CACd,WAAY,QAAS,OACrB,eAAgB,QAAS,SACzB,UAAW,OAAQ,QACnB,UACA,cAAe,WAAY,YAAa,aAAc,aACtD,aAAc,cAAe,cAAe,oBAC5C,eAAgB,eAChB,aAAc,YAAa,YAAa,WAAY,SAAU,SAC9D,QAAS,eAAgB,cACzB,MACA,QAEEC,EAAQP,EAAWM,GAEnBE,EAAe,CACjB,YAAa,WAAY,QAAS,UAAW,aA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,GAAaN,EAAOI,MAAM,eAAe,IAAU,IAAI,GAE3D,MAAkB,MAAdR,GAAmC,eAAdA,GACP,eAAdU,GAA4C,MAAdA,EAEzB,UAGA,MAEX,CAEA,OAAIN,EAAOI,MAAM9B,GAAkB,UAC/B0B,EAAOI,MAAMxB,GAAe,OAC5BoB,EAAOI,MAAMlB,GAAqB,WAGlCc,EAAOI,MAAMrB,GAAyB,YAG1CiB,EAAOO,OACA,KACT,CAiBgBC,CAAUR,EAAQC,GAE9B,GAAIC,EAAO,CACT,IAAIO,EAAMT,EAAOU,UACjBT,EAAML,UAAYa,EACJ,YAAVP,GACFD,EAAMJ,SAAWhB,EAAU8B,KAAKF,GAChCR,EAAMH,OAASG,EAAMH,QAAUhB,EAAQ6B,KAAKF,IAE5CR,EAAMJ,UAAW,CAErB,CAEA,OAAOK,CACT,EAEAU,aAAc,CACZC,aAAcxC,EAAayC,OAAOvC,GAAWuC,OAAOrC,GAAcqC,OAAOnC,I","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/webidl.js"],"sourcesContent":["function wordRegexp(words) {\n return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\");\n};\n\nvar builtinArray = [\n \"Clamp\",\n \"Constructor\",\n \"EnforceRange\",\n \"Exposed\",\n \"ImplicitThis\",\n \"Global\", \"PrimaryGlobal\",\n \"LegacyArrayClass\",\n \"LegacyUnenumerableNamedProperties\",\n \"LenientThis\",\n \"NamedConstructor\",\n \"NewObject\",\n \"NoInterfaceObject\",\n \"OverrideBuiltins\",\n \"PutForwards\",\n \"Replaceable\",\n \"SameObject\",\n \"TreatNonObjectAsNull\",\n \"TreatNullAs\",\n \"EmptyString\",\n \"Unforgeable\",\n \"Unscopeable\"\n];\nvar builtins = wordRegexp(builtinArray);\n\nvar typeArray = [\n \"unsigned\", \"short\", \"long\", // UnsignedIntegerType\n \"unrestricted\", \"float\", \"double\", // UnrestrictedFloatType\n \"boolean\", \"byte\", \"octet\", // Rest of PrimitiveType\n \"Promise\", // PromiseType\n \"ArrayBuffer\", \"DataView\", \"Int8Array\", \"Int16Array\", \"Int32Array\",\n \"Uint8Array\", \"Uint16Array\", \"Uint32Array\", \"Uint8ClampedArray\",\n \"Float32Array\", \"Float64Array\", // BufferRelatedType\n \"ByteString\", \"DOMString\", \"USVString\", \"sequence\", \"object\", \"RegExp\",\n \"Error\", \"DOMException\", \"FrozenArray\", // Rest of NonAnyType\n \"any\", // Rest of SingleType\n \"void\" // Rest of ReturnType\n];\nvar types = wordRegexp(typeArray);\n\nvar keywordArray = [\n \"attribute\", \"callback\", \"const\", \"deleter\", \"dictionary\", \"enum\", \"getter\",\n \"implements\", \"inherit\", \"interface\", \"iterable\", \"legacycaller\", \"maplike\",\n \"partial\", \"required\", \"serializer\", \"setlike\", \"setter\", \"static\",\n \"stringifier\", \"typedef\", // ArgumentNameKeyword except\n // \"unrestricted\"\n \"optional\", \"readonly\", \"or\"\n];\nvar keywords = wordRegexp(keywordArray);\n\nvar atomArray = [\n \"true\", \"false\", // BooleanLiteral\n \"Infinity\", \"NaN\", // FloatLiteral\n \"null\" // Rest of ConstValue\n];\nvar atoms = wordRegexp(atomArray);\n\nvar startDefArray = [\"callback\", \"dictionary\", \"enum\", \"interface\"];\nvar startDefs = wordRegexp(startDefArray);\n\nvar endDefArray = [\"typedef\"];\nvar endDefs = wordRegexp(endDefArray);\n\nvar singleOperators = /^[:<=>?]/;\nvar integers = /^-?([1-9][0-9]*|0[Xx][0-9A-Fa-f]+|0[0-7]*)/;\nvar floats = /^-?(([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+)([Ee][+-]?[0-9]+)?|[0-9]+[Ee][+-]?[0-9]+)/;\nvar identifiers = /^_?[A-Za-z][0-9A-Z_a-z-]*/;\nvar identifiersEnd = /^_?[A-Za-z][0-9A-Z_a-z-]*(?=\\s*;)/;\nvar strings = /^\"[^\"]*\"/;\nvar multilineComments = /^\\/\\*.*?\\*\\//;\nvar multilineCommentsStart = /^\\/\\*.*/;\nvar multilineCommentsEnd = /^.*?\\*\\//;\n\nfunction readToken(stream, state) {\n // whitespace\n if (stream.eatSpace()) return null;\n\n // comment\n if (state.inComment) {\n if (stream.match(multilineCommentsEnd)) {\n state.inComment = false;\n return \"comment\";\n }\n stream.skipToEnd();\n return \"comment\";\n }\n if (stream.match(\"//\")) {\n stream.skipToEnd();\n return \"comment\";\n }\n if (stream.match(multilineComments)) return \"comment\";\n if (stream.match(multilineCommentsStart)) {\n state.inComment = true;\n return \"comment\";\n }\n\n // integer and float\n if (stream.match(/^-?[0-9\\.]/, false)) {\n if (stream.match(integers) || stream.match(floats)) return \"number\";\n }\n\n // string\n if (stream.match(strings)) return \"string\";\n\n // identifier\n if (state.startDef && stream.match(identifiers)) return \"def\";\n\n if (state.endDef && stream.match(identifiersEnd)) {\n state.endDef = false;\n return \"def\";\n }\n\n if (stream.match(keywords)) return \"keyword\";\n\n if (stream.match(types)) {\n var lastToken = state.lastToken;\n var nextToken = (stream.match(/^\\s*(.+?)\\b/, false) || [])[1];\n\n if (lastToken === \":\" || lastToken === \"implements\" ||\n nextToken === \"implements\" || nextToken === \"=\") {\n // Used as identifier\n return \"builtin\";\n } else {\n // Used as type\n return \"type\";\n }\n }\n\n if (stream.match(builtins)) return \"builtin\";\n if (stream.match(atoms)) return \"atom\";\n if (stream.match(identifiers)) return \"variable\";\n\n // other\n if (stream.match(singleOperators)) return \"operator\";\n\n // unrecognized\n stream.next();\n return null;\n};\n\nexport const webIDL = {\n name: \"webidl\",\n startState: function() {\n return {\n // Is in multiline comment\n inComment: false,\n // Last non-whitespace, matched token\n lastToken: \"\",\n // Next token is a definition\n startDef: false,\n // Last token of the statement is a definition\n endDef: false\n };\n },\n token: function(stream, state) {\n var style = readToken(stream, state);\n\n if (style) {\n var cur = stream.current();\n state.lastToken = cur;\n if (style === \"keyword\") {\n state.startDef = startDefs.test(cur);\n state.endDef = state.endDef || endDefs.test(cur);\n } else {\n state.startDef = false;\n }\n }\n\n return style;\n },\n\n languageData: {\n autocomplete: builtinArray.concat(typeArray).concat(keywordArray).concat(atomArray)\n }\n};\n"],"names":["wordRegexp","words","RegExp","join","builtinArray","builtins","typeArray","types","keywordArray","keywords","atomArray","atoms","startDefs","endDefs","singleOperators","integers","floats","identifiers","identifiersEnd","strings","multilineComments","multilineCommentsStart","multilineCommentsEnd","webIDL","name","startState","inComment","lastToken","startDef","endDef","token","stream","state","style","eatSpace","match","skipToEnd","nextToken","next","readToken","cur","current","test","languageData","autocomplete","concat"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/4844.index.js b/book/_build/html/_static/4844.index.js new file mode 100644 index 0000000..3ff4ff8 --- /dev/null +++ b/book/_build/html/_static/4844.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[4844],{94844:(e,t,n)=>{function r(e){for(var t={},n=e.split(" "),r=0;rv});var a,o=r("abs acos allnodes ascii asin asstring atan atan2 ave case choose choosen choosesets clustersize combine correlation cos cosh count covariance cron dataset dedup define denormalize distribute distributed distribution ebcdic enth error evaluate event eventextra eventname exists exp failcode failmessage fetch fromunicode getisvalid global graph group hash hash32 hash64 hashcrc hashmd5 having if index intformat isvalid iterate join keyunicode length library limit ln local log loop map matched matchlength matchposition matchtext matchunicode max merge mergejoin min nolocal nonempty normalize parse pipe power preload process project pull random range rank ranked realformat recordof regexfind regexreplace regroup rejected rollup round roundup row rowdiff sample set sin sinh sizeof soapcall sort sorted sqrt stepped stored sum table tan tanh thisnode topn tounicode transfer trim truncate typeof ungroup unicodeorder variance which workunit xmldecode xmlencode xmltext xmlunicode"),i=r("apply assert build buildindex evaluate fail keydiff keypatch loadxml nothor notify output parallel sequential soapcall wait"),l=r("__compressed__ all and any as atmost before beginc++ best between case const counter csv descend encrypt end endc++ endmacro except exclusive expire export extend false few first flat from full function group header heading hole ifblock import in interface joined keep keyed last left limit load local locale lookup macro many maxcount maxlength min skew module named nocase noroot noscan nosort not of only opt or outer overwrite packed partition penalty physicallength pipe quote record relationship repeat return right scan self separator service shared skew skip sql store terminator thor threshold token transform trim true type unicodeorder unsorted validate virtual whole wild within xml xpath"),s=r("ascii big_endian boolean data decimal ebcdic integer pattern qstring real record rule set of string token udecimal unicode unsigned varstring varunicode"),u=r("checkpoint deprecated failcode failmessage failure global independent onwarning persist priority recovery stored success wait when"),c=r("catch class do else finally for if switch try while"),p=r("true false null"),d={"#":function(e,t){return!!t.startOfLine&&(e.skipToEnd(),"meta")}},m=/[+\-*&%=<>!?|\/]/;function f(e,t){var n,r=e.next();if(d[r]){var y=d[r](e,t);if(!1!==y)return y}if('"'==r||"'"==r)return t.tokenize=(n=r,function(e,t){for(var r,a=!1,o=!1;null!=(r=e.next());){if(r==n&&!a){o=!0;break}a=!a&&"\\"==r}return!o&&a||(t.tokenize=f),"string"}),t.tokenize(e,t);if(/[\[\]{}\(\),;\:\.]/.test(r))return a=r,null;if(/\d/.test(r))return e.eatWhile(/[\w\.]/),"number";if("/"==r){if(e.eat("*"))return t.tokenize=h,h(e,t);if(e.eat("/"))return e.skipToEnd(),"comment"}if(m.test(r))return e.eatWhile(m),"operator";e.eatWhile(/[\w\$_]/);var b=e.current().toLowerCase();if(o.propertyIsEnumerable(b))return c.propertyIsEnumerable(b)&&(a="newstatement"),"keyword";if(i.propertyIsEnumerable(b))return c.propertyIsEnumerable(b)&&(a="newstatement"),"variable";if(l.propertyIsEnumerable(b))return c.propertyIsEnumerable(b)&&(a="newstatement"),"modifier";if(s.propertyIsEnumerable(b))return c.propertyIsEnumerable(b)&&(a="newstatement"),"type";if(u.propertyIsEnumerable(b))return c.propertyIsEnumerable(b)&&(a="newstatement"),"builtin";for(var g=b.length-1;g>=0&&(!isNaN(b[g])||"_"==b[g]);)--g;if(g>0){var v=b.substr(0,g+1);if(s.propertyIsEnumerable(v))return c.propertyIsEnumerable(v)&&(a="newstatement"),"type"}return p.propertyIsEnumerable(b)?"atom":null}function h(e,t){for(var n,r=!1;n=e.next();){if("/"==n&&r){t.tokenize=f;break}r="*"==n}return"comment"}function y(e,t,n,r,a){this.indented=e,this.column=t,this.type=n,this.align=r,this.prev=a}function b(e,t,n){return e.context=new y(e.indented,t,n,null,e.context)}function g(e){var t=e.context.type;return")"!=t&&"]"!=t&&"}"!=t||(e.indented=e.context.indented),e.context=e.context.prev}const v={name:"ecl",startState:function(e){return{tokenize:null,context:new y(-e,0,"top",!1),indented:0,startOfLine:!0}},token:function(e,t){var n=t.context;if(e.sol()&&(null==n.align&&(n.align=!1),t.indented=e.indentation(),t.startOfLine=!0),e.eatSpace())return null;a=null;var r=(t.tokenize||f)(e,t);if("comment"==r||"meta"==r)return r;if(null==n.align&&(n.align=!0),";"!=a&&":"!=a||"statement"!=n.type)if("{"==a)b(t,e.column(),"}");else if("["==a)b(t,e.column(),"]");else if("("==a)b(t,e.column(),")");else if("}"==a){for(;"statement"==n.type;)n=g(t);for("}"==n.type&&(n=g(t));"statement"==n.type;)n=g(t)}else a==n.type?g(t):("}"==n.type||"top"==n.type||"statement"==n.type&&"newstatement"==a)&&b(t,e.column(),"statement");else g(t);return t.startOfLine=!1,r},indent:function(e,t,n){if(e.tokenize!=f&&null!=e.tokenize)return 0;var r=e.context,a=t&&t.charAt(0);"statement"==r.type&&"}"==a&&(r=r.prev);var o=a==r.type;return"statement"==r.type?r.indented+("{"==a?0:n.unit):r.align?r.column+(o?0:1):r.indented+(o?0:n.unit)},languageData:{indentOnInput:/^\s*[{}]$/}}}}]); +//# sourceMappingURL=4844.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/4844.index.js.map b/book/_build/html/_static/4844.index.js.map new file mode 100644 index 0000000..ff57b19 --- /dev/null +++ b/book/_build/html/_static/4844.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"4844.index.js","mappings":"+FAAA,SAASA,EAAMC,GAEb,IADA,IAAIC,EAAM,CAAC,EAAGF,EAAQC,EAAIE,MAAM,KACvBC,EAAI,EAAGA,EAAIJ,EAAMK,SAAUD,EAAGF,EAAIF,E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C3EyC,EAAY/B,EAAOD,EAAO2B,SAAU,kBAX6BQ,EAAWlC,GAa9E,OADAA,EAAMC,aAAc,EACb4C,CACT,EAEAC,OAAQ,SAAS9C,EAAO+C,EAAWC,GACjC,GAAIhD,EAAMS,UAAYL,GAA+B,MAAlBJ,EAAMS,SAAkB,OAAO,EAClE,IAAIgC,EAAMzC,EAAMiC,QAASgB,EAAYF,GAAaA,EAAUG,OAAO,GACnD,aAAZT,EAAId,MAAoC,KAAbsB,IAAkBR,EAAMA,EAAIZ,MAC3D,IAAIsB,EAAUF,GAAaR,EAAId,KAC/B,MAAgB,aAAZc,EAAId,KAA4Bc,EAAIhB,UAAyB,KAAbwB,EAAmB,EAAID,EAAGI,MACrEX,EAAIb,MAAca,EAAIf,QAAUyB,EAAU,EAAI,GAC3CV,EAAIhB,UAAY0B,EAAU,EAAIH,EAAGI,KAC/C,EAEAC,aAAc,CACZC,cAAe,a","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/ecl.js"],"sourcesContent":["function words(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n}\n\nfunction metaHook(stream, state) {\n if (!state.startOfLine) return false;\n stream.skipToEnd();\n return \"meta\";\n}\n\nvar keyword = words(\"abs acos allnodes ascii asin asstring atan atan2 ave case choose choosen choosesets clustersize combine correlation cos cosh count covariance cron dataset dedup define denormalize distribute distributed distribution ebcdic enth error evaluate event eventextra eventname exists exp failcode failmessage fetch fromunicode getisvalid global graph group hash hash32 hash64 hashcrc hashmd5 having if index intformat isvalid iterate join keyunicode length library limit ln local log loop map matched matchlength matchposition matchtext matchunicode max merge mergejoin min nolocal nonempty normalize parse pipe power preload process project pull random range rank ranked realformat recordof regexfind regexreplace regroup rejected rollup round roundup row rowdiff sample set sin sinh sizeof soapcall sort sorted sqrt stepped stored sum table tan tanh thisnode topn tounicode transfer trim truncate typeof ungroup unicodeorder variance which workunit xmldecode xmlencode xmltext xmlunicode\");\nvar variable = words(\"apply assert build buildindex evaluate fail keydiff keypatch loadxml nothor notify output parallel sequential soapcall wait\");\nvar variable_2 = words(\"__compressed__ all and any as atmost before beginc++ best between case const counter csv descend encrypt end endc++ endmacro except exclusive expire export extend false few first flat from full function group header heading hole ifblock import in interface joined keep keyed last left limit load local locale lookup macro many maxcount maxlength min skew module named nocase noroot noscan nosort not of only opt or outer overwrite packed partition penalty physicallength pipe quote record relationship repeat return right scan self separator service shared skew skip sql store terminator thor threshold token transform trim true type unicodeorder unsorted validate virtual whole wild within xml xpath\");\nvar variable_3 = words(\"ascii big_endian boolean data decimal ebcdic integer pattern qstring real record rule set of string token udecimal unicode unsigned varstring varunicode\");\nvar builtin = words(\"checkpoint deprecated failcode failmessage failure global independent onwarning persist priority recovery stored success wait when\");\nvar blockKeywords = words(\"catch class do else finally for if switch try while\");\nvar atoms = words(\"true false null\");\nvar hooks = {\"#\": metaHook};\nvar isOperatorChar = /[+\\-*&%=<>!?|\\/]/;\n\nvar curPunc;\n\nfunction tokenBase(stream, state) {\n var ch = stream.next();\n if (hooks[ch]) {\n var result = hooks[ch](stream, state);\n if (result !== false) return result;\n }\n if (ch == '\"' || ch == \"'\") {\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n }\n if (/[\\[\\]{}\\(\\),;\\:\\.]/.test(ch)) {\n curPunc = ch;\n return null;\n }\n if (/\\d/.test(ch)) {\n stream.eatWhile(/[\\w\\.]/);\n return \"number\";\n }\n if (ch == \"/\") {\n if (stream.eat(\"*\")) {\n state.tokenize = tokenComment;\n return tokenComment(stream, state);\n }\n if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return \"comment\";\n }\n }\n if (isOperatorChar.test(ch)) {\n stream.eatWhile(isOperatorChar);\n return \"operator\";\n }\n stream.eatWhile(/[\\w\\$_]/);\n var cur = stream.current().toLowerCase();\n if (keyword.propertyIsEnumerable(cur)) {\n if (blockKeywords.propertyIsEnumerable(cur)) curPunc = \"newstatement\";\n return \"keyword\";\n } else if (variable.propertyIsEnumerable(cur)) {\n if (blockKeywords.propertyIsEnumerable(cur)) curPunc = \"newstatement\";\n return \"variable\";\n } else if (variable_2.propertyIsEnumerable(cur)) {\n if (blockKeywords.propertyIsEnumerable(cur)) curPunc = \"newstatement\";\n return \"modifier\";\n } else if (variable_3.propertyIsEnumerable(cur)) {\n if (blockKeywords.propertyIsEnumerable(cur)) curPunc = \"newstatement\";\n return \"type\";\n } else if (builtin.propertyIsEnumerable(cur)) {\n if (blockKeywords.propertyIsEnumerable(cur)) curPunc = \"newstatement\";\n return \"builtin\";\n } else { //Data types are of from KEYWORD##\n var i = cur.length - 1;\n while(i >= 0 && (!isNaN(cur[i]) || cur[i] == '_'))\n --i;\n\n if (i > 0) {\n var cur2 = cur.substr(0, i + 1);\n if (variable_3.propertyIsEnumerable(cur2)) {\n if (blockKeywords.propertyIsEnumerable(cur2)) curPunc = \"newstatement\";\n return \"type\";\n }\n }\n }\n if (atoms.propertyIsEnumerable(cur)) return \"atom\";\n return null;\n}\n\nfunction tokenString(quote) {\n return function(stream, state) {\n var escaped = false, next, end = false;\n while ((next = stream.next()) != null) {\n if (next == quote && !escaped) {end = true; break;}\n escaped = !escaped && next == \"\\\\\";\n }\n if (end || !escaped)\n state.tokenize = tokenBase;\n return \"string\";\n };\n}\n\nfunction tokenComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if (ch == \"/\" && maybeEnd) {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return \"comment\";\n}\n\nfunction Context(indented, column, type, align, prev) {\n this.indented = indented;\n this.column = column;\n this.type = type;\n this.align = align;\n this.prev = prev;\n}\nfunction pushContext(state, col, type) {\n return state.context = new Context(state.indented, col, type, null, state.context);\n}\nfunction popContext(state) {\n var t = state.context.type;\n if (t == \")\" || t == \"]\" || t == \"}\")\n state.indented = state.context.indented;\n return state.context = state.context.prev;\n}\n\n// Interface\n\nexport const ecl = {\n name: \"ecl\",\n startState: function(indentUnit) {\n return {\n tokenize: null,\n context: new Context(-indentUnit, 0, \"top\", false),\n indented: 0,\n startOfLine: true\n };\n },\n\n token: function(stream, state) {\n var ctx = state.context;\n if (stream.sol()) {\n if (ctx.align == null) ctx.align = false;\n state.indented = stream.indentation();\n state.startOfLine = true;\n }\n if (stream.eatSpace()) return null;\n curPunc = null;\n var style = (state.tokenize || tokenBase)(stream, state);\n if (style == \"comment\" || style == \"meta\") return style;\n if (ctx.align == null) ctx.align = true;\n\n if ((curPunc == \";\" || curPunc == \":\") && ctx.type == \"statement\") popContext(state);\n else if (curPunc == \"{\") pushContext(state, stream.column(), \"}\");\n else if (curPunc == \"[\") pushContext(state, stream.column(), \"]\");\n else if (curPunc == \"(\") pushContext(state, stream.column(), \")\");\n else if (curPunc == \"}\") {\n while (ctx.type == \"statement\") ctx = popContext(state);\n if (ctx.type == \"}\") ctx = popContext(state);\n while (ctx.type == \"statement\") ctx = popContext(state);\n }\n else if (curPunc == ctx.type) popContext(state);\n else if (ctx.type == \"}\" || ctx.type == \"top\" || (ctx.type == \"statement\" && curPunc == \"newstatement\"))\n pushContext(state, stream.column(), \"statement\");\n state.startOfLine = false;\n return style;\n },\n\n indent: function(state, textAfter, cx) {\n if (state.tokenize != tokenBase && state.tokenize != null) return 0;\n var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);\n if (ctx.type == \"statement\" && firstChar == \"}\") ctx = ctx.prev;\n var closing = firstChar == ctx.type;\n if (ctx.type == \"statement\") return ctx.indented + (firstChar == \"{\" ? 0 : cx.unit);\n else if (ctx.align) return ctx.column + (closing ? 0 : 1);\n else return ctx.indented + (closing ? 0 : cx.unit);\n },\n\n languageData: {\n indentOnInput: /^\\s*[{}]$/\n }\n};\n"],"names":["words","str","obj","split","i","length","curPunc","keyword","variable","variable_2","variable_3","builtin","blockKeywords","atoms","hooks","stream","state","startOfLine","skipToEnd","isOperatorChar","tokenBase","quote","ch","next","result","tokenize","escaped","end","test","eatWhile","eat","tokenComment","cur","current","toLowerCase","propertyIsEnumerable","isNaN","cur2","substr","maybeEnd","Context","indented","column","type","align","prev","this","pushContext","col","context","popContext","t","ecl","name","startState","indentUnit","token","ctx","sol","indentation","eatSpace","style","indent","textAfter","cx","firstChar","charAt","closing","unit","languageData","indentOnInput"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/510.thebe-lite.min.js b/book/_build/html/_static/510.thebe-lite.min.js new file mode 100644 index 0000000..87d2efb --- /dev/null +++ b/book/_build/html/_static/510.thebe-lite.min.js @@ -0,0 +1,3 @@ +/*! For license information please see 510.thebe-lite.min.js.LICENSE.txt */ +(self.webpackChunkthebe_lite=self.webpackChunkthebe_lite||[]).push([[510],{144:(e,t,s)=>{"use strict";s.r(t),s.d(t,{PIPLITE_INDEX_SCHEMA:()=>N,PyodideKernel:()=>L,PyodideRemoteKernel:()=>z.O,allJSONUrl:()=>a,ipykernelWheelUrl:()=>r,pipliteWheelUrl:()=>l,pyodide_kernelWheelUrl:()=>c,widgetsnbextensionWheelUrl:()=>u,widgetsnbextensionWheelUrl1:()=>m});const n=s.p+"pypi/all.json";var a=s.t(n);const i=s.p+"pypi/ipykernel-6.9.2-py3-none-any.whl";var r=s.t(i);const o=s.p+"pypi/piplite-0.2.0-py3-none-any.whl";var l=s.t(o);const p=s.p+"pypi/pyodide_kernel-0.2.0-py3-none-any.whl";var c=s.t(p);const d=s.p+"pypi/widgetsnbextension-3.6.6-py3-none-any.whl";var u=s.t(d);const h=s.p+"pypi/widgetsnbextension-4.0.9-py3-none-any.whl";var m=s.t(h),y=s(5082),g=s(9622),_=s(6914),f=s(4016);class b{constructor(e){this._history=[],this._executionCount=0,this._isDisposed=!1,this._disposed=new f.Signal(this),this._parentHeader=void 0,this._parent=void 0;const{id:t,name:s,location:n,sendMessage:a}=e;this._id=t,this._name=s,this._location=n,this._sendMessage=a}get ready(){return Promise.resolve()}get isDisposed(){return this._isDisposed}get disposed(){return this._disposed}get id(){return this._id}get name(){return this._name}get location(){return this._location}get executionCount(){return this._executionCount}get parentHeader(){return this._parentHeader}get parent(){return this._parent}dispose(){this.isDisposed||(this._isDisposed=!0,this._disposed.emit(void 0))}async handleMessage(e){switch(this._busy(e),this._parent=e,e.header.msg_type){case"kernel_info_request":await this._kernelInfo(e);break;case"execute_request":await this._execute(e);break;case"input_reply":this.inputReply(e.content);break;case"inspect_request":await this._inspect(e);break;case"is_complete_request":await this._isCompleteRequest(e);break;case"complete_request":await this._complete(e);break;case"history_request":await this._historyRequest(e);break;case"comm_open":await this.commOpen(e);break;case"comm_msg":await this.commMsg(e);break;case"comm_close":await this.commClose(e)}this._idle(e)}stream(e,t=undefined){var s;const n=void 0!==t?t:this._parentHeader,a=_.KernelMessage.createMessage({channel:"iopub",msgType:"stream",session:null!==(s=null==n?void 0:n.session)&&void 0!==s?s:"",parentHeader:n,content:e});this._sendMessage(a)}displayData(e,t=undefined){var s,n;const a=void 0!==t?t:this._parentHeader;e.metadata=null!==(s=e.metadata)&&void 0!==s?s:{};const i=_.KernelMessage.createMessage({channel:"iopub",msgType:"display_data",session:null!==(n=null==a?void 0:a.session)&&void 0!==n?n:"",parentHeader:a,content:e});this._sendMessage(i)}inputRequest(e,t=undefined){var s;const n=void 0!==t?t:this._parentHeader,a=_.KernelMessage.createMessage({channel:"stdin",msgType:"input_request",session:null!==(s=null==n?void 0:n.session)&&void 0!==s?s:"",parentHeader:n,content:e});this._sendMessage(a)}publishExecuteResult(e,t=undefined){var s;const n=void 0!==t?t:this._parentHeader,a=_.KernelMessage.createMessage({channel:"iopub",msgType:"execute_result",session:null!==(s=null==n?void 0:n.session)&&void 0!==s?s:"",parentHeader:n,content:e});this._sendMessage(a)}publishExecuteError(e,t=undefined){var s;const n=void 0!==t?t:this._parentHeader,a=_.KernelMessage.createMessage({channel:"iopub",msgType:"error",session:null!==(s=null==n?void 0:n.session)&&void 0!==s?s:"",parentHeader:n,content:e});this._sendMessage(a)}updateDisplayData(e,t=undefined){var s;const n=void 0!==t?t:this._parentHeader,a=_.KernelMessage.createMessage({channel:"iopub",msgType:"update_display_data",session:null!==(s=null==n?void 0:n.session)&&void 0!==s?s:"",parentHeader:n,content:e});this._sendMessage(a)}clearOutput(e,t=undefined){var s;const n=void 0!==t?t:this._parentHeader,a=_.KernelMessage.createMessage({channel:"iopub",msgType:"clear_output",session:null!==(s=null==n?void 0:n.session)&&void 0!==s?s:"",parentHeader:n,content:e});this._sendMessage(a)}handleComm(e,t,s,n,a=undefined){var i;const r=void 0!==a?a:this._parentHeader,o=_.KernelMessage.createMessage({channel:"iopub",msgType:e,session:null!==(i=null==r?void 0:r.session)&&void 0!==i?i:"",parentHeader:r,content:t,metadata:s,buffers:n});this._sendMessage(o)}_idle(e){const t=_.KernelMessage.createMessage({msgType:"status",session:e.header.session,parentHeader:e.header,channel:"iopub",content:{execution_state:"idle"}});this._sendMessage(t)}_busy(e){const t=_.KernelMessage.createMessage({msgType:"status",session:e.header.session,parentHeader:e.header,channel:"iopub",content:{execution_state:"busy"}});this._sendMessage(t)}async _kernelInfo(e){const t=await this.kernelInfoRequest(),s=_.KernelMessage.createMessage({msgType:"kernel_info_reply",channel:"shell",session:e.header.session,parentHeader:e.header,content:t});this._sendMessage(s)}async _historyRequest(e){const t=e,s=_.KernelMessage.createMessage({msgType:"history_reply",channel:"shell",parentHeader:t.header,session:e.header.session,content:{status:"ok",history:this._history}});this._sendMessage(s)}_executeInput(e){const t=e,s=t.content.code,n=_.KernelMessage.createMessage({msgType:"execute_input",parentHeader:t.header,channel:"iopub",session:e.header.session,content:{code:s,execution_count:this._executionCount}});this._sendMessage(n)}async _execute(e){const t=e,s=t.content;s.store_history&&this._executionCount++,this._parentHeader=t.header,this._executeInput(t),s.store_history&&this._history.push([0,0,s.code]);const n=await this.executeRequest(t.content),a=_.KernelMessage.createMessage({msgType:"execute_reply",channel:"shell",parentHeader:t.header,session:e.header.session,content:n});this._sendMessage(a)}async _complete(e){const t=e,s=await this.completeRequest(t.content),n=_.KernelMessage.createMessage({msgType:"complete_reply",parentHeader:t.header,channel:"shell",session:e.header.session,content:s});this._sendMessage(n)}async _inspect(e){const t=e,s=await this.inspectRequest(t.content),n=_.KernelMessage.createMessage({msgType:"inspect_reply",parentHeader:t.header,channel:"shell",session:e.header.session,content:s});this._sendMessage(n)}async _isCompleteRequest(e){const t=e,s=await this.isCompleteRequest(t.content),n=_.KernelMessage.createMessage({msgType:"is_complete_reply",parentHeader:t.header,channel:"shell",session:e.header.session,content:s});this._sendMessage(n)}}const v=Symbol("Comlink.proxy"),w=Symbol("Comlink.endpoint"),M=Symbol("Comlink.releaseProxy"),k=Symbol("Comlink.finalizer"),x=Symbol("Comlink.thrown"),E=e=>"object"==typeof e&&null!==e||"function"==typeof e,H=new Map([["proxy",{canHandle:e=>E(e)&&e[v],serialize(e){const{port1:t,port2:s}=new MessageChannel;return R(e,t),[s,[s]]},deserialize:e=>(e.start(),C(e))}],["throw",{canHandle:e=>E(e)&&x in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){if(e.isError)throw Object.assign(new Error(e.value.message),e.value);throw e.value}}]]);function R(e,t=globalThis,s=["*"]){t.addEventListener("message",(function n(a){if(!a||!a.data)return;if(!function(e,t){for(const s of e){if(t===s||"*"===s)return!0;if(s instanceof RegExp&&s.test(t))return!0}return!1}(s,a.origin))return void console.warn(`Invalid origin '${a.origin}' for comlink proxy`);const{id:i,type:r,path:o}=Object.assign({path:[]},a.data),l=(a.data.argumentList||[]).map(I);let p;try{const t=o.slice(0,-1).reduce(((e,t)=>e[t]),e),s=o.reduce(((e,t)=>e[t]),e);switch(r){case"GET":p=s;break;case"SET":t[o.slice(-1)[0]]=I(a.data.value),p=!0;break;case"APPLY":p=s.apply(t,l);break;case"CONSTRUCT":p=function(e){return Object.assign(e,{[v]:!0})}(new s(...l));break;case"ENDPOINT":{const{port1:t,port2:s}=new MessageChannel;R(e,s),p=function(e,t){return U.set(e,t),e}(t,[t])}break;case"RELEASE":p=void 0;break;default:return}}catch(e){p={value:e,[x]:0}}Promise.resolve(p).catch((e=>({value:e,[x]:0}))).then((s=>{const[a,o]=j(s);t.postMessage(Object.assign(Object.assign({},a),{id:i}),o),"RELEASE"===r&&(t.removeEventListener("message",n),T(t),k in e&&"function"==typeof e[k]&&e[k]())})).catch((e=>{const[s,n]=j({value:new TypeError("Unserializable return value"),[x]:0});t.postMessage(Object.assign(Object.assign({},s),{id:i}),n)}))})),t.start&&t.start()}function T(e){(function(e){return"MessagePort"===e.constructor.name})(e)&&e.close()}function C(e,t){return S(e,[],t)}function K(e){if(e)throw new Error("Proxy has been released and is not useable")}function P(e){return A(e,{type:"RELEASE"}).then((()=>{T(e)}))}const O=new WeakMap,q="FinalizationRegistry"in globalThis&&new FinalizationRegistry((e=>{const t=(O.get(e)||0)-1;O.set(e,t),0===t&&P(e)}));function S(e,t=[],s=function(){}){let n=!1;const a=new Proxy(s,{get(s,i){if(K(n),i===M)return()=>{!function(e){q&&q.unregister(e)}(a),P(e),n=!0};if("then"===i){if(0===t.length)return{then:()=>a};const s=A(e,{type:"GET",path:t.map((e=>e.toString()))}).then(I);return s.then.bind(s)}return S(e,[...t,i])},set(s,a,i){K(n);const[r,o]=j(i);return A(e,{type:"SET",path:[...t,a].map((e=>e.toString())),value:r},o).then(I)},apply(s,a,i){K(n);const r=t[t.length-1];if(r===w)return A(e,{type:"ENDPOINT"}).then(I);if("bind"===r)return S(e,t.slice(0,-1));const[o,l]=D(i);return A(e,{type:"APPLY",path:t.map((e=>e.toString())),argumentList:o},l).then(I)},construct(s,a){K(n);const[i,r]=D(a);return A(e,{type:"CONSTRUCT",path:t.map((e=>e.toString())),argumentList:i},r).then(I)}});return function(e,t){const s=(O.get(t)||0)+1;O.set(t,s),q&&q.register(e,t,e)}(a,e),a}function D(e){const t=e.map(j);return[t.map((e=>e[0])),(s=t.map((e=>e[1])),Array.prototype.concat.apply([],s))];var s}const U=new WeakMap;function j(e){for(const[t,s]of H)if(s.canHandle(e)){const[n,a]=s.serialize(e);return[{type:"HANDLER",name:t,value:n},a]}return[{type:"RAW",value:e},U.get(e)||[]]}function I(e){switch(e.type){case"HANDLER":return H.get(e.name).deserialize(e.value);case"RAW":return e.value}}function A(e,t,s){return new Promise((n=>{const a=new Array(4).fill(0).map((()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16))).join("-");e.addEventListener("message",(function t(s){s.data&&s.data.id&&s.data.id===a&&(e.removeEventListener("message",t),n(s.data))})),e.start&&e.start(),e.postMessage(Object.assign({id:a},t),s)}))}class L extends b{constructor(e){super(e),this._ready=new y.PromiseDelegate,this._worker=this.initWorker(e),this._worker.onmessage=e=>this._processWorkerMessage(e.data),this._remoteKernel=C(this._worker),this.initRemote(e)}initWorker(e){return new Worker(new URL(s.p+s.u(946),s.b),{type:void 0})}async initRemote(e){const t=this.initRemoteOptions(e);await this._remoteKernel.initialize(t),this._ready.resolve()}initRemoteOptions(e){const{pyodideUrl:t}=e,s=t.slice(0,t.lastIndexOf("/")+1),a=g.PageConfig.getBaseUrl(),i=[...e.pipliteUrls||[],n],r=!!e.disablePyPIFallback;return{baseUrl:a,pyodideUrl:t,indexUrl:s,pipliteWheelUrl:e.pipliteWheelUrl||o,pipliteUrls:i,disablePyPIFallback:r,location:this.location,mountDrive:e.mountDrive}}dispose(){this.isDisposed||(this._worker.terminate(),this._worker=null,super.dispose())}get ready(){return this._ready.promise}_processWorkerMessage(e){var t,s,n,a,i,r,o;if(e.type)switch(e.type){case"stream":{const s=null!==(t=e.bundle)&&void 0!==t?t:{name:"stdout",text:""};this.stream(s,e.parentHeader);break}case"input_request":{const t=null!==(s=e.content)&&void 0!==s?s:{prompt:"",password:!1};this.inputRequest(t,e.parentHeader);break}case"display_data":{const t=null!==(n=e.bundle)&&void 0!==n?n:{data:{},metadata:{},transient:{}};this.displayData(t,e.parentHeader);break}case"update_display_data":{const t=null!==(a=e.bundle)&&void 0!==a?a:{data:{},metadata:{},transient:{}};this.updateDisplayData(t,e.parentHeader);break}case"clear_output":{const t=null!==(i=e.bundle)&&void 0!==i?i:{wait:!1};this.clearOutput(t,e.parentHeader);break}case"execute_result":{const t=null!==(r=e.bundle)&&void 0!==r?r:{execution_count:0,data:{},metadata:{}};this.publishExecuteResult(t,e.parentHeader);break}case"execute_error":{const t=null!==(o=e.bundle)&&void 0!==o?o:{ename:"",evalue:"",traceback:[]};this.publishExecuteError(t,e.parentHeader);break}case"comm_msg":case"comm_open":case"comm_close":this.handleComm(e.type,e.content,e.metadata,e.buffers,e.parentHeader)}}async kernelInfoRequest(){return{implementation:"pyodide",implementation_version:"0.1.0",language_info:{codemirror_mode:{name:"python",version:3},file_extension:".py",mimetype:"text/x-python",name:"python",nbconvert_exporter:"python",pygments_lexer:"ipython3",version:"3.8"},protocol_version:"5.3",status:"ok",banner:"A WebAssembly-powered Python kernel backed by Pyodide",help_links:[{text:"Python (WASM) Kernel",url:"https://pyodide.org"}]}}async executeRequest(e){await this.ready;const t=await this._remoteKernel.execute(e,this.parent);return t.execution_count=this.executionCount,t}async completeRequest(e){return await this._remoteKernel.complete(e,this.parent)}async inspectRequest(e){return await this._remoteKernel.inspect(e,this.parent)}async isCompleteRequest(e){return await this._remoteKernel.isComplete(e,this.parent)}async commInfoRequest(e){return await this._remoteKernel.commInfo(e,this.parent)}async commOpen(e){return await this._remoteKernel.commOpen(e,this.parent)}async commMsg(e){return await this._remoteKernel.commMsg(e,this.parent)}async commClose(e){return await this._remoteKernel.commClose(e,this.parent)}async inputReply(e){return await this._remoteKernel.inputReply(e,this.parent)}}const W=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema","$id":"https://jupyterlite-pyodide-kernel.readthedocs.org/en/latest/reference/schema/piplite-v0.html#","title":"PipLite Schema v0","description":"a schema for the warehouse-like API index","$ref":"#/definitions/top","definitions":{"top":{"type":"object","patternProperties":{".*":{"$ref":"#/definitions/a-piplite-project"}}},"a-piplite-project":{"type":"object","description":"a piplite-installable project, with one or more historical releases","properties":{"releases":{"patternProperties":{".*":{"type":"array","items":{"$ref":"#/definitions/a-piplite-distribution"}}}}}},"a-piplite-distribution":{"type":"object","properties":{"comment_text":{"type":"string"},"digests":{"type":"object","properties":{"md5":{"$ref":"#/definitions/an-md5-digest"},"sha256":{"$ref":"#/definitions/a-sha256-digest"}}},"downloads":{"type":"number"},"filename":{"type":"string"},"has_sig":{"type":"boolean"},"md5_digest":{"$ref":"#/definitions/an-md5-digest"},"packagetype":{"type":"string","enum":["bdist_wheel"]},"python_version":{"type":"string"},"requires_python":{"$ref":"#/definitions/string-or-null"},"size":{"type":"number"},"upload_time":{"type":"string","format":"date-time"},"upload_time_iso_8601":{"type":"string","format":"date-time"},"url":{"type":"string","format":"uri"},"yanked":{"type":"boolean"},"yanked_reason":{"$ref":"#/definitions/string-or-null"}}},"string-or-null":{"anyOf":[{"type":"string"},{"type":"null"}]},"an-md5-digest":{"type":"string","pattern":"[a-f0-9]{32}"},"a-sha256-digest":{"type":"string","pattern":"[a-f0-9]{64}"}}}');var N=s.t(W,2),z=s(3296)},265:e=>{function t(e){return Promise.resolve().then((()=>{var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}))}t.keys=()=>[],t.resolve=t,t.id=265,e.exports=t}}]); +//# sourceMappingURL=510.thebe-lite.min.js.map \ No newline at end of file diff --git a/book/_build/html/_static/510.thebe-lite.min.js.LICENSE.txt b/book/_build/html/_static/510.thebe-lite.min.js.LICENSE.txt new file mode 100644 index 0000000..479a8e5 --- /dev/null +++ b/book/_build/html/_static/510.thebe-lite.min.js.LICENSE.txt @@ -0,0 +1,5 @@ +/** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ diff --git a/book/_build/html/_static/510.thebe-lite.min.js.map b/book/_build/html/_static/510.thebe-lite.min.js.map new file mode 100644 index 0000000..8846324 --- /dev/null +++ b/book/_build/html/_static/510.thebe-lite.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":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O,IAAM,GACtCF,EAAyB9O,QAAU8O,EACnCA,EAAyBxP,GAAK,IAC9B2P,EAAOC,QAAUJ","sources":["webpack://thebe-lite/./node_modules/@jupyterlite/kernel/lib/kernel.js","webpack://thebe-lite/../../node_modules/comlink/dist/esm/comlink.mjs","webpack://thebe-lite/./node_modules/@jupyterlite/pyodide-kernel/lib/kernel.js","webpack://thebe-lite/./node_modules/@jupyterlite/pyodide-kernel/lib/ lazy namespace object"],"sourcesContent":["import { KernelMessage } from '@jupyterlab/services';\nimport { Signal } from '@lumino/signaling';\n/**\n * A base kernel class handling basic kernel messaging.\n */\nexport class BaseKernel {\n /**\n * Construct a new BaseKernel.\n *\n * @param options The instantiation options for a BaseKernel.\n */\n constructor(options) {\n this._history = [];\n this._executionCount = 0;\n this._isDisposed = false;\n this._disposed = new Signal(this);\n this._parentHeader = undefined;\n this._parent = undefined;\n const { id, name, location, sendMessage } = options;\n this._id = id;\n this._name = name;\n this._location = location;\n this._sendMessage = sendMessage;\n }\n /**\n * A promise that is fulfilled when the kernel is ready.\n */\n get ready() {\n return Promise.resolve();\n }\n /**\n * Return whether the kernel is disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * A signal emitted when the kernel is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * Get the kernel id\n */\n get id() {\n return this._id;\n }\n /**\n * Get the name of the kernel\n */\n get name() {\n return this._name;\n }\n /**\n * The location in the virtual filesystem from which the kernel was started.\n */\n get location() {\n return this._location;\n }\n /**\n * The current execution count\n */\n get executionCount() {\n return this._executionCount;\n }\n /**\n * Get the last parent header\n */\n get parentHeader() {\n return this._parentHeader;\n }\n /**\n * Get the last parent message (mimic ipykernel's get_parent)\n */\n get parent() {\n return this._parent;\n }\n /**\n * Dispose the kernel.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n this._disposed.emit(void 0);\n }\n /**\n * Handle an incoming message from the client.\n *\n * @param msg The message to handle\n */\n async handleMessage(msg) {\n this._busy(msg);\n this._parent = msg;\n const msgType = msg.header.msg_type;\n switch (msgType) {\n case 'kernel_info_request':\n await this._kernelInfo(msg);\n break;\n case 'execute_request':\n await this._execute(msg);\n break;\n case 'input_reply':\n this.inputReply(msg.content);\n break;\n case 'inspect_request':\n await this._inspect(msg);\n break;\n case 'is_complete_request':\n await this._isCompleteRequest(msg);\n break;\n case 'complete_request':\n await this._complete(msg);\n break;\n case 'history_request':\n await this._historyRequest(msg);\n break;\n case 'comm_open':\n await this.commOpen(msg);\n break;\n case 'comm_msg':\n await this.commMsg(msg);\n break;\n case 'comm_close':\n await this.commClose(msg);\n break;\n default:\n break;\n }\n this._idle(msg);\n }\n /**\n * Stream an event from the kernel\n *\n * @param parentHeader The parent header.\n * @param content The stream content.\n */\n stream(content, parentHeader = undefined) {\n var _a;\n const parentHeaderValue = typeof parentHeader !== 'undefined' ? parentHeader : this._parentHeader;\n const message = KernelMessage.createMessage({\n channel: 'iopub',\n msgType: 'stream',\n // TODO: better handle this\n session: (_a = parentHeaderValue === null || parentHeaderValue === void 0 ? void 0 : parentHeaderValue.session) !== null && _a !== void 0 ? _a : '',\n parentHeader: parentHeaderValue,\n content,\n });\n this._sendMessage(message);\n }\n /**\n * Send a `display_data` message to the client.\n *\n * @param parentHeader The parent header.\n * @param content The display_data content.\n */\n displayData(content, parentHeader = undefined) {\n var _a, _b;\n // Make sure metadata is always set\n const parentHeaderValue = typeof parentHeader !== 'undefined' ? parentHeader : this._parentHeader;\n content.metadata = (_a = content.metadata) !== null && _a !== void 0 ? _a : {};\n const message = KernelMessage.createMessage({\n channel: 'iopub',\n msgType: 'display_data',\n // TODO: better handle this\n session: (_b = parentHeaderValue === null || parentHeaderValue === void 0 ? void 0 : parentHeaderValue.session) !== null && _b !== void 0 ? _b : '',\n parentHeader: parentHeaderValue,\n content,\n });\n this._sendMessage(message);\n }\n /**\n * Send a `input_request` message to the client.\n *\n * @param parentHeader The parent header.\n * @param content The input_request content.\n */\n inputRequest(content, parentHeader = undefined) {\n var _a;\n const parentHeaderValue = typeof parentHeader !== 'undefined' ? parentHeader : this._parentHeader;\n const message = KernelMessage.createMessage({\n channel: 'stdin',\n msgType: 'input_request',\n // TODO: better handle this\n session: (_a = parentHeaderValue === null || parentHeaderValue === void 0 ? void 0 : parentHeaderValue.session) !== null && _a !== void 0 ? _a : '',\n parentHeader: parentHeaderValue,\n content,\n });\n this._sendMessage(message);\n }\n /**\n * Send an `execute_result` message.\n *\n * @param parentHeader The parent header.\n * @param content The execute result content.\n */\n publishExecuteResult(content, parentHeader = undefined) {\n var _a;\n const parentHeaderValue = typeof parentHeader !== 'undefined' ? parentHeader : this._parentHeader;\n const message = KernelMessage.createMessage({\n channel: 'iopub',\n msgType: 'execute_result',\n // TODO: better handle this\n session: (_a = parentHeaderValue === null || parentHeaderValue === void 0 ? void 0 : parentHeaderValue.session) !== null && _a !== void 0 ? _a : '',\n parentHeader: parentHeaderValue,\n content,\n });\n this._sendMessage(message);\n }\n /**\n * Send an `error` message to the client.\n *\n * @param parentHeader The parent header.\n * @param content The error content.\n */\n publishExecuteError(content, parentHeader = undefined) {\n var _a;\n const parentHeaderValue = typeof parentHeader !== 'undefined' ? parentHeader : this._parentHeader;\n const message = KernelMessage.createMessage({\n channel: 'iopub',\n msgType: 'error',\n // TODO: better handle this\n session: (_a = parentHeaderValue === null || parentHeaderValue === void 0 ? void 0 : parentHeaderValue.session) !== null && _a !== void 0 ? _a : '',\n parentHeader: parentHeaderValue,\n content,\n });\n this._sendMessage(message);\n }\n /**\n * Send a `update_display_data` message to the client.\n *\n * @param parentHeader The parent header.\n * @param content The update_display_data content.\n */\n updateDisplayData(content, parentHeader = undefined) {\n var _a;\n const parentHeaderValue = typeof parentHeader !== 'undefined' ? parentHeader : this._parentHeader;\n const message = KernelMessage.createMessage({\n channel: 'iopub',\n msgType: 'update_display_data',\n // TODO: better handle this\n session: (_a = parentHeaderValue === null || parentHeaderValue === void 0 ? void 0 : parentHeaderValue.session) !== null && _a !== void 0 ? _a : '',\n parentHeader: parentHeaderValue,\n content,\n });\n this._sendMessage(message);\n }\n /**\n * Send a `clear_output` message to the client.\n *\n * @param parentHeader The parent header.\n * @param content The clear_output content.\n */\n clearOutput(content, parentHeader = undefined) {\n var _a;\n const parentHeaderValue = typeof parentHeader !== 'undefined' ? parentHeader : this._parentHeader;\n const message = KernelMessage.createMessage({\n channel: 'iopub',\n msgType: 'clear_output',\n // TODO: better handle this\n session: (_a = parentHeaderValue === null || parentHeaderValue === void 0 ? void 0 : parentHeaderValue.session) !== null && _a !== void 0 ? _a : '',\n parentHeader: parentHeaderValue,\n content,\n });\n this._sendMessage(message);\n }\n /**\n * Send a `comm` message to the client.\n *\n * @param .\n */\n handleComm(type, content, metadata, buffers, parentHeader = undefined) {\n var _a;\n const parentHeaderValue = typeof parentHeader !== 'undefined' ? parentHeader : this._parentHeader;\n const message = KernelMessage.createMessage({\n channel: 'iopub',\n msgType: type,\n // TODO: better handle this\n session: (_a = parentHeaderValue === null || parentHeaderValue === void 0 ? void 0 : parentHeaderValue.session) !== null && _a !== void 0 ? _a : '',\n parentHeader: parentHeaderValue,\n content,\n metadata,\n buffers,\n });\n this._sendMessage(message);\n }\n /**\n * Send an 'idle' status message.\n *\n * @param parent The parent message\n */\n _idle(parent) {\n const message = KernelMessage.createMessage({\n msgType: 'status',\n session: parent.header.session,\n parentHeader: parent.header,\n channel: 'iopub',\n content: {\n execution_state: 'idle',\n },\n });\n this._sendMessage(message);\n }\n /**\n * Send a 'busy' status message.\n *\n * @param parent The parent message.\n */\n _busy(parent) {\n const message = KernelMessage.createMessage({\n msgType: 'status',\n session: parent.header.session,\n parentHeader: parent.header,\n channel: 'iopub',\n content: {\n execution_state: 'busy',\n },\n });\n this._sendMessage(message);\n }\n /**\n * Handle a kernel_info_request message\n *\n * @param parent The parent message.\n */\n async _kernelInfo(parent) {\n const content = await this.kernelInfoRequest();\n const message = KernelMessage.createMessage({\n msgType: 'kernel_info_reply',\n channel: 'shell',\n session: parent.header.session,\n parentHeader: parent.header,\n content,\n });\n this._sendMessage(message);\n }\n /**\n * Handle a `history_request` message\n *\n * @param msg The parent message.\n */\n async _historyRequest(msg) {\n const historyMsg = msg;\n const message = KernelMessage.createMessage({\n msgType: 'history_reply',\n channel: 'shell',\n parentHeader: historyMsg.header,\n session: msg.header.session,\n content: {\n status: 'ok',\n history: this._history,\n },\n });\n this._sendMessage(message);\n }\n /**\n * Send an `execute_input` message.\n *\n * @param msg The parent message.\n */\n _executeInput(msg) {\n const parent = msg;\n const code = parent.content.code;\n const message = KernelMessage.createMessage({\n msgType: 'execute_input',\n parentHeader: parent.header,\n channel: 'iopub',\n session: msg.header.session,\n content: {\n code,\n execution_count: this._executionCount,\n },\n });\n this._sendMessage(message);\n }\n /**\n * Handle an execute_request message.\n *\n * @param msg The parent message.\n */\n async _execute(msg) {\n const executeMsg = msg;\n const content = executeMsg.content;\n if (content.store_history) {\n this._executionCount++;\n }\n // TODO: handle differently\n this._parentHeader = executeMsg.header;\n this._executeInput(executeMsg);\n if (content.store_history) {\n this._history.push([0, 0, content.code]);\n }\n const reply = await this.executeRequest(executeMsg.content);\n const message = KernelMessage.createMessage({\n msgType: 'execute_reply',\n channel: 'shell',\n parentHeader: executeMsg.header,\n session: msg.header.session,\n content: reply,\n });\n this._sendMessage(message);\n }\n /**\n * Handle an complete_request message\n *\n * @param msg The parent message.\n */\n async _complete(msg) {\n const completeMsg = msg;\n const content = await this.completeRequest(completeMsg.content);\n const message = KernelMessage.createMessage({\n msgType: 'complete_reply',\n parentHeader: completeMsg.header,\n channel: 'shell',\n session: msg.header.session,\n content,\n });\n this._sendMessage(message);\n }\n /**\n * Handle an inspect_request message\n *\n * @param msg The parent message.\n */\n async _inspect(msg) {\n const inspectMsg = msg;\n const content = await this.inspectRequest(inspectMsg.content);\n const message = KernelMessage.createMessage({\n msgType: 'inspect_reply',\n parentHeader: inspectMsg.header,\n channel: 'shell',\n session: msg.header.session,\n content,\n });\n this._sendMessage(message);\n }\n /**\n * Handle an is_complete_request message\n *\n * @param msg The parent message.\n */\n async _isCompleteRequest(msg) {\n const isCompleteMsg = msg;\n const content = await this.isCompleteRequest(isCompleteMsg.content);\n const message = KernelMessage.createMessage({\n msgType: 'is_complete_reply',\n parentHeader: isCompleteMsg.header,\n channel: 'shell',\n session: msg.header.session,\n content,\n });\n this._sendMessage(message);\n }\n}\n//# sourceMappingURL=kernel.js.map","/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nconst proxyMarker = Symbol(\"Comlink.proxy\");\nconst createEndpoint = Symbol(\"Comlink.endpoint\");\nconst releaseProxy = Symbol(\"Comlink.releaseProxy\");\nconst finalizer = Symbol(\"Comlink.finalizer\");\nconst throwMarker = Symbol(\"Comlink.thrown\");\nconst isObject = (val) => (typeof val === \"object\" && val !== null) || typeof val === \"function\";\n/**\n * Internal transfer handle to handle objects marked to proxy.\n */\nconst proxyTransferHandler = {\n canHandle: (val) => isObject(val) && val[proxyMarker],\n serialize(obj) {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port1);\n return [port2, [port2]];\n },\n deserialize(port) {\n port.start();\n return wrap(port);\n },\n};\n/**\n * Internal transfer handler to handle thrown exceptions.\n */\nconst throwTransferHandler = {\n canHandle: (value) => isObject(value) && throwMarker in value,\n serialize({ value }) {\n let serialized;\n if (value instanceof Error) {\n serialized = {\n isError: true,\n value: {\n message: value.message,\n name: value.name,\n stack: value.stack,\n },\n };\n }\n else {\n serialized = { isError: false, value };\n }\n return [serialized, []];\n },\n deserialize(serialized) {\n if (serialized.isError) {\n throw Object.assign(new Error(serialized.value.message), serialized.value);\n }\n throw serialized.value;\n },\n};\n/**\n * Allows customizing the serialization of certain values.\n */\nconst transferHandlers = new Map([\n [\"proxy\", proxyTransferHandler],\n [\"throw\", throwTransferHandler],\n]);\nfunction isAllowedOrigin(allowedOrigins, origin) {\n for (const allowedOrigin of allowedOrigins) {\n if (origin === allowedOrigin || allowedOrigin === \"*\") {\n return true;\n }\n if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) {\n return true;\n }\n }\n return false;\n}\nfunction expose(obj, ep = globalThis, allowedOrigins = [\"*\"]) {\n ep.addEventListener(\"message\", function callback(ev) {\n if (!ev || !ev.data) {\n return;\n }\n if (!isAllowedOrigin(allowedOrigins, ev.origin)) {\n console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);\n return;\n }\n const { id, type, path } = Object.assign({ path: [] }, ev.data);\n const argumentList = (ev.data.argumentList || []).map(fromWireValue);\n let returnValue;\n try {\n const parent = path.slice(0, -1).reduce((obj, prop) => obj[prop], obj);\n const rawValue = path.reduce((obj, prop) => obj[prop], obj);\n switch (type) {\n case \"GET\" /* MessageType.GET */:\n {\n returnValue = rawValue;\n }\n break;\n case \"SET\" /* MessageType.SET */:\n {\n parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);\n returnValue = true;\n }\n break;\n case \"APPLY\" /* MessageType.APPLY */:\n {\n returnValue = rawValue.apply(parent, argumentList);\n }\n break;\n case \"CONSTRUCT\" /* MessageType.CONSTRUCT */:\n {\n const value = new rawValue(...argumentList);\n returnValue = proxy(value);\n }\n break;\n case \"ENDPOINT\" /* MessageType.ENDPOINT */:\n {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port2);\n returnValue = transfer(port1, [port1]);\n }\n break;\n case \"RELEASE\" /* MessageType.RELEASE */:\n {\n returnValue = undefined;\n }\n break;\n default:\n return;\n }\n }\n catch (value) {\n returnValue = { value, [throwMarker]: 0 };\n }\n Promise.resolve(returnValue)\n .catch((value) => {\n return { value, [throwMarker]: 0 };\n })\n .then((returnValue) => {\n const [wireValue, transferables] = toWireValue(returnValue);\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n if (type === \"RELEASE\" /* MessageType.RELEASE */) {\n // detach and deactive after sending release response above.\n ep.removeEventListener(\"message\", callback);\n closeEndPoint(ep);\n if (finalizer in obj && typeof obj[finalizer] === \"function\") {\n obj[finalizer]();\n }\n }\n })\n .catch((error) => {\n // Send Serialization Error To Caller\n const [wireValue, transferables] = toWireValue({\n value: new TypeError(\"Unserializable return value\"),\n [throwMarker]: 0,\n });\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n });\n });\n if (ep.start) {\n ep.start();\n }\n}\nfunction isMessagePort(endpoint) {\n return endpoint.constructor.name === \"MessagePort\";\n}\nfunction closeEndPoint(endpoint) {\n if (isMessagePort(endpoint))\n endpoint.close();\n}\nfunction wrap(ep, target) {\n return createProxy(ep, [], target);\n}\nfunction throwIfProxyReleased(isReleased) {\n if (isReleased) {\n throw new Error(\"Proxy has been released and is not useable\");\n }\n}\nfunction releaseEndpoint(ep) {\n return requestResponseMessage(ep, {\n type: \"RELEASE\" /* MessageType.RELEASE */,\n }).then(() => {\n closeEndPoint(ep);\n });\n}\nconst proxyCounter = new WeakMap();\nconst proxyFinalizers = \"FinalizationRegistry\" in globalThis &&\n new FinalizationRegistry((ep) => {\n const newCount = (proxyCounter.get(ep) || 0) - 1;\n proxyCounter.set(ep, newCount);\n if (newCount === 0) {\n releaseEndpoint(ep);\n }\n });\nfunction registerProxy(proxy, ep) {\n const newCount = (proxyCounter.get(ep) || 0) + 1;\n proxyCounter.set(ep, newCount);\n if (proxyFinalizers) {\n proxyFinalizers.register(proxy, ep, proxy);\n }\n}\nfunction unregisterProxy(proxy) {\n if (proxyFinalizers) {\n proxyFinalizers.unregister(proxy);\n }\n}\nfunction createProxy(ep, path = [], target = function () { }) {\n let isProxyReleased = false;\n const proxy = new Proxy(target, {\n get(_target, prop) {\n throwIfProxyReleased(isProxyReleased);\n if (prop === releaseProxy) {\n return () => {\n unregisterProxy(proxy);\n releaseEndpoint(ep);\n isProxyReleased = true;\n };\n }\n if (prop === \"then\") {\n if (path.length === 0) {\n return { then: () => proxy };\n }\n const r = requestResponseMessage(ep, {\n type: \"GET\" /* MessageType.GET */,\n path: path.map((p) => p.toString()),\n }).then(fromWireValue);\n return r.then.bind(r);\n }\n return createProxy(ep, [...path, prop]);\n },\n set(_target, prop, rawValue) {\n throwIfProxyReleased(isProxyReleased);\n // FIXME: ES6 Proxy Handler `set` methods are supposed to return a\n // boolean. To show good will, we return true asynchronously ¯\\_(ツ)_/¯\n const [value, transferables] = toWireValue(rawValue);\n return requestResponseMessage(ep, {\n type: \"SET\" /* MessageType.SET */,\n path: [...path, prop].map((p) => p.toString()),\n value,\n }, transferables).then(fromWireValue);\n },\n apply(_target, _thisArg, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const last = path[path.length - 1];\n if (last === createEndpoint) {\n return requestResponseMessage(ep, {\n type: \"ENDPOINT\" /* MessageType.ENDPOINT */,\n }).then(fromWireValue);\n }\n // We just pretend that `bind()` didn’t happen.\n if (last === \"bind\") {\n return createProxy(ep, path.slice(0, -1));\n }\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, {\n type: \"APPLY\" /* MessageType.APPLY */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n construct(_target, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, {\n type: \"CONSTRUCT\" /* MessageType.CONSTRUCT */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n });\n registerProxy(proxy, ep);\n return proxy;\n}\nfunction myFlat(arr) {\n return Array.prototype.concat.apply([], arr);\n}\nfunction processArguments(argumentList) {\n const processed = argumentList.map(toWireValue);\n return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];\n}\nconst transferCache = new WeakMap();\nfunction transfer(obj, transfers) {\n transferCache.set(obj, transfers);\n return obj;\n}\nfunction proxy(obj) {\n return Object.assign(obj, { [proxyMarker]: true });\n}\nfunction windowEndpoint(w, context = globalThis, targetOrigin = \"*\") {\n return {\n postMessage: (msg, transferables) => w.postMessage(msg, targetOrigin, transferables),\n addEventListener: context.addEventListener.bind(context),\n removeEventListener: context.removeEventListener.bind(context),\n };\n}\nfunction toWireValue(value) {\n for (const [name, handler] of transferHandlers) {\n if (handler.canHandle(value)) {\n const [serializedValue, transferables] = handler.serialize(value);\n return [\n {\n type: \"HANDLER\" /* WireValueType.HANDLER */,\n name,\n value: serializedValue,\n },\n transferables,\n ];\n }\n }\n return [\n {\n type: \"RAW\" /* WireValueType.RAW */,\n value,\n },\n transferCache.get(value) || [],\n ];\n}\nfunction fromWireValue(value) {\n switch (value.type) {\n case \"HANDLER\" /* WireValueType.HANDLER */:\n return transferHandlers.get(value.name).deserialize(value.value);\n case \"RAW\" /* WireValueType.RAW */:\n return value.value;\n }\n}\nfunction requestResponseMessage(ep, msg, transfers) {\n return new Promise((resolve) => {\n const id = generateUUID();\n ep.addEventListener(\"message\", function l(ev) {\n if (!ev.data || !ev.data.id || ev.data.id !== id) {\n return;\n }\n ep.removeEventListener(\"message\", l);\n resolve(ev.data);\n });\n if (ep.start) {\n ep.start();\n }\n ep.postMessage(Object.assign({ id }, msg), transfers);\n });\n}\nfunction generateUUID() {\n return new Array(4)\n .fill(0)\n .map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16))\n .join(\"-\");\n}\n\nexport { createEndpoint, expose, finalizer, proxy, proxyMarker, releaseProxy, transfer, transferHandlers, windowEndpoint, wrap };\n//# sourceMappingURL=comlink.mjs.map\n","import { PromiseDelegate } from '@lumino/coreutils';\nimport { PageConfig } from '@jupyterlab/coreutils';\nimport { BaseKernel } from '@jupyterlite/kernel';\nimport { wrap } from 'comlink';\nimport { allJSONUrl, pipliteWheelUrl } from './_pypi';\n/**\n * A kernel that executes Python code with Pyodide.\n */\nexport class PyodideKernel extends BaseKernel {\n /**\n * Instantiate a new PyodideKernel\n *\n * @param options The instantiation options for a new PyodideKernel\n */\n constructor(options) {\n super(options);\n this._ready = new PromiseDelegate();\n this._worker = this.initWorker(options);\n this._worker.onmessage = (e) => this._processWorkerMessage(e.data);\n this._remoteKernel = wrap(this._worker);\n this.initRemote(options);\n }\n /**\n * Load the worker.\n *\n * ### Note\n *\n * Subclasses must implement this typographically almost _exactly_ for\n * webpack to find it.\n */\n initWorker(options) {\n return new Worker(new URL('./comlink.worker.js', import.meta.url), {\n type: 'module',\n });\n }\n async initRemote(options) {\n const remoteOptions = this.initRemoteOptions(options);\n await this._remoteKernel.initialize(remoteOptions);\n this._ready.resolve();\n }\n initRemoteOptions(options) {\n const { pyodideUrl } = options;\n const indexUrl = pyodideUrl.slice(0, pyodideUrl.lastIndexOf('/') + 1);\n const baseUrl = PageConfig.getBaseUrl();\n const pipliteUrls = [...(options.pipliteUrls || []), allJSONUrl.default];\n const disablePyPIFallback = !!options.disablePyPIFallback;\n return {\n baseUrl,\n pyodideUrl,\n indexUrl,\n pipliteWheelUrl: options.pipliteWheelUrl || pipliteWheelUrl.default,\n pipliteUrls,\n disablePyPIFallback,\n location: this.location,\n mountDrive: options.mountDrive,\n };\n }\n /**\n * Dispose the kernel.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._worker.terminate();\n this._worker = null;\n super.dispose();\n }\n /**\n * A promise that is fulfilled when the kernel is ready.\n */\n get ready() {\n return this._ready.promise;\n }\n /**\n * Process a message coming from the pyodide web worker.\n *\n * @param msg The worker message to process.\n */\n _processWorkerMessage(msg) {\n var _a, _b, _c, _d, _e, _f, _g;\n if (!msg.type) {\n return;\n }\n switch (msg.type) {\n case 'stream': {\n const bundle = (_a = msg.bundle) !== null && _a !== void 0 ? _a : { name: 'stdout', text: '' };\n this.stream(bundle, msg.parentHeader);\n break;\n }\n case 'input_request': {\n const bundle = (_b = msg.content) !== null && _b !== void 0 ? _b : { prompt: '', password: false };\n this.inputRequest(bundle, msg.parentHeader);\n break;\n }\n case 'display_data': {\n const bundle = (_c = msg.bundle) !== null && _c !== void 0 ? _c : { data: {}, metadata: {}, transient: {} };\n this.displayData(bundle, msg.parentHeader);\n break;\n }\n case 'update_display_data': {\n const bundle = (_d = msg.bundle) !== null && _d !== void 0 ? _d : { data: {}, metadata: {}, transient: {} };\n this.updateDisplayData(bundle, msg.parentHeader);\n break;\n }\n case 'clear_output': {\n const bundle = (_e = msg.bundle) !== null && _e !== void 0 ? _e : { wait: false };\n this.clearOutput(bundle, msg.parentHeader);\n break;\n }\n case 'execute_result': {\n const bundle = (_f = msg.bundle) !== null && _f !== void 0 ? _f : {\n execution_count: 0,\n data: {},\n metadata: {},\n };\n this.publishExecuteResult(bundle, msg.parentHeader);\n break;\n }\n case 'execute_error': {\n const bundle = (_g = msg.bundle) !== null && _g !== void 0 ? _g : { ename: '', evalue: '', traceback: [] };\n this.publishExecuteError(bundle, msg.parentHeader);\n break;\n }\n case 'comm_msg':\n case 'comm_open':\n case 'comm_close': {\n this.handleComm(msg.type, msg.content, msg.metadata, msg.buffers, msg.parentHeader);\n break;\n }\n }\n }\n /**\n * Handle a kernel_info_request message\n */\n async kernelInfoRequest() {\n const content = {\n implementation: 'pyodide',\n implementation_version: '0.1.0',\n language_info: {\n codemirror_mode: {\n name: 'python',\n version: 3,\n },\n file_extension: '.py',\n mimetype: 'text/x-python',\n name: 'python',\n nbconvert_exporter: 'python',\n pygments_lexer: 'ipython3',\n version: '3.8',\n },\n protocol_version: '5.3',\n status: 'ok',\n banner: 'A WebAssembly-powered Python kernel backed by Pyodide',\n help_links: [\n {\n text: 'Python (WASM) Kernel',\n url: 'https://pyodide.org',\n },\n ],\n };\n return content;\n }\n /**\n * Handle an `execute_request` message\n *\n * @param msg The parent message.\n */\n async executeRequest(content) {\n await this.ready;\n const result = await this._remoteKernel.execute(content, this.parent);\n result.execution_count = this.executionCount;\n return result;\n }\n /**\n * Handle an complete_request message\n *\n * @param msg The parent message.\n */\n async completeRequest(content) {\n return await this._remoteKernel.complete(content, this.parent);\n }\n /**\n * Handle an `inspect_request` message.\n *\n * @param content - The content of the request.\n *\n * @returns A promise that resolves with the response message.\n */\n async inspectRequest(content) {\n return await this._remoteKernel.inspect(content, this.parent);\n }\n /**\n * Handle an `is_complete_request` message.\n *\n * @param content - The content of the request.\n *\n * @returns A promise that resolves with the response message.\n */\n async isCompleteRequest(content) {\n return await this._remoteKernel.isComplete(content, this.parent);\n }\n /**\n * Handle a `comm_info_request` message.\n *\n * @param content - The content of the request.\n *\n * @returns A promise that resolves with the response message.\n */\n async commInfoRequest(content) {\n return await this._remoteKernel.commInfo(content, this.parent);\n }\n /**\n * Send an `comm_open` message.\n *\n * @param msg - The comm_open message.\n */\n async commOpen(msg) {\n return await this._remoteKernel.commOpen(msg, this.parent);\n }\n /**\n * Send an `comm_msg` message.\n *\n * @param msg - The comm_msg message.\n */\n async commMsg(msg) {\n return await this._remoteKernel.commMsg(msg, this.parent);\n }\n /**\n * Send an `comm_close` message.\n *\n * @param close - The comm_close message.\n */\n async commClose(msg) {\n return await this._remoteKernel.commClose(msg, this.parent);\n }\n /**\n * Send an `input_reply` message.\n *\n * @param content - The content of the reply.\n */\n async inputReply(content) {\n return await this._remoteKernel.inputReply(content, this.parent);\n }\n}\n","function webpackEmptyAsyncContext(req) {\n\t// Here Promise.resolve().then() is used instead of new Promise() to prevent\n\t// uncaught exception popping up in devtools\n\treturn Promise.resolve().then(() => {\n\t\tvar e = new Error(\"Cannot find module '\" + req + \"'\");\n\t\te.code = 'MODULE_NOT_FOUND';\n\t\tthrow e;\n\t});\n}\nwebpackEmptyAsyncContext.keys = () => ([]);\nwebpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext;\nwebpackEmptyAsyncContext.id = 265;\nmodule.exports = webpackEmptyAsyncContext;"],"names":["BaseKernel","constructor","options","this","_history","_executionCount","_isDisposed","_disposed","Signal","_parentHeader","undefined","_parent","id","name","location","sendMessage","_id","_name","_location","_sendMessage","ready","Promise","resolve","isDisposed","disposed","executionCount","parentHeader","parent","dispose","emit","async","msg","_busy","header","msg_type","_kernelInfo","_execute","inputReply","content","_inspect","_isCompleteRequest","_complete","_historyRequest","commOpen","commMsg","commClose","_idle","stream","_a","parentHeaderValue","message","KernelMessage","channel","msgType","session","displayData","_b","metadata","inputRequest","publishExecuteResult","publishExecuteError","updateDisplayData","clearOutput","handleComm","type","buffers","execution_state","kernelInfoRequest","historyMsg","status","history","_executeInput","code","execution_count","executeMsg","store_history","push","reply","executeRequest","completeMsg","completeRequest","inspectMsg","inspectRequest","isCompleteMsg","isCompleteRequest","proxyMarker","Symbol","createEndpoint","releaseProxy","finalizer","throwMarker","isObject","val","transferHandlers","Map","canHandle","serialize","obj","port1","port2","MessageChannel","expose","deserialize","port","start","wrap","value","serialized","Error","isError","stack","Object","assign","ep","globalThis","allowedOrigins","addEventListener","callback","ev","data","origin","allowedOrigin","RegExp","test","isAllowedOrigin","console","warn","path","argumentList","map","fromWireValue","returnValue","slice","reduce","prop","rawValue","apply","proxy","transfers","transferCache","set","transfer","catch","then","wireValue","transferables","toWireValue","postMessage","removeEventListener","closeEndPoint","error","TypeError","endpoint","isMessagePort","close","target","createProxy","throwIfProxyReleased","isReleased","releaseEndpoint","requestResponseMessage","proxyCounter","WeakMap","proxyFinalizers","FinalizationRegistry","newCount","get","isProxyReleased","Proxy","_target","unregister","unregisterProxy","length","r","p","toString","bind","_thisArg","rawArgumentList","last","processArguments","construct","register","registerProxy","processed","v","arr","Array","prototype","concat","handler","serializedValue","fill","Math","floor","random","Number","MAX_SAFE_INTEGER","join","l","PyodideKernel","super","_ready","PromiseDelegate","_worker","initWorker","onmessage","e","_processWorkerMessage","_remoteKernel","initRemote","Worker","URL","remoteOptions","initRemoteOptions","initialize","pyodideUrl","indexUrl","lastIndexOf","baseUrl","PageConfig","pipliteUrls","disablePyPIFallback","pipliteWheelUrl","mountDrive","terminate","promise","_c","_d","_e","_f","_g","bundle","text","prompt","password","transient","wait","ename","evalue","traceback","implementation","implementation_version","language_info","codemirror_mode","version","file_extension","mimetype","nbconvert_exporter","pygments_lexer","protocol_version","banner","help_links","url","result","execute","complete","inspect","isComplete","commInfo","webpackEmptyAsyncContext","req","keys","module","exports"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/5144.index.js b/book/_build/html/_static/5144.index.js new file mode 100644 index 0000000..67babe6 --- /dev/null +++ b/book/_build/html/_static/5144.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[5144],{15144:(e,i,$)=>{function r(e){for(var i={},$=e.split(" "),r=0;r<$.length;++r)i[$[r]]=!0;return i}$.r(i),$.d(i,{mirc:()=>m});var t=r("$! $$ $& $? $+ $abook $abs $active $activecid $activewid $address $addtok $agent $agentname $agentstat $agentver $alias $and $anick $ansi2mirc $aop $appactive $appstate $asc $asctime $asin $atan $avoice $away $awaymsg $awaytime $banmask $base $bfind $binoff $biton $bnick $bvar $bytes $calc $cb $cd $ceil $chan $chanmodes $chantypes $chat $chr $cid $clevel $click $cmdbox $cmdline $cnick $color $com $comcall $comchan $comerr $compact $compress $comval $cos $count $cr $crc $creq $crlf $ctime $ctimer $ctrlenter $date $day $daylight $dbuh $dbuw $dccignore $dccport $dde $ddename $debug $decode $decompress $deltok $devent $dialog $did $didreg $didtok $didwm $disk $dlevel $dll $dllcall $dname $dns $duration $ebeeps $editbox $emailaddr $encode $error $eval $event $exist $feof $ferr $fgetc $file $filename $filtered $finddir $finddirn $findfile $findfilen $findtok $fline $floor $fopen $fread $fserve $fulladdress $fulldate $fullname $fullscreen $get $getdir $getdot $gettok $gmt $group $halted $hash $height $hfind $hget $highlight $hnick $hotline $hotlinepos $ial $ialchan $ibl $idle $iel $ifmatch $ignore $iif $iil $inelipse $ini $inmidi $inpaste $inpoly $input $inrect $inroundrect $insong $instok $int $inwave $ip $isalias $isbit $isdde $isdir $isfile $isid $islower $istok $isupper $keychar $keyrpt $keyval $knick $lactive $lactivecid $lactivewid $left $len $level $lf $line $lines $link $lock $lock $locked $log $logstamp $logstampfmt $longfn $longip $lower $ltimer $maddress $mask $matchkey $matchtok $md5 $me $menu $menubar $menucontext $menutype $mid $middir $mircdir $mircexe $mircini $mklogfn $mnick $mode $modefirst $modelast $modespl $mouse $msfile $network $newnick $nick $nofile $nopath $noqt $not $notags $notify $null $numeric $numok $oline $onpoly $opnick $or $ord $os $passivedcc $pic $play $pnick $port $portable $portfree $pos $prefix $prop $protect $puttok $qt $query $rand $r $rawmsg $read $readomo $readn $regex $regml $regsub $regsubex $remove $remtok $replace $replacex $reptok $result $rgb $right $round $scid $scon $script $scriptdir $scriptline $sdir $send $server $serverip $sfile $sha1 $shortfn $show $signal $sin $site $sline $snick $snicks $snotify $sock $sockbr $sockerr $sockname $sorttok $sound $sqrt $ssl $sreq $sslready $status $strip $str $stripped $syle $submenu $switchbar $tan $target $ticks $time $timer $timestamp $timestampfmt $timezone $tip $titlebar $toolbar $treebar $trust $ulevel $ulist $upper $uptime $url $usermode $v1 $v2 $var $vcmd $vcmdstat $vcmdver $version $vnick $vol $wid $width $wildsite $wildtok $window $wrap $xor"),a=r("abook ajinvite alias aline ame amsg anick aop auser autojoin avoice away background ban bcopy beep bread break breplace bset btrunc bunset bwrite channel clear clearall cline clipboard close cnick color comclose comopen comreg continue copy creq ctcpreply ctcps dcc dccserver dde ddeserver debug dec describe dialog did didtok disable disconnect dlevel dline dll dns dqwindow drawcopy drawdot drawfill drawline drawpic drawrect drawreplace drawrot drawsave drawscroll drawtext ebeeps echo editbox emailaddr enable events exit fclose filter findtext finger firewall flash flist flood flush flushini font fopen fseek fsend fserve fullname fwrite ghide gload gmove gopts goto gplay gpoint gqreq groups gshow gsize gstop gtalk gunload hadd halt haltdef hdec hdel help hfree hinc hload hmake hop hsave ial ialclear ialmark identd if ignore iline inc invite iuser join kick linesep links list load loadbuf localinfo log mdi me menubar mkdir mnick mode msg nick noop notice notify omsg onotice part partall pdcc perform play playctrl pop protect pvoice qme qmsg query queryn quit raw reload remini remote remove rename renwin reseterror resetidle return rlevel rline rmdir run ruser save savebuf saveini say scid scon server set showmirc signam sline sockaccept sockclose socklist socklisten sockmark sockopen sockpause sockread sockrename sockudp sockwrite sound speak splay sreq strip switchbar timer timestamp titlebar tnick tokenize toolbar topic tray treebar ulist unload unset unsetall updatenl url uwho var vcadd vcmd vcrem vol while whois window winhelp write writeint if isalnum isalpha isaop isavoice isban ischan ishop isignore isin isincs isletter islower isnotify isnum ison isop isprotect isreg isupper isvoice iswm iswmcs elseif else goto menu nicklist status title icon size option text edit button check radio box scroll list combo link tab item"),n=r("if elseif else and not or eq ne in ni for foreach while switch"),o=/[+\-*&%=<>!?^\/\|]/;function s(e,i,$){return i.tokenize=$,$(e,i)}function l(e,i){var $=i.beforeParams;i.beforeParams=!1;var r=e.next();if(/[\[\]{}\(\),\.]/.test(r))return"("==r&&$?i.inParams=!0:")"==r&&(i.inParams=!1),null;if(/\d/.test(r))return e.eatWhile(/[\w\.]/),"number";if("\\"==r)return e.eat("\\"),e.eat(/./),"number";if("/"==r&&e.eat("*"))return s(e,i,c);if(";"==r&&e.match(/ *\( *\(/))return s(e,i,d);if(";"!=r||i.inParams){if('"'==r)return e.eat(/"/),"keyword";if("$"==r)return e.eatWhile(/[$_a-z0-9A-Z\.:]/),t&&t.propertyIsEnumerable(e.current().toLowerCase())?"keyword":(i.beforeParams=!0,"builtin");if("%"==r)return e.eatWhile(/[^,\s()]/),i.beforeParams=!0,"string";if(o.test(r))return e.eatWhile(o),"operator";e.eatWhile(/[\w\$_{}]/);var l=e.current().toLowerCase();return a&&a.propertyIsEnumerable(l)?"keyword":n&&n.propertyIsEnumerable(l)?(i.beforeParams=!0,"keyword"):null}return e.skipToEnd(),"comment"}function c(e,i){for(var $,r=!1;$=e.next();){if("/"==$&&r){i.tokenize=l;break}r="*"==$}return"comment"}function d(e,i){for(var $,r=0;$=e.next();){if(";"==$&&2==r){i.tokenize=l;break}")"==$?r++:" "!=$&&(r=0)}return"meta"}const m={name:"mirc",startState:function(){return{tokenize:l,beforeParams:!1,inParams:!1}},token:function(e,i){return e.eatSpace()?null:i.tokenize(e,i)}}}}]); +//# sourceMappingURL=5144.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/5144.index.js.map b/book/_build/html/_static/5144.index.js.map new file mode 100644 index 0000000..0a69a3a --- /dev/null +++ b/book/_build/html/_static/5144.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"5144.index.js","mappings":"+FAAA,SAASA,EAAWC,GAElB,IADA,IAAIC,EAAM,CAAC,EAAGC,EAAQF,EAAIG,MAAM,KACvBC,EAAI,EAAGA,EAAIF,EAAMG,SAAUD,EAAGH,EAAIC,EAAME,KAAM,EACvD,OAAOH,CACT,C,2BACA,IAAIK,EAAWP,EAAW,ohFAoCtBQ,EAAWR,EAAW,m0DAyBtBS,EAAYT,EAAW,kEACvBU,EAAiB,qBACrB,SAASC,EAAMC,EAAQC,EAAOC,GAE5B,OADAD,EAAME,SAAWD,EACVA,EAAEF,EAAQC,EACnB,CACA,SAASG,EAAUJ,EAAQC,GACzB,IAAII,EAAeJ,EAAMI,aACzBJ,EAAMI,cAAe,EACrB,IAAIC,EAAKN,EAAOO,OAChB,GAAI,kBAAkBC,KAAKF,GAGzB,MAFU,KAANA,GAAaD,EAAcJ,EAAMQ,UAAW,EACjC,KAANH,IAAWL,EAAMQ,UAAW,GAC9B,KAEJ,GAAI,KAAKD,KAAKF,GAEjB,OADAN,EAAOU,SAAS,UACT,SAEJ,GAAU,MAANJ,EAGP,OAFAN,EAAOW,IAAI,MACXX,EAAOW,IAAI,KACJ,SAEJ,GAAU,KAANL,GAAaN,EAAOW,IAAI,KAC/B,OAAOZ,EAAMC,EAAQC,EAAOW,GAEzB,GAAU,KAANN,GAAaN,EAAOa,MAAM,YACjC,OAAOd,EAAMC,EAAQC,EAAOa,GAEzB,GAAU,KAANR,GAAcL,EAAMQ,SAIxB,IAAU,KAANH,EAEP,OADAN,EAAOW,IAAI,KACJ,UAEJ,GAAU,KAANL,EAEP,OADAN,EAAOU,SAAS,oBACZf,GAAYA,EAASoB,qBAAqBf,EAAOgB,UAAUC,eACtD,WAGPhB,EAAMI,cAAe,EACd,WAGN,GAAU,KAANC,EAGP,OAFAN,EAAOU,SAAS,YAChBT,EAAMI,cAAe,EACd,SAEJ,GAAIP,EAAeU,KAAKF,GAE3B,OADAN,EAAOU,SAASZ,GACT,WAGPE,EAAOU,SAAS,aAChB,IAAIQ,EAAOlB,EAAOgB,UAAUC,cAC5B,OAAIrB,GAAYA,EAASmB,qBAAqBG,GACrC,UACLrB,GAAaA,EAAUkB,qBAAqBG,IAC9CjB,EAAMI,cAAe,EACd,WAEF,IACT,CAnCE,OADAL,EAAOmB,YACA,SAoCX,CACA,SAASP,EAAaZ,EAAQC,GAE5B,IADA,IAAsBK,EAAlBc,GAAW,EACRd,EAAKN,EAAOO,QAAQ,CACzB,GAAU,KAAND,GAAac,EAAU,CACzBnB,EAAME,SAAWC,EACjB,KACF,CACAgB,EAAkB,KAANd,CACd,CACA,MAAO,SACT,CACA,SAASQ,EAAcd,EAAQC,GAE7B,IADA,IAAkBK,EAAdc,EAAW,EACRd,EAAKN,EAAOO,QAAQ,CACzB,GAAU,KAAND,GAAyB,GAAZc,EAAe,CAC9BnB,EAAME,SAAWC,EACjB,KACF,CACU,KAANE,EACFc,IACa,KAANd,IACPc,EAAW,EACf,CACA,MAAO,MACT,CACO,MAAMC,EAAO,CAClBC,KAAM,OACNC,WAAY,WACV,MAAO,CACLpB,SAAUC,EACVC,cAAc,EACdI,UAAU,EAEd,EACAe,MAAO,SAASxB,EAAQC,GACtB,OAAID,EAAOyB,WAAmB,KACvBxB,EAAME,SAASH,EAAQC,EAChC,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/mirc.js"],"sourcesContent":["function parseWords(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n}\nvar specials = parseWords(\"$! $$ $& $? $+ $abook $abs $active $activecid \" +\n \"$activewid $address $addtok $agent $agentname $agentstat $agentver \" +\n \"$alias $and $anick $ansi2mirc $aop $appactive $appstate $asc $asctime \" +\n \"$asin $atan $avoice $away $awaymsg $awaytime $banmask $base $bfind \" +\n \"$binoff $biton $bnick $bvar $bytes $calc $cb $cd $ceil $chan $chanmodes \" +\n \"$chantypes $chat $chr $cid $clevel $click $cmdbox $cmdline $cnick $color \" +\n \"$com $comcall $comchan $comerr $compact $compress $comval $cos $count \" +\n \"$cr $crc $creq $crlf $ctime $ctimer $ctrlenter $date $day $daylight \" +\n \"$dbuh $dbuw $dccignore $dccport $dde $ddename $debug $decode $decompress \" +\n \"$deltok $devent $dialog $did $didreg $didtok $didwm $disk $dlevel $dll \" +\n \"$dllcall $dname $dns $duration $ebeeps $editbox $emailaddr $encode $error \" +\n \"$eval $event $exist $feof $ferr $fgetc $file $filename $filtered $finddir \" +\n \"$finddirn $findfile $findfilen $findtok $fline $floor $fopen $fread $fserve \" +\n \"$fulladdress $fulldate $fullname $fullscreen $get $getdir $getdot $gettok $gmt \" +\n \"$group $halted $hash $height $hfind $hget $highlight $hnick $hotline \" +\n \"$hotlinepos $ial $ialchan $ibl $idle $iel $ifmatch $ignore $iif $iil \" +\n \"$inelipse $ini $inmidi $inpaste $inpoly $input $inrect $inroundrect \" +\n \"$insong $instok $int $inwave $ip $isalias $isbit $isdde $isdir $isfile \" +\n \"$isid $islower $istok $isupper $keychar $keyrpt $keyval $knick $lactive \" +\n \"$lactivecid $lactivewid $left $len $level $lf $line $lines $link $lock \" +\n \"$lock $locked $log $logstamp $logstampfmt $longfn $longip $lower $ltimer \" +\n \"$maddress $mask $matchkey $matchtok $md5 $me $menu $menubar $menucontext \" +\n \"$menutype $mid $middir $mircdir $mircexe $mircini $mklogfn $mnick $mode \" +\n \"$modefirst $modelast $modespl $mouse $msfile $network $newnick $nick $nofile \" +\n \"$nopath $noqt $not $notags $notify $null $numeric $numok $oline $onpoly \" +\n \"$opnick $or $ord $os $passivedcc $pic $play $pnick $port $portable $portfree \" +\n \"$pos $prefix $prop $protect $puttok $qt $query $rand $r $rawmsg $read $readomo \" +\n \"$readn $regex $regml $regsub $regsubex $remove $remtok $replace $replacex \" +\n \"$reptok $result $rgb $right $round $scid $scon $script $scriptdir $scriptline \" +\n \"$sdir $send $server $serverip $sfile $sha1 $shortfn $show $signal $sin \" +\n \"$site $sline $snick $snicks $snotify $sock $sockbr $sockerr $sockname \" +\n \"$sorttok $sound $sqrt $ssl $sreq $sslready $status $strip $str $stripped \" +\n \"$syle $submenu $switchbar $tan $target $ticks $time $timer $timestamp \" +\n \"$timestampfmt $timezone $tip $titlebar $toolbar $treebar $trust $ulevel \" +\n \"$ulist $upper $uptime $url $usermode $v1 $v2 $var $vcmd $vcmdstat $vcmdver \" +\n \"$version $vnick $vol $wid $width $wildsite $wildtok $window $wrap $xor\");\nvar keywords = parseWords(\"abook ajinvite alias aline ame amsg anick aop auser autojoin avoice \" +\n \"away background ban bcopy beep bread break breplace bset btrunc bunset bwrite \" +\n \"channel clear clearall cline clipboard close cnick color comclose comopen \" +\n \"comreg continue copy creq ctcpreply ctcps dcc dccserver dde ddeserver \" +\n \"debug dec describe dialog did didtok disable disconnect dlevel dline dll \" +\n \"dns dqwindow drawcopy drawdot drawfill drawline drawpic drawrect drawreplace \" +\n \"drawrot drawsave drawscroll drawtext ebeeps echo editbox emailaddr enable \" +\n \"events exit fclose filter findtext finger firewall flash flist flood flush \" +\n \"flushini font fopen fseek fsend fserve fullname fwrite ghide gload gmove \" +\n \"gopts goto gplay gpoint gqreq groups gshow gsize gstop gtalk gunload hadd \" +\n \"halt haltdef hdec hdel help hfree hinc hload hmake hop hsave ial ialclear \" +\n \"ialmark identd if ignore iline inc invite iuser join kick linesep links list \" +\n \"load loadbuf localinfo log mdi me menubar mkdir mnick mode msg nick noop notice \" +\n \"notify omsg onotice part partall pdcc perform play playctrl pop protect pvoice \" +\n \"qme qmsg query queryn quit raw reload remini remote remove rename renwin \" +\n \"reseterror resetidle return rlevel rline rmdir run ruser save savebuf saveini \" +\n \"say scid scon server set showmirc signam sline sockaccept sockclose socklist \" +\n \"socklisten sockmark sockopen sockpause sockread sockrename sockudp sockwrite \" +\n \"sound speak splay sreq strip switchbar timer timestamp titlebar tnick tokenize \" +\n \"toolbar topic tray treebar ulist unload unset unsetall updatenl url uwho \" +\n \"var vcadd vcmd vcrem vol while whois window winhelp write writeint if isalnum \" +\n \"isalpha isaop isavoice isban ischan ishop isignore isin isincs isletter islower \" +\n \"isnotify isnum ison isop isprotect isreg isupper isvoice iswm iswmcs \" +\n \"elseif else goto menu nicklist status title icon size option text edit \" +\n \"button check radio box scroll list combo link tab item\");\nvar functions = parseWords(\"if elseif else and not or eq ne in ni for foreach while switch\");\nvar isOperatorChar = /[+\\-*&%=<>!?^\\/\\|]/;\nfunction chain(stream, state, f) {\n state.tokenize = f;\n return f(stream, state);\n}\nfunction tokenBase(stream, state) {\n var beforeParams = state.beforeParams;\n state.beforeParams = false;\n var ch = stream.next();\n if (/[\\[\\]{}\\(\\),\\.]/.test(ch)) {\n if (ch == \"(\" && beforeParams) state.inParams = true;\n else if (ch == \")\") state.inParams = false;\n return null;\n }\n else if (/\\d/.test(ch)) {\n stream.eatWhile(/[\\w\\.]/);\n return \"number\";\n }\n else if (ch == \"\\\\\") {\n stream.eat(\"\\\\\");\n stream.eat(/./);\n return \"number\";\n }\n else if (ch == \"/\" && stream.eat(\"*\")) {\n return chain(stream, state, tokenComment);\n }\n else if (ch == \";\" && stream.match(/ *\\( *\\(/)) {\n return chain(stream, state, tokenUnparsed);\n }\n else if (ch == \";\" && !state.inParams) {\n stream.skipToEnd();\n return \"comment\";\n }\n else if (ch == '\"') {\n stream.eat(/\"/);\n return \"keyword\";\n }\n else if (ch == \"$\") {\n stream.eatWhile(/[$_a-z0-9A-Z\\.:]/);\n if (specials && specials.propertyIsEnumerable(stream.current().toLowerCase())) {\n return \"keyword\";\n }\n else {\n state.beforeParams = true;\n return \"builtin\";\n }\n }\n else if (ch == \"%\") {\n stream.eatWhile(/[^,\\s()]/);\n state.beforeParams = true;\n return \"string\";\n }\n else if (isOperatorChar.test(ch)) {\n stream.eatWhile(isOperatorChar);\n return \"operator\";\n }\n else {\n stream.eatWhile(/[\\w\\$_{}]/);\n var word = stream.current().toLowerCase();\n if (keywords && keywords.propertyIsEnumerable(word))\n return \"keyword\";\n if (functions && functions.propertyIsEnumerable(word)) {\n state.beforeParams = true;\n return \"keyword\";\n }\n return null;\n }\n}\nfunction tokenComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if (ch == \"/\" && maybeEnd) {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return \"comment\";\n}\nfunction tokenUnparsed(stream, state) {\n var maybeEnd = 0, ch;\n while (ch = stream.next()) {\n if (ch == \";\" && maybeEnd == 2) {\n state.tokenize = tokenBase;\n break;\n }\n if (ch == \")\")\n maybeEnd++;\n else if (ch != \" \")\n maybeEnd = 0;\n }\n return \"meta\";\n}\nexport const mirc = {\n name: \"mirc\",\n startState: function() {\n return {\n tokenize: tokenBase,\n beforeParams: false,\n inParams: false\n };\n },\n token: function(stream, state) {\n if (stream.eatSpace()) return null;\n return state.tokenize(stream, state);\n }\n};\n"],"names":["parseWords","str","obj","words","split","i","length","specials","keywords","functions","isOperatorChar","chain","stream","state","f","tokenize","tokenBase","beforeParams","ch","next","test","inParams","eatWhile","eat","tokenComment","match","tokenUnparsed","propertyIsEnumerable","current","toLowerCase","word","skipToEnd","maybeEnd","mirc","name","startState","token","eatSpace"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/5199.index.js b/book/_build/html/_static/5199.index.js new file mode 100644 index 0000000..323f06d --- /dev/null +++ b/book/_build/html/_static/5199.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[5199],{85199:(e,t,r)=>{function n(e){for(var t={},r=0,n=e.length;rs});var a=n(["note","across","when","variant","until","unique","undefine","then","strip","select","retry","rescue","require","rename","reference","redefine","prefix","once","old","obsolete","loop","local","like","is","inspect","infix","include","if","frozen","from","external","export","ensure","end","elseif","else","do","creation","create","check","alias","agent","separate","invariant","inherit","indexing","feature","expanded","deferred","class","Void","True","Result","Precursor","False","Current","create","attached","detachable","as","and","implies","not","or"]),i=n([":=","and then","and","or","<<",">>"]);function o(e,t){if(e.eatSpace())return null;var r,n=e.next();return'"'==n||"'"==n?function(e,t,r){return r.tokenize.push(e),e(t,r)}((r=n,"string",function(e,t){for(var n,a=!1;null!=(n=e.next());){if(n==r&&!a){t.tokenize.pop();break}a=!a&&"%"==n}return"string"}),e,t):"-"==n&&e.eat("-")?(e.skipToEnd(),"comment"):":"==n&&e.eat("=")?"operator":/[0-9]/.test(n)?(e.eatWhile(/[xXbBCc0-9\.]/),e.eat(/[\?\!]/),"variable"):/[a-zA-Z_0-9]/.test(n)?(e.eatWhile(/[a-zA-Z_0-9]/),e.eat(/[\?\!]/),"variable"):/[=+\-\/*^%<>~]/.test(n)?(e.eatWhile(/[=+\-\/*^%<>~]/),"operator"):null}const s={name:"eiffel",startState:function(){return{tokenize:[o]}},token:function(e,t){var r=t.tokenize[t.tokenize.length-1](e,t);if("variable"==r){var n=e.current();r=a.propertyIsEnumerable(e.current())?"keyword":i.propertyIsEnumerable(e.current())?"operator":/^[A-Z][A-Z_0-9]*$/g.test(n)?"tag":/^0[bB][0-1]+$/g.test(n)||/^0[cC][0-7]+$/g.test(n)||/^0[xX][a-fA-F0-9]+$/g.test(n)||/^([0-9]+\.[0-9]*)|([0-9]*\.[0-9]+)$/g.test(n)||/^[0-9]+$/g.test(n)?"number":"variable"}return r},languageData:{commentTokens:{line:"--"}}}}}]); +//# sourceMappingURL=5199.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/5199.index.js.map b/book/_build/html/_static/5199.index.js.map new file mode 100644 index 0000000..8647b74 --- /dev/null +++ b/book/_build/html/_static/5199.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"5199.index.js","mappings":"+FAAA,SAASA,EAAQC,GAEf,IADA,IAAIC,EAAI,CAAC,EACAC,EAAI,EAAGC,EAAIH,EAAMI,OAAQF,EAAIC,IAAKD,EAAGD,EAAED,EAAME,KAAM,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,WAAY,WACV,MAAO,CAACX,SAAU,CAACR,GACrB,EAEAoB,MAAO,SAASnB,EAAQC,GACtB,IAAImB,EAAQnB,EAAMM,SAASN,EAAMM,SAASX,OAAO,GAAGI,EAAQC,GAC5D,GAAa,YAATmB,EAAqB,CACvB,IAAIC,EAAOrB,EAAOsB,UAClBF,EAAQvB,EAAS0B,qBAAqBvB,EAAOsB,WAAa,UACtDxB,EAAUyB,qBAAqBvB,EAAOsB,WAAa,WACnD,qBAAqBR,KAAKO,GAAQ,MAClC,iBAAiBP,KAAKO,IACtB,iBAAiBP,KAAKO,IACtB,uBAAuBP,KAAKO,IAC5B,uCAAuCP,KAAKO,IAC5C,YAAYP,KAAKO,GAJa,SAK9B,UACN,CACA,OAAOD,CACT,EACAI,aAAc,CACZC,cAAe,CAACC,KAAM,O","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/eiffel.js"],"sourcesContent":["function wordObj(words) {\n var o = {};\n for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true;\n return o;\n}\nvar keywords = wordObj([\n 'note',\n 'across',\n 'when',\n 'variant',\n 'until',\n 'unique',\n 'undefine',\n 'then',\n 'strip',\n 'select',\n 'retry',\n 'rescue',\n 'require',\n 'rename',\n 'reference',\n 'redefine',\n 'prefix',\n 'once',\n 'old',\n 'obsolete',\n 'loop',\n 'local',\n 'like',\n 'is',\n 'inspect',\n 'infix',\n 'include',\n 'if',\n 'frozen',\n 'from',\n 'external',\n 'export',\n 'ensure',\n 'end',\n 'elseif',\n 'else',\n 'do',\n 'creation',\n 'create',\n 'check',\n 'alias',\n 'agent',\n 'separate',\n 'invariant',\n 'inherit',\n 'indexing',\n 'feature',\n 'expanded',\n 'deferred',\n 'class',\n 'Void',\n 'True',\n 'Result',\n 'Precursor',\n 'False',\n 'Current',\n 'create',\n 'attached',\n 'detachable',\n 'as',\n 'and',\n 'implies',\n 'not',\n 'or'\n]);\nvar operators = wordObj([\":=\", \"and then\",\"and\", \"or\",\"<<\",\">>\"]);\n\nfunction chain(newtok, stream, state) {\n state.tokenize.push(newtok);\n return newtok(stream, state);\n}\n\nfunction tokenBase(stream, state) {\n if (stream.eatSpace()) return null;\n var ch = stream.next();\n if (ch == '\"'||ch == \"'\") {\n return chain(readQuoted(ch, \"string\"), stream, state);\n } else if (ch == \"-\"&&stream.eat(\"-\")) {\n stream.skipToEnd();\n return \"comment\";\n } else if (ch == \":\"&&stream.eat(\"=\")) {\n return \"operator\";\n } else if (/[0-9]/.test(ch)) {\n stream.eatWhile(/[xXbBCc0-9\\.]/);\n stream.eat(/[\\?\\!]/);\n return \"variable\";\n } else if (/[a-zA-Z_0-9]/.test(ch)) {\n stream.eatWhile(/[a-zA-Z_0-9]/);\n stream.eat(/[\\?\\!]/);\n return \"variable\";\n } else if (/[=+\\-\\/*^%<>~]/.test(ch)) {\n stream.eatWhile(/[=+\\-\\/*^%<>~]/);\n return \"operator\";\n } else {\n return null;\n }\n}\n\nfunction readQuoted(quote, style, unescaped) {\n return function(stream, state) {\n var escaped = false, ch;\n while ((ch = stream.next()) != null) {\n if (ch == quote && (unescaped || !escaped)) {\n state.tokenize.pop();\n break;\n }\n escaped = !escaped && ch == \"%\";\n }\n return style;\n };\n}\n\nexport const eiffel = {\n name: \"eiffel\",\n startState: function() {\n return {tokenize: [tokenBase]};\n },\n\n token: function(stream, state) {\n var style = state.tokenize[state.tokenize.length-1](stream, state);\n if (style == \"variable\") {\n var word = stream.current();\n style = keywords.propertyIsEnumerable(stream.current()) ? \"keyword\"\n : operators.propertyIsEnumerable(stream.current()) ? \"operator\"\n : /^[A-Z][A-Z_0-9]*$/g.test(word) ? \"tag\"\n : /^0[bB][0-1]+$/g.test(word) ? \"number\"\n : /^0[cC][0-7]+$/g.test(word) ? \"number\"\n : /^0[xX][a-fA-F0-9]+$/g.test(word) ? \"number\"\n : /^([0-9]+\\.[0-9]*)|([0-9]*\\.[0-9]+)$/g.test(word) ? \"number\"\n : /^[0-9]+$/g.test(word) ? \"number\"\n : \"variable\";\n }\n return style;\n },\n languageData: {\n commentTokens: {line: \"--\"}\n }\n};\n\n"],"names":["wordObj","words","o","i","e","length","keywords","operators","tokenBase","stream","state","eatSpace","quote","ch","next","newtok","tokenize","push","chain","escaped","pop","eat","skipToEnd","test","eatWhile","eiffel","name","startState","token","style","word","current","propertyIsEnumerable","languageData","commentTokens","line"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/5395.index.js b/book/_build/html/_static/5395.index.js new file mode 100644 index 0000000..f06c5d7 --- /dev/null +++ b/book/_build/html/_static/5395.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[5395],{25395:(e,t,n)=>{n.r(t),n.d(t,{sas:()=>l});var r={},s={eq:"operator",lt:"operator",le:"operator",gt:"operator",ge:"operator",in:"operator",ne:"operator",or:"operator"},a=/(<=|>=|!=|<>)/,o=/[=\(:\),{}.*<>+\-\/^\[\]]/;function i(e,t,n){if(n)for(var s=t.split(" "),a=0;a=|!=|<>)/;\nvar isSingleOperatorChar = /[=\\(:\\),{}.*<>+\\-\\/^\\[\\]]/;\n\n// Takes a string of words separated by spaces and adds them as\n// keys with the value of the first argument 'style'\nfunction define(style, string, context) {\n if (context) {\n var split = string.split(' ');\n for (var i = 0; i < split.length; i++) {\n words[split[i]] = {style: style, state: context};\n }\n }\n}\n//datastep\ndefine('def', 'stack pgm view source debug nesting nolist', ['inDataStep']);\ndefine('def', 'if while until for do do; end end; then else cancel', ['inDataStep']);\ndefine('def', 'label format _n_ _error_', ['inDataStep']);\ndefine('def', 'ALTER BUFNO BUFSIZE CNTLLEV COMPRESS DLDMGACTION ENCRYPT ENCRYPTKEY EXTENDOBSCOUNTER GENMAX GENNUM INDEX LABEL OBSBUF OUTREP PW PWREQ READ REPEMPTY REPLACE REUSE ROLE SORTEDBY SPILL TOBSNO TYPE WRITE FILECLOSE FIRSTOBS IN OBS POINTOBS WHERE WHEREUP IDXNAME IDXWHERE DROP KEEP RENAME', ['inDataStep']);\ndefine('def', 'filevar finfo finv fipname fipnamel fipstate first firstobs floor', ['inDataStep']);\ndefine('def', 'varfmt varinfmt varlabel varlen varname varnum varray varrayx vartype verify vformat vformatd vformatdx vformatn vformatnx vformatw vformatwx vformatx vinarray vinarrayx vinformat vinformatd vinformatdx vinformatn vinformatnx vinformatw vinformatwx vinformatx vlabel vlabelx vlength vlengthx vname vnamex vnferr vtype vtypex weekday', ['inDataStep']);\ndefine('def', 'zipfips zipname zipnamel zipstate', ['inDataStep']);\ndefine('def', 'put putc putn', ['inDataStep']);\ndefine('builtin', 'data run', ['inDataStep']);\n\n\n//proc\ndefine('def', 'data', ['inProc']);\n\n// flow control for macros\ndefine('def', '%if %end %end; %else %else; %do %do; %then', ['inMacro']);\n\n//everywhere\ndefine('builtin', 'proc run; quit; libname filename %macro %mend option options', ['ALL']);\n\ndefine('def', 'footnote title libname ods', ['ALL']);\ndefine('def', '%let %put %global %sysfunc %eval ', ['ALL']);\n// automatic macro variables http://support.sas.com/documentation/cdl/en/mcrolref/61885/HTML/default/viewer.htm#a003167023.htm\ndefine('variable', '&sysbuffr &syscc &syscharwidth &syscmd &sysdate &sysdate9 &sysday &sysdevic &sysdmg &sysdsn &sysencoding &sysenv &syserr &syserrortext &sysfilrc &syshostname &sysindex &sysinfo &sysjobid &syslast &syslckrc &syslibrc &syslogapplname &sysmacroname &sysmenv &sysmsg &sysncpu &sysodspath &sysparm &syspbuff &sysprocessid &sysprocessname &sysprocname &sysrc &sysscp &sysscpl &sysscpl &syssite &sysstartid &sysstartname &systcpiphostname &systime &sysuserid &sysver &sysvlong &sysvlong4 &syswarningtext', ['ALL']);\n\n//footnote[1-9]? title[1-9]?\n\n//options statement\ndefine('def', 'source2 nosource2 page pageno pagesize', ['ALL']);\n\n//proc and datastep\ndefine('def', '_all_ _character_ _cmd_ _freq_ _i_ _infile_ _last_ _msg_ _null_ _numeric_ _temporary_ _type_ abort abs addr adjrsq airy alpha alter altlog altprint and arcos array arsin as atan attrc attrib attrn authserver autoexec awscontrol awsdef awsmenu awsmenumerge awstitle backward band base betainv between blocksize blshift bnot bor brshift bufno bufsize bxor by byerr byline byte calculated call cards cards4 catcache cbufno cdf ceil center cexist change chisq cinv class cleanup close cnonct cntllev coalesce codegen col collate collin column comamid comaux1 comaux2 comdef compbl compound compress config continue convert cos cosh cpuid create cross crosstab css curobs cv daccdb daccdbsl daccsl daccsyd dacctab dairy datalines datalines4 datejul datepart datetime day dbcslang dbcstype dclose ddfm ddm delete delimiter depdb depdbsl depsl depsyd deptab dequote descending descript design= device dflang dhms dif digamma dim dinfo display distinct dkricond dkrocond dlm dnum do dopen doptname doptnum dread drop dropnote dsname dsnferr echo else emaildlg emailid emailpw emailserver emailsys encrypt end endsas engine eof eov erf erfc error errorcheck errors exist exp fappend fclose fcol fdelete feedback fetch fetchobs fexist fget file fileclose fileexist filefmt filename fileref fmterr fmtsearch fnonct fnote font fontalias fopen foptname foptnum force formatted formchar formdelim formdlim forward fpoint fpos fput fread frewind frlen from fsep fuzz fwrite gaminv gamma getoption getvarc getvarn go goto group gwindow hbar hbound helpenv helploc hms honorappearance hosthelp hostprint hour hpct html hvar ibessel ibr id if index indexc indexw initcmd initstmt inner input inputc inputn inr insert int intck intnx into intrr invaliddata irr is jbessel join juldate keep kentb kurtosis label lag last lbound leave left length levels lgamma lib library libref line linesize link list log log10 log2 logpdf logpmf logsdf lostcard lowcase lrecl ls macro macrogen maps mautosource max maxdec maxr mdy mean measures median memtype merge merror min minute missing missover mlogic mod mode model modify month mopen mort mprint mrecall msglevel msymtabmax mvarsize myy n nest netpv new news nmiss no nobatch nobs nocaps nocardimage nocenter nocharcode nocmdmac nocol nocum nodate nodbcs nodetails nodmr nodms nodmsbatch nodup nodupkey noduplicates noechoauto noequals noerrorabend noexitwindows nofullstimer noicon noimplmac noint nolist noloadlist nomiss nomlogic nomprint nomrecall nomsgcase nomstored nomultenvappl nonotes nonumber noobs noovp nopad nopercent noprint noprintinit normal norow norsasuser nosetinit nosplash nosymbolgen note notes notitle notitles notsorted noverbose noxsync noxwait npv null number numkeys nummousekeys nway obs on open order ordinal otherwise out outer outp= output over ovp p(1 5 10 25 50 75 90 95 99) pad pad2 paired parm parmcards path pathdll pathname pdf peek peekc pfkey pmf point poisson poke position printer probbeta probbnml probchi probf probgam probhypr probit probnegb probnorm probsig probt procleave prt ps pw pwreq qtr quote r ranbin rancau random ranexp rangam range ranks rannor ranpoi rantbl rantri ranuni rcorr read recfm register regr remote remove rename repeat repeated replace resolve retain return reuse reverse rewind right round rsquare rtf rtrace rtraceloc s s2 samploc sasautos sascontrol sasfrscr sasmsg sasmstore sasscript sasuser saving scan sdf second select selection separated seq serror set setcomm setot sign simple sin sinh siteinfo skewness skip sle sls sortedby sortpgm sortseq sortsize soundex spedis splashlocation split spool sqrt start std stderr stdin stfips stimer stname stnamel stop stopover sub subgroup subpopn substr sum sumwgt symbol symbolgen symget symput sysget sysin sysleave sysmsg sysparm sysprint sysprintfont sysprod sysrc system t table tables tan tanh tapeclose tbufsize terminal test then timepart tinv tnonct to today tol tooldef totper transformout translate trantab tranwrd trigamma trim trimn trunc truncover type unformatted uniform union until upcase update user usericon uss validate value var weight when where while wincharset window work workinit workterm write wsum xsync xwait yearcutoff yes yyq min max', ['inDataStep', 'inProc']);\ndefine('operator', 'and not ', ['inDataStep', 'inProc']);\n\n// Main function\nfunction tokenize(stream, state) {\n // Finally advance the stream\n var ch = stream.next();\n\n // BLOCKCOMMENT\n if (ch === '/' && stream.eat('*')) {\n state.continueComment = true;\n return \"comment\";\n } else if (state.continueComment === true) { // in comment block\n //comment ends at the beginning of the line\n if (ch === '*' && stream.peek() === '/') {\n stream.next();\n state.continueComment = false;\n } else if (stream.skipTo('*')) { //comment is potentially later in line\n stream.skipTo('*');\n stream.next();\n if (stream.eat('/'))\n state.continueComment = false;\n } else {\n stream.skipToEnd();\n }\n return \"comment\";\n }\n\n if (ch == \"*\" && stream.column() == stream.indentation()) {\n stream.skipToEnd()\n return \"comment\"\n }\n\n // DoubleOperator match\n var doubleOperator = ch + stream.peek();\n\n if ((ch === '\"' || ch === \"'\") && !state.continueString) {\n state.continueString = ch\n return \"string\"\n } else if (state.continueString) {\n if (state.continueString == ch) {\n state.continueString = null;\n } else if (stream.skipTo(state.continueString)) {\n // quote found on this line\n stream.next();\n state.continueString = null;\n } else {\n stream.skipToEnd();\n }\n return \"string\";\n } else if (state.continueString !== null && stream.eol()) {\n stream.skipTo(state.continueString) || stream.skipToEnd();\n return \"string\";\n } else if (/[\\d\\.]/.test(ch)) { //find numbers\n if (ch === \".\")\n stream.match(/^[0-9]+([eE][\\-+]?[0-9]+)?/);\n else if (ch === \"0\")\n stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/);\n else\n stream.match(/^[0-9]*\\.?[0-9]*([eE][\\-+]?[0-9]+)?/);\n return \"number\";\n } else if (isDoubleOperatorChar.test(ch + stream.peek())) { // TWO SYMBOL TOKENS\n stream.next();\n return \"operator\";\n } else if (isDoubleOperatorSym.hasOwnProperty(doubleOperator)) {\n stream.next();\n if (stream.peek() === ' ')\n return isDoubleOperatorSym[doubleOperator.toLowerCase()];\n } else if (isSingleOperatorChar.test(ch)) { // SINGLE SYMBOL TOKENS\n return \"operator\";\n }\n\n // Matches one whole word -- even if the word is a character\n var word;\n if (stream.match(/[%&;\\w]+/, false) != null) {\n word = ch + stream.match(/[%&;\\w]+/, true);\n if (/&/.test(word)) return 'variable'\n } else {\n word = ch;\n }\n // the word after DATA PROC or MACRO\n if (state.nextword) {\n stream.match(/[\\w]+/);\n // match memname.libname\n if (stream.peek() === '.') stream.skipTo(' ');\n state.nextword = false;\n return 'variableName.special';\n }\n\n word = word.toLowerCase()\n // Are we in a DATA Step?\n if (state.inDataStep) {\n if (word === 'run;' || stream.match(/run\\s;/)) {\n state.inDataStep = false;\n return 'builtin';\n }\n // variable formats\n if ((word) && stream.next() === '.') {\n //either a format or libname.memname\n if (/\\w/.test(stream.peek())) return 'variableName.special';\n else return 'variable';\n }\n // do we have a DATA Step keyword\n if (word && words.hasOwnProperty(word) &&\n (words[word].state.indexOf(\"inDataStep\") !== -1 ||\n words[word].state.indexOf(\"ALL\") !== -1)) {\n //backup to the start of the word\n if (stream.start < stream.pos)\n stream.backUp(stream.pos - stream.start);\n //advance the length of the word and return\n for (var i = 0; i < word.length; ++i) stream.next();\n return words[word].style;\n }\n }\n // Are we in an Proc statement?\n if (state.inProc) {\n if (word === 'run;' || word === 'quit;') {\n state.inProc = false;\n return 'builtin';\n }\n // do we have a proc keyword\n if (word && words.hasOwnProperty(word) &&\n (words[word].state.indexOf(\"inProc\") !== -1 ||\n words[word].state.indexOf(\"ALL\") !== -1)) {\n stream.match(/[\\w]+/);\n return words[word].style;\n }\n }\n // Are we in a Macro statement?\n if (state.inMacro) {\n if (word === '%mend') {\n if (stream.peek() === ';') stream.next();\n state.inMacro = false;\n return 'builtin';\n }\n if (word && words.hasOwnProperty(word) &&\n (words[word].state.indexOf(\"inMacro\") !== -1 ||\n words[word].state.indexOf(\"ALL\") !== -1)) {\n stream.match(/[\\w]+/);\n return words[word].style;\n }\n\n return 'atom';\n }\n // Do we have Keywords specific words?\n if (word && words.hasOwnProperty(word)) {\n // Negates the initial next()\n stream.backUp(1);\n // Actually move the stream\n stream.match(/[\\w]+/);\n if (word === 'data' && /=/.test(stream.peek()) === false) {\n state.inDataStep = true;\n state.nextword = true;\n return 'builtin';\n }\n if (word === 'proc') {\n state.inProc = true;\n state.nextword = true;\n return 'builtin';\n }\n if (word === '%macro') {\n state.inMacro = true;\n state.nextword = true;\n return 'builtin';\n }\n if (/title[1-9]/.test(word)) return 'def';\n\n if (word === 'footnote') {\n stream.eat(/[1-9]/);\n return 'def';\n }\n\n // Returns their value as state in the prior define methods\n if (state.inDataStep === true && words[word].state.indexOf(\"inDataStep\") !== -1)\n return words[word].style;\n if (state.inProc === true && words[word].state.indexOf(\"inProc\") !== -1)\n return words[word].style;\n if (state.inMacro === true && words[word].state.indexOf(\"inMacro\") !== -1)\n return words[word].style;\n if (words[word].state.indexOf(\"ALL\") !== -1)\n return words[word].style;\n return null;\n }\n // Unrecognized syntax\n return null;\n}\n\nexport const sas = {\n name: \"sas\",\n startState: function () {\n return {\n inDataStep: false,\n inProc: false,\n inMacro: false,\n nextword: false,\n continueString: null,\n continueComment: false\n };\n },\n token: function (stream, state) {\n // Strip the spaces, but regex will account for them either way\n if (stream.eatSpace()) return null;\n // Go through the main process\n return tokenize(stream, state);\n },\n\n languageData: {\n commentTokens: {block: {open: \"/*\", close: \"*/\"}}\n }\n};\n"],"names":["words","isDoubleOperatorSym","eq","lt","le","gt","ge","ne","or","isDoubleOperatorChar","isSingleOperatorChar","define","style","string","context","split","i","length","state","sas","name","startState","inDataStep","inProc","inMacro","nextword","continueString","continueComment","token","stream","eatSpace","ch","next","eat","peek","skipTo","skipToEnd","column","indentation","word","doubleOperator","eol","test","match","hasOwnProperty","toLowerCase","indexOf","start","pos","backUp","tokenize","languageData","commentTokens","block","open","close"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/545.index.js b/book/_build/html/_static/545.index.js new file mode 100644 index 0000000..da404b4 --- /dev/null +++ b/book/_build/html/_static/545.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[545],{60545:(t,e,n)=>{n.r(e),n.d(e,{shell:()=>k});var r={};function s(t,e){for(var n=0;n1&&t.eat("$");var n=t.next();return/['"({]/.test(n)?(e.tokens[0]=f(n,"("==n?"quote":"{"==n?"def":"string"),h(t,e)):(/\d/.test(n)||t.eatWhile(/\w/),e.tokens.shift(),"def")};function h(t,e){return(e.tokens[0]||a)(t,e)}const k={name:"shell",startState:function(){return{tokens:[]}},token:function(t,e){return h(t,e)},languageData:{autocomplete:i.concat(o,u),closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"#"}}}}}]); +//# sourceMappingURL=545.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/545.index.js.map b/book/_build/html/_static/545.index.js.map new file mode 100644 index 0000000..128433e --- /dev/null +++ b/book/_build/html/_static/545.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"545.index.js","mappings":"0HAAA,IAAIA,EAAQ,CAAC,EACb,SAASC,EAAOC,EAAOC,GACrB,IAAI,IAAIC,EAAI,EAAGA,EAAID,EAAKE,OAAQD,IAC9BJ,EAAMG,EAAKC,IAAMF,CAErB,CAEA,IAAII,EAAc,CAAC,OAAQ,SACvBC,EAAiB,CAAC,KAAM,OAAQ,KAAM,OAAQ,OAAQ,QAAS,QAAS,MAAO,KAAM,OAAQ,KAC3E,MAAO,MAAO,OAAQ,OAAQ,MAAO,QAAS,SAAU,YAC1EC,EAAiB,CAAC,KAAM,MAAO,OAAQ,OAAQ,MAAO,KAAM,KAAM,QAAS,QAAS,SAAU,QAC5E,KAAM,OAAQ,MAAO,OAAQ,OAAQ,OAAQ,OAAQ,MAAO,MAAO,MAAO,OAAQ,KAAM,OAAQ,UAChG,KAAM,KAAM,OAAQ,QAAS,UAAW,KAAM,KAAM,KAAM,OAAQ,MAAO,OAAQ,KAAM,UAAW,KAClG,QAAS,MAAO,UAAW,KAAM,QAAS,QAAS,SAAU,OAAQ,QAAS,MAAO,QAAS,OAC9F,KAAM,OAAQ,MAAO,MAAO,SAAU,MAAO,QAAS,KAAM,MAAO,OAAQ,KAAM,OAAQ,MAAO,QAChG,MAAO,OAM7B,SAASC,EAAUC,EAAQC,GACzB,GAAID,EAAOE,WAAY,OAAO,KAE9B,IAkGoBC,EAlGhBC,EAAMJ,EAAOI,MACbC,EAAKL,EAAOM,OAEhB,GAAW,OAAPD,EAEF,OADAL,EAAOM,OACA,KAET,GAAW,MAAPD,GAAsB,MAAPA,GAAqB,MAAPA,EAE/B,OADAJ,EAAMM,OAAOC,QAAQC,EAAYJ,EAAW,MAAPA,EAAa,QAAU,WACrDK,EAASV,EAAQC,GAE1B,GAAW,MAAPI,EACF,OAAID,GAAOJ,EAAOW,IAAI,MAC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cesContent":["var words = {};\nfunction define(style, dict) {\n for(var i = 0; i < dict.length; i++) {\n words[dict[i]] = style;\n }\n};\n\nvar commonAtoms = [\"true\", \"false\"];\nvar commonKeywords = [\"if\", \"then\", \"do\", \"else\", \"elif\", \"while\", \"until\", \"for\", \"in\", \"esac\", \"fi\",\n \"fin\", \"fil\", \"done\", \"exit\", \"set\", \"unset\", \"export\", \"function\"];\nvar commonCommands = [\"ab\", \"awk\", \"bash\", \"beep\", \"cat\", \"cc\", \"cd\", \"chown\", \"chmod\", \"chroot\", \"clear\",\n \"cp\", \"curl\", \"cut\", \"diff\", \"echo\", \"find\", \"gawk\", \"gcc\", \"get\", \"git\", \"grep\", \"hg\", \"kill\", \"killall\",\n \"ln\", \"ls\", \"make\", \"mkdir\", \"openssl\", \"mv\", \"nc\", \"nl\", \"node\", \"npm\", \"ping\", \"ps\", \"restart\", \"rm\",\n \"rmdir\", \"sed\", \"service\", \"sh\", \"shopt\", \"shred\", \"source\", \"sort\", \"sleep\", \"ssh\", \"start\", \"stop\",\n \"su\", \"sudo\", \"svn\", \"tee\", \"telnet\", \"top\", \"touch\", \"vi\", \"vim\", \"wall\", \"wc\", \"wget\", \"who\", \"write\",\n \"yes\", \"zsh\"];\n\ndefine('atom', commonAtoms);\ndefine('keyword', commonKeywords);\ndefine('builtin', commonCommands);\n\nfunction tokenBase(stream, state) {\n if (stream.eatSpace()) return null;\n\n var sol = stream.sol();\n var ch = stream.next();\n\n if (ch === '\\\\') {\n stream.next();\n return null;\n }\n if (ch === '\\'' || ch === '\"' || ch === '`') {\n state.tokens.unshift(tokenString(ch, ch === \"`\" ? \"quote\" : \"string\"));\n return tokenize(stream, state);\n }\n if (ch === '#') {\n if (sol && stream.eat('!')) {\n stream.skipToEnd();\n return 'meta'; // 'comment'?\n }\n stream.skipToEnd();\n return 'comment';\n }\n if (ch === '$') {\n state.tokens.unshift(tokenDollar);\n return tokenize(stream, state);\n }\n if (ch === '+' || ch === '=') {\n return 'operator';\n }\n if (ch === '-') {\n stream.eat('-');\n stream.eatWhile(/\\w/);\n return 'attribute';\n }\n if (ch == \"<\") {\n if (stream.match(\"<<\")) return \"operator\"\n var heredoc = stream.match(/^<-?\\s*(?:['\"]([^'\"]*)['\"]|([^'\"\\s]*))/)\n if (heredoc) {\n state.tokens.unshift(tokenHeredoc(heredoc[1] || heredoc[2]))\n return 'string.special'\n }\n }\n if (/\\d/.test(ch)) {\n stream.eatWhile(/\\d/);\n if(stream.eol() || !/\\w/.test(stream.peek())) {\n return 'number';\n }\n }\n stream.eatWhile(/[\\w-]/);\n var cur = stream.current();\n if (stream.peek() === '=' && /\\w+/.test(cur)) return 'def';\n return words.hasOwnProperty(cur) ? words[cur] : null;\n}\n\nfunction tokenString(quote, style) {\n var close = quote == \"(\" ? \")\" : quote == \"{\" ? \"}\" : quote\n return function(stream, state) {\n var next, escaped = false;\n while ((next = stream.next()) != null) {\n if (next === close && !escaped) {\n state.tokens.shift();\n break;\n } else if (next === '$' && !escaped && quote !== \"'\" && stream.peek() != close) {\n escaped = true;\n stream.backUp(1);\n state.tokens.unshift(tokenDollar);\n break;\n } else if (!escaped && quote !== close && next === quote) {\n state.tokens.unshift(tokenString(quote, style))\n return tokenize(stream, state)\n } else if (!escaped && /['\"]/.test(next) && !/['\"]/.test(quote)) {\n state.tokens.unshift(tokenStringStart(next, \"string\"));\n stream.backUp(1);\n break;\n }\n escaped = !escaped && next === '\\\\';\n }\n return style;\n };\n};\n\nfunction tokenStringStart(quote, style) {\n return function(stream, state) {\n state.tokens[0] = tokenString(quote, style)\n stream.next()\n return tokenize(stream, state)\n }\n}\n\nvar tokenDollar = function(stream, state) {\n if (state.tokens.length > 1) stream.eat('$');\n var ch = stream.next()\n if (/['\"({]/.test(ch)) {\n state.tokens[0] = tokenString(ch, ch == \"(\" ? \"quote\" : ch == \"{\" ? \"def\" : \"string\");\n return tokenize(stream, state);\n }\n if (!/\\d/.test(ch)) stream.eatWhile(/\\w/);\n state.tokens.shift();\n return 'def';\n};\n\nfunction tokenHeredoc(delim) {\n return function(stream, state) {\n if (stream.sol() && stream.string == delim) state.tokens.shift()\n stream.skipToEnd()\n return \"string.special\"\n }\n}\n\nfunction tokenize(stream, state) {\n return (state.tokens[0] || tokenBase) (stream, state);\n};\n\nexport const shell = {\n name: \"shell\",\n startState: function() {return {tokens:[]};},\n token: function(stream, state) {\n return tokenize(stream, state);\n },\n languageData: {\n autocomplete: commonAtoms.concat(commonKeywords, commonCommands),\n closeBrackets: {brackets: [\"(\", \"[\", \"{\", \"'\", '\"', \"`\"]},\n commentTokens: {line: \"#\"}\n }\n};\n"],"names":["words","define","style","dict","i","length","commonAtoms","commonKeywords","commonCommands","tokenBase","stream","state","eatSpace","delim","sol","ch","next","tokens","unshift","tokenString","tokenize","eat","skipToEnd","tokenDollar","eatWhile","match","heredoc","string","shift","test","eol","peek","cur","current","hasOwnProperty","quote","close","escaped","backUp","tokenStringStart","shell","name","startState","token","languageData","autocomplete","concat","closeBrackets","brackets","commentTokens","line"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/5571.index.js b/book/_build/html/_static/5571.index.js new file mode 100644 index 0000000..65f04f9 --- /dev/null +++ b/book/_build/html/_static/5571.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[5571],{55571:(e,t,n)=>{function r(e,t,n,r,a,o){this.indented=e,this.column=t,this.type=n,this.info=r,this.align=a,this.prev=o}function a(e,t,n,a){var o=e.indented;return e.context&&"statement"==e.context.type&&"statement"!=n&&(o=e.context.indented),e.context=new r(o,t,n,a,null,e.context)}function o(e){var t=e.context.type;return")"!=t&&"]"!=t&&"}"!=t||(e.indented=e.context.indented),e.context=e.context.prev}function i(e,t,n){return"variable"==t.prevToken||"type"==t.prevToken||!!/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(e.string.slice(0,n))||!(!t.typeAtEndOfLine||e.column()!=e.indentation())||void 0}function l(e){for(;;){if(!e||"top"==e.type)return!0;if("}"==e.type&&"namespace"!=e.prev.info)return!1;e=e.prev}}function s(e){var t,n,s=e.statementIndentUnit,c=e.dontAlignCalls,d=e.keywords||{},f=e.types||{},p=e.builtin||{},m=e.blockKeywords||{},h=e.defKeywords||{},y=e.atoms||{},g=e.hooks||{},k=e.multiLineStrings,b=!1!==e.indentStatements,v=!1!==e.indentSwitch,w=e.namespaceSeparator,_=e.isPunctuationChar||/[\[\]{}\(\),;\:\.]/,x=e.numberStart||/[\d\.]/,S=e.number||/^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i,T=e.isOperatorChar||/[+\-*&%=<>!?|\/]/,N=e.isIdentifierChar||/[\w\$_\xa1-\uffff]/,C=e.isReservedIdentifier||!1;function I(e,r){var a,o=e.next();if(g[o]){var i=g[o](e,r);if(!1!==i)return i}if('"'==o||"'"==o)return r.tokenize=(a=o,function(e,t){for(var n,r=!1,o=!1;null!=(n=e.next());){if(n==a&&!r){o=!0;break}r=!r&&"\\"==n}return(o||!r&&!k)&&(t.tokenize=null),"string"}),r.tokenize(e,r);if(x.test(o)){if(e.backUp(1),e.match(S))return"number";e.next()}if(_.test(o))return t=o,null;if("/"==o){if(e.eat("*"))return r.tokenize=D,D(e,r);if(e.eat("/"))return e.skipToEnd(),"comment"}if(T.test(o)){for(;!e.match(/^\/[\/*]/,!1)&&e.eat(T););return"operator"}if(e.eatWhile(N),w)for(;e.match(w);)e.eatWhile(N);var l=e.current();return u(d,l)?(u(m,l)&&(t="newstatement"),u(h,l)&&(n=!0),"keyword"):u(f,l)?"type":u(p,l)||C&&C(l)?(u(m,l)&&(t="newstatement"),"builtin"):u(y,l)?"atom":"variable"}function D(e,t){for(var n,r=!1;n=e.next();){if("/"==n&&r){t.tokenize=null;break}r="*"==n}return"comment"}function z(t,n){e.typeFirstDefinitions&&t.eol()&&l(n.context)&&(n.typeAtEndOfLine=i(t,n,t.pos))}return{name:e.name,startState:function(e){return{tokenize:null,context:new r(-e,0,"top",null,!1),indented:0,startOfLine:!0,prevToken:null}},token:function(r,s){var c=s.context;if(r.sol()&&(null==c.align&&(c.align=!1),s.indented=r.indentation(),s.startOfLine=!0),r.eatSpace())return z(r,s),null;t=n=null;var u=(s.tokenize||I)(r,s);if("comment"==u||"meta"==u)return u;if(null==c.align&&(c.align=!0),";"==t||":"==t||","==t&&r.match(/^\s*(?:\/\/.*)?$/,!1))for(;"statement"==s.context.type;)o(s);else if("{"==t)a(s,r.column(),"}");else if("["==t)a(s,r.column(),"]");else if("("==t)a(s,r.column(),")");else if("}"==t){for(;"statement"==c.type;)c=o(s);for("}"==c.type&&(c=o(s));"statement"==c.type;)c=o(s)}else t==c.type?o(s):b&&(("}"==c.type||"top"==c.type)&&";"!=t||"statement"==c.type&&"newstatement"==t)&&a(s,r.column(),"statement",r.current());if("variable"==u&&("def"==s.prevToken||e.typeFirstDefinitions&&i(r,s,r.start)&&l(s.context)&&r.match(/^\s*\(/,!1))&&(u="def"),g.token){var d=g.token(r,s,u);void 0!==d&&(u=d)}return"def"==u&&!1===e.styleDefs&&(u="variable"),s.startOfLine=!1,s.prevToken=n?"def":u||t,z(r,s),u},indent:function(t,n,r){if(t.tokenize!=I&&null!=t.tokenize||t.typeAtEndOfLine&&l(t.context))return null;var a=t.context,o=n&&n.charAt(0),i=o==a.type;if("statement"==a.type&&"}"==o&&(a=a.prev),e.dontIndentStatements)for(;"statement"==a.type&&e.dontIndentStatements.test(a.info);)a=a.prev;if(g.indent){var u=g.indent(t,a,n,r.unit);if("number"==typeof u)return u}var d=a.prev&&"switch"==a.prev.info;if(e.allmanIndentation&&/[{(]/.test(o)){for(;"top"!=a.type&&"}"!=a.type;)a=a.prev;return a.indented}return"statement"==a.type?a.indented+("{"==o?0:s||r.unit):!a.align||c&&")"==a.type?")"!=a.type||i?a.indented+(i?0:r.unit)+(i||!d||/^(?:case|default)\b/.test(n)?0:r.unit):a.indented+(s||r.unit):a.column+(i?0:1)},languageData:{indentOnInput:v?/^\s*(?:case .*?:|default:|\{\}?|\})$/:/^\s*[{}]$/,commentTokens:{line:"//",block:{open:"/*",close:"*/"}},autocomplete:Object.keys(d).concat(Object.keys(f)).concat(Object.keys(p)).concat(Object.keys(y)),...e.languageData}}}function c(e){for(var t={},n=e.split(" "),r=0;rD,ceylon:()=>q,clike:()=>s,cpp:()=>z,csharp:()=>M,dart:()=>X,java:()=>L,kotlin:()=>R,nesC:()=>j,objectiveC:()=>A,objectiveCpp:()=>U,scala:()=>P,shader:()=>O,squirrel:()=>$});var d="auto if break case register continue return default do sizeof static else struct switch extern typedef union for goto while enum const volatile inline restrict asm fortran",f="alignas alignof and and_eq audit axiom bitand bitor catch class compl concept constexpr const_cast decltype delete dynamic_cast explicit export final friend import module mutable namespace new noexcept not not_eq operator or or_eq override private protected public reinterpret_cast requires static_assert static_cast template this thread_local throw try typeid typename using virtual xor xor_eq",p="bycopy byref in inout oneway out self super atomic nonatomic retain copy readwrite readonly strong weak assign typeof nullable nonnull null_resettable _cmd @interface @implementation @end @protocol @encode @property @synthesize @dynamic @class @public @package @private @protected @required @optional @try @catch @finally @import @selector @encode @defs @synchronized @autoreleasepool @compatibility_alias @available",m="FOUNDATION_EXPORT FOUNDATION_EXTERN NS_INLINE NS_FORMAT_FUNCTION NS_RETURNS_RETAINEDNS_ERROR_ENUM NS_RETURNS_NOT_RETAINED NS_RETURNS_INNER_POINTER NS_DESIGNATED_INITIALIZER NS_ENUM NS_OPTIONS NS_REQUIRES_NIL_TERMINATION NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_SWIFT_NAME NS_REFINED_FOR_SWIFT",h=c("int long char short double float unsigned signed void bool"),y=c("SEL instancetype id Class Protocol BOOL");function g(e){return u(h,e)||/.+_t$/.test(e)}function k(e){return g(e)||u(y,e)}var b="case do else for if switch while struct enum union",v="struct enum union";function w(e,t){if(!t.startOfLine)return!1;for(var n,r=null;n=e.peek();){if("\\"==n&&e.match(/^.$/)){r=w;break}if("/"==n&&e.match(/^\/[\/\*]/,!1))break;e.next()}return t.tokenize=r,"meta"}function _(e,t){return"type"==t.prevToken&&"type"}function x(e){return!(!e||e.length<2||"_"!=e[0]||"_"!=e[1]&&e[1]===e[1].toLowerCase())}function S(e){return e.eatWhile(/[\w\.']/),"number"}function T(e,t){if(e.backUp(1),e.match(/^(?:R|u8R|uR|UR|LR)/)){var n=e.match(/^"([^\s\\()]{0,16})\(/);return!!n&&(t.cpp11RawStringDelim=n[1],t.tokenize=I,I(e,t))}return e.match(/^(?:u8|u|U|L)/)?!!e.match(/^["']/,!1)&&"string":(e.next(),!1)}function N(e){var t=/(\w+)::~?(\w+)$/.exec(e);return t&&t[1]==t[2]}function C(e,t){for(var n;null!=(n=e.next());)if('"'==n&&!e.eat('"')){t.tokenize=null;break}return"string"}function I(e,t){var n=t.cpp11RawStringDelim.replace(/[^\w\s]/g,"\\$&");return e.match(new RegExp(".*?\\)"+n+'"'))?t.tokenize=null:e.skipToEnd(),"string"}const D=s({name:"c",keywords:c(d),types:g,blockKeywords:c(b),defKeywords:c(v),typeFirstDefinitions:!0,atoms:c("NULL true false"),isReservedIdentifier:x,hooks:{"#":w,"*":_}}),z=s({name:"cpp",keywords:c(d+" "+f),types:g,blockKeywords:c(b+" class try catch"),defKeywords:c(v+" class namespace"),typeFirstDefinitions:!0,atoms:c("true false NULL nullptr"),dontIndentStatements:/^template$/,isIdentifierChar:/[\w\$_~\xa1-\uffff]/,isReservedIdentifier:x,hooks:{"#":w,"*":_,u:T,U:T,L:T,R:T,0:S,1:S,2:S,3:S,4:S,5:S,6:S,7:S,8:S,9:S,token:function(e,t,n){if("variable"==n&&"("==e.peek()&&(";"==t.prevToken||null==t.prevToken||"}"==t.prevToken)&&N(e.current()))return"def"}},namespaceSeparator:"::"}),L=s({name:"java",keywords:c("abstract assert break case catch class const continue default do else enum extends final finally for goto if implements import instanceof interface native new package private protected public return static strictfp super switch synchronized this throw throws transient try volatile while @interface"),types:c("var byte short int long float double boolean char void Boolean Byte Character Double Float Integer Long Number Object Short String StringBuffer StringBuilder Void"),blockKeywords:c("catch class do else finally for if switch try while"),defKeywords:c("class interface enum @interface"),typeFirstDefinitions:!0,atoms:c("true false null"),number:/^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,hooks:{"@":function(e){return!e.match("interface",!1)&&(e.eatWhile(/[\w\$_]/),"meta")},'"':function(e,t){return!!e.match(/""$/)&&(t.tokenize=E,t.tokenize(e,t))}}}),M=s({name:"csharp",keywords:c("abstract as async await base break case catch checked class const continue default delegate do else enum event explicit extern finally fixed for foreach goto if implicit in init interface internal is lock namespace new operator out override params private protected public readonly record ref required return sealed sizeof stackalloc static struct switch this throw try typeof unchecked unsafe using virtual void volatile while add alias ascending descending dynamic from get global group into join let orderby partial remove select set value var yield"),types:c("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32 UInt64 bool byte char decimal double short int long object sbyte float string ushort uint ulong"),blockKeywords:c("catch class do else finally for foreach if struct switch try while"),defKeywords:c("class interface namespace record struct var"),typeFirstDefinitions:!0,atoms:c("true false null"),hooks:{"@":function(e,t){return e.eat('"')?(t.tokenize=C,C(e,t)):(e.eatWhile(/[\w\$_]/),"meta")}}});function E(e,t){for(var n=!1;!e.eol();){if(!n&&e.match('"""')){t.tokenize=null;break}n="\\"==e.next()&&!n}return"string"}function F(e){return function(t,n){for(var r;r=t.next();){if("*"==r&&t.eat("/")){if(1==e){n.tokenize=null;break}return n.tokenize=F(e-1),n.tokenize(t,n)}if("/"==r&&t.eat("*"))return n.tokenize=F(e+1),n.tokenize(t,n)}return"comment"}}const P=s({name:"scala",keywords:c("abstract case catch class def do else extends final finally for forSome if implicit import lazy match new null object override package private protected return sealed super this throw trait try type val var while with yield _ assert assume require print println printf readLine readBoolean readByte readShort readChar readInt readLong readFloat readDouble"),types:c("AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable Compiler Double Exception Float Integer Long Math Number Object Package Pair Process Runtime Runnable SecurityManager Short StackTraceElement StrictMath String StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"),multiLineStrings:!0,blockKeywords:c("catch class enum do else finally for forSome if match switch try while"),defKeywords:c("class enum def object package trait type val var"),atoms:c("true false null"),indentStatements:!1,indentSwitch:!1,isOperatorChar:/[+\-*&%=<>!?|\/#:@]/,hooks:{"@":function(e){return e.eatWhile(/[\w\$_]/),"meta"},'"':function(e,t){return!!e.match('""')&&(t.tokenize=E,t.tokenize(e,t))},"'":function(e){return e.match(/^(\\[^'\s]+|[^\\'])'/)?"character":(e.eatWhile(/[\w\$_\xa1-\uffff]/),"atom")},"=":function(e,t){var n=t.context;return!("}"!=n.type||!n.align||!e.eat(">"))&&(t.context=new r(n.indented,n.column,n.type,n.info,null,n.prev),"operator")},"/":function(e,t){return!!e.eat("*")&&(t.tokenize=F(1),t.tokenize(e,t))}},languageData:{closeBrackets:{brackets:["(","[","{","'",'"','"""']}}}),R=s({name:"kotlin",keywords:c("package as typealias class interface this super val operator var fun for is in This throw return annotation break continue object if else while do try when !in !is as? file import where by get set abstract enum open inner override private public internal protected catch finally out final vararg reified dynamic companion constructor init sealed field property receiver param sparam lateinit data inline noinline tailrec external annotation crossinline const operator infix suspend actual expect setparam"),types:c("Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable Compiler Double Exception Float Integer Long Math Number Object Package Pair Process Runtime Runnable SecurityManager Short StackTraceElement StrictMath String StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void Annotation Any BooleanArray ByteArray Char CharArray DeprecationLevel DoubleArray Enum FloatArray Function Int IntArray Lazy LazyThreadSafetyMode LongArray Nothing ShortArray Unit"),intendSwitch:!1,indentStatements:!1,multiLineStrings:!0,number:/^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+(\.\d+)?|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,blockKeywords:c("catch class do else finally for if where try while enum"),defKeywords:c("class val var object interface fun"),atoms:c("true false null this"),hooks:{"@":function(e){return e.eatWhile(/[\w\$_]/),"meta"},"*":function(e,t){return"."==t.prevToken?"variable":"operator"},'"':function(e,t){var n;return t.tokenize=(n=e.match('""'),function(e,t){for(var r,a=!1,o=!1;!e.eol();){if(!n&&!a&&e.match('"')){o=!0;break}if(n&&e.match('"""')){o=!0;break}r=e.next(),!a&&"$"==r&&e.match("{")&&e.skipTo("}"),a=!a&&"\\"==r&&!n}return!o&&n||(t.tokenize=null),"string"}),t.tokenize(e,t)},"/":function(e,t){return!!e.eat("*")&&(t.tokenize=F(1),t.tokenize(e,t))},indent:function(e,t,n,r){var a=n&&n.charAt(0);return"}"!=e.prevToken&&")"!=e.prevToken||""!=n?"operator"==e.prevToken&&"}"!=n&&"}"!=e.context.type||"variable"==e.prevToken&&"."==a||("}"==e.prevToken||")"==e.prevToken)&&"."==a?2*r+t.indented:t.align&&"}"==t.type?t.indented+(e.context.type==(n||"").charAt(0)?0:r):void 0:e.indented}},languageData:{closeBrackets:{brackets:["(","[","{","'",'"','"""']}}}),O=s({name:"shader",keywords:c("sampler1D sampler2D sampler3D samplerCube sampler1DShadow sampler2DShadow const attribute uniform varying break continue discard return for while do if else struct in out inout"),types:c("float int bool void vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 mat2 mat3 mat4"),blockKeywords:c("for while do if else struct"),builtin:c("radians degrees sin cos tan asin acos atan pow exp log exp2 sqrt inversesqrt abs sign floor ceil fract mod min max clamp mix step smoothstep length distance dot cross normalize ftransform faceforward reflect refract matrixCompMult lessThan lessThanEqual greaterThan greaterThanEqual equal notEqual any all not texture1D texture1DProj texture1DLod texture1DProjLod texture2D texture2DProj texture2DLod texture2DProjLod texture3D texture3DProj texture3DLod texture3DProjLod textureCube textureCubeLod shadow1D shadow2D shadow1DProj shadow2DProj shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod dFdx dFdy fwidth noise1 noise2 noise3 noise4"),atoms:c("true false gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 gl_FogCoord gl_PointCoord gl_Position gl_PointSize gl_ClipVertex gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor gl_TexCoord gl_FogFragCoord gl_FragCoord gl_FrontFacing gl_FragData gl_FragDepth gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse gl_TextureMatrixTranspose gl_ModelViewMatrixInverseTranspose gl_ProjectionMatrixInverseTranspose gl_ModelViewProjectionMatrixInverseTranspose gl_TextureMatrixInverseTranspose gl_NormalScale gl_DepthRange gl_ClipPlane gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel gl_FrontLightModelProduct gl_BackLightModelProduct gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ gl_FogParameters gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits gl_MaxDrawBuffers"),indentSwitch:!1,hooks:{"#":w}}),j=s({name:"nesc",keywords:c(d+" as atomic async call command component components configuration event generic implementation includes interface module new norace nx_struct nx_union post provides signal task uses abstract extends"),types:g,blockKeywords:c(b),atoms:c("null true false"),hooks:{"#":w}}),A=s({name:"objectivec",keywords:c(d+" "+p),types:k,builtin:c(m),blockKeywords:c(b+" @synthesize @try @catch @finally @autoreleasepool @synchronized"),defKeywords:c(v+" @interface @implementation @protocol @class"),dontIndentStatements:/^@.*$/,typeFirstDefinitions:!0,atoms:c("YES NO NULL Nil nil true false nullptr"),isReservedIdentifier:x,hooks:{"#":w,"*":_}}),U=s({name:"objectivecpp",keywords:c(d+" "+p+" "+f),types:k,builtin:c(m),blockKeywords:c(b+" @synthesize @try @catch @finally @autoreleasepool @synchronized class try catch"),defKeywords:c(v+" @interface @implementation @protocol @class class namespace"),dontIndentStatements:/^@.*$|^template$/,typeFirstDefinitions:!0,atoms:c("YES NO NULL Nil nil true false nullptr"),isReservedIdentifier:x,hooks:{"#":w,"*":_,u:T,U:T,L:T,R:T,0:S,1:S,2:S,3:S,4:S,5:S,6:S,7:S,8:S,9:S,token:function(e,t,n){if("variable"==n&&"("==e.peek()&&(";"==t.prevToken||null==t.prevToken||"}"==t.prevToken)&&N(e.current()))return"def"}},namespaceSeparator:"::"}),$=s({name:"squirrel",keywords:c("base break clone continue const default delete enum extends function in class foreach local resume return this throw typeof yield constructor instanceof static"),types:g,blockKeywords:c("case catch class else for foreach if switch try while"),defKeywords:c("function local class"),typeFirstDefinitions:!0,atoms:c("true false null"),hooks:{"#":w}});var B=null;function K(e){return function(t,n){for(var r,a=!1,o=!1;!t.eol();){if(!a&&t.match('"')&&("single"==e||t.match('""'))){o=!0;break}if(!a&&t.match("``")){B=K(e),o=!0;break}r=t.next(),a="single"==e&&!a&&"\\"==r}return o&&(n.tokenize=null),"string"}}const q=s({name:"ceylon",keywords:c("abstracts alias assembly assert assign break case catch class continue dynamic else exists extends finally for function given if import in interface is let module new nonempty object of out outer package return satisfies super switch then this throw try value void while"),types:function(e){var t=e.charAt(0);return t===t.toUpperCase()&&t!==t.toLowerCase()},blockKeywords:c("case catch class dynamic else finally for function if interface module new object switch try while"),defKeywords:c("class dynamic function interface module object package value"),builtin:c("abstract actual aliased annotation by default deprecated doc final formal late license native optional sealed see serializable shared suppressWarnings tagged throws variable"),isPunctuationChar:/[\[\]{}\(\),;\:\.`]/,isOperatorChar:/[+\-*&%=<>!?|^~:\/]/,numberStart:/[\d#$]/,number:/^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i,multiLineStrings:!0,typeFirstDefinitions:!0,atoms:c("true false null larger smaller equal empty finished"),indentSwitch:!1,styleDefs:!1,hooks:{"@":function(e){return e.eatWhile(/[\w\$_]/),"meta"},'"':function(e,t){return t.tokenize=K(e.match('""')?"triple":"single"),t.tokenize(e,t)},"`":function(e,t){return!(!B||!e.match("`"))&&(t.tokenize=B,B=null,t.tokenize(e,t))},"'":function(e){return e.match(/^(\\[^'\s]+|[^\\'])'/)?"string.special":(e.eatWhile(/[\w\$_\xa1-\uffff]/),"atom")},token:function(e,t,n){if(("variable"==n||"type"==n)&&"."==t.prevToken)return"variableName.special"}},languageData:{closeBrackets:{brackets:["(","[","{","'",'"','"""']}}});function V(e){(e.interpolationStack||(e.interpolationStack=[])).push(e.tokenize)}function W(e){return(e.interpolationStack||(e.interpolationStack=[])).pop()}function G(e,t,n,r){var a=!1;if(t.eat(e)){if(!t.eat(e))return"string";a=!0}function o(t,n){for(var o=!1;!t.eol();){if(!r&&!o&&"$"==t.peek())return V(n),n.tokenize=Z,"string";var i=t.next();if(i==e&&!o&&(!a||t.match(e+e))){n.tokenize=null;break}o=!r&&!o&&"\\"==i}return"string"}return n.tokenize=o,o(t,n)}function Z(e,t){return e.eat("$"),e.eat("{")?t.tokenize=null:t.tokenize=Q,null}function Q(e,t){return e.eatWhile(/[\w_]/),t.tokenize=W(t),"variable"}const X=s({name:"dart",keywords:c("this super static final const abstract class extends external factory implements mixin get native set typedef with enum throw rethrow assert break case continue default in return new deferred async await covariant try catch finally do else for if switch while import library export part of show hide is as extension on yield late required sealed base interface when inline"),blockKeywords:c("try catch finally do else for if switch while"),builtin:c("void bool num int double dynamic var String Null Never"),atoms:c("true false null"),hooks:{"@":function(e){return e.eatWhile(/[\w\$_\.]/),"meta"},"'":function(e,t){return G("'",e,t,!1)},'"':function(e,t){return G('"',e,t,!1)},r:function(e,t){var n=e.peek();return("'"==n||'"'==n)&&G(e.next(),e,t,!0)},"}":function(e,t){return function(e){return e.interpolationStack?e.interpolationStack.length:0}(t)>0&&(t.tokenize=W(t),null)},"/":function(e,t){return!!e.eat("*")&&(t.tokenize=F(1),t.tokenize(e,t))},token:function(e,t,n){if("variable"==n&&RegExp("^[_$]*[A-Z][a-zA-Z0-9_$]*$","g").test(e.current()))return"type"}}})}}]); +//# sourceMappingURL=5571.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/5571.index.js.map b/book/_build/html/_static/5571.index.js.map new file mode 100644 index 0000000..1be2ecf --- /dev/null +++ b/book/_build/html/_static/5571.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"5571.index.js","mappings":"+FAAA,SAASA,EAAQC,EAAUC,EAAQC,EAAMC,EAAMC,EAAOC,GACpDC,KAAKN,SAAWA,EAChBM,KAAKL,OAASA,EACdK,KAAKJ,KAAOA,EACZI,KAAKH,KAAOA,EACZG,KAAKF,MAAQA,EACbE,KAAKD,KAAOA,CACd,CACA,SAASE,EAAYC,EAAOC,EAAKP,EAAMC,GACrC,IAAIO,EAASF,EAAMR,SAGnB,OAFIQ,EAAMG,SAAiC,aAAtBH,EAAMG,QAAQT,MAA+B,aAARA,IACxDQ,EAASF,EAAMG,QAAQX,UAClBQ,EAAMG,QAAU,IAAIZ,EAAQW,EAAQD,EAAKP,EAAMC,EAAM,KAAMK,EAAMG,QAC1E,CACA,SAASC,EAAWJ,GAClB,IAAIK,EAAIL,EAAMG,QAAQT,KA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OAAY,KAARA,GAAuB,KAARA,IACV8C,EAAgBvJ,EAAOmC,OAAQnC,EAAQP,GAAO,EAGzD,EAEA,IAAK,SAASkH,EAASlH,GAErB,OAlFN,SAAgCA,GAC9B,OAAOA,EAAM0J,mBAAqB1J,EAAM0J,mBAAmBzD,OAAS,CACtE,CAgFUoE,CAAuBrK,GAAS,IAClCA,EAAM4C,SAAWgH,EAAsB5J,GAChC,KAGX,EAEA,IAAK,SAASO,EAAQP,GACpB,QAAKO,EAAO0C,IAAI,OAChBjD,EAAM4C,SAAWyF,EAAmB,GAC7BrI,EAAM4C,SAASrC,EAAQP,GAChC,EACAgE,MAAO,SAASzD,EAAQ+J,EAAGlG,GACzB,GAAa,YAATA,GAEY2D,OAAO,6BAA6B,KACtCrH,KAAKH,EAAO+C,WACtB,MAAO,MAGb,I","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/clike.js"],"sourcesContent":["function Context(indented, column, type, info, align, prev) {\n this.indented = indented;\n this.column = column;\n this.type = type;\n this.info = info;\n this.align = align;\n this.prev = prev;\n}\nfunction pushContext(state, col, type, info) {\n var indent = state.indented;\n if (state.context && state.context.type == \"statement\" && type != \"statement\")\n indent = state.context.indented;\n return state.context = new Context(indent, col, type, info, null, state.context);\n}\nfunction popContext(state) {\n var t = state.context.type;\n if (t == \")\" || t == \"]\" || t == \"}\")\n state.indented = state.context.indented;\n return state.context = state.context.prev;\n}\n\nfunction typeBefore(stream, state, pos) {\n if (state.prevToken == \"variable\" || state.prevToken == \"type\") return true;\n if (/\\S(?:[^- ]>|[*\\]])\\s*$|\\*$/.test(stream.string.slice(0, pos))) return true;\n if (state.typeAtEndOfLine && stream.column() == stream.indentation()) return true;\n}\n\nfunction isTopScope(context) {\n for (;;) {\n if (!context || context.type == \"top\") return true;\n if (context.type == \"}\" && context.prev.info != \"namespace\") return false;\n context = context.prev;\n }\n}\n\nexport function clike(parserConfig) {\n var statementIndentUnit = parserConfig.statementIndentUnit,\n dontAlignCalls = parserConfig.dontAlignCalls,\n keywords = parserConfig.keywords || {},\n types = parserConfig.types || {},\n builtin = parserConfig.builtin || {},\n blockKeywords = parserConfig.blockKeywords || {},\n defKeywords = parserConfig.defKeywords || {},\n atoms = parserConfig.atoms || {},\n hooks = parserConfig.hooks || {},\n multiLineStrings = parserConfig.multiLineStrings,\n indentStatements = parserConfig.indentStatements !== false,\n indentSwitch = parserConfig.indentSwitch !== false,\n namespaceSeparator = parserConfig.namespaceSeparator,\n isPunctuationChar = parserConfig.isPunctuationChar || /[\\[\\]{}\\(\\),;\\:\\.]/,\n numberStart = parserConfig.numberStart || /[\\d\\.]/,\n number = parserConfig.number || /^(?:0x[a-f\\d]+|0b[01]+|(?:\\d+\\.?\\d*|\\.\\d+)(?:e[-+]?\\d+)?)(u|ll?|l|f)?/i,\n isOperatorChar = parserConfig.isOperatorChar || /[+\\-*&%=<>!?|\\/]/,\n isIdentifierChar = parserConfig.isIdentifierChar || /[\\w\\$_\\xa1-\\uffff]/,\n // An optional function that takes a {string} token and returns true if it\n // should be treated as a builtin.\n isReservedIdentifier = parserConfig.isReservedIdentifier || false;\n\n var curPunc, isDefKeyword;\n\n function tokenBase(stream, state) {\n var ch = stream.next();\n if (hooks[ch]) {\n var result = hooks[ch](stream, state);\n if (result !== false) return result;\n }\n if (ch == '\"' || ch == \"'\") {\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n }\n if (numberStart.test(ch)) {\n stream.backUp(1)\n if (stream.match(number)) return \"number\"\n stream.next()\n }\n if (isPunctuationChar.test(ch)) {\n curPunc = ch;\n return null;\n }\n if (ch == \"/\") {\n if (stream.eat(\"*\")) {\n state.tokenize = tokenComment;\n return tokenComment(stream, state);\n }\n if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return \"comment\";\n }\n }\n if (isOperatorChar.test(ch)) {\n while (!stream.match(/^\\/[\\/*]/, false) && stream.eat(isOperatorChar)) {}\n return \"operator\";\n }\n stream.eatWhile(isIdentifierChar);\n if (namespaceSeparator) while (stream.match(namespaceSeparator))\n stream.eatWhile(isIdentifierChar);\n\n var cur = stream.current();\n if (contains(keywords, cur)) {\n if (contains(blockKeywords, cur)) curPunc = \"newstatement\";\n if (contains(defKeywords, cur)) isDefKeyword = true;\n return \"keyword\";\n }\n if (contains(types, cur)) return \"type\";\n if (contains(builtin, cur)\n || (isReservedIdentifier && isReservedIdentifier(cur))) {\n if (contains(blockKeywords, cur)) curPunc = \"newstatement\";\n return \"builtin\";\n }\n if (contains(atoms, cur)) return \"atom\";\n return \"variable\";\n }\n\n function tokenString(quote) {\n return function(stream, state) {\n var escaped = false, next, end = false;\n while ((next = stream.next()) != null) {\n if (next == quote && !escaped) {end = true; break;}\n escaped = !escaped && next == \"\\\\\";\n }\n if (end || !(escaped || multiLineStrings))\n state.tokenize = null;\n return \"string\";\n };\n }\n\n function tokenComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if (ch == \"/\" && maybeEnd) {\n state.tokenize = null;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return \"comment\";\n }\n\n function maybeEOL(stream, state) {\n if (parserConfig.typeFirstDefinitions && stream.eol() && isTopScope(state.context))\n state.typeAtEndOfLine = typeBefore(stream, state, stream.pos)\n }\n\n // Interface\n\n return {\n name: parserConfig.name,\n startState: function(indentUnit) {\n return {\n tokenize: null,\n context: new Context(-indentUnit, 0, \"top\", null, false),\n indented: 0,\n startOfLine: true,\n prevToken: null\n };\n },\n\n token: function(stream, state) {\n var ctx = state.context;\n if (stream.sol()) {\n if (ctx.align == null) ctx.align = false;\n state.indented = stream.indentation();\n state.startOfLine = true;\n }\n if (stream.eatSpace()) { maybeEOL(stream, state); return null; }\n curPunc = isDefKeyword = null;\n var style = (state.tokenize || tokenBase)(stream, state);\n if (style == \"comment\" || style == \"meta\") return style;\n if (ctx.align == null) ctx.align = true;\n\n if (curPunc == \";\" || curPunc == \":\" || (curPunc == \",\" && stream.match(/^\\s*(?:\\/\\/.*)?$/, false)))\n while (state.context.type == \"statement\") popContext(state);\n else if (curPunc == \"{\") pushContext(state, stream.column(), \"}\");\n else if (curPunc == \"[\") pushContext(state, stream.column(), \"]\");\n else if (curPunc == \"(\") pushContext(state, stream.column(), \")\");\n else if (curPunc == \"}\") {\n while (ctx.type == \"statement\") ctx = popContext(state);\n if (ctx.type == \"}\") ctx = popContext(state);\n while (ctx.type == \"statement\") ctx = popContext(state);\n }\n else if (curPunc == ctx.type) popContext(state);\n else if (indentStatements &&\n (((ctx.type == \"}\" || ctx.type == \"top\") && curPunc != \";\") ||\n (ctx.type == \"statement\" && curPunc == \"newstatement\"))) {\n pushContext(state, stream.column(), \"statement\", stream.current());\n }\n\n if (style == \"variable\" &&\n ((state.prevToken == \"def\" ||\n (parserConfig.typeFirstDefinitions && typeBefore(stream, state, stream.start) &&\n isTopScope(state.context) && stream.match(/^\\s*\\(/, false)))))\n style = \"def\";\n\n if (hooks.token) {\n var result = hooks.token(stream, state, style);\n if (result !== undefined) style = result;\n }\n\n if (style == \"def\" && parserConfig.styleDefs === false) style = \"variable\";\n\n state.startOfLine = false;\n state.prevToken = isDefKeyword ? \"def\" : style || curPunc;\n maybeEOL(stream, state);\n return style;\n },\n\n indent: function(state, textAfter, context) {\n if (state.tokenize != tokenBase && state.tokenize != null || state.typeAtEndOfLine && isTopScope(state.context))\n return null;\n var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);\n var closing = firstChar == ctx.type;\n if (ctx.type == \"statement\" && firstChar == \"}\") ctx = ctx.prev;\n if (parserConfig.dontIndentStatements)\n while (ctx.type == \"statement\" && parserConfig.dontIndentStatements.test(ctx.info))\n ctx = ctx.prev\n if (hooks.indent) {\n var hook = hooks.indent(state, ctx, textAfter, context.unit);\n if (typeof hook == \"number\") return hook\n }\n var switchBlock = ctx.prev && ctx.prev.info == \"switch\";\n if (parserConfig.allmanIndentation && /[{(]/.test(firstChar)) {\n while (ctx.type != \"top\" && ctx.type != \"}\") ctx = ctx.prev\n return ctx.indented\n }\n if (ctx.type == \"statement\")\n return ctx.indented + (firstChar == \"{\" ? 0 : statementIndentUnit || context.unit);\n if (ctx.align && (!dontAlignCalls || ctx.type != \")\"))\n return ctx.column + (closing ? 0 : 1);\n if (ctx.type == \")\" && !closing)\n return ctx.indented + (statementIndentUnit || context.unit);\n\n return ctx.indented + (closing ? 0 : context.unit) +\n (!closing && switchBlock && !/^(?:case|default)\\b/.test(textAfter) ? context.unit : 0);\n },\n\n languageData: {\n indentOnInput: indentSwitch ? /^\\s*(?:case .*?:|default:|\\{\\}?|\\})$/ : /^\\s*[{}]$/,\n commentTokens: {line: \"//\", block: {open: \"/*\", close: \"*/\"}},\n autocomplete: Object.keys(keywords).concat(Object.keys(types)).concat(Object.keys(builtin)).concat(Object.keys(atoms)),\n ...parserConfig.languageData\n }\n };\n};\n\nfunction words(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n}\nfunction contains(words, word) {\n if (typeof words === \"function\") {\n return words(word);\n } else {\n return words.propertyIsEnumerable(word);\n }\n}\nvar cKeywords = \"auto if break case register continue return default do sizeof \" +\n \"static else struct switch extern typedef union for goto while enum const \" +\n \"volatile inline restrict asm fortran\";\n\n// Keywords from https://en.cppreference.com/w/cpp/keyword includes C++20.\nvar cppKeywords = \"alignas alignof and and_eq audit axiom bitand bitor catch \" +\n \"class compl concept constexpr const_cast decltype delete dynamic_cast \" +\n \"explicit export final friend import module mutable namespace new noexcept \" +\n \"not not_eq operator or or_eq override private protected public \" +\n \"reinterpret_cast requires static_assert static_cast template this \" +\n \"thread_local throw try typeid typename using virtual xor xor_eq\";\n\nvar objCKeywords = \"bycopy byref in inout oneway out self super atomic nonatomic retain copy \" +\n \"readwrite readonly strong weak assign typeof nullable nonnull null_resettable _cmd \" +\n \"@interface @implementation @end @protocol @encode @property @synthesize @dynamic @class \" +\n \"@public @package @private @protected @required @optional @try @catch @finally @import \" +\n \"@selector @encode @defs @synchronized @autoreleasepool @compatibility_alias @available\";\n\nvar objCBuiltins = \"FOUNDATION_EXPORT FOUNDATION_EXTERN NS_INLINE NS_FORMAT_FUNCTION \" +\n \" NS_RETURNS_RETAINEDNS_ERROR_ENUM NS_RETURNS_NOT_RETAINED NS_RETURNS_INNER_POINTER \" +\n \"NS_DESIGNATED_INITIALIZER NS_ENUM NS_OPTIONS NS_REQUIRES_NIL_TERMINATION \" +\n \"NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_SWIFT_NAME NS_REFINED_FOR_SWIFT\"\n\n// Do not use this. Use the cTypes function below. This is global just to avoid\n// excessive calls when cTypes is being called multiple times during a parse.\nvar basicCTypes = words(\"int long char short double float unsigned signed \" +\n \"void bool\");\n\n// Do not use this. Use the objCTypes function below. This is global just to avoid\n// excessive calls when objCTypes is being called multiple times during a parse.\nvar basicObjCTypes = words(\"SEL instancetype id Class Protocol BOOL\");\n\n// Returns true if identifier is a \"C\" type.\n// C type is defined as those that are reserved by the compiler (basicTypes),\n// and those that end in _t (Reserved by POSIX for types)\n// http://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html\nfunction cTypes(identifier) {\n return contains(basicCTypes, identifier) || /.+_t$/.test(identifier);\n}\n\n// Returns true if identifier is a \"Objective C\" type.\nfunction objCTypes(identifier) {\n return cTypes(identifier) || contains(basicObjCTypes, identifier);\n}\n\nvar cBlockKeywords = \"case do else for if switch while struct enum union\";\nvar cDefKeywords = \"struct enum union\";\n\nfunction cppHook(stream, state) {\n if (!state.startOfLine) return false\n for (var ch, next = null; ch = stream.peek();) {\n if (ch == \"\\\\\" && stream.match(/^.$/)) {\n next = cppHook\n break\n } else if (ch == \"/\" && stream.match(/^\\/[\\/\\*]/, false)) {\n break\n }\n stream.next()\n }\n state.tokenize = next\n return \"meta\"\n}\n\nfunction pointerHook(_stream, state) {\n if (state.prevToken == \"type\") return \"type\";\n return false;\n}\n\n// For C and C++ (and ObjC): identifiers starting with __\n// or _ followed by a capital letter are reserved for the compiler.\nfunction cIsReservedIdentifier(token) {\n if (!token || token.length < 2) return false;\n if (token[0] != '_') return false;\n return (token[1] == '_') || (token[1] !== token[1].toLowerCase());\n}\n\nfunction cpp14Literal(stream) {\n stream.eatWhile(/[\\w\\.']/);\n return \"number\";\n}\n\nfunction cpp11StringHook(stream, state) {\n stream.backUp(1);\n // Raw strings.\n if (stream.match(/^(?:R|u8R|uR|UR|LR)/)) {\n var match = stream.match(/^\"([^\\s\\\\()]{0,16})\\(/);\n if (!match) {\n return false;\n }\n state.cpp11RawStringDelim = match[1];\n state.tokenize = tokenRawString;\n return tokenRawString(stream, state);\n }\n // Unicode strings/chars.\n if (stream.match(/^(?:u8|u|U|L)/)) {\n if (stream.match(/^[\"']/, /* eat */ false)) {\n return \"string\";\n }\n return false;\n }\n // Ignore this hook.\n stream.next();\n return false;\n}\n\nfunction cppLooksLikeConstructor(word) {\n var lastTwo = /(\\w+)::~?(\\w+)$/.exec(word);\n return lastTwo && lastTwo[1] == lastTwo[2];\n}\n\n// C#-style strings where \"\" escapes a quote.\nfunction tokenAtString(stream, state) {\n var next;\n while ((next = stream.next()) != null) {\n if (next == '\"' && !stream.eat('\"')) {\n state.tokenize = null;\n break;\n }\n }\n return \"string\";\n}\n\n// C++11 raw string literal is \"( anything )\", where\n// can be a string up to 16 characters long.\nfunction tokenRawString(stream, state) {\n // Escape characters that have special regex meanings.\n var delim = state.cpp11RawStringDelim.replace(/[^\\w\\s]/g, '\\\\$&');\n var match = stream.match(new RegExp(\".*?\\\\)\" + delim + '\"'));\n if (match)\n state.tokenize = null;\n else\n stream.skipToEnd();\n return \"string\";\n}\n\nexport const c = clike({\n name: \"c\",\n keywords: words(cKeywords),\n types: cTypes,\n blockKeywords: words(cBlockKeywords),\n defKeywords: words(cDefKeywords),\n typeFirstDefinitions: true,\n atoms: words(\"NULL true false\"),\n isReservedIdentifier: cIsReservedIdentifier,\n hooks: {\n \"#\": cppHook,\n \"*\": pointerHook,\n }\n})\n\nexport const cpp = clike({\n name: \"cpp\",\n keywords: words(cKeywords + \" \" + cppKeywords),\n types: cTypes,\n blockKeywords: words(cBlockKeywords + \" class try catch\"),\n defKeywords: words(cDefKeywords + \" class namespace\"),\n typeFirstDefinitions: true,\n atoms: words(\"true false NULL nullptr\"),\n dontIndentStatements: /^template$/,\n isIdentifierChar: /[\\w\\$_~\\xa1-\\uffff]/,\n isReservedIdentifier: cIsReservedIdentifier,\n hooks: {\n \"#\": cppHook,\n \"*\": pointerHook,\n \"u\": cpp11StringHook,\n \"U\": cpp11StringHook,\n \"L\": cpp11StringHook,\n \"R\": cpp11StringHook,\n \"0\": cpp14Literal,\n \"1\": cpp14Literal,\n \"2\": cpp14Literal,\n \"3\": cpp14Literal,\n \"4\": cpp14Literal,\n \"5\": cpp14Literal,\n \"6\": cpp14Literal,\n \"7\": cpp14Literal,\n \"8\": cpp14Literal,\n \"9\": cpp14Literal,\n token: function(stream, state, style) {\n if (style == \"variable\" && stream.peek() == \"(\" &&\n (state.prevToken == \";\" || state.prevToken == null ||\n state.prevToken == \"}\") &&\n cppLooksLikeConstructor(stream.current()))\n return \"def\";\n }\n },\n namespaceSeparator: \"::\"\n});\n\nexport const java = clike({\n name: \"java\",\n keywords: words(\"abstract assert break case catch class const continue default \" +\n \"do else enum extends final finally for goto if implements import \" +\n \"instanceof interface native new package private protected public \" +\n \"return static strictfp super switch synchronized this throw throws transient \" +\n \"try volatile while @interface\"),\n types: words(\"var byte short int long float double boolean char void Boolean Byte Character Double Float \" +\n \"Integer Long Number Object Short String StringBuffer StringBuilder Void\"),\n blockKeywords: words(\"catch class do else finally for if switch try while\"),\n defKeywords: words(\"class interface enum @interface\"),\n typeFirstDefinitions: true,\n atoms: words(\"true false null\"),\n number: /^(?:0x[a-f\\d_]+|0b[01_]+|(?:[\\d_]+\\.?\\d*|\\.\\d+)(?:e[-+]?[\\d_]+)?)(u|ll?|l|f)?/i,\n hooks: {\n \"@\": function(stream) {\n // Don't match the @interface keyword.\n if (stream.match('interface', false)) return false;\n\n stream.eatWhile(/[\\w\\$_]/);\n return \"meta\";\n },\n '\"': function(stream, state) {\n if (!stream.match(/\"\"$/)) return false;\n state.tokenize = tokenTripleString;\n return state.tokenize(stream, state);\n }\n }\n})\n\nexport const csharp = clike({\n name: \"csharp\",\n keywords: words(\"abstract as async await base break case catch checked class const continue\" +\n \" default delegate do else enum event explicit extern finally fixed for\" +\n \" foreach goto if implicit in init interface internal is lock namespace new\" +\n \" operator out override params private protected public readonly record ref required return sealed\" +\n \" sizeof stackalloc static struct switch this throw try typeof unchecked\" +\n \" unsafe using virtual void volatile while add alias ascending descending dynamic from get\" +\n \" global group into join let orderby partial remove select set value var yield\"),\n types: words(\"Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func\" +\n \" Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32\" +\n \" UInt64 bool byte char decimal double short int long object\" +\n \" sbyte float string ushort uint ulong\"),\n blockKeywords: words(\"catch class do else finally for foreach if struct switch try while\"),\n defKeywords: words(\"class interface namespace record struct var\"),\n typeFirstDefinitions: true,\n atoms: words(\"true false null\"),\n hooks: {\n \"@\": function(stream, state) {\n if (stream.eat('\"')) {\n state.tokenize = tokenAtString;\n return tokenAtString(stream, state);\n }\n stream.eatWhile(/[\\w\\$_]/);\n return \"meta\";\n }\n }\n});\n\nfunction tokenTripleString(stream, state) {\n var escaped = false;\n while (!stream.eol()) {\n if (!escaped && stream.match('\"\"\"')) {\n state.tokenize = null;\n break;\n }\n escaped = stream.next() == \"\\\\\" && !escaped;\n }\n return \"string\";\n}\n\nfunction tokenNestedComment(depth) {\n return function (stream, state) {\n var ch\n while (ch = stream.next()) {\n if (ch == \"*\" && stream.eat(\"/\")) {\n if (depth == 1) {\n state.tokenize = null\n break\n } else {\n state.tokenize = tokenNestedComment(depth - 1)\n return state.tokenize(stream, state)\n }\n } else if (ch == \"/\" && stream.eat(\"*\")) {\n state.tokenize = tokenNestedComment(depth + 1)\n return state.tokenize(stream, state)\n }\n }\n return \"comment\"\n }\n}\n\nexport const scala = clike({\n name: \"scala\",\n keywords: words(\n /* scala */\n \"abstract case catch class def do else extends final finally for forSome if \" +\n \"implicit import lazy match new null object override package private protected return \" +\n \"sealed super this throw trait try type val var while with yield _ \" +\n\n /* package scala */\n \"assert assume require print println printf readLine readBoolean readByte readShort \" +\n \"readChar readInt readLong readFloat readDouble\"\n ),\n types: words(\n \"AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either \" +\n \"Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable \" +\n \"Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering \" +\n \"Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder \" +\n \"StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector \" +\n\n /* package java.lang */\n \"Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable \" +\n \"Compiler Double Exception Float Integer Long Math Number Object Package Pair Process \" +\n \"Runtime Runnable SecurityManager Short StackTraceElement StrictMath String \" +\n \"StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void\"\n ),\n multiLineStrings: true,\n blockKeywords: words(\"catch class enum do else finally for forSome if match switch try while\"),\n defKeywords: words(\"class enum def object package trait type val var\"),\n atoms: words(\"true false null\"),\n indentStatements: false,\n indentSwitch: false,\n isOperatorChar: /[+\\-*&%=<>!?|\\/#:@]/,\n hooks: {\n \"@\": function(stream) {\n stream.eatWhile(/[\\w\\$_]/);\n return \"meta\";\n },\n '\"': function(stream, state) {\n if (!stream.match('\"\"')) return false;\n state.tokenize = tokenTripleString;\n return state.tokenize(stream, state);\n },\n \"'\": function(stream) {\n if (stream.match(/^(\\\\[^'\\s]+|[^\\\\'])'/)) return \"character\"\n stream.eatWhile(/[\\w\\$_\\xa1-\\uffff]/);\n return \"atom\";\n },\n \"=\": function(stream, state) {\n var cx = state.context\n if (cx.type == \"}\" && cx.align && stream.eat(\">\")) {\n state.context = new Context(cx.indented, cx.column, cx.type, cx.info, null, cx.prev)\n return \"operator\"\n } else {\n return false\n }\n },\n\n \"/\": function(stream, state) {\n if (!stream.eat(\"*\")) return false\n state.tokenize = tokenNestedComment(1)\n return state.tokenize(stream, state)\n }\n },\n languageData: {\n closeBrackets: {brackets: [\"(\", \"[\", \"{\", \"'\", '\"', '\"\"\"']}\n }\n});\n\nfunction tokenKotlinString(tripleString){\n return function (stream, state) {\n var escaped = false, next, end = false;\n while (!stream.eol()) {\n if (!tripleString && !escaped && stream.match('\"') ) {end = true; break;}\n if (tripleString && stream.match('\"\"\"')) {end = true; break;}\n next = stream.next();\n if(!escaped && next == \"$\" && stream.match('{'))\n stream.skipTo(\"}\");\n escaped = !escaped && next == \"\\\\\" && !tripleString;\n }\n if (end || !tripleString)\n state.tokenize = null;\n return \"string\";\n }\n}\n\nexport const kotlin = clike({\n name: \"kotlin\",\n keywords: words(\n /*keywords*/\n \"package as typealias class interface this super val operator \" +\n \"var fun for is in This throw return annotation \" +\n \"break continue object if else while do try when !in !is as? \" +\n\n /*soft keywords*/\n \"file import where by get set abstract enum open inner override private public internal \" +\n \"protected catch finally out final vararg reified dynamic companion constructor init \" +\n \"sealed field property receiver param sparam lateinit data inline noinline tailrec \" +\n \"external annotation crossinline const operator infix suspend actual expect setparam\"\n ),\n types: words(\n /* package java.lang */\n \"Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable \" +\n \"Compiler Double Exception Float Integer Long Math Number Object Package Pair Process \" +\n \"Runtime Runnable SecurityManager Short StackTraceElement StrictMath String \" +\n \"StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void Annotation Any BooleanArray \" +\n \"ByteArray Char CharArray DeprecationLevel DoubleArray Enum FloatArray Function Int IntArray Lazy \" +\n \"LazyThreadSafetyMode LongArray Nothing ShortArray Unit\"\n ),\n intendSwitch: false,\n indentStatements: false,\n multiLineStrings: true,\n number: /^(?:0x[a-f\\d_]+|0b[01_]+|(?:[\\d_]+(\\.\\d+)?|\\.\\d+)(?:e[-+]?[\\d_]+)?)(u|ll?|l|f)?/i,\n blockKeywords: words(\"catch class do else finally for if where try while enum\"),\n defKeywords: words(\"class val var object interface fun\"),\n atoms: words(\"true false null this\"),\n hooks: {\n \"@\": function(stream) {\n stream.eatWhile(/[\\w\\$_]/);\n return \"meta\";\n },\n '*': function(_stream, state) {\n return state.prevToken == '.' ? 'variable' : 'operator';\n },\n '\"': function(stream, state) {\n state.tokenize = tokenKotlinString(stream.match('\"\"'));\n return state.tokenize(stream, state);\n },\n \"/\": function(stream, state) {\n if (!stream.eat(\"*\")) return false;\n state.tokenize = tokenNestedComment(1);\n return state.tokenize(stream, state)\n },\n indent: function(state, ctx, textAfter, indentUnit) {\n var firstChar = textAfter && textAfter.charAt(0);\n if ((state.prevToken == \"}\" || state.prevToken == \")\") && textAfter == \"\")\n return state.indented;\n if ((state.prevToken == \"operator\" && textAfter != \"}\" && state.context.type != \"}\") ||\n state.prevToken == \"variable\" && firstChar == \".\" ||\n (state.prevToken == \"}\" || state.prevToken == \")\") && firstChar == \".\")\n return indentUnit * 2 + ctx.indented;\n if (ctx.align && ctx.type == \"}\")\n return ctx.indented + (state.context.type == (textAfter || \"\").charAt(0) ? 0 : indentUnit);\n }\n },\n languageData: {\n closeBrackets: {brackets: [\"(\", \"[\", \"{\", \"'\", '\"', '\"\"\"']}\n }\n});\n\nexport const shader = clike({\n name: \"shader\",\n keywords: words(\"sampler1D sampler2D sampler3D samplerCube \" +\n \"sampler1DShadow sampler2DShadow \" +\n \"const attribute uniform varying \" +\n \"break continue discard return \" +\n \"for while do if else struct \" +\n \"in out inout\"),\n types: words(\"float int bool void \" +\n \"vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 \" +\n \"mat2 mat3 mat4\"),\n blockKeywords: words(\"for while do if else struct\"),\n builtin: words(\"radians degrees sin cos tan asin acos atan \" +\n \"pow exp log exp2 sqrt inversesqrt \" +\n \"abs sign floor ceil fract mod min max clamp mix step smoothstep \" +\n \"length distance dot cross normalize ftransform faceforward \" +\n \"reflect refract matrixCompMult \" +\n \"lessThan lessThanEqual greaterThan greaterThanEqual \" +\n \"equal notEqual any all not \" +\n \"texture1D texture1DProj texture1DLod texture1DProjLod \" +\n \"texture2D texture2DProj texture2DLod texture2DProjLod \" +\n \"texture3D texture3DProj texture3DLod texture3DProjLod \" +\n \"textureCube textureCubeLod \" +\n \"shadow1D shadow2D shadow1DProj shadow2DProj \" +\n \"shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod \" +\n \"dFdx dFdy fwidth \" +\n \"noise1 noise2 noise3 noise4\"),\n atoms: words(\"true false \" +\n \"gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex \" +\n \"gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 \" +\n \"gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 \" +\n \"gl_FogCoord gl_PointCoord \" +\n \"gl_Position gl_PointSize gl_ClipVertex \" +\n \"gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor \" +\n \"gl_TexCoord gl_FogFragCoord \" +\n \"gl_FragCoord gl_FrontFacing \" +\n \"gl_FragData gl_FragDepth \" +\n \"gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix \" +\n \"gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse \" +\n \"gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse \" +\n \"gl_TextureMatrixTranspose gl_ModelViewMatrixInverseTranspose \" +\n \"gl_ProjectionMatrixInverseTranspose \" +\n \"gl_ModelViewProjectionMatrixInverseTranspose \" +\n \"gl_TextureMatrixInverseTranspose \" +\n \"gl_NormalScale gl_DepthRange gl_ClipPlane \" +\n \"gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel \" +\n \"gl_FrontLightModelProduct gl_BackLightModelProduct \" +\n \"gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ \" +\n \"gl_FogParameters \" +\n \"gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords \" +\n \"gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats \" +\n \"gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits \" +\n \"gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits \" +\n \"gl_MaxDrawBuffers\"),\n indentSwitch: false,\n hooks: {\"#\": cppHook}\n})\n\nexport const nesC = clike({\n name: \"nesc\",\n keywords: words(cKeywords + \" as atomic async call command component components configuration event generic \" +\n \"implementation includes interface module new norace nx_struct nx_union post provides \" +\n \"signal task uses abstract extends\"),\n types: cTypes,\n blockKeywords: words(cBlockKeywords),\n atoms: words(\"null true false\"),\n hooks: {\"#\": cppHook}\n})\n\nexport const objectiveC = clike({\n name: \"objectivec\",\n keywords: words(cKeywords + \" \" + objCKeywords),\n types: objCTypes,\n builtin: words(objCBuiltins),\n blockKeywords: words(cBlockKeywords + \" @synthesize @try @catch @finally @autoreleasepool @synchronized\"),\n defKeywords: words(cDefKeywords + \" @interface @implementation @protocol @class\"),\n dontIndentStatements: /^@.*$/,\n typeFirstDefinitions: true,\n atoms: words(\"YES NO NULL Nil nil true false nullptr\"),\n isReservedIdentifier: cIsReservedIdentifier,\n hooks: {\n \"#\": cppHook,\n \"*\": pointerHook,\n }\n})\n\nexport const objectiveCpp = clike({\n name: \"objectivecpp\",\n keywords: words(cKeywords + \" \" + objCKeywords + \" \" + cppKeywords),\n types: objCTypes,\n builtin: words(objCBuiltins),\n blockKeywords: words(cBlockKeywords + \" @synthesize @try @catch @finally @autoreleasepool @synchronized class try catch\"),\n defKeywords: words(cDefKeywords + \" @interface @implementation @protocol @class class namespace\"),\n dontIndentStatements: /^@.*$|^template$/,\n typeFirstDefinitions: true,\n atoms: words(\"YES NO NULL Nil nil true false nullptr\"),\n isReservedIdentifier: cIsReservedIdentifier,\n hooks: {\n \"#\": cppHook,\n \"*\": pointerHook,\n \"u\": cpp11StringHook,\n \"U\": cpp11StringHook,\n \"L\": cpp11StringHook,\n \"R\": cpp11StringHook,\n \"0\": cpp14Literal,\n \"1\": cpp14Literal,\n \"2\": cpp14Literal,\n \"3\": cpp14Literal,\n \"4\": cpp14Literal,\n \"5\": cpp14Literal,\n \"6\": cpp14Literal,\n \"7\": cpp14Literal,\n \"8\": cpp14Literal,\n \"9\": cpp14Literal,\n token: function(stream, state, style) {\n if (style == \"variable\" && stream.peek() == \"(\" &&\n (state.prevToken == \";\" || state.prevToken == null ||\n state.prevToken == \"}\") &&\n cppLooksLikeConstructor(stream.current()))\n return \"def\";\n }\n },\n namespaceSeparator: \"::\"\n})\n\nexport const squirrel = clike({\n name: \"squirrel\",\n keywords: words(\"base break clone continue const default delete enum extends function in class\" +\n \" foreach local resume return this throw typeof yield constructor instanceof static\"),\n types: cTypes,\n blockKeywords: words(\"case catch class else for foreach if switch try while\"),\n defKeywords: words(\"function local class\"),\n typeFirstDefinitions: true,\n atoms: words(\"true false null\"),\n hooks: {\"#\": cppHook}\n})\n\n// Ceylon Strings need to deal with interpolation\nvar stringTokenizer = null;\nfunction tokenCeylonString(type) {\n return function(stream, state) {\n var escaped = false, next, end = false;\n while (!stream.eol()) {\n if (!escaped && stream.match('\"') &&\n (type == \"single\" || stream.match('\"\"'))) {\n end = true;\n break;\n }\n if (!escaped && stream.match('``')) {\n stringTokenizer = tokenCeylonString(type);\n end = true;\n break;\n }\n next = stream.next();\n escaped = type == \"single\" && !escaped && next == \"\\\\\";\n }\n if (end)\n state.tokenize = null;\n return \"string\";\n }\n}\n\nexport const ceylon = clike({\n name: \"ceylon\",\n keywords: words(\"abstracts alias assembly assert assign break case catch class continue dynamic else\" +\n \" exists extends finally for function given if import in interface is let module new\" +\n \" nonempty object of out outer package return satisfies super switch then this throw\" +\n \" try value void while\"),\n types: function(word) {\n // In Ceylon all identifiers that start with an uppercase are types\n var first = word.charAt(0);\n return (first === first.toUpperCase() && first !== first.toLowerCase());\n },\n blockKeywords: words(\"case catch class dynamic else finally for function if interface module new object switch try while\"),\n defKeywords: words(\"class dynamic function interface module object package value\"),\n builtin: words(\"abstract actual aliased annotation by default deprecated doc final formal late license\" +\n \" native optional sealed see serializable shared suppressWarnings tagged throws variable\"),\n isPunctuationChar: /[\\[\\]{}\\(\\),;\\:\\.`]/,\n isOperatorChar: /[+\\-*&%=<>!?|^~:\\/]/,\n numberStart: /[\\d#$]/,\n number: /^(?:#[\\da-fA-F_]+|\\$[01_]+|[\\d_]+[kMGTPmunpf]?|[\\d_]+\\.[\\d_]+(?:[eE][-+]?\\d+|[kMGTPmunpf]|)|)/i,\n multiLineStrings: true,\n typeFirstDefinitions: true,\n atoms: words(\"true false null larger smaller equal empty finished\"),\n indentSwitch: false,\n styleDefs: false,\n hooks: {\n \"@\": function(stream) {\n stream.eatWhile(/[\\w\\$_]/);\n return \"meta\";\n },\n '\"': function(stream, state) {\n state.tokenize = tokenCeylonString(stream.match('\"\"') ? \"triple\" : \"single\");\n return state.tokenize(stream, state);\n },\n '`': function(stream, state) {\n if (!stringTokenizer || !stream.match('`')) return false;\n state.tokenize = stringTokenizer;\n stringTokenizer = null;\n return state.tokenize(stream, state);\n },\n \"'\": function(stream) {\n if (stream.match(/^(\\\\[^'\\s]+|[^\\\\'])'/)) return \"string.special\"\n stream.eatWhile(/[\\w\\$_\\xa1-\\uffff]/);\n return \"atom\";\n },\n token: function(_stream, state, style) {\n if ((style == \"variable\" || style == \"type\") &&\n state.prevToken == \".\") {\n return \"variableName.special\";\n }\n }\n },\n languageData: {\n closeBrackets: {brackets: [\"(\", \"[\", \"{\", \"'\", '\"', '\"\"\"']}\n }\n})\n\nfunction pushInterpolationStack(state) {\n (state.interpolationStack || (state.interpolationStack = [])).push(state.tokenize);\n}\n\nfunction popInterpolationStack(state) {\n return (state.interpolationStack || (state.interpolationStack = [])).pop();\n}\n\nfunction sizeInterpolationStack(state) {\n return state.interpolationStack ? state.interpolationStack.length : 0;\n}\n\nfunction tokenDartString(quote, stream, state, raw) {\n var tripleQuoted = false;\n if (stream.eat(quote)) {\n if (stream.eat(quote)) tripleQuoted = true;\n else return \"string\"; //empty string\n }\n function tokenStringHelper(stream, state) {\n var escaped = false;\n while (!stream.eol()) {\n if (!raw && !escaped && stream.peek() == \"$\") {\n pushInterpolationStack(state);\n state.tokenize = tokenInterpolation;\n return \"string\";\n }\n var next = stream.next();\n if (next == quote && !escaped && (!tripleQuoted || stream.match(quote + quote))) {\n state.tokenize = null;\n break;\n }\n escaped = !raw && !escaped && next == \"\\\\\";\n }\n return \"string\";\n }\n state.tokenize = tokenStringHelper;\n return tokenStringHelper(stream, state);\n}\n\nfunction tokenInterpolation(stream, state) {\n stream.eat(\"$\");\n if (stream.eat(\"{\")) {\n // let clike handle the content of ${...},\n // we take over again when \"}\" appears (see hooks).\n state.tokenize = null;\n } else {\n state.tokenize = tokenInterpolationIdentifier;\n }\n return null;\n}\n\nfunction tokenInterpolationIdentifier(stream, state) {\n stream.eatWhile(/[\\w_]/);\n state.tokenize = popInterpolationStack(state);\n return \"variable\";\n}\n\nexport const dart = clike({\n name: \"dart\",\n keywords: words(\"this super static final const abstract class extends external factory \" +\n \"implements mixin get native set typedef with enum throw rethrow assert break case \" +\n \"continue default in return new deferred async await covariant try catch finally \" +\n \"do else for if switch while import library export part of show hide is as extension \" +\n \"on yield late required sealed base interface when inline\"),\n blockKeywords: words(\"try catch finally do else for if switch while\"),\n builtin: words(\"void bool num int double dynamic var String Null Never\"),\n atoms: words(\"true false null\"),\n hooks: {\n \"@\": function(stream) {\n stream.eatWhile(/[\\w\\$_\\.]/);\n return \"meta\";\n },\n\n // custom string handling to deal with triple-quoted strings and string interpolation\n \"'\": function(stream, state) {\n return tokenDartString(\"'\", stream, state, false);\n },\n \"\\\"\": function(stream, state) {\n return tokenDartString(\"\\\"\", stream, state, false);\n },\n \"r\": function(stream, state) {\n var peek = stream.peek();\n if (peek == \"'\" || peek == \"\\\"\") {\n return tokenDartString(stream.next(), stream, state, true);\n }\n return false;\n },\n\n \"}\": function(_stream, state) {\n // \"}\" is end of interpolation, if interpolation stack is non-empty\n if (sizeInterpolationStack(state) > 0) {\n state.tokenize = popInterpolationStack(state);\n return null;\n }\n return false;\n },\n\n \"/\": function(stream, state) {\n if (!stream.eat(\"*\")) return false\n state.tokenize = tokenNestedComment(1)\n return state.tokenize(stream, state)\n },\n token: function(stream, _, style) {\n if (style == \"variable\") {\n // Assume uppercase symbols are classes\n var isUpper = RegExp('^[_$]*[A-Z][a-zA-Z0-9_$]*$','g');\n if (isUpper.test(stream.current())) {\n return 'type';\n }\n }\n }\n }\n})\n"],"names":["Context","indented","column","type","info","align","prev","this","pushContext","state","col","indent","context","popContext","t","typeBefore","stream","pos","prevToken","test","string","slice","typeAtEndOfLine","indentation","isTopScope","clike","parserConfig","curPunc","isDefKeyword","statementIndentUnit","dontAlignCalls","keywords","types","builtin","blockKeywords","defKeywords","atoms","hooks","multiLineStrings","indentStatements","indentSwitch","namespaceSeparator","isPunctuationChar","numberStart","number","isOperatorChar","isIdentifierChar","isReservedIdentifier","tokenBase","quote","ch","next","result","tokenize","escaped","end","backUp","match","eat","tokenComment","skipToEnd","eatWhile","cur","current","contains","maybeEnd","maybeEOL","typeFirstDefinitions","eol","name","startState","indentUnit","startOfLine","token","ctx","sol","eatSpace","style","start","undefined","styleDefs","textAfter","firstChar","charAt","closing","dontIndentStatements","hook","unit","switchBlock","allmanIndentation","languageData","indentOnInput","commentTokens","line","block","open","close","autocomplete","Object","keys","concat","words","str","obj","split","i","length","word","propertyIsEnumerable","cKeywords","cppKeywords","objCKeywords","objCBuiltins","basicCTypes","basicObjCTypes","cTypes","identifier","objCTypes","cBlockKeywords","cDefKeywords","cppHook","peek","pointerHook","_stream","cIsReservedIdentifier","toLowerCase","cpp14Literal","cpp11StringHook","cpp11RawStringDelim","tokenRawString","cppLooksLikeConstructor","lastTwo","exec","tokenAtString","delim","replace","RegExp","c","cpp","java","tokenTripleString","csharp","tokenNestedComment","depth","scala","cx","closeBrackets","brackets","kotlin","intendSwitch","tripleString","skipTo","shader","nesC","objectiveC","objectiveCpp","squirrel","stringTokenizer","tokenCeylonString","ceylon","first","toUpperCase","pushInterpolationStack","interpolationStack","push","popInterpolationStack","pop","tokenDartString","raw","tripleQuoted","tokenStringHelper","tokenInterpolation","tokenInterpolationIdentifier","dart","sizeInterpolationStack","_"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/5808.index.js b/book/_build/html/_static/5808.index.js new file mode 100644 index 0000000..a92a234 --- /dev/null +++ b/book/_build/html/_static/5808.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[5808],{45808:(e,t,n)=>{n.r(t),n.d(t,{clojure:()=>g});var r=["false","nil","true"],a=[".","catch","def","do","if","monitor-enter","monitor-exit","new","quote","recur","set!","throw","try","var"],s=["*","*'","*1","*2","*3","*agent*","*allow-unresolved-vars*","*assert*","*clojure-version*","*command-line-args*","*compile-files*","*compile-path*","*compiler-options*","*data-readers*","*default-data-reader-fn*","*e","*err*","*file*","*flush-on-newline*","*fn-loader*","*in*","*math-context*","*ns*","*out*","*print-dup*","*print-length*","*print-level*","*print-meta*","*print-namespace-maps*","*print-readably*","*read-eval*","*reader-resolver*","*source-path*","*suppress-read*","*unchecked-math*","*use-context-classloader*","*verbose-defrecords*","*warn-on-reflection*","+","+'","-","-'","->","->>","->ArrayChunk","->Eduction","->Vec","->VecNode","->VecSeq","-cache-protocol-fn","-reset-methods","..","/","<","<=","=","==",">",">=","EMPTY-NODE","Inst","StackTraceElement->vec","Throwable->map","accessor","aclone","add-classpath","add-watch","agent","agent-error","agent-errors","aget","alength","alias","all-ns","alter","alter-meta!","alter-var-root","amap","ancestors","and","any?","apply","areduce","array-map","as->","aset","aset-boolean","aset-byte","aset-char","aset-double","aset-float","aset-int","aset-long","aset-short","assert","assoc","assoc!","assoc-in","associative?","atom","await","await-for","await1","bases","bean","bigdec","bigint","biginteger","binding","bit-and","bit-and-not","bit-clear","bit-flip","bit-not","bit-or","bit-set","bit-shift-left","bit-shift-right","bit-test","bit-xor","boolean","boolean-array","boolean?","booleans","bound-fn","bound-fn*","bound?","bounded-count","butlast","byte","byte-array","bytes","bytes?","case","cast","cat","char","char-array","char-escape-string","char-name-string","char?","chars","chunk","chunk-append","chunk-buffer","chunk-cons","chunk-first","chunk-next","chunk-rest","chunked-seq?","class","class?","clear-agent-errors","clojure-version","coll?","comment","commute","comp","comparator","compare","compare-and-set!","compile","complement","completing","concat","cond","cond->","cond->>","condp","conj","conj!","cons","constantly","construct-proxy","contains?","count","counted?","create-ns","create-struct","cycle","dec","dec'","decimal?","declare","dedupe","default-data-readers","definline","definterface","defmacro","defmethod","defmulti","defn","defn-","defonce","defprotocol","defrecord","defstruct","deftype","delay","delay?","deliver","denominator","deref","derive","descendants","destructure","disj","disj!","dissoc","dissoc!","distinct","distinct?","doall","dorun","doseq","dosync","dotimes","doto","double","double-array","double?","doubles","drop","drop-last","drop-while","eduction","empty","empty?","ensure","ensure-reduced","enumeration-seq","error-handler","error-mode","eval","even?","every-pred","every?","ex-data","ex-info","extend","extend-protocol","extend-type","extenders","extends?","false?","ffirst","file-seq","filter","filterv","find","find-keyword","find-ns","find-protocol-impl","find-protocol-method","find-var","first","flatten","float","float-array","float?","floats","flush","fn","fn?","fnext","fnil","for","force","format","frequencies","future","future-call","future-cancel","future-cancelled?","future-done?","future?","gen-class","gen-interface","gensym","get","get-in","get-method","get-proxy-class","get-thread-bindings","get-validator","group-by","halt-when","hash","hash-combine","hash-map","hash-ordered-coll","hash-set","hash-unordered-coll","ident?","identical?","identity","if-let","if-not","if-some","ifn?","import","in-ns","inc","inc'","indexed?","init-proxy","inst-ms","inst-ms*","inst?","instance?","int","int-array","int?","integer?","interleave","intern","interpose","into","into-array","ints","io!","isa?","iterate","iterator-seq","juxt","keep","keep-indexed","key","keys","keyword","keyword?","last","lazy-cat","lazy-seq","let","letfn","line-seq","list","list*","list?","load","load-file","load-reader","load-string","loaded-libs","locking","long","long-array","longs","loop","macroexpand","macroexpand-1","make-array","make-hierarchy","map","map-entry?","map-indexed","map?","mapcat","mapv","max","max-key","memfn","memoize","merge","merge-with","meta","method-sig","methods","min","min-key","mix-collection-hash","mod","munge","name","namespace","namespace-munge","nat-int?","neg-int?","neg?","newline","next","nfirst","nil?","nnext","not","not-any?","not-empty","not-every?","not=","ns","ns-aliases","ns-imports","ns-interns","ns-map","ns-name","ns-publics","ns-refers","ns-resolve","ns-unalias","ns-unmap","nth","nthnext","nthrest","num","number?","numerator","object-array","odd?","or","parents","partial","partition","partition-all","partition-by","pcalls","peek","persistent!","pmap","pop","pop!","pop-thread-bindings","pos-int?","pos?","pr","pr-str","prefer-method","prefers","primitives-classnames","print","print-ctor","print-dup","print-method","print-simple","print-str","printf","println","println-str","prn","prn-str","promise","proxy","proxy-call-with-super","proxy-mappings","proxy-name","proxy-super","push-thread-bindings","pvalues","qualified-ident?","qualified-keyword?","qualified-symbol?","quot","rand","rand-int","rand-nth","random-sample","range","ratio?","rational?","rationalize","re-find","re-groups","re-matcher","re-matches","re-pattern","re-seq","read","read-line","read-string","reader-conditional","reader-conditional?","realized?","record?","reduce","reduce-kv","reduced","reduced?","reductions","ref","ref-history-count","ref-max-history","ref-min-history","ref-set","refer","refer-clojure","reify","release-pending-sends","rem","remove","remove-all-methods","remove-method","remove-ns","remove-watch","repeat","repeatedly","replace","replicate","require","reset!","reset-meta!","reset-vals!","resolve","rest","restart-agent","resultset-seq","reverse","reversible?","rseq","rsubseq","run!","satisfies?","second","select-keys","send","send-off","send-via","seq","seq?","seqable?","seque","sequence","sequential?","set","set-agent-send-executor!","set-agent-send-off-executor!","set-error-handler!","set-error-mode!","set-validator!","set?","short","short-array","shorts","shuffle","shutdown-agents","simple-ident?","simple-keyword?","simple-symbol?","slurp","some","some->","some->>","some-fn","some?","sort","sort-by","sorted-map","sorted-map-by","sorted-set","sorted-set-by","sorted?","special-symbol?","spit","split-at","split-with","str","string?","struct","struct-map","subs","subseq","subvec","supers","swap!","swap-vals!","symbol","symbol?","sync","tagged-literal","tagged-literal?","take","take-last","take-nth","take-while","test","the-ns","thread-bound?","time","to-array","to-array-2d","trampoline","transduce","transient","tree-seq","true?","type","unchecked-add","unchecked-add-int","unchecked-byte","unchecked-char","unchecked-dec","unchecked-dec-int","unchecked-divide-int","unchecked-double","unchecked-float","unchecked-inc","unchecked-inc-int","unchecked-int","unchecked-long","unchecked-multiply","unchecked-multiply-int","unchecked-negate","unchecked-negate-int","unchecked-remainder-int","unchecked-short","unchecked-subtract","unchecked-subtract-int","underive","unquote","unquote-splicing","unreduced","unsigned-bit-shift-right","update","update-in","update-proxy","uri?","use","uuid?","val","vals","var-get","var-set","var?","vary-meta","vec","vector","vector-of","vector?","volatile!","volatile?","vreset!","vswap!","when","when-first","when-let","when-not","when-some","while","with-bindings","with-bindings*","with-in-str","with-loading-context","with-local-vars","with-meta","with-open","with-out-str","with-precision","with-redefs","with-redefs-fn","xml-seq","zero?","zipmap"],o=y(r),i=y(a),c=y(s),d=y(["->","->>","as->","binding","bound-fn","case","catch","comment","cond","cond->","cond->>","condp","def","definterface","defmethod","defn","defmacro","defprotocol","defrecord","defstruct","deftype","do","doseq","dotimes","doto","extend","extend-protocol","extend-type","fn","for","future","if","if-let","if-not","if-some","let","letfn","locking","loop","ns","proxy","reify","struct-map","some->","some->>","try","when","when-first","when-let","when-not","when-some","while","with-bindings","with-bindings*","with-in-str","with-loading-context","with-local-vars","with-meta","with-open","with-out-str","with-precision","with-redefs","with-redefs-fn"]),l=/^(?:[\\\[\]\s"(),;@^`{}~]|$)/,u=/^(?:[+\-]?\d+(?:(?:N|(?:[eE][+\-]?\d+))|(?:\.?\d*(?:M|(?:[eE][+\-]?\d+))?)|\/\d+|[xX][0-9a-fA-F]+|r[0-9a-zA-Z]+)?(?=[\\\[\]\s"#'(),;@^`{}~]|$))/,p=/^(?:\\(?:backspace|formfeed|newline|return|space|tab|o[0-7]{3}|u[0-9A-Fa-f]{4}|x[0-9A-Fa-f]{4}|.)?(?=[\\\[\]\s"(),;@^`{}~]|$))/,m=/^(?:(?:[^\\\/\[\]\d\s"#'(),;@^`{}~.][^\\\[\]\s"(),;@^`{}~.\/]*(?:\.[^\\\/\[\]\d\s"#'(),;@^`{}~.][^\\\[\]\s"(),;@^`{}~.\/]*)*\/)?(?:\/|[^\\\/\[\]\d\s"#'(),;@^`{}~][^\\\[\]\s"(),;@^`{}~]*)*(?=[\\\[\]\s"(),;@^`{}~]|$))/;function f(e,t){if(e.eatSpace()||e.eat(","))return["space",null];if(e.match(u))return[null,"number"];if(e.match(p))return[null,"string.special"];if(e.eat(/^"/))return(t.tokenize=h)(e,t);if(e.eat(/^[(\[{]/))return["open","bracket"];if(e.eat(/^[)\]}]/))return["close","bracket"];if(e.eat(/^;/))return e.skipToEnd(),["space","comment"];if(e.eat(/^[#'@^`~]/))return[null,"meta"];var n=e.match(m),r=n&&n[0];return r?"comment"===r&&"("===t.lastToken?(t.tokenize=b)(e,t):k(r,o)||":"===r.charAt(0)?["symbol","atom"]:k(r,i)||k(r,c)?["symbol","keyword"]:"("===t.lastToken?["symbol","builtin"]:["symbol","variable"]:(e.next(),e.eatWhile((function(e){return!k(e,l)})),[null,"error"])}function h(e,t){for(var n,r=!1;n=e.next();){if('"'===n&&!r){t.tokenize=f;break}r=!r&&"\\"===n}return[null,"string"]}function b(e,t){for(var n,r=1;n=e.next();)if(")"===n&&r--,"("===n&&r++,0===r){e.backUp(1),t.tokenize=f;break}return["space","comment"]}function y(e){for(var t={},n=0;n\", \"->>\", \"->ArrayChunk\", \"->Eduction\", \"->Vec\", \"->VecNode\",\n \"->VecSeq\", \"-cache-protocol-fn\", \"-reset-methods\", \"..\", \"/\", \"<\", \"<=\",\n \"=\", \"==\", \">\", \">=\", \"EMPTY-NODE\", \"Inst\", \"StackTraceElement->vec\",\n \"Throwable->map\", \"accessor\", \"aclone\", \"add-classpath\", \"add-watch\",\n \"agent\", \"agent-error\", \"agent-errors\", \"aget\", \"alength\", \"alias\",\n \"all-ns\", \"alter\", \"alter-meta!\", \"alter-var-root\", \"amap\", \"ancestors\",\n \"and\", \"any?\", \"apply\", \"areduce\", \"array-map\", \"as->\", \"aset\",\n \"aset-boolean\", \"aset-byte\", \"aset-char\", \"aset-double\", \"aset-float\",\n \"aset-int\", \"aset-long\", \"aset-short\", \"assert\", \"assoc\", \"assoc!\",\n \"assoc-in\", \"associative?\", \"atom\", \"await\", \"await-for\", \"await1\",\n \"bases\", \"bean\", \"bigdec\", \"bigint\", \"biginteger\", \"binding\", \"bit-and\",\n \"bit-and-not\", \"bit-clear\", \"bit-flip\", \"bit-not\", \"bit-or\", \"bit-set\",\n \"bit-shift-left\", \"bit-shift-right\", \"bit-test\", \"bit-xor\", \"boolean\",\n \"boolean-array\", \"boolean?\", \"booleans\", \"bound-fn\", \"bound-fn*\",\n \"bound?\", \"bounded-count\", \"butlast\", \"byte\", \"byte-array\", \"bytes\",\n \"bytes?\", \"case\", \"cast\", \"cat\", \"char\", \"char-array\",\n \"char-escape-string\", \"char-name-string\", \"char?\", \"chars\", \"chunk\",\n \"chunk-append\", \"chunk-buffer\", \"chunk-cons\", \"chunk-first\", \"chunk-next\",\n \"chunk-rest\", \"chunked-seq?\", \"class\", \"class?\", \"clear-agent-errors\",\n \"clojure-version\", \"coll?\", \"comment\", \"commute\", \"comp\", \"comparator\",\n \"compare\", \"compare-and-set!\", \"compile\", \"complement\", \"completing\",\n \"concat\", \"cond\", \"cond->\", \"cond->>\", \"condp\", \"conj\", \"conj!\", \"cons\",\n \"constantly\", \"construct-proxy\", \"contains?\", \"count\", \"counted?\",\n \"create-ns\", \"create-struct\", \"cycle\", \"dec\", \"dec'\", \"decimal?\",\n \"declare\", \"dedupe\", \"default-data-readers\", \"definline\", \"definterface\",\n \"defmacro\", \"defmethod\", \"defmulti\", \"defn\", \"defn-\", \"defonce\",\n \"defprotocol\", \"defrecord\", \"defstruct\", \"deftype\", \"delay\", \"delay?\",\n \"deliver\", \"denominator\", \"deref\", \"derive\", \"descendants\", \"destructure\",\n \"disj\", \"disj!\", \"dissoc\", \"dissoc!\", \"distinct\", \"distinct?\", \"doall\",\n \"dorun\", \"doseq\", \"dosync\", \"dotimes\", \"doto\", \"double\", \"double-array\",\n \"double?\", \"doubles\", \"drop\", \"drop-last\", \"drop-while\", \"eduction\",\n \"empty\", \"empty?\", \"ensure\", \"ensure-reduced\", \"enumeration-seq\",\n \"error-handler\", \"error-mode\", \"eval\", \"even?\", \"every-pred\", \"every?\",\n \"ex-data\", \"ex-info\", \"extend\", \"extend-protocol\", \"extend-type\",\n \"extenders\", \"extends?\", \"false?\", \"ffirst\", \"file-seq\", \"filter\",\n \"filterv\", \"find\", \"find-keyword\", \"find-ns\", \"find-protocol-impl\",\n \"find-protocol-method\", \"find-var\", \"first\", \"flatten\", \"float\",\n \"float-array\", \"float?\", \"floats\", \"flush\", \"fn\", \"fn?\", \"fnext\", \"fnil\",\n \"for\", \"force\", \"format\", \"frequencies\", \"future\", \"future-call\",\n \"future-cancel\", \"future-cancelled?\", \"future-done?\", \"future?\",\n \"gen-class\", \"gen-interface\", \"gensym\", \"get\", \"get-in\", \"get-method\",\n \"get-proxy-class\", \"get-thread-bindings\", \"get-validator\", \"group-by\",\n \"halt-when\", \"hash\", \"hash-combine\", \"hash-map\", \"hash-ordered-coll\",\n \"hash-set\", \"hash-unordered-coll\", \"ident?\", \"identical?\", \"identity\",\n \"if-let\", \"if-not\", \"if-some\", \"ifn?\", \"import\", \"in-ns\", \"inc\", \"inc'\",\n \"indexed?\", \"init-proxy\", \"inst-ms\", \"inst-ms*\", \"inst?\", \"instance?\",\n \"int\", \"int-array\", \"int?\", \"integer?\", \"interleave\", \"intern\",\n \"interpose\", \"into\", \"into-array\", \"ints\", \"io!\", \"isa?\", \"iterate\",\n \"iterator-seq\", \"juxt\", \"keep\", \"keep-indexed\", \"key\", \"keys\", \"keyword\",\n \"keyword?\", \"last\", \"lazy-cat\", \"lazy-seq\", \"let\", \"letfn\", \"line-seq\",\n \"list\", \"list*\", \"list?\", \"load\", \"load-file\", \"load-reader\",\n \"load-string\", \"loaded-libs\", \"locking\", \"long\", \"long-array\", \"longs\",\n \"loop\", \"macroexpand\", \"macroexpand-1\", \"make-array\", \"make-hierarchy\",\n \"map\", \"map-entry?\", \"map-indexed\", \"map?\", \"mapcat\", \"mapv\", \"max\",\n \"max-key\", \"memfn\", \"memoize\", \"merge\", \"merge-with\", \"meta\",\n \"method-sig\", \"methods\", \"min\", \"min-key\", \"mix-collection-hash\", \"mod\",\n \"munge\", \"name\", \"namespace\", \"namespace-munge\", \"nat-int?\", \"neg-int?\",\n \"neg?\", \"newline\", \"next\", \"nfirst\", \"nil?\", \"nnext\", \"not\", \"not-any?\",\n \"not-empty\", \"not-every?\", \"not=\", \"ns\", \"ns-aliases\", \"ns-imports\",\n \"ns-interns\", \"ns-map\", \"ns-name\", \"ns-publics\", \"ns-refers\",\n \"ns-resolve\", \"ns-unalias\", \"ns-unmap\", \"nth\", \"nthnext\", \"nthrest\",\n \"num\", \"number?\", \"numerator\", \"object-array\", \"odd?\", \"or\", \"parents\",\n \"partial\", \"partition\", \"partition-all\", \"partition-by\", \"pcalls\", \"peek\",\n \"persistent!\", \"pmap\", \"pop\", \"pop!\", \"pop-thread-bindings\", \"pos-int?\",\n \"pos?\", \"pr\", \"pr-str\", \"prefer-method\", \"prefers\",\n \"primitives-classnames\", \"print\", \"print-ctor\", \"print-dup\",\n \"print-method\", \"print-simple\", \"print-str\", \"printf\", \"println\",\n \"println-str\", \"prn\", \"prn-str\", \"promise\", \"proxy\",\n \"proxy-call-with-super\", \"proxy-mappings\", \"proxy-name\", \"proxy-super\",\n \"push-thread-bindings\", \"pvalues\", \"qualified-ident?\",\n \"qualified-keyword?\", \"qualified-symbol?\", \"quot\", \"rand\", \"rand-int\",\n \"rand-nth\", \"random-sample\", \"range\", \"ratio?\", \"rational?\",\n \"rationalize\", \"re-find\", \"re-groups\", \"re-matcher\", \"re-matches\",\n \"re-pattern\", \"re-seq\", \"read\", \"read-line\", \"read-string\",\n \"reader-conditional\", \"reader-conditional?\", \"realized?\", \"record?\",\n \"reduce\", \"reduce-kv\", \"reduced\", \"reduced?\", \"reductions\", \"ref\",\n \"ref-history-count\", \"ref-max-history\", \"ref-min-history\", \"ref-set\",\n \"refer\", \"refer-clojure\", \"reify\", \"release-pending-sends\", \"rem\",\n \"remove\", \"remove-all-methods\", \"remove-method\", \"remove-ns\",\n \"remove-watch\", \"repeat\", \"repeatedly\", \"replace\", \"replicate\", \"require\",\n \"reset!\", \"reset-meta!\", \"reset-vals!\", \"resolve\", \"rest\",\n \"restart-agent\", \"resultset-seq\", \"reverse\", \"reversible?\", \"rseq\",\n \"rsubseq\", \"run!\", \"satisfies?\", \"second\", \"select-keys\", \"send\",\n \"send-off\", \"send-via\", \"seq\", \"seq?\", \"seqable?\", \"seque\", \"sequence\",\n \"sequential?\", \"set\", \"set-agent-send-executor!\",\n \"set-agent-send-off-executor!\", \"set-error-handler!\", \"set-error-mode!\",\n \"set-validator!\", \"set?\", \"short\", \"short-array\", \"shorts\", \"shuffle\",\n \"shutdown-agents\", \"simple-ident?\", \"simple-keyword?\", \"simple-symbol?\",\n \"slurp\", \"some\", \"some->\", \"some->>\", \"some-fn\", \"some?\", \"sort\",\n \"sort-by\", \"sorted-map\", \"sorted-map-by\", \"sorted-set\", \"sorted-set-by\",\n \"sorted?\", \"special-symbol?\", \"spit\", \"split-at\", \"split-with\", \"str\",\n \"string?\", \"struct\", \"struct-map\", \"subs\", \"subseq\", \"subvec\", \"supers\",\n \"swap!\", \"swap-vals!\", \"symbol\", \"symbol?\", \"sync\", \"tagged-literal\",\n \"tagged-literal?\", \"take\", \"take-last\", \"take-nth\", \"take-while\", \"test\",\n \"the-ns\", \"thread-bound?\", \"time\", \"to-array\", \"to-array-2d\",\n \"trampoline\", \"transduce\", \"transient\", \"tree-seq\", \"true?\", \"type\",\n \"unchecked-add\", \"unchecked-add-int\", \"unchecked-byte\", \"unchecked-char\",\n \"unchecked-dec\", \"unchecked-dec-int\", \"unchecked-divide-int\",\n \"unchecked-double\", \"unchecked-float\", \"unchecked-inc\",\n \"unchecked-inc-int\", \"unchecked-int\", \"unchecked-long\",\n \"unchecked-multiply\", \"unchecked-multiply-int\", \"unchecked-negate\",\n \"unchecked-negate-int\", \"unchecked-remainder-int\", \"unchecked-short\",\n \"unchecked-subtract\", \"unchecked-subtract-int\", \"underive\", \"unquote\",\n \"unquote-splicing\", \"unreduced\", \"unsigned-bit-shift-right\", \"update\",\n \"update-in\", \"update-proxy\", \"uri?\", \"use\", \"uuid?\", \"val\", \"vals\",\n \"var-get\", \"var-set\", \"var?\", \"vary-meta\", \"vec\", \"vector\", \"vector-of\",\n \"vector?\", \"volatile!\", \"volatile?\", \"vreset!\", \"vswap!\", \"when\",\n \"when-first\", \"when-let\", \"when-not\", \"when-some\", \"while\",\n \"with-bindings\", \"with-bindings*\", \"with-in-str\", \"with-loading-context\",\n \"with-local-vars\", \"with-meta\", \"with-open\", \"with-out-str\",\n \"with-precision\", \"with-redefs\", \"with-redefs-fn\", \"xml-seq\", \"zero?\",\n \"zipmap\"];\nvar haveBodyParameter = [\n \"->\", \"->>\", \"as->\", \"binding\", \"bound-fn\", \"case\", \"catch\", \"comment\",\n \"cond\", \"cond->\", \"cond->>\", \"condp\", \"def\", \"definterface\", \"defmethod\",\n \"defn\", \"defmacro\", \"defprotocol\", \"defrecord\", \"defstruct\", \"deftype\",\n \"do\", \"doseq\", \"dotimes\", \"doto\", \"extend\", \"extend-protocol\",\n \"extend-type\", \"fn\", \"for\", \"future\", \"if\", \"if-let\", \"if-not\", \"if-some\",\n \"let\", \"letfn\", \"locking\", \"loop\", \"ns\", \"proxy\", \"reify\", \"struct-map\",\n \"some->\", \"some->>\", \"try\", \"when\", \"when-first\", \"when-let\", \"when-not\",\n \"when-some\", \"while\", \"with-bindings\", \"with-bindings*\", \"with-in-str\",\n \"with-loading-context\", \"with-local-vars\", \"with-meta\", \"with-open\",\n \"with-out-str\", \"with-precision\", \"with-redefs\", \"with-redefs-fn\"];\n\nvar atom = createLookupMap(atoms);\nvar specialForm = createLookupMap(specialForms);\nvar coreSymbol = createLookupMap(coreSymbols);\nvar hasBodyParameter = createLookupMap(haveBodyParameter);\nvar delimiter = /^(?:[\\\\\\[\\]\\s\"(),;@^`{}~]|$)/;\nvar numberLiteral = /^(?:[+\\-]?\\d+(?:(?:N|(?:[eE][+\\-]?\\d+))|(?:\\.?\\d*(?:M|(?:[eE][+\\-]?\\d+))?)|\\/\\d+|[xX][0-9a-fA-F]+|r[0-9a-zA-Z]+)?(?=[\\\\\\[\\]\\s\"#'(),;@^`{}~]|$))/;\nvar characterLiteral = /^(?:\\\\(?:backspace|formfeed|newline|return|space|tab|o[0-7]{3}|u[0-9A-Fa-f]{4}|x[0-9A-Fa-f]{4}|.)?(?=[\\\\\\[\\]\\s\"(),;@^`{}~]|$))/;\n\n// simple-namespace := /^[^\\\\\\/\\[\\]\\d\\s\"#'(),;@^`{}~.][^\\\\\\[\\]\\s\"(),;@^`{}~.\\/]*/\n// simple-symbol := /^(?:\\/|[^\\\\\\/\\[\\]\\d\\s\"#'(),;@^`{}~][^\\\\\\[\\]\\s\"(),;@^`{}~]*)/\n// qualified-symbol := ((<.>)*)?\nvar qualifiedSymbol = /^(?:(?:[^\\\\\\/\\[\\]\\d\\s\"#'(),;@^`{}~.][^\\\\\\[\\]\\s\"(),;@^`{}~.\\/]*(?:\\.[^\\\\\\/\\[\\]\\d\\s\"#'(),;@^`{}~.][^\\\\\\[\\]\\s\"(),;@^`{}~.\\/]*)*\\/)?(?:\\/|[^\\\\\\/\\[\\]\\d\\s\"#'(),;@^`{}~][^\\\\\\[\\]\\s\"(),;@^`{}~]*)*(?=[\\\\\\[\\]\\s\"(),;@^`{}~]|$))/;\n\nfunction base(stream, state) {\n if (stream.eatSpace() || stream.eat(\",\")) return [\"space\", null];\n if (stream.match(numberLiteral)) return [null, \"number\"];\n if (stream.match(characterLiteral)) return [null, \"string.special\"];\n if (stream.eat(/^\"/)) return (state.tokenize = inString)(stream, state);\n if (stream.eat(/^[(\\[{]/)) return [\"open\", \"bracket\"];\n if (stream.eat(/^[)\\]}]/)) return [\"close\", \"bracket\"];\n if (stream.eat(/^;/)) {stream.skipToEnd(); return [\"space\", \"comment\"];}\n if (stream.eat(/^[#'@^`~]/)) return [null, \"meta\"];\n\n var matches = stream.match(qualifiedSymbol);\n var symbol = matches && matches[0];\n\n if (!symbol) {\n // advance stream by at least one character so we don't get stuck.\n stream.next();\n stream.eatWhile(function (c) {return !is(c, delimiter);});\n return [null, \"error\"];\n }\n\n if (symbol === \"comment\" && state.lastToken === \"(\")\n return (state.tokenize = inComment)(stream, state);\n if (is(symbol, atom) || symbol.charAt(0) === \":\") return [\"symbol\", \"atom\"];\n if (is(symbol, specialForm) || is(symbol, coreSymbol)) return [\"symbol\", \"keyword\"];\n if (state.lastToken === \"(\") return [\"symbol\", \"builtin\"]; // other operator\n\n return [\"symbol\", \"variable\"];\n}\n\nfunction inString(stream, state) {\n var escaped = false, next;\n\n while (next = stream.next()) {\n if (next === \"\\\"\" && !escaped) {state.tokenize = base; break;}\n escaped = !escaped && next === \"\\\\\";\n }\n\n return [null, \"string\"];\n}\n\nfunction inComment(stream, state) {\n var parenthesisCount = 1;\n var next;\n\n while (next = stream.next()) {\n if (next === \")\") parenthesisCount--;\n if (next === \"(\") parenthesisCount++;\n if (parenthesisCount === 0) {\n stream.backUp(1);\n state.tokenize = base;\n break;\n }\n }\n\n return [\"space\", \"comment\"];\n}\n\nfunction createLookupMap(words) {\n var obj = {};\n\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n\n return obj;\n}\n\nfunction is(value, test) {\n if (test instanceof RegExp) return test.test(value);\n if (test instanceof Object) return test.propertyIsEnumerable(value);\n}\n\nexport const clojure = {\n name: \"clojure\",\n startState: function () {\n return {\n ctx: {prev: null, start: 0, indentTo: 0},\n lastToken: null,\n tokenize: base\n };\n },\n\n token: function (stream, state) {\n if (stream.sol() && (typeof state.ctx.indentTo !== \"number\"))\n state.ctx.indentTo = state.ctx.start + 1;\n\n var typeStylePair = state.tokenize(stream, state);\n var type = typeStylePair[0];\n var style = typeStylePair[1];\n var current = stream.current();\n\n if (type !== \"space\") {\n if (state.lastToken === \"(\" && state.ctx.indentTo === null) {\n if (type === \"symbol\" && is(current, hasBodyParameter))\n state.ctx.indentTo = state.ctx.start + stream.indentUnit;\n else state.ctx.indentTo = \"next\";\n } else if (state.ctx.indentTo === \"next\") {\n state.ctx.indentTo = stream.column();\n }\n\n state.lastToken = current;\n }\n\n if (type === \"open\")\n state.ctx = {prev: state.ctx, start: stream.column(), indentTo: null};\n else if (type === \"close\") state.ctx = state.ctx.prev || state.ctx;\n\n return style;\n },\n\n indent: function (state) {\n var i = state.ctx.indentTo;\n\n return (typeof i === \"number\") ?\n i :\n state.ctx.start + 1;\n },\n\n languageData: {\n closeBrackets: {brackets: [\"(\", \"[\", \"{\", '\"']},\n commentTokens: {line: \";;\"},\n autocomplete: [].concat(atoms, specialForms, coreSymbols)\n }\n};\n"],"names":["atoms","specialForms","coreSymbols","atom","createLookupMap","specialForm","coreSymbol","hasBodyParameter","delimiter","numberLiteral","characterLiteral","qualifiedSymbol","base","stream","state","eatSpace","eat","match","tokenize","inString","skipToEnd","matches","symbol","lastToken","inComment","is","charAt","next","eatWhile","c","escaped","parenthesisCount","backUp","words","obj","i","length","value","test","RegExp","Object","propertyIsEnumerable","clojure","name","startState","ctx","prev","start","indentTo","token","sol","typeStylePair","type","style","current","indentUnit","column","indent","languageData","closeBrackets","brackets","commentTokens","line","autocomplete","concat"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/5815.index.js b/book/_build/html/_static/5815.index.js new file mode 100644 index 0000000..54c7671 --- /dev/null +++ b/book/_build/html/_static/5815.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[5815],{65815:(e,t,n)=>{function r(e,t,n){return function(r,i){for(;!r.eol();){if(r.match(t)){i.tokenize=a;break}r.next()}return n&&(i.tokenize=n),e}}function i(e){return function(t,n){for(;!t.eol();)t.next();return n.tokenize=a,e}}function a(e,t){function n(n){return t.tokenize=n,n(e,t)}var u=e.sol(),o=e.next();switch(o){case"{":return e.eat("/"),e.eatSpace(),e.eatWhile(/[^\s\u00a0=\"\'\/?(}]/),t.tokenize=s,"tag";case"_":if(e.eat("_"))return n(r("strong","__",a));break;case"'":if(e.eat("'"))return n(r("em","''",a));break;case"(":if(e.eat("("))return n(r("link","))",a));break;case"[":return n(r("url","]",a));case"|":if(e.eat("|"))return n(r("comment","||"));break;case"-":if(e.eat("="))return n(r("header string","=-",a));if(e.eat("-"))return n(r("error tw-deleted","--",a));break;case"=":if(e.match("=="))return n(r("tw-underline","===",a));break;case":":if(e.eat(":"))return n(r("comment","::"));break;case"^":return n(r("tw-box","^"));case"~":if(e.match("np~"))return n(r("meta","~/np~"))}if(u)switch(o){case"!":return e.match("!!!!!")||e.match("!!!!")||e.match("!!!")||e.match("!!"),n(i("header string"));case"*":case"#":case"+":return n(i("tw-listitem bracket"))}return null}var u,o,c,f;function s(e,t){var n,r=e.next(),i=e.peek();return"}"==r?(t.tokenize=a,"tag"):"("==r||")"==r?"bracket":"="==r?(o="equals",">"==i&&(e.next(),i=e.peek()),/[\'\"]/.test(i)||(t.tokenize=function(e,t){for(;!e.eol();){var n=e.next(),r=e.peek();if(" "==n||","==n||/[ )}]/.test(r)){t.tokenize=s;break}}return"string"}),"operator"):/[\'\"]/.test(r)?(t.tokenize=(n=r,function(e,t){for(;!e.eol();)if(e.next()==n){t.tokenize=s;break}return"string"}),t.tokenize(e,t)):(e.eatWhile(/[^\s\u00a0=\"\'\/?]/),"keyword")}function l(){for(var e=arguments.length-1;e>=0;e--)c.cc.push(arguments[e])}function k(){return l.apply(null,arguments),!0}function d(e,t){var n=c.context&&c.context.noIndent;c.context={prev:c.context,pluginName:e,indent:c.indented,startOfLine:t,noIndent:n}}function p(){c.context&&(c.context=c.context.prev)}function g(e){if("openPlugin"==e)return c.pluginName=u,k(m,(n=c.startOfLine,function(e){return"selfclosePlugin"==e||"endPlugin"==e?k():"endPlugin"==e?(d(c.pluginName,n),k()):k()}));if("closePlugin"==e){var t=!1;return c.context?(t=c.context.pluginName!=u,p()):t=!0,t&&(f="error"),k(function(e){return function(t){return e&&(f="error"),"endPlugin"==t?k():l()}}(t))}return"string"==e?(c.context&&"!cdata"==c.context.name||d("!cdata"),c.tokenize==a&&p(),k()):k();var n}function m(e){return"keyword"==e?(f="attribute",k(m)):"equals"==e?k(x,m):l()}function x(e){return"keyword"==e?(f="string",k()):"string"==e?k(h):l()}function h(e){return"string"==e?k(h):l()}n.r(t),n.d(t,{tiki:()=>b});const b={name:"tiki",startState:function(){return{tokenize:a,cc:[],indented:0,startOfLine:!0,pluginName:null,context:null}},token:function(e,t){if(e.sol()&&(t.startOfLine=!0,t.indented=e.indentation()),e.eatSpace())return null;f=o=u=null;var n=t.tokenize(e,t);if((n||o)&&"comment"!=n)for(c=t;!(t.cc.pop()||g)(o||n););return t.startOfLine=!1,f||n},indent:function(e,t,n){var r=e.context;if(r&&r.noIndent)return 0;for(r&&/^{\//.test(t)&&(r=r.prev);r&&!r.startOfLine;)r=r.prev;return r?r.indent+n.unit:0}}}}]); +//# sourceMappingURL=5815.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/5815.index.js.map b/book/_build/html/_static/5815.index.js.map new file mode 100644 index 0000000..68fc1b8 --- /dev/null +++ b/book/_build/html/_static/5815.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"5815.index.js","mappings":"+FAAA,SAASA,EAAQC,EAAOC,EAAYC,GAClC,OAAO,SAASC,EAAQC,GACtB,MAAQD,EAAOE,OAAO,CACpB,GAAIF,EAAOG,MAAML,GAAa,CAC5BG,EAAMG,SAAWC,EACjB,KACF,CACAL,EAAOM,MACT,CAIA,OAFIP,I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SAAU,EAAGL,aAAa,EAAMhB,WAAY,KAAMkB,QAAS,KAC/F,EACAc,MAAO,SAAShD,EAAQC,GAKtB,GAJID,EAAOU,QACTT,EAAM+B,aAAc,EACpB/B,EAAMoC,SAAWrC,EAAOiD,eAEtBjD,EAAOa,WAAY,OAAO,KAE9BM,EAAWF,EAAOD,EAAa,KAC/B,IAAInB,EAAQI,EAAMG,SAASJ,EAAQC,GACnC,IAAKJ,GAASoB,IAAkB,WAATpB,EAErB,IADAqB,EAAWjB,IAEEA,EAAM0B,GAAGuB,OAASX,GACpBtB,GAAQpB,KAIrB,OADAI,EAAM+B,aAAc,EACbb,GAAYtB,CACrB,EACAuC,OAAQ,SAASnC,EAAOkD,EAAWC,GACjC,IAAIlB,EAAUjC,EAAMiC,QACpB,GAAIA,GAAWA,EAAQD,SAAU,OAAO,EAGxC,IAFIC,GAAW,OAAOZ,KAAK6B,KACzBjB,EAAUA,EAAQC,MACbD,IAAYA,EAAQF,aACzBE,EAAUA,EAAQC,KACpB,OAAID,EAAgBA,EAAQE,OAASgB,EAAGC,KAC5B,CACd,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/tiki.js"],"sourcesContent":["function inBlock(style, terminator, returnTokenizer) {\n return function(stream, state) {\n while (!stream.eol()) {\n if (stream.match(terminator)) {\n state.tokenize = inText;\n break;\n }\n stream.next();\n }\n\n if (returnTokenizer) state.tokenize = returnTokenizer;\n\n return style;\n };\n}\n\nfunction inLine(style) {\n return function(stream, state) {\n while(!stream.eol()) {\n stream.next();\n }\n state.tokenize = inText;\n return style;\n };\n}\n\nfunction inText(stream, state) {\n function chain(parser) {\n state.tokenize = parser;\n return parser(stream, state);\n }\n\n var sol = stream.sol();\n var ch = stream.next();\n\n //non start of line\n switch (ch) { //switch is generally much faster than if, so it is used here\n case \"{\": //plugin\n stream.eat(\"/\");\n stream.eatSpace();\n stream.eatWhile(/[^\\s\\u00a0=\\\"\\'\\/?(}]/);\n state.tokenize = inPlugin;\n return \"tag\";\n case \"_\": //bold\n if (stream.eat(\"_\"))\n return chain(inBlock(\"strong\", \"__\", inText));\n break;\n case \"'\": //italics\n if (stream.eat(\"'\"))\n return chain(inBlock(\"em\", \"''\", inText));\n break;\n case \"(\":// Wiki Link\n if (stream.eat(\"(\"))\n return chain(inBlock(\"link\", \"))\", inText));\n break;\n case \"[\":// Weblink\n return chain(inBlock(\"url\", \"]\", inText));\n break;\n case \"|\": //table\n if (stream.eat(\"|\"))\n return chain(inBlock(\"comment\", \"||\"));\n break;\n case \"-\":\n if (stream.eat(\"=\")) {//titleBar\n return chain(inBlock(\"header string\", \"=-\", inText));\n } else if (stream.eat(\"-\")) {//deleted\n return chain(inBlock(\"error tw-deleted\", \"--\", inText));\n }\n break;\n case \"=\": //underline\n if (stream.match(\"==\"))\n return chain(inBlock(\"tw-underline\", \"===\", inText));\n break;\n case \":\":\n if (stream.eat(\":\"))\n return chain(inBlock(\"comment\", \"::\"));\n break;\n case \"^\": //box\n return chain(inBlock(\"tw-box\", \"^\"));\n break;\n case \"~\": //np\n if (stream.match(\"np~\"))\n return chain(inBlock(\"meta\", \"~/np~\"));\n break;\n }\n\n //start of line types\n if (sol) {\n switch (ch) {\n case \"!\": //header at start of line\n if (stream.match('!!!!!')) {\n return chain(inLine(\"header string\"));\n } else if (stream.match('!!!!')) {\n return chain(inLine(\"header string\"));\n } else if (stream.match('!!!')) {\n return chain(inLine(\"header string\"));\n } else if (stream.match('!!')) {\n return chain(inLine(\"header string\"));\n } else {\n return chain(inLine(\"header string\"));\n }\n break;\n case \"*\": //unordered list line item, or
  • at start of line\n case \"#\": //ordered list line item, or
  • at start of line\n case \"+\": //ordered list line item, or
  • at start of line\n return chain(inLine(\"tw-listitem bracket\"));\n break;\n }\n }\n\n //stream.eatWhile(/[&{]/); was eating up plugins, turned off to act less like html and more like tiki\n return null;\n}\n\n// Return variables for tokenizers\nvar pluginName, type;\nfunction inPlugin(stream, state) {\n var ch = stream.next();\n var peek = stream.peek();\n\n if (ch == \"}\") {\n state.tokenize = inText;\n //type = ch == \")\" ? \"endPlugin\" : \"selfclosePlugin\"; inPlugin\n return \"tag\";\n } else if (ch == \"(\" || ch == \")\") {\n return \"bracket\";\n } else if (ch == \"=\") {\n type = \"equals\";\n\n if (peek == \">\") {\n stream.next();\n peek = stream.peek();\n }\n\n //here we detect values directly after equal character with no quotes\n if (!/[\\'\\\"]/.test(peek)) {\n state.tokenize = inAttributeNoQuote();\n }\n //end detect values\n\n return \"operator\";\n } else if (/[\\'\\\"]/.test(ch)) {\n state.tokenize = inAttribute(ch);\n return state.tokenize(stream, state);\n } else {\n stream.eatWhile(/[^\\s\\u00a0=\\\"\\'\\/?]/);\n return \"keyword\";\n }\n}\n\nfunction inAttribute(quote) {\n return function(stream, state) {\n while (!stream.eol()) {\n if (stream.next() == quote) {\n state.tokenize = inPlugin;\n break;\n }\n }\n return \"string\";\n };\n}\n\nfunction inAttributeNoQuote() {\n return function(stream, state) {\n while (!stream.eol()) {\n var ch = stream.next();\n var peek = stream.peek();\n if (ch == \" \" || ch == \",\" || /[ )}]/.test(peek)) {\n state.tokenize = inPlugin;\n break;\n }\n }\n return \"string\";\n };\n}\n\nvar curState, setStyle;\nfunction pass() {\n for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]);\n}\n\nfunction cont() {\n pass.apply(null, arguments);\n return true;\n}\n\nfunction pushContext(pluginName, startOfLine) {\n var noIndent = curState.context && curState.context.noIndent;\n curState.context = {\n prev: curState.context,\n pluginName: pluginName,\n indent: curState.indented,\n startOfLine: startOfLine,\n noIndent: noIndent\n };\n}\n\nfunction popContext() {\n if (curState.context) curState.context = curState.context.prev;\n}\n\nfunction element(type) {\n if (type == \"openPlugin\") {curState.pluginName = pluginName; return cont(attributes, endplugin(curState.startOfLine));}\n else if (type == \"closePlugin\") {\n var err = false;\n if (curState.context) {\n err = curState.context.pluginName != pluginName;\n popContext();\n } else {\n err = true;\n }\n if (err) setStyle = \"error\";\n return cont(endcloseplugin(err));\n }\n else if (type == \"string\") {\n if (!curState.context || curState.context.name != \"!cdata\") pushContext(\"!cdata\");\n if (curState.tokenize == inText) popContext();\n return cont();\n }\n else return cont();\n}\n\nfunction endplugin(startOfLine) {\n return function(type) {\n if (\n type == \"selfclosePlugin\" ||\n type == \"endPlugin\"\n )\n return cont();\n if (type == \"endPlugin\") {pushContext(curState.pluginName, startOfLine); return cont();}\n return cont();\n };\n}\n\nfunction endcloseplugin(err) {\n return function(type) {\n if (err) setStyle = \"error\";\n if (type == \"endPlugin\") return cont();\n return pass();\n };\n}\n\nfunction attributes(type) {\n if (type == \"keyword\") {setStyle = \"attribute\"; return cont(attributes);}\n if (type == \"equals\") return cont(attvalue, attributes);\n return pass();\n}\nfunction attvalue(type) {\n if (type == \"keyword\") {setStyle = \"string\"; return cont();}\n if (type == \"string\") return cont(attvaluemaybe);\n return pass();\n}\nfunction attvaluemaybe(type) {\n if (type == \"string\") return cont(attvaluemaybe);\n else return pass();\n}\nexport const tiki = {\n name: \"tiki\",\n startState: function() {\n return {tokenize: inText, cc: [], indented: 0, startOfLine: true, pluginName: null, context: null};\n },\n token: function(stream, state) {\n if (stream.sol()) {\n state.startOfLine = true;\n state.indented = stream.indentation();\n }\n if (stream.eatSpace()) return null;\n\n setStyle = type = pluginName = null;\n var style = state.tokenize(stream, state);\n if ((style || type) && style != \"comment\") {\n curState = state;\n while (true) {\n var comb = state.cc.pop() || element;\n if (comb(type || style)) break;\n }\n }\n state.startOfLine = false;\n return setStyle || style;\n },\n indent: function(state, textAfter, cx) {\n var context = state.context;\n if (context && context.noIndent) return 0;\n if (context && /^{\\//.test(textAfter))\n context = context.prev;\n while (context && !context.startOfLine)\n context = context.prev;\n if (context) return context.indent + cx.unit;\n else return 0;\n }\n};\n"],"names":["inBlock","style","terminator","returnTokenizer","stream","state","eol","match","tokenize","inText","next","inLine","chain","parser","sol","ch","eat","eatSpace","eatWhile","inPlugin","pluginName","type","curState","setStyle","quote","peek","test","pass","i","arguments","length","cc","push","cont","apply","pushContext","startOfLine","noIndent","context","prev","indent","indented","popContext","element","attributes","err","endcloseplugin","name","attvalue","attvaluemaybe","tiki","startState","token","indentation","pop","textAfter","cx","unit"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/5836.index.js b/book/_build/html/_static/5836.index.js new file mode 100644 index 0000000..5c5a94d --- /dev/null +++ b/book/_build/html/_static/5836.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[5836],{55836:(I,_,R)=>{R.r(_),R.d(_,{ntriples:()=>t});var e={PRE_SUBJECT:0,WRITING_SUB_URI:1,WRITING_BNODE_URI:2,PRE_PRED:3,WRITING_PRED_URI:4,PRE_OBJ:5,WRITING_OBJ_URI:6,WRITING_OBJ_BNODE:7,WRITING_OBJ_LITERAL:8,WRITING_LIT_LANG:9,WRITING_LIT_TYPE:10,POST_OBJ:11,ERROR:12};function n(I,_){var R,n=I.location;R=n==e.PRE_SUBJECT&&"<"==_?e.WRITING_SUB_URI:n==e.PRE_SUBJECT&&"_"==_?e.WRITING_BNODE_URI:n==e.PRE_PRED&&"<"==_?e.WRITING_PRED_URI:n==e.PRE_OBJ&&"<"==_?e.WRITING_OBJ_URI:n==e.PRE_OBJ&&"_"==_?e.WRITING_OBJ_BNODE:n==e.PRE_OBJ&&'"'==_?e.WRITING_OBJ_LITERAL:n==e.WRITING_SUB_URI&&">"==_||n==e.WRITING_BNODE_URI&&" "==_?e.PRE_PRED:n==e.WRITING_PRED_URI&&">"==_?e.PRE_OBJ:n==e.WRITING_OBJ_URI&&">"==_||n==e.WRITING_OBJ_BNODE&&" "==_||n==e.WRITING_OBJ_LITERAL&&'"'==_||n==e.WRITING_LIT_LANG&&" "==_||n==e.WRITING_LIT_TYPE&&">"==_?e.POST_OBJ:n==e.WRITING_OBJ_LITERAL&&"@"==_?e.WRITING_LIT_LANG:n==e.WRITING_OBJ_LITERAL&&"^"==_?e.WRITING_LIT_TYPE:" "!=_||n!=e.PRE_SUBJECT&&n!=e.PRE_PRED&&n!=e.PRE_OBJ&&n!=e.POST_OBJ?n==e.POST_OBJ&&"."==_?e.PRE_SUBJECT:e.ERROR:n,I.location=R}const t={name:"ntriples",startState:function(){return{location:e.PRE_SUBJECT,uris:[],anchors:[],bnodes:[],langs:[],types:[]}},token:function(I,_){var R=I.next();if("<"==R){n(_,R);var e="";return I.eatWhile((function(I){return"#"!=I&&">"!=I&&(e+=I,!0)})),_.uris.push(e),I.match("#",!1)||(I.next(),n(_,">")),"variable"}if("#"==R){var t="";return I.eatWhile((function(I){return">"!=I&&" "!=I&&(t+=I,!0)})),_.anchors.push(t),"url"}if(">"==R)return n(_,">"),"variable";if("_"==R){n(_,R);var r="";return I.eatWhile((function(I){return" "!=I&&(r+=I,!0)})),_.bnodes.push(r),I.next(),n(_," "),"builtin"}if('"'==R)return n(_,R),I.eatWhile((function(I){return'"'!=I})),I.next(),"@"!=I.peek()&&"^"!=I.peek()&&n(_,'"'),"string";if("@"==R){n(_,"@");var T="";return I.eatWhile((function(I){return" "!=I&&(T+=I,!0)})),_.langs.push(T),I.next(),n(_," "),"string.special"}if("^"==R){I.next(),n(_,"^");var E="";return I.eatWhile((function(I){return">"!=I&&(E+=I,!0)})),_.types.push(E),I.next(),n(_,">"),"variable"}" "==R&&n(_,R),"."==R&&n(_,R)}}}}]); +//# sourceMappingURL=5836.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/5836.index.js.map b/book/_build/html/_static/5836.index.js.map new file mode 100644 index 0000000..0525549 --- /dev/null +++ b/book/_build/html/_static/5836.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"5836.index.js","mappings":"8HAAA,IAAIA,EAAW,CACbC,YAAsB,EACtBC,gBAAsB,EACtBC,kBAAsB,EACtBC,SAAsB,EACtBC,iBAAsB,EACtBC,QAAsB,EACtBC,gBAAsB,EACtBC,kBAAsB,EACtBC,oBAAsB,EACtBC,iBAAsB,EACtBC,iBAAsB,GACtBC,SAAsB,GACt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AZ,EAAOK,UAAS,SAASlB,GAAK,MAAS,KAALA,IAAayB,GAAczB,GAAU,EAAqB,IAC5Fc,EAAMH,MAAMQ,KAAKM,GACjBZ,EAAOG,OACPlB,EAAagB,EAAO,KACb,UACT,CACU,KAANC,GACFjB,EAAagB,EAAOC,GAEZ,KAANA,GACFjB,EAAagB,EAAOC,EAExB,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/ntriples.js"],"sourcesContent":["var Location = {\n PRE_SUBJECT : 0,\n WRITING_SUB_URI : 1,\n WRITING_BNODE_URI : 2,\n PRE_PRED : 3,\n WRITING_PRED_URI : 4,\n PRE_OBJ : 5,\n WRITING_OBJ_URI : 6,\n WRITING_OBJ_BNODE : 7,\n WRITING_OBJ_LITERAL : 8,\n WRITING_LIT_LANG : 9,\n WRITING_LIT_TYPE : 10,\n POST_OBJ : 11,\n ERROR : 12\n};\nfunction transitState(currState, c) {\n var currLocation = currState.location;\n var ret;\n\n // Opening.\n if (currLocation == Location.PRE_SUBJECT && c == '<') ret = Location.WRITING_SUB_URI;\n else if(currLocation == Location.PRE_SUBJECT && c == '_') ret = Location.WRITING_BNODE_URI;\n else if(currLocation == Location.PRE_PRED && c == '<') ret = Location.WRITING_PRED_URI;\n else if(currLocation == Location.PRE_OBJ && c == '<') ret = Location.WRITING_OBJ_URI;\n else if(currLocation == Location.PRE_OBJ && c == '_') ret = Location.WRITING_OBJ_BNODE;\n else if(currLocation == Location.PRE_OBJ && c == '\"') ret = Location.WRITING_OBJ_LITERAL;\n\n // Closing.\n else if(currLocation == Location.WRITING_SUB_URI && c == '>') ret = Location.PRE_PRED;\n else if(currLocation == Location.WRITING_BNODE_URI && c == ' ') ret = Location.PRE_PRED;\n else if(currLocation == Location.WRITING_PRED_URI && c == '>') ret = Location.PRE_OBJ;\n else if(currLocation == Location.WRITING_OBJ_URI && c == '>') ret = Location.POST_OBJ;\n else if(currLocation == Location.WRITING_OBJ_BNODE && c == ' ') ret = Location.POST_OBJ;\n else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '\"') ret = Location.POST_OBJ;\n else if(currLocation == Location.WRITING_LIT_LANG && c == ' ') ret = Location.POST_OBJ;\n else if(currLocation == Location.WRITING_LIT_TYPE && c == '>') ret = Location.POST_OBJ;\n\n // Closing typed and language literal.\n else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '@') ret = Location.WRITING_LIT_LANG;\n else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '^') ret = Location.WRITING_LIT_TYPE;\n\n // Spaces.\n else if( c == ' ' &&\n (\n currLocation == Location.PRE_SUBJECT ||\n currLocation == Location.PRE_PRED ||\n currLocation == Location.PRE_OBJ ||\n currLocation == Location.POST_OBJ\n )\n ) ret = currLocation;\n\n // Reset.\n else if(currLocation == Location.POST_OBJ && c == '.') ret = Location.PRE_SUBJECT;\n\n // Error\n else ret = Location.ERROR;\n\n currState.location=ret;\n}\n\nexport const ntriples = {\n name: \"ntriples\",\n startState: function() {\n return {\n location : Location.PRE_SUBJECT,\n uris : [],\n anchors : [],\n bnodes : [],\n langs : [],\n types : []\n };\n },\n token: function(stream, state) {\n var ch = stream.next();\n if(ch == '<') {\n transitState(state, ch);\n var parsedURI = '';\n stream.eatWhile( function(c) { if( c != '#' && c != '>' ) { parsedURI += c; return true; } return false;} );\n state.uris.push(parsedURI);\n if( stream.match('#', false) ) return 'variable';\n stream.next();\n transitState(state, '>');\n return 'variable';\n }\n if(ch == '#') {\n var parsedAnchor = '';\n stream.eatWhile(function(c) { if(c != '>' && c != ' ') { parsedAnchor+= c; return true; } return false;});\n state.anchors.push(parsedAnchor);\n return 'url';\n }\n if(ch == '>') {\n transitState(state, '>');\n return 'variable';\n }\n if(ch == '_') {\n transitState(state, ch);\n var parsedBNode = '';\n stream.eatWhile(function(c) { if( c != ' ' ) { parsedBNode += c; return true; } return false;});\n state.bnodes.push(parsedBNode);\n stream.next();\n transitState(state, ' ');\n return 'builtin';\n }\n if(ch == '\"') {\n transitState(state, ch);\n stream.eatWhile( function(c) { return c != '\"'; } );\n stream.next();\n if( stream.peek() != '@' && stream.peek() != '^' ) {\n transitState(state, '\"');\n }\n return 'string';\n }\n if( ch == '@' ) {\n transitState(state, '@');\n var parsedLang = '';\n stream.eatWhile(function(c) { if( c != ' ' ) { parsedLang += c; return true; } return false;});\n state.langs.push(parsedLang);\n stream.next();\n transitState(state, ' ');\n return 'string.special';\n }\n if( ch == '^' ) {\n stream.next();\n transitState(state, '^');\n var parsedType = '';\n stream.eatWhile(function(c) { if( c != '>' ) { parsedType += c; return true; } return false;} );\n state.types.push(parsedType);\n stream.next();\n transitState(state, '>');\n return 'variable';\n }\n if( ch == ' ' ) {\n transitState(state, ch);\n }\n if( ch == '.' ) {\n transitState(state, ch);\n }\n }\n};\n"],"names":["Location","PRE_SUBJECT","WRITING_SUB_URI","WRITING_BNODE_URI","PRE_PRED","WRITING_PRED_URI","PRE_OBJ","WRITING_OBJ_URI","WRITING_OBJ_BNODE","WRITING_OBJ_LITERAL","WRITING_LIT_LANG","WRITING_LIT_TYPE","POST_OBJ","ERROR","transitState","currState","c","ret","currLocation","location","ntriples","name","startState","uris","anchors","bnodes","langs","types","token","stream","state","ch","next","parsedURI","eatWhile","push","match","parsedAnchor","parsedBNode","peek","parsedLang","parsedType"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/5950.index.js b/book/_build/html/_static/5950.index.js new file mode 100644 index 0000000..54451a9 --- /dev/null +++ b/book/_build/html/_static/5950.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[5950],{15950:(i,l,e)=>{function a(i){var l=[],e="",a={".abort":"builtin",".align":"builtin",".altmacro":"builtin",".ascii":"builtin",".asciz":"builtin",".balign":"builtin",".balignw":"builtin",".balignl":"builtin",".bundle_align_mode":"builtin",".bundle_lock":"builtin",".bundle_unlock":"builtin",".byte":"builtin",".cfi_startproc":"builtin",".comm":"builtin",".data":"builtin",".def":"builtin",".desc":"builtin",".dim":"builtin",".double":"builtin",".eject":"builtin",".else":"builtin",".elseif":"builtin",".end":"builtin",".endef":"builtin",".endfunc":"builtin",".endif":"builtin",".equ":"builtin",".equiv":"builtin",".eqv":"builtin",".err":"builtin",".error":"builtin",".exitm":"builtin",".extern":"builtin",".fail":"builtin",".file":"builtin",".fill":"builtin",".float":"builtin",".func":"builtin",".global":"builtin",".gnu_attribute":"builtin",".hidden":"builtin",".hword":"builtin",".ident":"builtin",".if":"builtin",".incbin":"builtin",".include":"builtin",".int":"builtin",".internal":"builtin",".irp":"builtin",".irpc":"builtin",".lcomm":"builtin",".lflags":"builtin",".line":"builtin",".linkonce":"builtin",".list":"builtin",".ln":"builtin",".loc":"builtin",".loc_mark_labels":"builtin",".local":"builtin",".long":"builtin",".macro":"builtin",".mri":"builtin",".noaltmacro":"builtin",".nolist":"builtin",".octa":"builtin",".offset":"builtin",".org":"builtin",".p2align":"builtin",".popsection":"builtin",".previous":"builtin",".print":"builtin",".protected":"builtin",".psize":"builtin",".purgem":"builtin",".pushsection":"builtin",".quad":"builtin",".reloc":"builtin",".rept":"builtin",".sbttl":"builtin",".scl":"builtin",".section":"builtin",".set":"builtin",".short":"builtin",".single":"builtin",".size":"builtin",".skip":"builtin",".sleb128":"builtin",".space":"builtin",".stab":"builtin",".string":"builtin",".struct":"builtin",".subsection":"builtin",".symver":"builtin",".tag":"builtin",".text":"builtin",".title":"builtin",".type":"builtin",".uleb128":"builtin",".val":"builtin",".version":"builtin",".vtable_entry":"builtin",".vtable_inherit":"builtin",".warning":"builtin",".weak":"builtin",".weakref":"builtin",".word":"builtin"},t={};function n(i,l){for(var e,a=!1;null!=(e=i.next());){if("/"===e&&a){l.tokenize=null;break}a="*"===e}return"comment"}return"x86"===i?(e="#",t.al="variable",t.ah="variable",t.ax="variable",t.eax="variableName.special",t.rax="variableName.special",t.bl="variable",t.bh="variable",t.bx="variable",t.ebx="variableName.special",t.rbx="variableName.special",t.cl="variable",t.ch="variable",t.cx="variable",t.ecx="variableName.special",t.rcx="variableName.special",t.dl="variable",t.dh="variable",t.dx="variable",t.edx="variableName.special",t.rdx="variableName.special",t.si="variable",t.esi="variableName.special",t.rsi="variableName.special",t.di="variable",t.edi="variableName.special",t.rdi="variableName.special",t.sp="variable",t.esp="variableName.special",t.rsp="variableName.special",t.bp="variable",t.ebp="variableName.special",t.rbp="variableName.special",t.ip="variable",t.eip="variableName.special",t.rip="variableName.special",t.cs="keyword",t.ds="keyword",t.ss="keyword",t.es="keyword",t.fs="keyword",t.gs="keyword"):"arm"!==i&&"armv6"!==i||(e="@",a.syntax="builtin",t.r0="variable",t.r1="variable",t.r2="variable",t.r3="variable",t.r4="variable",t.r5="variable",t.r6="variable",t.r7="variable",t.r8="variable",t.r9="variable",t.r10="variable",t.r11="variable",t.r12="variable",t.sp="variableName.special",t.lr="variableName.special",t.pc="variableName.special",t.r13=t.sp,t.r14=t.lr,t.r15=t.pc,l.push((function(i,l){if("#"===i)return l.eatWhile(/\w/),"number"}))),{name:"gas",startState:function(){return{tokenize:null}},token:function(i,b){if(b.tokenize)return b.tokenize(i,b);if(i.eatSpace())return null;var r,u,s=i.next();if("/"===s&&i.eat("*"))return b.tokenize=n,n(i,b);if(s===e)return i.skipToEnd(),"comment";if('"'===s)return function(i,l){for(var e,a=!1;null!=(e=i.next());){if('"'===e&&!a)return!1;a=!a&&"\\"===e}}(i),"string";if("."===s)return i.eatWhile(/\w/),u=i.current().toLowerCase(),(r=a[u])||null;if("="===s)return i.eatWhile(/\w/),"tag";if("{"===s)return"bracket";if("}"===s)return"bracket";if(/\d/.test(s))return"0"===s&&i.eat("x")?(i.eatWhile(/[0-9a-fA-F]/),"number"):(i.eatWhile(/\d/),"number");if(/\w/.test(s))return i.eatWhile(/\w/),i.eat(":")?"tag":(u=i.current().toLowerCase(),(r=t[u])||null);for(var c=0;ct,gasArm:()=>n});const t=a("x86"),n=a("arm")}}]); +//# sourceMappingURL=5950.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/5950.index.js.map b/book/_build/html/_static/5950.index.js.map new file mode 100644 index 0000000..62cfd81 --- /dev/null +++ b/book/_build/html/_static/5950.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"5950.index.js","mappings":"+FAAA,SAASA,EAAMC,GAIb,IAAIC,EAAS,GAMTC,EAAyB,GAOzBC,EAAa,CACf,SAAW,UACX,SAAW,UACX,YAAc,UACd,SAAW,UACX,SAAW,UACX,UAAY,UACZ,WAAa,UACb,WAAa,UACb,qBAAuB,UACvB,eAAiB,UACjB,iBAAmB,UACnB,QAAU,UACV,iBAAmB,UACnB,QAAU,UACV,QAAU,UACV,OAAS,UACT,QAAU,UACV,OAAS,UACT,UAAY,UACZ,SAAW,UACX,QAAU,UACV,UAAY,UACZ,OAAS,UACT,SAAW,UACX,WAAa,UACb,SAAW,UACX,OAAS,UACT,SAAW,UACX,OAAS,UACT,OAAS,UACT,SAAW,UACX,SAAW,UACX,UAAY,UACZ,QAAU,UACV,QAAU,UACV,QAAU,UACV,SAAW,UACX,QAAU,UACV,UAAY,UACZ,iBAAmB,UACnB,UAAY,UACZ,SAAW,UACX,SAAW,UACX,MAAQ,UACR,UAAY,UACZ,WAAa,UACb,OAAS,UACT,YAAc,UACd,OAAS,UACT,QAAU,UACV,SAAW,UACX,UAAY,UACZ,QAAU,UACV,YAAc,UACd,QAAU,UACV,MAAQ,UACR,OAAS,UACT,mBAAqB,UACrB,SAAW,UACX,QAAU,UACV,SAAW,UACX,OAAS,UACT,cAAgB,UAChB,UAAY,UACZ,QAAU,UACV,UAAY,UACZ,OAAS,UACT,WAAa,UACb,cAAgB,UAChB,YAAc,UACd,SAAW,UACX,aAAe,UACf,SAAW,UACX,UAAY,UACZ,eAAiB,UACjB,QAAU,UACV,SAAW,UACX,QAAU,UACV,SAAW,UACX,OAAS,UACT,WAAa,UACb,OAAS,UACT,SAAW,UACX,UAAY,UACZ,QAAU,UACV,QAAU,UACV,WAAa,UACb,SAAW,UACX,QAAU,UACV,UAAY,UACZ,UAAY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AU,EACmB,OAAzBxE,EAAOJ,EAAOI,SAAiB,CACrC,GAoD6B,MApDzBA,IAAiBwE,EACnB,OAAO,EAETA,GAAWA,GAAoB,OAATxE,CACxB,CAEF,CA8CMyE,CAAmB7E,GACZ,SAGT,GAAW,MAAPE,EAIF,OAHAF,EAAOkE,SAAS,MAChBM,EAAMxE,EAAO8E,UAAUC,eACvBR,EAAQ1E,EAAW2E,KACH,KAGlB,GAAW,MAAPtE,EAEF,OADAF,EAAOkE,SAAS,MACT,MAGT,GAAW,MAAPhE,EACF,MAAO,UAGT,GAAW,MAAPA,EACF,MAAO,UAGT,GAAI,KAAK8E,KAAK9E,GACZ,MAAW,MAAPA,GAAcF,EAAOyE,IAAI,MAC3BzE,EAAOkE,SAAS,eACT,WAETlE,EAAOkE,SAAS,MACT,UAGT,GAAI,KAAKc,KAAK9E,GAEZ,OADAF,EAAOkE,SAAS,MACZlE,EAAOyE,IAAI,KACN,OAETD,EAAMxE,EAAO8E,UAAUC,eACvBR,EAAQzE,EAAU0E,KACF,MAGlB,IAAK,IAAIS,EAAI,EAAGA,EAAItF,EAAOuF,OAAQD,IAEjC,GADAV,EAAQ5E,EAAOsF,GAAG/E,EAAIF,EAAQC,GAE5B,OAAOsE,CAGb,EAEAY,aAAc,CACZC,cAAe,CACbC,KAAMzF,EACN0F,MAAO,CAACC,KAAM,KAAMC,MAAO,QAInC,C,uCAEO,MAAMC,EAAMhG,EAAM,OACZiG,EAASjG,EAAM,M","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/gas.js"],"sourcesContent":["function mkGas(arch) {\n // If an architecture is specified, its initialization function may\n // populate this array with custom parsing functions which will be\n // tried in the event that the standard functions do not find a match.\n var custom = [];\n\n // The symbol used to start a line comment changes based on the target\n // architecture.\n // If no architecture is pased in \"parserConfig\" then only multiline\n // comments will have syntax support.\n var lineCommentStartSymbol = \"\";\n\n // These directives are architecture independent.\n // Machine specific directives should go in their respective\n // architecture initialization function.\n // Reference:\n // http://sourceware.org/binutils/docs/as/Pseudo-Ops.html#Pseudo-Ops\n var directives = {\n \".abort\" : \"builtin\",\n \".align\" : \"builtin\",\n \".altmacro\" : \"builtin\",\n \".ascii\" : \"builtin\",\n \".asciz\" : \"builtin\",\n \".balign\" : \"builtin\",\n \".balignw\" : \"builtin\",\n \".balignl\" : \"builtin\",\n \".bundle_align_mode\" : \"builtin\",\n \".bundle_lock\" : \"builtin\",\n \".bundle_unlock\" : \"builtin\",\n \".byte\" : \"builtin\",\n \".cfi_startproc\" : \"builtin\",\n \".comm\" : \"builtin\",\n \".data\" : \"builtin\",\n \".def\" : \"builtin\",\n \".desc\" : \"builtin\",\n \".dim\" : \"builtin\",\n \".double\" : \"builtin\",\n \".eject\" : \"builtin\",\n \".else\" : \"builtin\",\n \".elseif\" : \"builtin\",\n \".end\" : \"builtin\",\n \".endef\" : \"builtin\",\n \".endfunc\" : \"builtin\",\n \".endif\" : \"builtin\",\n \".equ\" : \"builtin\",\n \".equiv\" : \"builtin\",\n \".eqv\" : \"builtin\",\n \".err\" : \"builtin\",\n \".error\" : \"builtin\",\n \".exitm\" : \"builtin\",\n \".extern\" : \"builtin\",\n \".fail\" : \"builtin\",\n \".file\" : \"builtin\",\n \".fill\" : \"builtin\",\n \".float\" : \"builtin\",\n \".func\" : \"builtin\",\n \".global\" : \"builtin\",\n \".gnu_attribute\" : \"builtin\",\n \".hidden\" : \"builtin\",\n \".hword\" : \"builtin\",\n \".ident\" : \"builtin\",\n \".if\" : \"builtin\",\n \".incbin\" : \"builtin\",\n \".include\" : \"builtin\",\n \".int\" : \"builtin\",\n \".internal\" : \"builtin\",\n \".irp\" : \"builtin\",\n \".irpc\" : \"builtin\",\n \".lcomm\" : \"builtin\",\n \".lflags\" : \"builtin\",\n \".line\" : \"builtin\",\n \".linkonce\" : \"builtin\",\n \".list\" : \"builtin\",\n \".ln\" : \"builtin\",\n \".loc\" : \"builtin\",\n \".loc_mark_labels\" : \"builtin\",\n \".local\" : \"builtin\",\n \".long\" : \"builtin\",\n \".macro\" : \"builtin\",\n \".mri\" : \"builtin\",\n \".noaltmacro\" : \"builtin\",\n \".nolist\" : \"builtin\",\n \".octa\" : \"builtin\",\n \".offset\" : \"builtin\",\n \".org\" : \"builtin\",\n \".p2align\" : \"builtin\",\n \".popsection\" : \"builtin\",\n \".previous\" : \"builtin\",\n \".print\" : \"builtin\",\n \".protected\" : \"builtin\",\n \".psize\" : \"builtin\",\n \".purgem\" : \"builtin\",\n \".pushsection\" : \"builtin\",\n \".quad\" : \"builtin\",\n \".reloc\" : \"builtin\",\n \".rept\" : \"builtin\",\n \".sbttl\" : \"builtin\",\n \".scl\" : \"builtin\",\n \".section\" : \"builtin\",\n \".set\" : \"builtin\",\n \".short\" : \"builtin\",\n \".single\" : \"builtin\",\n \".size\" : \"builtin\",\n \".skip\" : \"builtin\",\n \".sleb128\" : \"builtin\",\n \".space\" : \"builtin\",\n \".stab\" : \"builtin\",\n \".string\" : \"builtin\",\n \".struct\" : \"builtin\",\n \".subsection\" : \"builtin\",\n \".symver\" : \"builtin\",\n \".tag\" : \"builtin\",\n \".text\" : \"builtin\",\n \".title\" : \"builtin\",\n \".type\" : \"builtin\",\n \".uleb128\" : \"builtin\",\n \".val\" : \"builtin\",\n \".version\" : \"builtin\",\n \".vtable_entry\" : \"builtin\",\n \".vtable_inherit\" : \"builtin\",\n \".warning\" : \"builtin\",\n \".weak\" : \"builtin\",\n \".weakref\" : \"builtin\",\n \".word\" : \"builtin\"\n };\n\n var registers = {};\n\n function x86() {\n lineCommentStartSymbol = \"#\";\n\n registers.al = \"variable\";\n registers.ah = \"variable\";\n registers.ax = \"variable\";\n registers.eax = \"variableName.special\";\n registers.rax = \"variableName.special\";\n\n registers.bl = \"variable\";\n registers.bh = \"variable\";\n registers.bx = \"variable\";\n registers.ebx = \"variableName.special\";\n registers.rbx = \"variableName.special\";\n\n registers.cl = \"variable\";\n registers.ch = \"variable\";\n registers.cx = \"variable\";\n registers.ecx = \"variableName.special\";\n registers.rcx = \"variableName.special\";\n\n registers.dl = \"variable\";\n registers.dh = \"variable\";\n registers.dx = \"variable\";\n registers.edx = \"variableName.special\";\n registers.rdx = \"variableName.special\";\n\n registers.si = \"variable\";\n registers.esi = \"variableName.special\";\n registers.rsi = \"variableName.special\";\n\n registers.di = \"variable\";\n registers.edi = \"variableName.special\";\n registers.rdi = \"variableName.special\";\n\n registers.sp = \"variable\";\n registers.esp = \"variableName.special\";\n registers.rsp = \"variableName.special\";\n\n registers.bp = \"variable\";\n registers.ebp = \"variableName.special\";\n registers.rbp = \"variableName.special\";\n\n registers.ip = \"variable\";\n registers.eip = \"variableName.special\";\n registers.rip = \"variableName.special\";\n\n registers.cs = \"keyword\";\n registers.ds = \"keyword\";\n registers.ss = \"keyword\";\n registers.es = \"keyword\";\n registers.fs = \"keyword\";\n registers.gs = \"keyword\";\n }\n\n function armv6() {\n // Reference:\n // http://infocenter.arm.com/help/topic/com.arm.doc.qrc0001l/QRC0001_UAL.pdf\n // http://infocenter.arm.com/help/topic/com.arm.doc.ddi0301h/DDI0301H_arm1176jzfs_r0p7_trm.pdf\n lineCommentStartSymbol = \"@\";\n directives.syntax = \"builtin\";\n\n registers.r0 = \"variable\";\n registers.r1 = \"variable\";\n registers.r2 = \"variable\";\n registers.r3 = \"variable\";\n registers.r4 = \"variable\";\n registers.r5 = \"variable\";\n registers.r6 = \"variable\";\n registers.r7 = \"variable\";\n registers.r8 = \"variable\";\n registers.r9 = \"variable\";\n registers.r10 = \"variable\";\n registers.r11 = \"variable\";\n registers.r12 = \"variable\";\n\n registers.sp = \"variableName.special\";\n registers.lr = \"variableName.special\";\n registers.pc = \"variableName.special\";\n registers.r13 = registers.sp;\n registers.r14 = registers.lr;\n registers.r15 = registers.pc;\n\n custom.push(function(ch, stream) {\n if (ch === '#') {\n stream.eatWhile(/\\w/);\n return \"number\";\n }\n });\n }\n\n if (arch === \"x86\") {\n x86();\n } else if (arch === \"arm\" || arch === \"armv6\") {\n armv6();\n }\n\n function nextUntilUnescaped(stream, end) {\n var escaped = false, next;\n while ((next = stream.next()) != null) {\n if (next === end && !escaped) {\n return false;\n }\n escaped = !escaped && next === \"\\\\\";\n }\n return escaped;\n }\n\n function clikeComment(stream, state) {\n var maybeEnd = false, ch;\n while ((ch = stream.next()) != null) {\n if (ch === \"/\" && maybeEnd) {\n state.tokenize = null;\n break;\n }\n maybeEnd = (ch === \"*\");\n }\n return \"comment\";\n }\n\n return {\n name: \"gas\",\n startState: function() {\n return {\n tokenize: null\n };\n },\n\n token: function(stream, state) {\n if (state.tokenize) {\n return state.tokenize(stream, state);\n }\n\n if (stream.eatSpace()) {\n return null;\n }\n\n var style, cur, ch = stream.next();\n\n if (ch === \"/\") {\n if (stream.eat(\"*\")) {\n state.tokenize = clikeComment;\n return clikeComment(stream, state);\n }\n }\n\n if (ch === lineCommentStartSymbol) {\n stream.skipToEnd();\n return \"comment\";\n }\n\n if (ch === '\"') {\n nextUntilUnescaped(stream, '\"');\n return \"string\";\n }\n\n if (ch === '.') {\n stream.eatWhile(/\\w/);\n cur = stream.current().toLowerCase();\n style = directives[cur];\n return style || null;\n }\n\n if (ch === '=') {\n stream.eatWhile(/\\w/);\n return \"tag\";\n }\n\n if (ch === '{') {\n return \"bracket\";\n }\n\n if (ch === '}') {\n return \"bracket\";\n }\n\n if (/\\d/.test(ch)) {\n if (ch === \"0\" && stream.eat(\"x\")) {\n stream.eatWhile(/[0-9a-fA-F]/);\n return \"number\";\n }\n stream.eatWhile(/\\d/);\n return \"number\";\n }\n\n if (/\\w/.test(ch)) {\n stream.eatWhile(/\\w/);\n if (stream.eat(\":\")) {\n return 'tag';\n }\n cur = stream.current().toLowerCase();\n style = registers[cur];\n return style || null;\n }\n\n for (var i = 0; i < custom.length; i++) {\n style = custom[i](ch, stream, state);\n if (style) {\n return style;\n }\n }\n },\n\n languageData: {\n commentTokens: {\n line: lineCommentStartSymbol,\n block: {open: \"/*\", close: \"*/\"}\n }\n }\n };\n};\n\nexport const gas = mkGas(\"x86\")\nexport const gasArm = mkGas(\"arm\")\n"],"names":["mkGas","arch","custom","lineCommentStartSymbol","directives","registers","clikeComment","stream","state","ch","maybeEnd","next","tokenize","al","ah","ax","eax","rax","bl","bh","bx","ebx","rbx","cl","cx","ecx","rcx","dl","dh","dx","edx","rdx","si","esi","rsi","di","edi","rdi","sp","esp","rsp","bp","ebp","rbp","ip","eip","rip","cs","ds","ss","es","fs","gs","syntax","r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","r10","r11","r12","lr","pc","r13","r14","r15","push","eatWhile","name","startState","token","eatSpace","style","cur","eat","skipToEnd","end","escaped","nextUntilUnescaped","current","toLowerCase","test","i","length","languageData","commentTokens","line","block","open","close","gas","gasArm"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/5983.index.js b/book/_build/html/_static/5983.index.js new file mode 100644 index 0000000..5c9ba28 --- /dev/null +++ b/book/_build/html/_static/5983.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[5983],{55983:(O,Q,$)=>{$.r(Q),$.d(Q,{autoCloseTags:()=>A,completionPath:()=>u,esLint:()=>N,javascript:()=>J,javascriptLanguage:()=>h,jsxLanguage:()=>G,localCompletionSource:()=>v,scopeCompletionSource:()=>j,snippets:()=>m,tsxLanguage:()=>R,typescriptLanguage:()=>q,typescriptSnippets:()=>b});var i=$(51392),e=$(86253);const a=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],Z=new i.IK({start:!1,shift:(O,Q)=>3==Q||4==Q||307==Q?O:308==Q,strict:!1}),S=new i.Jq(((O,Q)=>{let{next:$}=O;(125==$||-1==$||Q.context)&&O.acceptToken(305)}),{contextual:!0,fallback:!0}),r=new i.Jq(((O,Q)=>{let $,{next:i}=O;a.indexOf(i)>-1||(47!=i||47!=($=O.peek(1))&&42!=$)&&(125==i||59==i||-1==i||Q.context||O.acceptToken(304))}),{contextual:!0}),t=new i.Jq(((O,Q)=>{let{next:$}=O;if((43==$||45==$)&&(O.advance(),$==O.next)){O.advance();let $=!Q.context&&Q.canShift(1);O.acceptToken($?1:2)}}),{contextual:!0}),o=(0,e.Gv)({"get set async static":e.pJ.modifier,"for while do if else switch try catch finally return throw break continue default case":e.pJ.controlKeyword,"in of await yield void typeof delete instanceof":e.pJ.operatorKeyword,"let var const using function class extends":e.pJ.definitionKeyword,"import export from":e.pJ.moduleKeyword,"with debugger as new":e.pJ.keyword,TemplateString:e.pJ.special(e.pJ.string),super:e.pJ.atom,BooleanLiteral:e.pJ.bool,this:e.pJ.self,null:e.pJ.null,Star:e.pJ.modifier,VariableName:e.pJ.variableName,"CallExpression/VariableName TaggedTemplateExpression/VariableName":e.pJ.function(e.pJ.variableName),VariableDefinition:e.pJ.definition(e.pJ.variableName),Label:e.pJ.labelName,PropertyName:e.pJ.propertyName,PrivatePropertyName:e.pJ.special(e.pJ.propertyName),"CallExpression/MemberExpression/PropertyName":e.pJ.function(e.pJ.propertyName),"FunctionDeclaration/VariableDefinition":e.pJ.function(e.pJ.definition(e.pJ.variableName)),"ClassDeclaration/VariableDefinition":e.pJ.definition(e.pJ.className),PropertyDefinition:e.pJ.definition(e.pJ.propertyName),PrivatePropertyDefinition:e.pJ.definition(e.pJ.special(e.pJ.propertyName)),UpdateOp:e.pJ.updateOperator,"LineComment Hashbang":e.pJ.lineComment,BlockComment:e.pJ.blockComment,Number:e.pJ.number,String:e.pJ.string,Escape:e.pJ.escape,ArithOp:e.pJ.arithmeticOperator,LogicOp:e.pJ.logicOperator,BitOp:e.pJ.bitwiseOperator,CompareOp:e.pJ.compareOperator,RegExp:e.pJ.regexp,Equals:e.pJ.definitionOperator,Arrow:e.pJ.function(e.pJ.punctuation),": Spread":e.pJ.punctuation,"( )":e.pJ.paren,"[ ]":e.pJ.squareBracket,"{ }":e.pJ.brace,"InterpolationStart InterpolationEnd":e.pJ.special(e.pJ.brace),".":e.pJ.derefOperator,", ;":e.pJ.separator,"@":e.pJ.meta,TypeName:e.pJ.typeName,TypeDefinition:e.pJ.definition(e.pJ.typeName),"type enum interface implements namespace module declare":e.pJ.definitionKeyword,"abstract global Privacy readonly override":e.pJ.modifier,"is keyof unique infer":e.pJ.operatorKeyword,JSXAttributeValue:e.pJ.attributeValue,JSXText:e.pJ.content,"JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag":e.pJ.angleBracket,"JSXIdentifier JSXNameSpacedName":e.pJ.tagName,"JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName":e.pJ.attributeName,"JSXBuiltin/JSXIdentifier":e.pJ.standard(e.pJ.tagName)}),n={__proto__:null,export:16,as:21,from:29,default:32,async:37,function:38,extends:48,this:52,true:60,false:60,null:72,void:76,typeof:80,super:98,new:132,delete:148,yield:157,await:161,class:166,public:223,private:223,protected:223,readonly:225,instanceof:244,satisfies:247,in:248,const:250,import:282,keyof:337,unique:341,infer:347,is:383,abstract:403,implements:405,type:407,let:410,var:412,using:415,interface:421,enum:425,namespace:431,module:433,declare:437,global:441,for:460,of:469,while:472,with:476,do:480,if:484,else:486,switch:490,case:496,try:502,catch:506,finally:510,return:514,throw:518,break:522,continue:526,debugger:530},l={__proto__:null,async:119,get:121,set:123,declare:183,public:185,private:185,protected:185,static:187,abstract:189,override:191,readonly:197,accessor:199,new:387},p={__proto__:null,"<":139},P=i.WQ.deserialize({version:14,states:"$6zO%TQUOOO%[QUOOO'_QWOOP(lOSOOO*zQ(CjO'#CgO+ROpO'#ChO+aO!bO'#ChO+oO07`O'#D[O.QQUO'#DbO.bQUO'#DmO%[QUO'#DwO0fQUO'#EPOOQ(CY'#EX'#EXO1PQSO'#EUOOQO'#Ej'#EjOOQO'#Id'#IdO1XQSO'#GlO1dQSO'#EiO1iQSO'#EiO3kQ(CjO'#JeO6[Q(CjO'#JfO6xQSO'#FXO6}Q#tO'#FpOOQ(CY'#Fa'#FaO7YO&jO'#FaO7hQ,UO'#FwO9OQSO'#FvO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z-|2g2h5|Q1a,^Q1w,tQ5j1oQ7r5kT:}'O*{T#`W%aS#_W%aS'z#V(SS(P#Y*zS,y'O*{T-m'y-rT'T!e%bQ$kfR)o$pT)d$k)eR3`.pT*T$x*VR*]${Q0V+VQ2j.TQ4x0|Q6Q2nQ7^4{Q7}6PQ8j7]Q8|7|Q9]8lQ9e9OQ9j9^R9m9fnqOXst!Z#c%f&i&k&l&n,b,g1g1jQ&c!VR,V&`tmOXst!U!V!Z#c%f&`&i&k&l&n,b,g1g1jR,^&fT%em,^R0v+vR,U&^Q%||R+n%}R+d%wT&g!W&jT&h!W&jT1i,g1j",nodeNames:"⚠ ArithOp ArithOp LineComment BlockComment Script Hashbang ExportDeclaration export Star as VariableName String Escape from ; default FunctionDeclaration async function VariableDefinition > TypeParamList TypeDefinition extends ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation InterpolationStart NullType null VoidType void TypeofType typeof MemberExpression . ?. PropertyName [ TemplateString Escape Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewExpression new TypeArgList CompareOp < ) ( ArgList UnaryExpression delete LogicOp BitOp YieldExpression yield AwaitExpression await ParenthesizedExpression ClassExpression class ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression declare Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies in const CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXStartTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast ArrowFunction TypeParamList SequenceExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var using TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression SingleClassItem",maxTerm:367,context:Z,nodeProps:[["group",-26,7,15,17,63,200,204,208,209,211,214,217,227,229,235,237,239,241,244,250,256,258,260,262,264,266,267,"Statement",-32,11,12,26,29,30,36,46,49,50,52,57,65,73,77,79,81,82,104,105,114,115,132,135,137,138,139,140,142,143,163,164,166,"Expression",-23,25,27,31,35,37,39,167,169,171,172,174,175,176,178,179,180,182,183,184,194,196,198,199,"Type",-3,85,97,103,"ClassItem"],["openedBy",32,"InterpolationStart",51,"[",55,"{",70,"(",144,"JSXStartTag",156,"JSXStartTag JSXStartCloseTag"],["closedBy",34,"InterpolationEnd",45,"]",56,"}",71,")",145,"JSXSelfCloseEndTag JSXEndTag",161,"JSXEndTag"]],propSources:[o],skippedNodes:[0,3,4,270],repeatNodeCount:33,tokenData:"$Fl(CSR!bOX%ZXY+gYZ-yZ[+g[]%Z]^.c^p%Zpq+gq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ic;'S;=`!JT<%lO!Ic!f!JWP;=`<%l!Ic!f!J^P;=`<%l!GY(Q!Jh^$e&j'|!bOY!JaYZ&cZw!Jawx!Bwx!^!Ja!^!_!Ic!_#O!Ja#O#P!Cr#P#Q!Q#V#X%Z#X#Y!4|#Y#b%Z#b#c#Zd$e&j'yp'|!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!R#?i!R!S#?i!S!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#?i#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z$/l#?tf$e&j'yp'|!bm$'|OY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!R#?i!R!S#?i!S!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#?i#S#b%Z#b#c#n[O]||-1},{term:330,get:O=>l[O]||-1},{term:68,get:O=>p[O]||-1}],tokenPrec:12868});var Y=$(77120),g=$(1727),X=$(65329),c=$(64100),s=$(21649);const m=[(0,c.Gn)("function ${name}(${params}) {\n\t${}\n}",{label:"function",detail:"definition",type:"keyword"}),(0,c.Gn)("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n\t${}\n}",{label:"for",detail:"loop",type:"keyword"}),(0,c.Gn)("for (let ${name} of ${collection}) {\n\t${}\n}",{label:"for",detail:"of loop",type:"keyword"}),(0,c.Gn)("do {\n\t${}\n} while (${})",{label:"do",detail:"loop",type:"keyword"}),(0,c.Gn)("while (${}) {\n\t${}\n}",{label:"while",detail:"loop",type:"keyword"}),(0,c.Gn)("try {\n\t${}\n} catch (${error}) {\n\t${}\n}",{label:"try",detail:"/ catch block",type:"keyword"}),(0,c.Gn)("if (${}) {\n\t${}\n}",{label:"if",detail:"block",type:"keyword"}),(0,c.Gn)("if (${}) {\n\t${}\n} else {\n\t${}\n}",{label:"if",detail:"/ else block",type:"keyword"}),(0,c.Gn)("class ${name} {\n\tconstructor(${params}) {\n\t\t${}\n\t}\n}",{label:"class",detail:"definition",type:"keyword"}),(0,c.Gn)('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),(0,c.Gn)('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],b=m.concat([(0,c.Gn)("interface ${name} {\n\t${}\n}",{label:"interface",detail:"definition",type:"keyword"}),(0,c.Gn)("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),(0,c.Gn)("enum ${name} {\n\t${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),d=new s.hr,x=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function w(O){return(Q,$)=>{let i=Q.node.getChild("VariableDefinition");return i&&$(i,O),!0}}const y=["FunctionDeclaration"],U={FunctionDeclaration:w("function"),ClassDeclaration:w("class"),ClassExpression:()=>!0,EnumDeclaration:w("constant"),TypeAliasDeclaration:w("type"),NamespaceDeclaration:w("namespace"),VariableDefinition(O,Q){O.matchContext(y)||Q(O,"variable")},TypeDefinition(O,Q){Q(O,"type")},__proto__:null};function _(O,Q){let $=d.get(Q);if($)return $;let i=[],e=!0;function a(Q,$){let e=O.sliceString(Q.from,Q.to);i.push({label:e,type:$})}return Q.cursor(s.vj.IncludeAnonymous).iterate((Q=>{if(e)e=!1;else if(Q.name){let O=U[Q.name];if(O&&O(Q,a)||x.has(Q.name))return!1}else if(Q.to-Q.from>8192){for(let $ of _(O,Q.node))i.push($);return!1}})),d.set(Q,i),i}const W=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,f=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName",".","?."];function v(O){let Q=(0,Y.qz)(O.state).resolveInner(O.pos,-1);if(f.indexOf(Q.name)>-1)return null;let $="VariableName"==Q.name||Q.to-Q.from<20&&W.test(O.state.sliceDoc(Q.from,Q.to));if(!$&&!O.explicit)return null;let i=[];for(let $=Q;$;$=$.parent)x.has($.name)&&(i=i.concat(_(O.state.doc,$)));return{options:i,from:$?Q.from:O.pos,validFor:W}}function T(O,Q,$){var i;let e=[];for(;;){let a,Z=Q.firstChild;if("VariableName"==(null==Z?void 0:Z.name))return e.push(O(Z)),{path:e.reverse(),name:$};if("MemberExpression"!=(null==Z?void 0:Z.name)||"PropertyName"!=(null===(i=a=Z.lastChild)||void 0===i?void 0:i.name))return null;e.push(O(a)),Q=Z}}function u(O){let Q=Q=>O.state.doc.sliceString(Q.from,Q.to),$=(0,Y.qz)(O.state).resolveInner(O.pos,-1);return"PropertyName"==$.name?T(Q,$.parent,Q($)):"."!=$.name&&"?."!=$.name||"MemberExpression"!=$.parent.name?f.indexOf($.name)>-1?null:"VariableName"==$.name||$.to-$.from<20&&W.test(Q($))?{path:[],name:Q($)}:"MemberExpression"==$.name?T(Q,$,""):O.explicit?{path:[],name:""}:null:T(Q,$.parent,"")}function j(O){let Q=new Map;return $=>{let i=u($);if(!i)return null;let e=O;for(let O of i.path)if(e=e[O],!e)return null;let a=Q.get(e);return a||Q.set(e,a=function(O,Q){let $=[],i=new Set;for(let e=0;;e++){for(let a of(Object.getOwnPropertyNames||Object.keys)(O)){if(!/^[a-zA-Z_$\xaa-\uffdc][\w$\xaa-\uffdc]*$/.test(a)||i.has(a))continue;let Z;i.add(a);try{Z=O[a]}catch(O){continue}$.push({label:a,type:"function"==typeof Z?/^[A-Z]/.test(a)?"class":Q?"function":"method":Q?"variable":"property",boost:-e})}let a=Object.getPrototypeOf(O);if(!a)return $;O=a}}(e,!i.path.length)),{from:$.pos-i.name.length,options:a,validFor:W}}}const h=Y.qp.define({name:"javascript",parser:P.configure({props:[Y.uj.add({IfStatement:(0,Y.tC)({except:/^\s*({|else\b)/}),TryStatement:(0,Y.tC)({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:Y.ze,SwitchBody:O=>{let Q=O.textAfter,$=/^\s*\}/.test(Q),i=/^\s*(case|default)\b/.test(Q);return O.baseIndent+($?0:i?1:2)*O.unit},Block:(0,Y.vw)({closing:"}"}),ArrowFunction:O=>O.baseIndent+O.unit,"TemplateString BlockComment":()=>null,"Statement Property":(0,Y.tC)({except:/^{/}),JSXElement(O){let Q=/^\s*<\//.test(O.textAfter);return O.lineIndent(O.node.from)+(Q?0:O.unit)},JSXEscape(O){let Q=/\s*\}/.test(O.textAfter);return O.lineIndent(O.node.from)+(Q?0:O.unit)},"JSXOpenTag JSXSelfClosingTag":O=>O.column(O.node.from)+O.unit}),Y.x0.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":Y.Dv,BlockComment:O=>({from:O.from+2,to:O.to-2})})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),k={test:O=>/^JSX/.test(O.name),facet:(0,Y.kU)({commentTokens:{block:{open:"{/*",close:"*/}"}}})},q=h.configure({dialect:"ts"},"typescript"),G=h.configure({dialect:"jsx",props:[Y.KC.add((O=>O.isTop?[k]:void 0))]}),R=h.configure({dialect:"jsx ts",props:[Y.KC.add((O=>O.isTop?[k]:void 0))]},"typescript");let C=O=>({label:O,type:"keyword"});const z="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(C),V=z.concat(["declare","implements","private","protected","public"].map(C));function J(O={}){let Q=O.jsx?O.typescript?R:G:O.typescript?q:h,$=O.typescript?b.concat(V):m.concat(z);return new Y.ri(Q,[h.data.of({autocomplete:(0,c.eC)(f,(0,c.Mb)($))}),h.data.of({autocomplete:v}),O.jsx?A:[]])}function E(O,Q,$=O.length){for(let i=null==Q?void 0:Q.firstChild;i;i=i.nextSibling)if("JSXIdentifier"==i.name||"JSXBuiltin"==i.name||"JSXNamespacedName"==i.name||"JSXMemberExpression"==i.name)return O.sliceString(i.from,Math.min(i.to,$));return""}const I="object"==typeof navigator&&/Android\b/.test(navigator.userAgent),A=X.tk.inputHandler.of(((O,Q,$,i,e)=>{if((I?O.composing:O.compositionStarted)||O.state.readOnly||Q!=$||">"!=i&&"/"!=i||!h.isActiveAt(O.state,Q,-1))return!1;let a=e(),{state:Z}=a,S=Z.changeByRange((O=>{var Q;let $,{head:e}=O,a=(0,Y.qz)(Z).resolveInner(e-1,-1);if("JSXStartTag"==a.name&&(a=a.parent),Z.doc.sliceString(e-1,e)!=i||"JSXAttributeValue"==a.name&&a.to>e);else{if(">"==i&&"JSXFragmentTag"==a.name)return{range:O,changes:{from:e,insert:""}};if("/"==i&&"JSXStartCloseTag"==a.name){let O=a.parent,i=O.parent;if(i&&O.from==e-2&&(($=E(Z.doc,i.firstChild,e))||"JSXFragmentTag"==(null===(Q=i.firstChild)||void 0===Q?void 0:Q.name))){let O=`${$}>`;return{range:g.jT.cursor(e+O.length,-1),changes:{from:e,insert:O}}}}else if(">"==i){let Q=function(O){for(;;){if("JSXOpenTag"==O.name||"JSXSelfClosingTag"==O.name||"JSXFragmentTag"==O.name)return O;if("JSXEscape"==O.name||!O.parent)return null;O=O.parent}}(a);if(Q&&!/^\/?>|^<\//.test(Z.doc.sliceString(e,e+2))&&($=E(Z.doc,Q,e)))return{range:O,changes:{from:e,insert:``}}}}return{range:O}}));return!S.changes.empty&&(O.dispatch([a,Z.update(S,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}));function N(O,Q){return Q||(Q={parserOptions:{ecmaVersion:2019,sourceType:"module"},env:{browser:!0,node:!0,es6:!0,es2015:!0,es2017:!0,es2020:!0},rules:{}},O.getRules().forEach(((O,$)=>{O.meta.docs.recommended&&(Q.rules[$]=2)}))),$=>{let{state:i}=$,e=[];for(let{from:$,to:a}of h.findRegions(i)){let Z=i.doc.lineAt($),S={line:Z.number-1,col:$-Z.from,pos:$};for(let Z of O.verify(i.sliceDoc($,a),Q))e.push(K(Z,i.doc,S))}return e}}function D(O,Q,$,i){return $.line(O+i.line).from+Q+(1==O?i.col-1:-1)}function K(O,Q,$){let i=D(O.line,O.column,Q,$),e={from:i,to:null!=O.endLine&&1!=O.endColumn?D(O.endLine,O.endColumn,Q,$):i,message:O.message,source:O.ruleId?"eslint:"+O.ruleId:"eslint",severity:1==O.severity?"warning":"error"};if(O.fix){let{range:Q,text:a}=O.fix,Z=Q[0]+$.pos-i,S=Q[1]+$.pos-i;e.actions=[{name:"fix",apply(O,Q){O.dispatch({changes:{from:Q+Z,to:Q+S,insert:a},scrollIntoView:!0})}}]}return e}}}]); +//# sourceMappingURL=5983.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/5983.index.js.map b/book/_build/html/_static/5983.index.js.map new file mode 100644 index 0000000..a7f9ca4 --- /dev/null +++ b/book/_build/html/_static/5983.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"5983.index.js","mappings":"sYAIA,MAYMA,EAAQ,CAAC,EAAG,GAAI,GAAI,GAAI,GAAI,GAAI,IAAK,IAAK,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KACvF,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,OAI7CC,EAAe,IAAI,KAAe,CACtCC,OAAO,EACPC,MAAK,CAACC,EAASC,IAbD,GAcLA,GAbM,GAaiBA,GAhBvB,KAgB+CA,EAAiBD,EAf/D,KAeyEC,EAEnFC,QAAQ,IAGJC,EAAkB,IAAI,MAAkB,CAACC,EAAOC,KACpD,IAAI,KAACC,GAAQF,GAXA,KAYTE,IAA2B,GAATA,GAAcD,EAAML,UACxCI,EAAMG,YAzBK,IAyBkB,GAC9B,CAACC,YAAY,EAAMC,UAAU,IAE1BC,EAAc,IAAI,MAAkB,CAACN,EAAOC,KAChD,IAAoBM,GAAhB,KAACL,GAAQF,EACTR,EAAMgB,QAAQN,IAAS,IAlBe,IAmBtCA,GAnBsC,KAmBnBK,EAAQP,EAAMS,KAAK,KAnBW,IAmBKF,KAnB7C,KAoBTL,GApB0B,IAoBRA,IAA8B,GAATA,GAAeD,EAAML,SAC9DI,EAAM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5O,KAAMtD,EAAQsD,EAAMiH,GAAIvK,EAAQuK,EAAI4H,OAAQb,GAAQoB,gBAAgB,GACnG,GAEZ,CACA,OAAO8B,CACX,C","sources":["webpack://thebe/../../node_modules/@lezer/javascript/dist/index.js","webpack://thebe/../../node_modules/@codemirror/lang-javascript/dist/index.js"],"sourcesContent":["import { ContextTracker, ExternalTokenizer, LRParser, LocalTokenGroup } from '@lezer/lr';\nimport { styleTags, tags } from '@lezer/highlight';\n\n// This file was generated by lezer-generator. You probably shouldn't edit it.\nconst noSemi = 304,\n incdec = 1,\n incdecPrefix = 2,\n insertSemi = 305,\n spaces = 307,\n newline = 308,\n LineComment = 3,\n BlockComment = 4;\n\n/* Hand-written tokenizers for JavaScript tokens that can't be\n expressed by lezer's built-in tokenizer. */\n\nconst space = [9, 10, 11, 12, 13, 32, 133, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200,\n 8201, 8202, 8232, 8233, 8239, 8287, 12288];\n\nconst braceR = 125, semicolon = 59, slash = 47, star = 42, plus = 43, minus = 45;\n\nconst trackNewline = new ContextTracker({\n start: false,\n shift(context, term) {\n return term == LineComment || term == BlockComment || term == spaces ? context : term == newline\n },\n strict: false\n});\n\nconst insertSemicolon = new ExternalTokenizer((input, stack) => {\n let {next} = input;\n if (next == braceR || next == -1 || stack.context)\n input.acceptToken(insertSemi);\n}, {contextual: true, fallback: true});\n\nconst noSemicolon = new ExternalTokenizer((input, stack) => {\n let {next} = input, after;\n if (space.indexOf(next) > -1) return\n if (next == slash && ((after = input.peek(1)) == slash || after == star)) return\n if (next != braceR && next != semicolon && next != -1 && !stack.context)\n input.acceptToken(noSemi);\n}, {contextual: true});\n\nconst incdecToken = new ExternalTokenizer((input, stack) => {\n let {next} = input;\n if (next == plus || next == minus) {\n input.advance();\n if (next == input.next) {\n input.advance();\n let mayPostfix = !stack.context && stack.canShift(incdec);\n input.acceptToken(mayPostfix ? incdec : incdecPrefix);\n }\n }\n}, {contextual: true});\n\nconst jsHighlight = styleTags({\n \"get set async static\": tags.modifier,\n \"for while do if else switch try catch finally return throw break continue default case\": tags.controlKeyword,\n \"in of await yield void typeof delete instanceof\": tags.operatorKeyword,\n \"let var const using function class extends\": tags.definitionKeyword,\n \"import export from\": tags.moduleKeyword,\n \"with debugger as new\": tags.keyword,\n TemplateString: tags.special(tags.string),\n super: tags.atom,\n BooleanLiteral: tags.bool,\n this: tags.self,\n null: tags.null,\n Star: tags.modifier,\n VariableName: tags.variableName,\n \"CallExpression/VariableName TaggedTemplateExpression/VariableName\": tags.function(tags.variableName),\n VariableDefinition: tags.definition(tags.variableName),\n Label: tags.labelName,\n PropertyName: tags.propertyName,\n PrivatePropertyName: tags.special(tags.propertyName),\n \"CallExpression/MemberExpression/PropertyName\": tags.function(tags.propertyName),\n \"FunctionDeclaration/VariableDefinition\": tags.function(tags.definition(tags.variableName)),\n \"ClassDeclaration/VariableDefinition\": tags.definition(tags.className),\n PropertyDefinition: tags.definition(tags.propertyName),\n PrivatePropertyDefinition: tags.definition(tags.special(tags.propertyName)),\n UpdateOp: tags.updateOperator,\n \"LineComment Hashbang\": tags.lineComment,\n BlockComment: tags.blockComment,\n Number: tags.number,\n String: tags.string,\n Escape: tags.escape,\n ArithOp: tags.arithmeticOperator,\n LogicOp: tags.logicOperator,\n BitOp: tags.bitwiseOperator,\n CompareOp: tags.compareOperator,\n RegExp: tags.regexp,\n Equals: tags.definitionOperator,\n Arrow: tags.function(tags.punctuation),\n \": Spread\": tags.punctuation,\n \"( )\": tags.paren,\n \"[ ]\": tags.squareBracket,\n \"{ }\": tags.brace,\n \"InterpolationStart InterpolationEnd\": tags.special(tags.brace),\n \".\": tags.derefOperator,\n \", ;\": tags.separator,\n \"@\": tags.meta,\n\n TypeName: tags.typeName,\n TypeDefinition: tags.definition(tags.typeName),\n \"type enum interface implements namespace module declare\": tags.definitionKeyword,\n \"abstract global Privacy readonly override\": tags.modifier,\n \"is keyof unique infer\": tags.operatorKeyword,\n\n JSXAttributeValue: tags.attributeValue,\n JSXText: tags.content,\n \"JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag\": tags.angleBracket,\n \"JSXIdentifier JSXNameSpacedName\": tags.tagName,\n \"JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName\": tags.attributeName,\n \"JSXBuiltin/JSXIdentifier\": tags.standard(tags.tagName)\n});\n\n// This file was generated by lezer-generator. You probably shouldn't edit it.\nconst spec_identifier = {__proto__:null,export:16, as:21, from:29, default:32, async:37, function:38, extends:48, this:52, true:60, false:60, null:72, void:76, typeof:80, super:98, new:132, delete:148, yield:157, await:161, class:166, public:223, private:223, protected:223, readonly:225, instanceof:244, satisfies:247, in:248, const:250, import:282, keyof:337, unique:341, infer:347, is:383, abstract:403, implements:405, type:407, let:410, var:412, using:415, interface:421, enum:425, namespace:431, module:433, declare:437, global:441, for:460, of:469, while:472, with:476, do:480, if:484, else:486, switch:490, case:496, try:502, catch:506, finally:510, return:514, throw:518, break:522, continue:526, debugger:530};\nconst spec_word = {__proto__:null,async:119, get:121, set:123, declare:183, public:185, private:185, protected:185, static:187, abstract:189, override:191, readonly:197, accessor:199, new:387};\nconst spec_LessThan = {__proto__:null,\"<\":139};\nconst parser = LRParser.deserialize({\n version: 14,\n states: \"$6zO%TQUOOO%[QUOOO'_QWOOP(lOSOOO*zQ(CjO'#CgO+ROpO'#ChO+aO!bO'#ChO+oO07`O'#D[O.QQUO'#DbO.bQUO'#DmO%[QUO'#DwO0fQUO'#EPOOQ(CY'#EX'#EXO1PQSO'#EUOOQO'#Ej'#EjOOQO'#Id'#IdO1XQSO'#GlO1dQSO'#EiO1iQSO'#EiO3kQ(CjO'#JeO6[Q(CjO'#JfO6xQSO'#FXO6}Q#tO'#FpOOQ(CY'#Fa'#FaO7YO&jO'#FaO7hQ,UO'#FwO9OQSO'#FvOOQ(CY'#Jf'#JfOOQ(CW'#Je'#JeO9TQSO'#GpOOQQ'#KQ'#KQO9`QSO'#IQO9eQ(C[O'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T-m'y-rT'T!e%bQ$kfR)o$pT)d$k)eR3`.pT*T$x*VR*]${Q0V+VQ2j.TQ4x0|Q6Q2nQ7^4{Q7}6PQ8j7]Q8|7|Q9]8lQ9e9OQ9j9^R9m9fnqOXst!Z#c%f&i&k&l&n,b,g1g1jQ&c!VR,V&`tmOXst!U!V!Z#c%f&`&i&k&l&n,b,g1g1jR,^&fT%em,^R0v+vR,U&^Q%||R+n%}R+d%wT&g!W&jT&h!W&jT1i,g1j\",\n nodeNames: \"⚠ ArithOp ArithOp LineComment BlockComment Script Hashbang ExportDeclaration export Star as VariableName String Escape from ; default FunctionDeclaration async function VariableDefinition > TypeParamList TypeDefinition extends ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation InterpolationStart NullType null VoidType void TypeofType typeof MemberExpression . ?. PropertyName [ TemplateString Escape Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewExpression new TypeArgList CompareOp < ) ( ArgList UnaryExpression delete LogicOp BitOp YieldExpression yield AwaitExpression await ParenthesizedExpression ClassExpression class ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression declare Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies in const CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXStartTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast ArrowFunction TypeParamList SequenceExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var using TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression SingleClassItem\",\n maxTerm: 367,\n context: trackNewline,\n nodeProps: [\n [\"group\", -26,7,15,17,63,200,204,208,209,211,214,217,227,229,235,237,239,241,244,250,256,258,260,262,264,266,267,\"Statement\",-32,11,12,26,29,30,36,46,49,50,52,57,65,73,77,79,81,82,104,105,114,115,132,135,137,138,139,140,142,143,163,164,166,\"Expression\",-23,25,27,31,35,37,39,167,169,171,172,174,175,176,178,179,180,182,183,184,194,196,198,199,\"Type\",-3,85,97,103,\"ClassItem\"],\n [\"openedBy\", 32,\"InterpolationStart\",51,\"[\",55,\"{\",70,\"(\",144,\"JSXStartTag\",156,\"JSXStartTag JSXStartCloseTag\"],\n [\"closedBy\", 34,\"InterpolationEnd\",45,\"]\",56,\"}\",71,\")\",145,\"JSXSelfCloseEndTag JSXEndTag\",161,\"JSXEndTag\"]\n ],\n propSources: [jsHighlight],\n skippedNodes: [0,3,4,270],\n repeatNodeCount: 33,\n tokenData: \"$Fl(CSR!bOX%ZXY+gYZ-yZ[+g[]%Z]^.c^p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#Q;'S!Ic;'S;=`!JT<%lO!Ic!f!JWP;=`<%l!Ic!f!J^P;=`<%l!GY(Q!Jh^$e&j'|!bOY!JaYZ&cZw!Jawx!Bwx!^!Ja!^!_!Ic!_#O!Ja#O#P!Cr#P#Q!Q#V#X%Z#X#Y!4|#Y#b%Z#b#c#Zd$e&j'yp'|!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!R#?i!R!S#?i!S!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#?i#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z$/l#?tf$e&j'yp'|!bm$'|OY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!R#?i!R!S#?i!S!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#?i#S#b%Z#b#c# spec_identifier[value] || -1},{term: 330, get: (value) => spec_word[value] || -1},{term: 68, get: (value) => spec_LessThan[value] || -1}],\n tokenPrec: 12868\n});\n\nexport { parser };\n","import { parser } from '@lezer/javascript';\nimport { syntaxTree, LRLanguage, indentNodeProp, continuedIndent, flatIndent, delimitedIndent, foldNodeProp, foldInside, defineLanguageFacet, sublanguageProp, LanguageSupport } from '@codemirror/language';\nimport { EditorSelection } from '@codemirror/state';\nimport { EditorView } from '@codemirror/view';\nimport { snippetCompletion, ifNotIn, completeFromList } from '@codemirror/autocomplete';\nimport { NodeWeakMap, IterMode } from '@lezer/common';\n\n/**\nA collection of JavaScript-related\n[snippets](https://codemirror.net/6/docs/ref/#autocomplete.snippet).\n*/\nconst snippets = [\n /*@__PURE__*/snippetCompletion(\"function ${name}(${params}) {\\n\\t${}\\n}\", {\n label: \"function\",\n detail: \"definition\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\\n\\t${}\\n}\", {\n label: \"for\",\n detail: \"loop\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"for (let ${name} of ${collection}) {\\n\\t${}\\n}\", {\n label: \"for\",\n detail: \"of loop\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"do {\\n\\t${}\\n} while (${})\", {\n label: \"do\",\n detail: \"loop\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"while (${}) {\\n\\t${}\\n}\", {\n label: \"while\",\n detail: \"loop\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"try {\\n\\t${}\\n} catch (${error}) {\\n\\t${}\\n}\", {\n label: \"try\",\n detail: \"/ catch block\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"if (${}) {\\n\\t${}\\n}\", {\n label: \"if\",\n detail: \"block\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"if (${}) {\\n\\t${}\\n} else {\\n\\t${}\\n}\", {\n label: \"if\",\n detail: \"/ else block\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"class ${name} {\\n\\tconstructor(${params}) {\\n\\t\\t${}\\n\\t}\\n}\", {\n label: \"class\",\n detail: \"definition\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"import {${names}} from \\\"${module}\\\"\\n${}\", {\n label: \"import\",\n detail: \"named\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"import ${name} from \\\"${module}\\\"\\n${}\", {\n label: \"import\",\n detail: \"default\",\n type: \"keyword\"\n })\n];\n/**\nA collection of snippet completions for TypeScript. Includes the\nJavaScript [snippets](https://codemirror.net/6/docs/ref/#lang-javascript.snippets).\n*/\nconst typescriptSnippets = /*@__PURE__*/snippets.concat([\n /*@__PURE__*/snippetCompletion(\"interface ${name} {\\n\\t${}\\n}\", {\n label: \"interface\",\n detail: \"definition\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"type ${name} = ${type}\", {\n label: \"type\",\n detail: \"definition\",\n type: \"keyword\"\n }),\n /*@__PURE__*/snippetCompletion(\"enum ${name} {\\n\\t${}\\n}\", {\n label: \"enum\",\n detail: \"definition\",\n type: \"keyword\"\n })\n]);\n\nconst cache = /*@__PURE__*/new NodeWeakMap();\nconst ScopeNodes = /*@__PURE__*/new Set([\n \"Script\", \"Block\",\n \"FunctionExpression\", \"FunctionDeclaration\", \"ArrowFunction\", \"MethodDeclaration\",\n \"ForStatement\"\n]);\nfunction defID(type) {\n return (node, def) => {\n let id = node.node.getChild(\"VariableDefinition\");\n if (id)\n def(id, type);\n return true;\n };\n}\nconst functionContext = [\"FunctionDeclaration\"];\nconst gatherCompletions = {\n FunctionDeclaration: /*@__PURE__*/defID(\"function\"),\n ClassDeclaration: /*@__PURE__*/defID(\"class\"),\n ClassExpression: () => true,\n EnumDeclaration: /*@__PURE__*/defID(\"constant\"),\n TypeAliasDeclaration: /*@__PURE__*/defID(\"type\"),\n NamespaceDeclaration: /*@__PURE__*/defID(\"namespace\"),\n VariableDefinition(node, def) { if (!node.matchContext(functionContext))\n def(node, \"variable\"); },\n TypeDefinition(node, def) { def(node, \"type\"); },\n __proto__: null\n};\nfunction getScope(doc, node) {\n let cached = cache.get(node);\n if (cached)\n return cached;\n let completions = [], top = true;\n function def(node, type) {\n let name = doc.sliceString(node.from, node.to);\n completions.push({ label: name, type });\n }\n node.cursor(IterMode.IncludeAnonymous).iterate(node => {\n if (top) {\n top = false;\n }\n else if (node.name) {\n let gather = gatherCompletions[node.name];\n if (gather && gather(node, def) || ScopeNodes.has(node.name))\n return false;\n }\n else if (node.to - node.from > 8192) {\n // Allow caching for bigger internal nodes\n for (let c of getScope(doc, node.node))\n completions.push(c);\n return false;\n }\n });\n cache.set(node, completions);\n return completions;\n}\nconst Identifier = /^[\\w$\\xa1-\\uffff][\\w$\\d\\xa1-\\uffff]*$/;\nconst dontComplete = [\n \"TemplateString\", \"String\", \"RegExp\",\n \"LineComment\", \"BlockComment\",\n \"VariableDefinition\", \"TypeDefinition\", \"Label\",\n \"PropertyDefinition\", \"PropertyName\",\n \"PrivatePropertyDefinition\", \"PrivatePropertyName\",\n \".\", \"?.\"\n];\n/**\nCompletion source that looks up locally defined names in\nJavaScript code.\n*/\nfunction localCompletionSource(context) {\n let inner = syntaxTree(context.state).resolveInner(context.pos, -1);\n if (dontComplete.indexOf(inner.name) > -1)\n return null;\n let isWord = inner.name == \"VariableName\" ||\n inner.to - inner.from < 20 && Identifier.test(context.state.sliceDoc(inner.from, inner.to));\n if (!isWord && !context.explicit)\n return null;\n let options = [];\n for (let pos = inner; pos; pos = pos.parent) {\n if (ScopeNodes.has(pos.name))\n options = options.concat(getScope(context.state.doc, pos));\n }\n return {\n options,\n from: isWord ? inner.from : context.pos,\n validFor: Identifier\n };\n}\nfunction pathFor(read, member, name) {\n var _a;\n let path = [];\n for (;;) {\n let obj = member.firstChild, prop;\n if ((obj === null || obj === void 0 ? void 0 : obj.name) == \"VariableName\") {\n path.push(read(obj));\n return { path: path.reverse(), name };\n }\n else if ((obj === null || obj === void 0 ? void 0 : obj.name) == \"MemberExpression\" && ((_a = (prop = obj.lastChild)) === null || _a === void 0 ? void 0 : _a.name) == \"PropertyName\") {\n path.push(read(prop));\n member = obj;\n }\n else {\n return null;\n }\n }\n}\n/**\nHelper function for defining JavaScript completion sources. It\nreturns the completable name and object path for a completion\ncontext, or null if no name/property completion should happen at\nthat position. For example, when completing after `a.b.c` it will\nreturn `{path: [\"a\", \"b\"], name: \"c\"}`. When completing after `x`\nit will return `{path: [], name: \"x\"}`. When not in a property or\nname, it will return null if `context.explicit` is false, and\n`{path: [], name: \"\"}` otherwise.\n*/\nfunction completionPath(context) {\n let read = (node) => context.state.doc.sliceString(node.from, node.to);\n let inner = syntaxTree(context.state).resolveInner(context.pos, -1);\n if (inner.name == \"PropertyName\") {\n return pathFor(read, inner.parent, read(inner));\n }\n else if ((inner.name == \".\" || inner.name == \"?.\") && inner.parent.name == \"MemberExpression\") {\n return pathFor(read, inner.parent, \"\");\n }\n else if (dontComplete.indexOf(inner.name) > -1) {\n return null;\n }\n else if (inner.name == \"VariableName\" || inner.to - inner.from < 20 && Identifier.test(read(inner))) {\n return { path: [], name: read(inner) };\n }\n else if (inner.name == \"MemberExpression\") {\n return pathFor(read, inner, \"\");\n }\n else {\n return context.explicit ? { path: [], name: \"\" } : null;\n }\n}\nfunction enumeratePropertyCompletions(obj, top) {\n let options = [], seen = new Set;\n for (let depth = 0;; depth++) {\n for (let name of (Object.getOwnPropertyNames || Object.keys)(obj)) {\n if (!/^[a-zA-Z_$\\xaa-\\uffdc][\\w$\\xaa-\\uffdc]*$/.test(name) || seen.has(name))\n continue;\n seen.add(name);\n let value;\n try {\n value = obj[name];\n }\n catch (_) {\n continue;\n }\n options.push({\n label: name,\n type: typeof value == \"function\" ? (/^[A-Z]/.test(name) ? \"class\" : top ? \"function\" : \"method\")\n : top ? \"variable\" : \"property\",\n boost: -depth\n });\n }\n let next = Object.getPrototypeOf(obj);\n if (!next)\n return options;\n obj = next;\n }\n}\n/**\nDefines a [completion source](https://codemirror.net/6/docs/ref/#autocomplete.CompletionSource) that\ncompletes from the given scope object (for example `globalThis`).\nWill enter properties of the object when completing properties on\na directly-named path.\n*/\nfunction scopeCompletionSource(scope) {\n let cache = new Map;\n return (context) => {\n let path = completionPath(context);\n if (!path)\n return null;\n let target = scope;\n for (let step of path.path) {\n target = target[step];\n if (!target)\n return null;\n }\n let options = cache.get(target);\n if (!options)\n cache.set(target, options = enumeratePropertyCompletions(target, !path.path.length));\n return {\n from: context.pos - path.name.length,\n options,\n validFor: Identifier\n };\n };\n}\n\n/**\nA language provider based on the [Lezer JavaScript\nparser](https://github.com/lezer-parser/javascript), extended with\nhighlighting and indentation information.\n*/\nconst javascriptLanguage = /*@__PURE__*/LRLanguage.define({\n name: \"javascript\",\n parser: /*@__PURE__*/parser.configure({\n props: [\n /*@__PURE__*/indentNodeProp.add({\n IfStatement: /*@__PURE__*/continuedIndent({ except: /^\\s*({|else\\b)/ }),\n TryStatement: /*@__PURE__*/continuedIndent({ except: /^\\s*({|catch\\b|finally\\b)/ }),\n LabeledStatement: flatIndent,\n SwitchBody: context => {\n let after = context.textAfter, closed = /^\\s*\\}/.test(after), isCase = /^\\s*(case|default)\\b/.test(after);\n return context.baseIndent + (closed ? 0 : isCase ? 1 : 2) * context.unit;\n },\n Block: /*@__PURE__*/delimitedIndent({ closing: \"}\" }),\n ArrowFunction: cx => cx.baseIndent + cx.unit,\n \"TemplateString BlockComment\": () => null,\n \"Statement Property\": /*@__PURE__*/continuedIndent({ except: /^{/ }),\n JSXElement(context) {\n let closed = /^\\s*<\\//.test(context.textAfter);\n return context.lineIndent(context.node.from) + (closed ? 0 : context.unit);\n },\n JSXEscape(context) {\n let closed = /\\s*\\}/.test(context.textAfter);\n return context.lineIndent(context.node.from) + (closed ? 0 : context.unit);\n },\n \"JSXOpenTag JSXSelfClosingTag\"(context) {\n return context.column(context.node.from) + context.unit;\n }\n }),\n /*@__PURE__*/foldNodeProp.add({\n \"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType\": foldInside,\n BlockComment(tree) { return { from: tree.from + 2, to: tree.to - 2 }; }\n })\n ]\n }),\n languageData: {\n closeBrackets: { brackets: [\"(\", \"[\", \"{\", \"'\", '\"', \"`\"] },\n commentTokens: { line: \"//\", block: { open: \"/*\", close: \"*/\" } },\n indentOnInput: /^\\s*(?:case |default:|\\{|\\}|<\\/)$/,\n wordChars: \"$\"\n }\n});\nconst jsxSublanguage = {\n test: node => /^JSX/.test(node.name),\n facet: /*@__PURE__*/defineLanguageFacet({ commentTokens: { block: { open: \"{/*\", close: \"*/}\" } } })\n};\n/**\nA language provider for TypeScript.\n*/\nconst typescriptLanguage = /*@__PURE__*/javascriptLanguage.configure({ dialect: \"ts\" }, \"typescript\");\n/**\nLanguage provider for JSX.\n*/\nconst jsxLanguage = /*@__PURE__*/javascriptLanguage.configure({\n dialect: \"jsx\",\n props: [/*@__PURE__*/sublanguageProp.add(n => n.isTop ? [jsxSublanguage] : undefined)]\n});\n/**\nLanguage provider for JSX + TypeScript.\n*/\nconst tsxLanguage = /*@__PURE__*/javascriptLanguage.configure({\n dialect: \"jsx ts\",\n props: [/*@__PURE__*/sublanguageProp.add(n => n.isTop ? [jsxSublanguage] : undefined)]\n}, \"typescript\");\nlet kwCompletion = (name) => ({ label: name, type: \"keyword\" });\nconst keywords = /*@__PURE__*/\"break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield\".split(\" \").map(kwCompletion);\nconst typescriptKeywords = /*@__PURE__*/keywords.concat(/*@__PURE__*/[\"declare\", \"implements\", \"private\", \"protected\", \"public\"].map(kwCompletion));\n/**\nJavaScript support. Includes [snippet](https://codemirror.net/6/docs/ref/#lang-javascript.snippets)\ncompletion.\n*/\nfunction javascript(config = {}) {\n let lang = config.jsx ? (config.typescript ? tsxLanguage : jsxLanguage)\n : config.typescript ? typescriptLanguage : javascriptLanguage;\n let completions = config.typescript ? typescriptSnippets.concat(typescriptKeywords) : snippets.concat(keywords);\n return new LanguageSupport(lang, [\n javascriptLanguage.data.of({\n autocomplete: ifNotIn(dontComplete, completeFromList(completions))\n }),\n javascriptLanguage.data.of({\n autocomplete: localCompletionSource\n }),\n config.jsx ? autoCloseTags : [],\n ]);\n}\nfunction findOpenTag(node) {\n for (;;) {\n if (node.name == \"JSXOpenTag\" || node.name == \"JSXSelfClosingTag\" || node.name == \"JSXFragmentTag\")\n return node;\n if (node.name == \"JSXEscape\" || !node.parent)\n return null;\n node = node.parent;\n }\n}\nfunction elementName(doc, tree, max = doc.length) {\n for (let ch = tree === null || tree === void 0 ? void 0 : tree.firstChild; ch; ch = ch.nextSibling) {\n if (ch.name == \"JSXIdentifier\" || ch.name == \"JSXBuiltin\" || ch.name == \"JSXNamespacedName\" ||\n ch.name == \"JSXMemberExpression\")\n return doc.sliceString(ch.from, Math.min(ch.to, max));\n }\n return \"\";\n}\nconst android = typeof navigator == \"object\" && /*@__PURE__*//Android\\b/.test(navigator.userAgent);\n/**\nExtension that will automatically insert JSX close tags when a `>` or\n`/` is typed.\n*/\nconst autoCloseTags = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, text, defaultInsert) => {\n if ((android ? view.composing : view.compositionStarted) || view.state.readOnly ||\n from != to || (text != \">\" && text != \"/\") ||\n !javascriptLanguage.isActiveAt(view.state, from, -1))\n return false;\n let base = defaultInsert(), { state } = base;\n let closeTags = state.changeByRange(range => {\n var _a;\n let { head } = range, around = syntaxTree(state).resolveInner(head - 1, -1), name;\n if (around.name == \"JSXStartTag\")\n around = around.parent;\n if (state.doc.sliceString(head - 1, head) != text || around.name == \"JSXAttributeValue\" && around.to > head) ;\n else if (text == \">\" && around.name == \"JSXFragmentTag\") {\n return { range, changes: { from: head, insert: `` } };\n }\n else if (text == \"/\" && around.name == \"JSXStartCloseTag\") {\n let empty = around.parent, base = empty.parent;\n if (base && empty.from == head - 2 &&\n ((name = elementName(state.doc, base.firstChild, head)) || ((_a = base.firstChild) === null || _a === void 0 ? void 0 : _a.name) == \"JSXFragmentTag\")) {\n let insert = `${name}>`;\n return { range: EditorSelection.cursor(head + insert.length, -1), changes: { from: head, insert } };\n }\n }\n else if (text == \">\") {\n let openTag = findOpenTag(around);\n if (openTag &&\n !/^\\/?>|^<\\//.test(state.doc.sliceString(head, head + 2)) &&\n (name = elementName(state.doc, openTag, head)))\n return { range, changes: { from: head, insert: `` } };\n }\n return { range };\n });\n if (closeTags.changes.empty)\n return false;\n view.dispatch([\n base,\n state.update(closeTags, { userEvent: \"input.complete\", scrollIntoView: true })\n ]);\n return true;\n});\n\n/**\nConnects an [ESLint](https://eslint.org/) linter to CodeMirror's\n[lint](https://codemirror.net/6/docs/ref/#lint) integration. `eslint` should be an instance of the\n[`Linter`](https://eslint.org/docs/developer-guide/nodejs-api#linter)\nclass, and `config` an optional ESLint configuration. The return\nvalue of this function can be passed to [`linter`](https://codemirror.net/6/docs/ref/#lint.linter)\nto create a JavaScript linting extension.\n\nNote that ESLint targets node, and is tricky to run in the\nbrowser. The\n[eslint-linter-browserify](https://github.com/UziTech/eslint-linter-browserify)\npackage may help with that (see\n[example](https://github.com/UziTech/eslint-linter-browserify/blob/master/example/script.js)).\n*/\nfunction esLint(eslint, config) {\n if (!config) {\n config = {\n parserOptions: { ecmaVersion: 2019, sourceType: \"module\" },\n env: { browser: true, node: true, es6: true, es2015: true, es2017: true, es2020: true },\n rules: {}\n };\n eslint.getRules().forEach((desc, name) => {\n if (desc.meta.docs.recommended)\n config.rules[name] = 2;\n });\n }\n return (view) => {\n let { state } = view, found = [];\n for (let { from, to } of javascriptLanguage.findRegions(state)) {\n let fromLine = state.doc.lineAt(from), offset = { line: fromLine.number - 1, col: from - fromLine.from, pos: from };\n for (let d of eslint.verify(state.sliceDoc(from, to), config))\n found.push(translateDiagnostic(d, state.doc, offset));\n }\n return found;\n };\n}\nfunction mapPos(line, col, doc, offset) {\n return doc.line(line + offset.line).from + col + (line == 1 ? offset.col - 1 : -1);\n}\nfunction translateDiagnostic(input, doc, offset) {\n let start = mapPos(input.line, input.column, doc, offset);\n let result = {\n from: start,\n to: input.endLine != null && input.endColumn != 1 ? mapPos(input.endLine, input.endColumn, doc, offset) : start,\n message: input.message,\n source: input.ruleId ? \"eslint:\" + input.ruleId : \"eslint\",\n severity: input.severity == 1 ? \"warning\" : \"error\",\n };\n if (input.fix) {\n let { range, text } = input.fix, from = range[0] + offset.pos - start, to = range[1] + offset.pos - start;\n result.actions = [{\n name: \"fix\",\n apply(view, start) {\n view.dispatch({ changes: { from: start + from, to: start + to, insert: text }, scrollIntoView: true });\n }\n }];\n }\n return result;\n}\n\nexport { autoCloseTags, completionPath, esLint, javascript, javascriptLanguage, jsxLanguage, localCompletionSource, scopeCompletionSource, snippets, tsxLanguage, typescriptLanguage, typescriptSnippets };\n"],"names":["space","trackNewline","start","shift","context","term","strict","insertSemicolon","input","stack","next","acceptToken","contextual","fallback","noSemicolon","after","indexOf","peek","incdecToken","advance","mayPostfix","canShift","jsHighlight","TemplateString","super","BooleanLiteral","this","null","Star","VariableName","VariableDefinition","Label","PropertyName","PrivatePropertyName","PropertyDefinition","PrivatePropertyDefinition","UpdateOp","BlockComment","Number","String","Escape","ArithOp","LogicOp","BitOp","CompareOp","RegExp","Equals","Arrow","TypeName","TypeDefinition","JSXAttributeValue","JSXText","spec_identifier","__proto__","export","as","from","default","async","function","extends","true","false","void","typeof","new","delete","yield","await","class","public","private","protected","readonly","instanceof","satisfies","in","const","import","keyof","unique","infer","is","abstract","implements","type","let","var","using","interface","enum","namespace","module","declare","global","for","of","while","with","do","if","else","switch","case","try","catch","finally","return","throw","break","continue","debugger","spec_word","get","set","static","override","accessor","spec_LessThan","parser","version","states","stateData","goto","nodeNames","maxTerm","nodeProps","propSources","skippedNodes","repeatNodeCount","tokenData","tokenizers","topRules","dialects","jsx","ts","dynamicPrecedences","specialized","value","tokenPrec","snippets","label","detail","typescriptSnippets","concat","cache","ScopeNodes","Set","defID","node","def","id","getChild","functionContext","gatherCompletions","FunctionDeclaration","ClassDeclaration","ClassExpression","EnumDeclaration","TypeAliasDeclaration","NamespaceDeclaration","matchContext","getScope","doc","cached","completions","top","name","sliceString","to","push","cursor","iterate","gather","has","c","Identifier","dontComplete","localCompletionSource","inner","state","resolveInner","pos","isWord","test","sliceDoc","explicit","options","parent","validFor","pathFor","read","member","_a","path","prop","obj","firstChild","reverse","lastChild","completionPath","scopeCompletionSource","scope","Map","target","step","seen","depth","Object","getOwnPropertyNames","keys","add","_","boost","getPrototypeOf","enumeratePropertyCompletions","length","javascriptLanguage","configure","props","IfStatement","except","TryStatement","LabeledStatement","SwitchBody","textAfter","closed","isCase","baseIndent","unit","Block","closing","ArrowFunction","cx","JSXElement","lineIndent","JSXEscape","column","tree","languageData","closeBrackets","brackets","commentTokens","line","block","open","close","indentOnInput","wordChars","jsxSublanguage","facet","typescriptLanguage","dialect","jsxLanguage","n","isTop","undefined","tsxLanguage","kwCompletion","keywords","split","map","typescriptKeywords","javascript","config","lang","typescript","data","autocomplete","autoCloseTags","elementName","max","ch","nextSibling","Math","min","android","navigator","userAgent","view","text","defaultInsert","composing","compositionStarted","readOnly","isActiveAt","base","closeTags","changeByRange","range","head","around","changes","insert","empty","openTag","findOpenTag","dispatch","update","userEvent","scrollIntoView","esLint","eslint","parserOptions","ecmaVersion","sourceType","env","browser","es6","es2015","es2017","es2020","rules","getRules","forEach","desc","meta","docs","recommended","found","findRegions","fromLine","lineAt","offset","number","col","d","verify","translateDiagnostic","mapPos","result","endLine","endColumn","message","source","ruleId","severity","fix","actions","apply"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/6007.index.js b/book/_build/html/_static/6007.index.js new file mode 100644 index 0000000..84e0219 --- /dev/null +++ b/book/_build/html/_static/6007.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[6007],{16007:(e,t,r)=>{function o(e){var t,r,o=(e={...q,...e}).inline,i=e.tokenHooks,a=e.documentTypes||{},n=e.mediaTypes||{},l=e.mediaFeatures||{},s=e.mediaValueKeywords||{},c=e.propertyKeywords||{},d=e.nonStandardPropertyKeywords||{},p=e.fontProperties||{},u=e.counterDescriptors||{},m=e.colorKeywords||{},g=e.valueKeywords||{},h=e.allowNested,b=e.lineComment,f=!0===e.supportsAtComponent,k=!1!==e.highlightNonStandardPropertyKeywords;function y(e,r){return t=r,e}function w(e,t){var r=e.next();if(i[r]){var o=i[r](e,t);if(!1!==o)return o}return"@"==r?(e.eatWhile(/[\w\\\-]/),y("def",e.current())):"="==r||("~"==r||"|"==r)&&e.eat("=")?y(null,"compare"):'"'==r||"'"==r?(t.tokenize=v(r),t.tokenize(e,t)):"#"==r?(e.eatWhile(/[\w\\\-]/),y("atom","hash")):"!"==r?(e.match(/^\s*\w*/),y("keyword","important")):/\d/.test(r)||"."==r&&e.eat(/\d/)?(e.eatWhile(/[\w.%]/),y("number","unit")):"-"!==r?/[,+>*\/]/.test(r)?y(null,"select-op"):"."==r&&e.match(/^-?[_a-z][_a-z0-9-]*/i)?y("qualifier","qualifier"):/[:;{}\[\]\(\)]/.test(r)?y(null,r):e.match(/^[\w-.]+(?=\()/)?(/^(url(-prefix)?|domain|regexp)$/i.test(e.current())&&(t.tokenize=x),y("variableName.function","variable")):/[\w\\\-]/.test(r)?(e.eatWhile(/[\w\\\-]/),y("property","word")):y(null,null):/[\d.]/.test(e.peek())?(e.eatWhile(/[\w.%]/),y("number","unit")):e.match(/^-[\w\\\-]*/)?(e.eatWhile(/[\w\\\-]/),e.match(/^\s*:/,!1)?y("def","variable-definition"):y("variableName","variable")):e.match(/^\w+-/)?y("meta","meta"):void 0}function v(e){return function(t,r){for(var o,i=!1;null!=(o=t.next());){if(o==e&&!i){")"==e&&t.backUp(1);break}i=!i&&"\\"==o}return(o==e||!i&&")"!=e)&&(r.tokenize=null),y("string","string")}}function x(e,t){return e.next(),e.match(/^\s*[\"\')]/,!1)?t.tokenize=null:t.tokenize=v(")"),y(null,"(")}function z(e,t,r){this.type=e,this.indent=t,this.prev=r}function j(e,t,r,o){return e.context=new z(r,t.indentation()+(!1===o?0:t.indentUnit),e.context),r}function K(e){return e.context.prev&&(e.context=e.context.prev),e.context.type}function B(e,t,r){return O[r.context.type](e,t,r)}function _(e,t,r,o){for(var i=o||1;i>0;i--)r.context=r.context.prev;return B(e,t,r)}function C(e){var t=e.current().toLowerCase();r=g.hasOwnProperty(t)?"atom":m.hasOwnProperty(t)?"keyword":"variable"}var O={top:function(e,t,o){if("{"==e)return j(o,t,"block");if("}"==e&&o.context.prev)return K(o);if(f&&/@component/i.test(e))return j(o,t,"atComponentBlock");if(/^@(-moz-)?document$/i.test(e))return j(o,t,"documentTypes");if(/^@(media|supports|(-moz-)?document|import)$/i.test(e))return j(o,t,"atBlock");if(/^@(font-face|counter-style)/i.test(e))return o.stateArg=e,"restricted_atBlock_before";if(/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(e))return"keyframes";if(e&&"@"==e.charAt(0))return j(o,t,"at");if("hash"==e)r="builtin";else if("word"==e)r="tag";else{if("variable-definition"==e)return"maybeprop";if("interpolation"==e)return j(o,t,"interpolation");if(":"==e)return"pseudo";if(h&&"("==e)return j(o,t,"parens")}return o.context.type},block:function(e,t,o){if("word"==e){var i=t.current().toLowerCase();return c.hasOwnProperty(i)?(r="property","maybeprop"):d.hasOwnProperty(i)?(r=k?"string.special":"property","maybeprop"):h?(r=t.match(/^\s*:(?:\s|$)/,!1)?"property":"tag","block"):(r="error","maybeprop")}return"meta"==e?"block":h||"hash"!=e&&"qualifier"!=e?O.top(e,t,o):(r="error","block")},maybeprop:function(e,t,r){return":"==e?j(r,t,"prop"):B(e,t,r)},prop:function(e,t,o){if(";"==e)return K(o);if("{"==e&&h)return j(o,t,"propBlock");if("}"==e||"{"==e)return _(e,t,o);if("("==e)return j(o,t,"parens");if("hash"!=e||/^#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(t.current())){if("word"==e)C(t);else if("interpolation"==e)return j(o,t,"interpolation")}else r="error";return"prop"},propBlock:function(e,t,o){return"}"==e?K(o):"word"==e?(r="property","maybeprop"):o.context.type},parens:function(e,t,r){return"{"==e||"}"==e?_(e,t,r):")"==e?K(r):"("==e?j(r,t,"parens"):"interpolation"==e?j(r,t,"interpolation"):("word"==e&&C(t),"parens")},pseudo:function(e,t,o){return"meta"==e?"pseudo":"word"==e?(r="variableName.constant",o.context.type):B(e,t,o)},documentTypes:function(e,t,o){return"word"==e&&a.hasOwnProperty(t.current())?(r="tag",o.context.type):O.atBlock(e,t,o)},atBlock:function(e,t,o){if("("==e)return j(o,t,"atBlock_parens");if("}"==e||";"==e)return _(e,t,o);if("{"==e)return K(o)&&j(o,t,h?"block":"top");if("interpolation"==e)return j(o,t,"interpolation");if("word"==e){var i=t.current().toLowerCase();r="only"==i||"not"==i||"and"==i||"or"==i?"keyword":n.hasOwnProperty(i)?"attribute":l.hasOwnProperty(i)?"property":s.hasOwnProperty(i)?"keyword":c.hasOwnProperty(i)?"property":d.hasOwnProperty(i)?k?"string.special":"property":g.hasOwnProperty(i)?"atom":m.hasOwnProperty(i)?"keyword":"error"}return o.context.type},atComponentBlock:function(e,t,o){return"}"==e?_(e,t,o):"{"==e?K(o)&&j(o,t,h?"block":"top",!1):("word"==e&&(r="error"),o.context.type)},atBlock_parens:function(e,t,r){return")"==e?K(r):"{"==e||"}"==e?_(e,t,r,2):O.atBlock(e,t,r)},restricted_atBlock_before:function(e,t,o){return"{"==e?j(o,t,"restricted_atBlock"):"word"==e&&"@counter-style"==o.stateArg?(r="variable","restricted_atBlock_before"):B(e,t,o)},restricted_atBlock:function(e,t,o){return"}"==e?(o.stateArg=null,K(o)):"word"==e?(r="@font-face"==o.stateArg&&!p.hasOwnProperty(t.current().toLowerCase())||"@counter-style"==o.stateArg&&!u.hasOwnProperty(t.current().toLowerCase())?"error":"property","maybeprop"):"restricted_atBlock"},keyframes:function(e,t,o){return"word"==e?(r="variable","keyframes"):"{"==e?j(o,t,"top"):B(e,t,o)},at:function(e,t,o){return";"==e?K(o):"{"==e||"}"==e?_(e,t,o):("word"==e?r="tag":"hash"==e&&(r="builtin"),"at")},interpolation:function(e,t,o){return"}"==e?K(o):"{"==e||";"==e?_(e,t,o):("word"==e?r="variable":"variable"!=e&&"("!=e&&")"!=e&&(r="error"),"interpolation")}};return{name:e.name,startState:function(){return{tokenize:null,state:o?"block":"top",stateArg:null,context:new z(o?"block":"top",0,null)}},token:function(e,o){if(!o.tokenize&&e.eatSpace())return null;var i=(o.tokenize||w)(e,o);return i&&"object"==typeof i&&(t=i[1],i=i[0]),r=i,"comment"!=t&&(o.state=O[o.state](t,e,o)),r},indent:function(e,t,r){var o=e.context,i=t&&t.charAt(0),a=o.indent;return"prop"!=o.type||"}"!=i&&")"!=i||(o=o.prev),o.prev&&("}"!=i||"block"!=o.type&&"top"!=o.type&&"interpolation"!=o.type&&"restricted_atBlock"!=o.type?(")"!=i||"parens"!=o.type&&"atBlock_parens"!=o.type)&&("{"!=i||"at"!=o.type&&"atBlock"!=o.type)||(a=Math.max(0,o.indent-r.unit)):a=(o=o.prev).indent),a},languageData:{indentOnInput:/^\s*\}$/,commentTokens:{line:b,block:{open:"/*",close:"*/"}},autocomplete:P}}}function i(e){for(var t={},r=0;rK,gss:()=>O,keywords:()=>j,less:()=>C,mkCSS:()=>o,sCSS:()=>_});var a=["domain","regexp","url","url-prefix"],n=i(a),l=["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"],s=i(l),c=["width","min-width","max-width","height","min-height","max-height","device-width","min-device-width","max-device-width","device-height","min-device-height","max-device-height","aspect-ratio","min-aspect-ratio","max-aspect-ratio","device-aspect-ratio","min-device-aspect-ratio","max-device-aspect-ratio","color","min-color","max-color","color-index","min-color-index","max-color-index","monochrome","min-monochrome","max-monochrome","resolution","min-resolution","max-resolution","scan","grid","orientation","device-pixel-ratio","min-device-pixel-ratio","max-device-pixel-ratio","pointer","any-pointer","hover","any-hover","prefers-color-scheme","dynamic-range","video-dynamic-range"],d=i(c),p=["landscape","portrait","none","coarse","fine","on-demand","hover","interlace","progressive","dark","light","standard","high"],u=i(p),m=["align-content","align-items","align-self","alignment-adjust","alignment-baseline","all","anchor-point","animation","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-timing-function","appearance","azimuth","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","binding","bleed","block-size","bookmark-label","bookmark-level","bookmark-state","bookmark-target","border","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-decoration-break","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","color","color-profile","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","content","counter-increment","counter-reset","crop","cue","cue-after","cue-before","cursor","direction","display","dominant-baseline","drop-initial-after-adjust","drop-initial-after-align","drop-initial-before-adjust","drop-initial-before-align","drop-initial-size","drop-initial-value","elevation","empty-cells","fit","fit-content","fit-position","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","float-offset","flow-from","flow-into","font","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-size","font-size-adjust","font-stretch","font-style","font-synthesis","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","gap","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-gap","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-gap","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","inline-box-align","inset","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","left","letter-spacing","line-break","line-height","line-height-step","line-stacking","line-stacking-ruby","line-stacking-shift","line-stacking-strategy","list-style","list-style-image","list-style-position","list-style-type","margin","margin-bottom","margin-left","margin-right","margin-top","marks","marquee-direction","marquee-loop","marquee-play-count","marquee-speed","marquee-style","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","move-to","nav-down","nav-index","nav-left","nav-right","nav-up","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-style","overflow-wrap","overflow-x","overflow-y","padding","padding-bottom","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","page-policy","pause","pause-after","pause-before","perspective","perspective-origin","pitch","pitch-range","place-content","place-items","place-self","play-during","position","presentation-level","punctuation-trim","quotes","region-break-after","region-break-before","region-break-inside","region-fragment","rendering-intent","resize","rest","rest-after","rest-before","richness","right","rotate","rotation","rotation-point","row-gap","ruby-align","ruby-overhang","ruby-position","ruby-span","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-type","shape-image-threshold","shape-inside","shape-margin","shape-outside","size","speak","speak-as","speak-header","speak-numeral","speak-punctuation","speech-rate","stress","string-set","tab-size","table-layout","target","target-name","target-new","target-position","text-align","text-align-last","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-height","text-indent","text-justify","text-orientation","text-outline","text-overflow","text-rendering","text-shadow","text-size-adjust","text-space-collapse","text-transform","text-underline-position","text-wrap","top","touch-action","transform","transform-origin","transform-style","transition","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-select","vertical-align","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","volume","white-space","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","z-index","clip-path","clip-rule","mask","enable-background","filter","flood-color","flood-opacity","lighting-color","stop-color","stop-opacity","pointer-events","color-interpolation","color-interpolation-filters","color-rendering","fill","fill-opacity","fill-rule","image-rendering","marker","marker-end","marker-mid","marker-start","paint-order","shape-rendering","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-rendering","baseline-shift","dominant-baseline","glyph-orientation-horizontal","glyph-orientation-vertical","text-anchor","writing-mode"],g=i(m),h=["accent-color","aspect-ratio","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","content-visibility","margin-block","margin-block-end","margin-block-start","margin-inline","margin-inline-end","margin-inline-start","overflow-anchor","overscroll-behavior","padding-block","padding-block-end","padding-block-start","padding-inline","padding-inline-end","padding-inline-start","scroll-snap-stop","scrollbar-3d-light-color","scrollbar-arrow-color","scrollbar-base-color","scrollbar-dark-shadow-color","scrollbar-face-color","scrollbar-highlight-color","scrollbar-shadow-color","scrollbar-track-color","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","shape-inside","zoom"],b=i(h),f=["font-display","font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"],k=i(f),y=i(["additive-symbols","fallback","negative","pad","prefix","range","speak-as","suffix","symbols","system"]),w=["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"],v=i(w),x=["above","absolute","activeborder","additive","activecaption","afar","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","amharic","amharic-abegede","antialiased","appworkspace","arabic-indic","armenian","asterisks","attr","auto","auto-flow","avoid","avoid-column","avoid-page","avoid-region","axis-pan","background","backwards","baseline","below","bidi-override","binary","bengali","blink","block","block-axis","blur","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","brightness","bullets","button","buttonface","buttonhighlight","buttonshadow","buttontext","calc","cambodian","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","conic-gradient","contain","content","contents","content-box","context-menu","continuous","contrast","copy","counter","counters","cover","crop","cross","crosshair","cubic-bezier","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","devanagari","difference","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","drop-shadow","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic","ethiopic-abegede","ethiopic-abegede-am-et","ethiopic-abegede-gez","ethiopic-abegede-ti-er","ethiopic-abegede-ti-et","ethiopic-halehame-aa-er","ethiopic-halehame-aa-et","ethiopic-halehame-am-et","ethiopic-halehame-gez","ethiopic-halehame-om-et","ethiopic-halehame-sid-et","ethiopic-halehame-so-et","ethiopic-halehame-ti-er","ethiopic-halehame-ti-et","ethiopic-halehame-tig","ethiopic-numeric","ew-resize","exclusion","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fill-box","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","georgian","grayscale","graytext","grid","groove","gujarati","gurmukhi","hand","hangul","hangul-consonant","hard-light","hebrew","help","hidden","hide","higher","highlight","highlighttext","hiragana","hiragana-iroha","horizontal","hsl","hsla","hue","hue-rotate","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-grid","inline-table","inset","inside","intrinsic","invert","italic","japanese-formal","japanese-informal","justify","kannada","katakana","katakana-iroha","keep-all","khmer","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","landscape","lao","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-alpha","lower-armenian","lower-greek","lower-hexadecimal","lower-latin","lower-norwegian","lower-roman","lowercase","ltr","luminosity","malayalam","manipulation","match","matrix","matrix3d","media-play-button","media-slider","media-sliderthumb","media-volume-slider","media-volume-sliderthumb","medium","menu","menulist","menulist-button","menutext","message-box","middle","min-intrinsic","mix","mongolian","monospace","move","multiple","multiple_mask_images","multiply","myanmar","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","octal","opacity","open-quote","optimizeLegibility","optimizeSpeed","oriya","oromo","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","persian","perspective","pinch-zoom","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturate","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","scroll-position","se-resize","searchfield","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","self-start","self-end","semi-condensed","semi-expanded","separate","sepia","serif","show","sidama","simp-chinese-formal","simp-chinese-informal","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","somali","source-atop","source-in","source-out","source-over","space","space-around","space-between","space-evenly","spell-out","square","square-button","start","static","status-bar","stretch","stroke","stroke-box","sub","subpixel-antialiased","svg_masks","super","sw-resize","symbolic","symbols","system-ui","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tamil","telugu","text","text-bottom","text-top","textarea","textfield","thai","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","tibetan","tigre","tigrinya-er","tigrinya-er-abegede","tigrinya-et","tigrinya-et-abegede","to","top","trad-chinese-formal","trad-chinese-informal","transform","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","unidirectional-pan","unset","up","upper-alpha","upper-armenian","upper-greek","upper-hexadecimal","upper-latin","upper-norwegian","upper-roman","uppercase","urdu","url","var","vertical","vertical-text","view-box","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"],z=i(x),P=a.concat(l).concat(c).concat(p).concat(m).concat(h).concat(w).concat(x);const j={properties:m,colors:w,fonts:f,values:x,all:P},q={documentTypes:n,mediaTypes:s,mediaFeatures:d,mediaValueKeywords:u,propertyKeywords:g,nonStandardPropertyKeywords:b,fontProperties:k,counterDescriptors:y,colorKeywords:v,valueKeywords:z,tokenHooks:{"/":function(e,t){return!!e.eat("*")&&(t.tokenize=B,B(e,t))}}},K=o({name:"css"});function B(e,t){for(var r,o=!1;null!=(r=e.next());){if(o&&"/"==r){t.tokenize=null;break}o="*"==r}return["comment","comment"]}const _=o({name:"scss",mediaTypes:s,mediaFeatures:d,mediaValueKeywords:u,propertyKeywords:g,nonStandardPropertyKeywords:b,colorKeywords:v,valueKeywords:z,fontProperties:k,allowNested:!0,lineComment:"//",tokenHooks:{"/":function(e,t){return e.eat("/")?(e.skipToEnd(),["comment","comment"]):e.eat("*")?(t.tokenize=B,B(e,t)):["operator","operator"]},":":function(e){return!!e.match(/^\s*\{/,!1)&&[null,null]},$:function(e){return e.match(/^[\w-]+/),e.match(/^\s*:/,!1)?["def","variable-definition"]:["variableName.special","variable"]},"#":function(e){return!!e.eat("{")&&[null,"interpolation"]}}}),C=o({name:"less",mediaTypes:s,mediaFeatures:d,mediaValueKeywords:u,propertyKeywords:g,nonStandardPropertyKeywords:b,colorKeywords:v,valueKeywords:z,fontProperties:k,allowNested:!0,lineComment:"//",tokenHooks:{"/":function(e,t){return e.eat("/")?(e.skipToEnd(),["comment","comment"]):e.eat("*")?(t.tokenize=B,B(e,t)):["operator","operator"]},"@":function(e){return e.eat("{")?[null,"interpolation"]:!e.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i,!1)&&(e.eatWhile(/[\w\\\-]/),e.match(/^\s*:/,!1)?["def","variable-definition"]:["variableName","variable"])},"&":function(){return["atom","atom"]}}}),O=o({name:"gss",documentTypes:n,mediaTypes:s,mediaFeatures:d,propertyKeywords:g,nonStandardPropertyKeywords:b,fontProperties:k,counterDescriptors:y,colorKeywords:v,valueKeywords:z,supportsAtComponent:!0,tokenHooks:{"/":function(e,t){return!!e.eat("*")&&(t.tokenize=B,B(e,t))}}})}}]); +//# sourceMappingURL=6007.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/6007.index.js.map b/book/_build/html/_static/6007.index.js.map new file mode 100644 index 0000000..dcaaca2 --- /dev/null +++ b/book/_build/html/_static/6007.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"6007.index.js","mappings":"+FAAO,SAASA,EAAMC,GAEpB,IAkBIC,EAAMC,EAlBNC,GADJH,EAAe,IAAII,KAAaJ,IACNG,OAEtBE,EAAaL,EAAaK,WAC1BC,EAAgBN,EAAaM,eAAiB,CAAC,EAC/CC,EAAaP,EAAaO,YAAc,CAAC,EACzCC,EAAgBR,EAAaQ,eAAiB,CAAC,EAC/CC,EAAqBT,EAAaS,oBAAsB,CAAC,EACzDC,EAAmBV,EAAaU,kBAAoB,CAAC,EACrDC,EAA8BX,EAAaW,6BAA+B,CAAC,EAC3EC,EAAiBZ,EAAaY,gBAAkB,CAAC,EACjDC,EAAqBb,EAAaa,oBAAsB,CAAC,EACzDC,EAAgBd,EAAac,eAAiB,CAAC,EAC/CC,EAAgBf,EAAae,eAAiB,CAAC,EAC/CC,EAAchB,EAAagB,YAC3BC,EAAcjB,EAAaiB,YAC3BC,GAA2D,IAArClB,EAAakB,oBACnCC,GAA6F,IAAtDnB,EAAamB,qCAGxD,SAASC,EAAIC,EAAOC,GAAiB,OAAXrB,EAAOqB,EAAWD,CAAO,CAInD,SAASE,EAAUC,EAAQC,GACzB,IAAIC,EAAKF,EAAOG,OAChB,GAAItB,EAAWqB,GAAK,CAClB,IAAIE,EAASvB,EAAWqB,GAAIF,EAAQC,GACpC,IAAe,IAAXG,EAAkB,OAAOA,CAC/B,CACA,MAAU,KAANF,GACFF,EAAOK,SAAS,YACTT,EAA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AAQC,GACpB,QAAKD,EAAOO,IAAI,OAChBN,EAAMO,SAAWuE,EACVA,EAAc/E,EAAQC,GAC/B,I","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/css.js"],"sourcesContent":["export function mkCSS(parserConfig) {\n parserConfig = {...defaults, ...parserConfig}\n var inline = parserConfig.inline\n\n var tokenHooks = parserConfig.tokenHooks,\n documentTypes = parserConfig.documentTypes || {},\n mediaTypes = parserConfig.mediaTypes || {},\n mediaFeatures = parserConfig.mediaFeatures || {},\n mediaValueKeywords = parserConfig.mediaValueKeywords || {},\n propertyKeywords = parserConfig.propertyKeywords || {},\n nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {},\n fontProperties = parserConfig.fontProperties || {},\n counterDescriptors = parserConfig.counterDescriptors || {},\n colorKeywords = parserConfig.colorKeywords || {},\n valueKeywords = parserConfig.valueKeywords || {},\n allowNested = parserConfig.allowNested,\n lineComment = parserConfig.lineComment,\n supportsAtComponent = parserConfig.supportsAtComponent === true,\n highlightNonStandardPropertyKeywords = parserConfig.highlightNonStandardPropertyKeywords !== false;\n\n var type, override;\n function ret(style, tp) { type = tp; return style; }\n\n // Tokenizers\n\n function tokenBase(stream, state) {\n var ch = stream.next();\n if (tokenHooks[ch]) {\n var result = tokenHooks[ch](stream, state);\n if (result !== false) return result;\n }\n if (ch == \"@\") {\n stream.eatWhile(/[\\w\\\\\\-]/);\n return ret(\"def\", stream.current());\n } else if (ch == \"=\" || (ch == \"~\" || ch == \"|\") && stream.eat(\"=\")) {\n return ret(null, \"compare\");\n } else if (ch == \"\\\"\" || ch == \"'\") {\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n } else if (ch == \"#\") {\n stream.eatWhile(/[\\w\\\\\\-]/);\n return ret(\"atom\", \"hash\");\n } else if (ch == \"!\") {\n stream.match(/^\\s*\\w*/);\n return ret(\"keyword\", \"important\");\n } else if (/\\d/.test(ch) || ch == \".\" && stream.eat(/\\d/)) {\n stream.eatWhile(/[\\w.%]/);\n return ret(\"number\", \"unit\");\n } else if (ch === \"-\") {\n if (/[\\d.]/.test(stream.peek())) {\n stream.eatWhile(/[\\w.%]/);\n return ret(\"number\", \"unit\");\n } else if (stream.match(/^-[\\w\\\\\\-]*/)) {\n stream.eatWhile(/[\\w\\\\\\-]/);\n if (stream.match(/^\\s*:/, false))\n return ret(\"def\", \"variable-definition\");\n return ret(\"variableName\", \"variable\");\n } else if (stream.match(/^\\w+-/)) {\n return ret(\"meta\", \"meta\");\n }\n } else if (/[,+>*\\/]/.test(ch)) {\n return ret(null, \"select-op\");\n } else if (ch == \".\" && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {\n return ret(\"qualifier\", \"qualifier\");\n } else if (/[:;{}\\[\\]\\(\\)]/.test(ch)) {\n return ret(null, ch);\n } else if (stream.match(/^[\\w-.]+(?=\\()/)) {\n if (/^(url(-prefix)?|domain|regexp)$/i.test(stream.current())) {\n state.tokenize = tokenParenthesized;\n }\n return ret(\"variableName.function\", \"variable\");\n } else if (/[\\w\\\\\\-]/.test(ch)) {\n stream.eatWhile(/[\\w\\\\\\-]/);\n return ret(\"property\", \"word\");\n } else {\n return ret(null, null);\n }\n }\n\n function tokenString(quote) {\n return function(stream, state) {\n var escaped = false, ch;\n while ((ch = stream.next()) != null) {\n if (ch == quote && !escaped) {\n if (quote == \")\") stream.backUp(1);\n break;\n }\n escaped = !escaped && ch == \"\\\\\";\n }\n if (ch == quote || !escaped && quote != \")\") state.tokenize = null;\n return ret(\"string\", \"string\");\n };\n }\n\n function tokenParenthesized(stream, state) {\n stream.next(); // Must be '('\n if (!stream.match(/^\\s*[\\\"\\')]/, false))\n state.tokenize = tokenString(\")\");\n else\n state.tokenize = null;\n return ret(null, \"(\");\n }\n\n // Context management\n\n function Context(type, indent, prev) {\n this.type = type;\n this.indent = indent;\n this.prev = prev;\n }\n\n function pushContext(state, stream, type, indent) {\n state.context = new Context(type, stream.indentation() + (indent === false ? 0 : stream.indentUnit), state.context);\n return type;\n }\n\n function popContext(state) {\n if (state.context.prev)\n state.context = state.context.prev;\n return state.context.type;\n }\n\n function pass(type, stream, state) {\n return states[state.context.type](type, stream, state);\n }\n function popAndPass(type, stream, state, n) {\n for (var i = n || 1; i > 0; i--)\n state.context = state.context.prev;\n return pass(type, stream, state);\n }\n\n // Parser\n\n function wordAsValue(stream) {\n var word = stream.current().toLowerCase();\n if (valueKeywords.hasOwnProperty(word))\n override = \"atom\";\n else if (colorKeywords.hasOwnProperty(word))\n override = \"keyword\";\n else\n override = \"variable\";\n }\n\n var states = {};\n\n states.top = function(type, stream, state) {\n if (type == \"{\") {\n return pushContext(state, stream, \"block\");\n } else if (type == \"}\" && state.context.prev) {\n return popContext(state);\n } else if (supportsAtComponent && /@component/i.test(type)) {\n return pushContext(state, stream, \"atComponentBlock\");\n } else if (/^@(-moz-)?document$/i.test(type)) {\n return pushContext(state, stream, \"documentTypes\");\n } else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) {\n return pushContext(state, stream, \"atBlock\");\n } else if (/^@(font-face|counter-style)/i.test(type)) {\n state.stateArg = type;\n return \"restricted_atBlock_before\";\n } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) {\n return \"keyframes\";\n } else if (type && type.charAt(0) == \"@\") {\n return pushContext(state, stream, \"at\");\n } else if (type == \"hash\") {\n override = \"builtin\";\n } else if (type == \"word\") {\n override = \"tag\";\n } else if (type == \"variable-definition\") {\n return \"maybeprop\";\n } else if (type == \"interpolation\") {\n return pushContext(state, stream, \"interpolation\");\n } else if (type == \":\") {\n return \"pseudo\";\n } else if (allowNested && type == \"(\") {\n return pushContext(state, stream, \"parens\");\n }\n return state.context.type;\n };\n\n states.block = function(type, stream, state) {\n if (type == \"word\") {\n var word = stream.current().toLowerCase();\n if (propertyKeywords.hasOwnProperty(word)) {\n override = \"property\";\n return \"maybeprop\";\n } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) {\n override = highlightNonStandardPropertyKeywords ? \"string.special\" : \"property\";\n return \"maybeprop\";\n } else if (allowNested) {\n override = stream.match(/^\\s*:(?:\\s|$)/, false) ? \"property\" : \"tag\";\n return \"block\";\n } else {\n override = \"error\";\n return \"maybeprop\";\n }\n } else if (type == \"meta\") {\n return \"block\";\n } else if (!allowNested && (type == \"hash\" || type == \"qualifier\")) {\n override = \"error\";\n return \"block\";\n } else {\n return states.top(type, stream, state);\n }\n };\n\n states.maybeprop = function(type, stream, state) {\n if (type == \":\") return pushContext(state, stream, \"prop\");\n return pass(type, stream, state);\n };\n\n states.prop = function(type, stream, state) {\n if (type == \";\") return popContext(state);\n if (type == \"{\" && allowNested) return pushContext(state, stream, \"propBlock\");\n if (type == \"}\" || type == \"{\") return popAndPass(type, stream, state);\n if (type == \"(\") return pushContext(state, stream, \"parens\");\n\n if (type == \"hash\" && !/^#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(stream.current())) {\n override = \"error\";\n } else if (type == \"word\") {\n wordAsValue(stream);\n } else if (type == \"interpolation\") {\n return pushContext(state, stream, \"interpolation\");\n }\n return \"prop\";\n };\n\n states.propBlock = function(type, _stream, state) {\n if (type == \"}\") return popContext(state);\n if (type == \"word\") { override = \"property\"; return \"maybeprop\"; }\n return state.context.type;\n };\n\n states.parens = function(type, stream, state) {\n if (type == \"{\" || type == \"}\") return popAndPass(type, stream, state);\n if (type == \")\") return popContext(state);\n if (type == \"(\") return pushContext(state, stream, \"parens\");\n if (type == \"interpolation\") return pushContext(state, stream, \"interpolation\");\n if (type == \"word\") wordAsValue(stream);\n return \"parens\";\n };\n\n states.pseudo = function(type, stream, state) {\n if (type == \"meta\") return \"pseudo\";\n\n if (type == \"word\") {\n override = \"variableName.constant\";\n return state.context.type;\n }\n return pass(type, stream, state);\n };\n\n states.documentTypes = function(type, stream, state) {\n if (type == \"word\" && documentTypes.hasOwnProperty(stream.current())) {\n override = \"tag\";\n return state.context.type;\n } else {\n return states.atBlock(type, stream, state);\n }\n };\n\n states.atBlock = function(type, stream, state) {\n if (type == \"(\") return pushContext(state, stream, \"atBlock_parens\");\n if (type == \"}\" || type == \";\") return popAndPass(type, stream, state);\n if (type == \"{\") return popContext(state) && pushContext(state, stream, allowNested ? \"block\" : \"top\");\n\n if (type == \"interpolation\") return pushContext(state, stream, \"interpolation\");\n\n if (type == \"word\") {\n var word = stream.current().toLowerCase();\n if (word == \"only\" || word == \"not\" || word == \"and\" || word == \"or\")\n override = \"keyword\";\n else if (mediaTypes.hasOwnProperty(word))\n override = \"attribute\";\n else if (mediaFeatures.hasOwnProperty(word))\n override = \"property\";\n else if (mediaValueKeywords.hasOwnProperty(word))\n override = \"keyword\";\n else if (propertyKeywords.hasOwnProperty(word))\n override = \"property\";\n else if (nonStandardPropertyKeywords.hasOwnProperty(word))\n override = highlightNonStandardPropertyKeywords ? \"string.special\" : \"property\";\n else if (valueKeywords.hasOwnProperty(word))\n override = \"atom\";\n else if (colorKeywords.hasOwnProperty(word))\n override = \"keyword\";\n else\n override = \"error\";\n }\n return state.context.type;\n };\n\n states.atComponentBlock = function(type, stream, state) {\n if (type == \"}\")\n return popAndPass(type, stream, state);\n if (type == \"{\")\n return popContext(state) && pushContext(state, stream, allowNested ? \"block\" : \"top\", false);\n if (type == \"word\")\n override = \"error\";\n return state.context.type;\n };\n\n states.atBlock_parens = function(type, stream, state) {\n if (type == \")\") return popContext(state);\n if (type == \"{\" || type == \"}\") return popAndPass(type, stream, state, 2);\n return states.atBlock(type, stream, state);\n };\n\n states.restricted_atBlock_before = function(type, stream, state) {\n if (type == \"{\")\n return pushContext(state, stream, \"restricted_atBlock\");\n if (type == \"word\" && state.stateArg == \"@counter-style\") {\n override = \"variable\";\n return \"restricted_atBlock_before\";\n }\n return pass(type, stream, state);\n };\n\n states.restricted_atBlock = function(type, stream, state) {\n if (type == \"}\") {\n state.stateArg = null;\n return popContext(state);\n }\n if (type == \"word\") {\n if ((state.stateArg == \"@font-face\" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) ||\n (state.stateArg == \"@counter-style\" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))\n override = \"error\";\n else\n override = \"property\";\n return \"maybeprop\";\n }\n return \"restricted_atBlock\";\n };\n\n states.keyframes = function(type, stream, state) {\n if (type == \"word\") { override = \"variable\"; return \"keyframes\"; }\n if (type == \"{\") return pushContext(state, stream, \"top\");\n return pass(type, stream, state);\n };\n\n states.at = function(type, stream, state) {\n if (type == \";\") return popContext(state);\n if (type == \"{\" || type == \"}\") return popAndPass(type, stream, state);\n if (type == \"word\") override = \"tag\";\n else if (type == \"hash\") override = \"builtin\";\n return \"at\";\n };\n\n states.interpolation = function(type, stream, state) {\n if (type == \"}\") return popContext(state);\n if (type == \"{\" || type == \";\") return popAndPass(type, stream, state);\n if (type == \"word\") override = \"variable\";\n else if (type != \"variable\" && type != \"(\" && type != \")\") override = \"error\";\n return \"interpolation\";\n };\n\n return {\n name: parserConfig.name,\n startState: function() {\n return {tokenize: null,\n state: inline ? \"block\" : \"top\",\n stateArg: null,\n context: new Context(inline ? \"block\" : \"top\", 0, null)};\n },\n\n token: function(stream, state) {\n if (!state.tokenize && stream.eatSpace()) return null;\n var style = (state.tokenize || tokenBase)(stream, state);\n if (style && typeof style == \"object\") {\n type = style[1];\n style = style[0];\n }\n override = style;\n if (type != \"comment\")\n state.state = states[state.state](type, stream, state);\n return override;\n },\n\n indent: function(state, textAfter, iCx) {\n var cx = state.context, ch = textAfter && textAfter.charAt(0);\n var indent = cx.indent;\n if (cx.type == \"prop\" && (ch == \"}\" || ch == \")\")) cx = cx.prev;\n if (cx.prev) {\n if (ch == \"}\" && (cx.type == \"block\" || cx.type == \"top\" ||\n cx.type == \"interpolation\" || cx.type == \"restricted_atBlock\")) {\n // Resume indentation from parent context.\n cx = cx.prev;\n indent = cx.indent;\n } else if (ch == \")\" && (cx.type == \"parens\" || cx.type == \"atBlock_parens\") ||\n ch == \"{\" && (cx.type == \"at\" || cx.type == \"atBlock\")) {\n // Dedent relative to current context.\n indent = Math.max(0, cx.indent - iCx.unit);\n }\n }\n return indent;\n },\n\n languageData: {\n indentOnInput: /^\\s*\\}$/,\n commentTokens: {line: lineComment, block: {open: \"/*\", close: \"*/\"}},\n autocomplete: allWords\n }\n };\n};\n\nfunction keySet(array) {\n var keys = {};\n for (var i = 0; i < array.length; ++i) {\n keys[array[i].toLowerCase()] = true;\n }\n return keys;\n}\n\nvar documentTypes_ = [\n \"domain\", \"regexp\", \"url\", \"url-prefix\"\n], documentTypes = keySet(documentTypes_);\n\nvar mediaTypes_ = [\n \"all\", \"aural\", \"braille\", \"handheld\", \"print\", \"projection\", \"screen\",\n \"tty\", \"tv\", \"embossed\"\n], mediaTypes = keySet(mediaTypes_);\n\nvar mediaFeatures_ = [\n \"width\", \"min-width\", \"max-width\", \"height\", \"min-height\", \"max-height\",\n \"device-width\", \"min-device-width\", \"max-device-width\", \"device-height\",\n \"min-device-height\", \"max-device-height\", \"aspect-ratio\",\n \"min-aspect-ratio\", \"max-aspect-ratio\", \"device-aspect-ratio\",\n \"min-device-aspect-ratio\", \"max-device-aspect-ratio\", \"color\", \"min-color\",\n \"max-color\", \"color-index\", \"min-color-index\", \"max-color-index\",\n \"monochrome\", \"min-monochrome\", \"max-monochrome\", \"resolution\",\n \"min-resolution\", \"max-resolution\", \"scan\", \"grid\", \"orientation\",\n \"device-pixel-ratio\", \"min-device-pixel-ratio\", \"max-device-pixel-ratio\",\n \"pointer\", \"any-pointer\", \"hover\", \"any-hover\", \"prefers-color-scheme\",\n \"dynamic-range\", \"video-dynamic-range\"\n], mediaFeatures = keySet(mediaFeatures_);\n\nvar mediaValueKeywords_ = [\n \"landscape\", \"portrait\", \"none\", \"coarse\", \"fine\", \"on-demand\", \"hover\",\n \"interlace\", \"progressive\",\n \"dark\", \"light\",\n \"standard\", \"high\"\n], mediaValueKeywords = keySet(mediaValueKeywords_);\n\nvar propertyKeywords_ = [\n \"align-content\", \"align-items\", \"align-self\", \"alignment-adjust\",\n \"alignment-baseline\", \"all\", \"anchor-point\", \"animation\", \"animation-delay\",\n \"animation-direction\", \"animation-duration\", \"animation-fill-mode\",\n \"animation-iteration-count\", \"animation-name\", \"animation-play-state\",\n \"animation-timing-function\", \"appearance\", \"azimuth\", \"backdrop-filter\",\n \"backface-visibility\", \"background\", \"background-attachment\",\n \"background-blend-mode\", \"background-clip\", \"background-color\",\n \"background-image\", \"background-origin\", \"background-position\",\n \"background-position-x\", \"background-position-y\", \"background-repeat\",\n \"background-size\", \"baseline-shift\", \"binding\", \"bleed\", \"block-size\",\n \"bookmark-label\", \"bookmark-level\", \"bookmark-state\", \"bookmark-target\",\n \"border\", \"border-bottom\", \"border-bottom-color\", \"border-bottom-left-radius\",\n \"border-bottom-right-radius\", \"border-bottom-style\", \"border-bottom-width\",\n \"border-collapse\", \"border-color\", \"border-image\", \"border-image-outset\",\n \"border-image-repeat\", \"border-image-slice\", \"border-image-source\",\n \"border-image-width\", \"border-left\", \"border-left-color\", \"border-left-style\",\n \"border-left-width\", \"border-radius\", \"border-right\", \"border-right-color\",\n \"border-right-style\", \"border-right-width\", \"border-spacing\", \"border-style\",\n \"border-top\", \"border-top-color\", \"border-top-left-radius\",\n \"border-top-right-radius\", \"border-top-style\", \"border-top-width\",\n \"border-width\", \"bottom\", \"box-decoration-break\", \"box-shadow\", \"box-sizing\",\n \"break-after\", \"break-before\", \"break-inside\", \"caption-side\", \"caret-color\",\n \"clear\", \"clip\", \"color\", \"color-profile\", \"column-count\", \"column-fill\",\n \"column-gap\", \"column-rule\", \"column-rule-color\", \"column-rule-style\",\n \"column-rule-width\", \"column-span\", \"column-width\", \"columns\", \"contain\",\n \"content\", \"counter-increment\", \"counter-reset\", \"crop\", \"cue\", \"cue-after\",\n \"cue-before\", \"cursor\", \"direction\", \"display\", \"dominant-baseline\",\n \"drop-initial-after-adjust\", \"drop-initial-after-align\",\n \"drop-initial-before-adjust\", \"drop-initial-before-align\", \"drop-initial-size\",\n \"drop-initial-value\", \"elevation\", \"empty-cells\", \"fit\", \"fit-content\", \"fit-position\",\n \"flex\", \"flex-basis\", \"flex-direction\", \"flex-flow\", \"flex-grow\",\n \"flex-shrink\", \"flex-wrap\", \"float\", \"float-offset\", \"flow-from\", \"flow-into\",\n \"font\", \"font-family\", \"font-feature-settings\", \"font-kerning\",\n \"font-language-override\", \"font-optical-sizing\", \"font-size\",\n \"font-size-adjust\", \"font-stretch\", \"font-style\", \"font-synthesis\",\n \"font-variant\", \"font-variant-alternates\", \"font-variant-caps\",\n \"font-variant-east-asian\", \"font-variant-ligatures\", \"font-variant-numeric\",\n \"font-variant-position\", \"font-variation-settings\", \"font-weight\", \"gap\",\n \"grid\", \"grid-area\", \"grid-auto-columns\", \"grid-auto-flow\", \"grid-auto-rows\",\n \"grid-column\", \"grid-column-end\", \"grid-column-gap\", \"grid-column-start\",\n \"grid-gap\", \"grid-row\", \"grid-row-end\", \"grid-row-gap\", \"grid-row-start\",\n \"grid-template\", \"grid-template-areas\", \"grid-template-columns\",\n \"grid-template-rows\", \"hanging-punctuation\", \"height\", \"hyphens\", \"icon\",\n \"image-orientation\", \"image-rendering\", \"image-resolution\", \"inline-box-align\",\n \"inset\", \"inset-block\", \"inset-block-end\", \"inset-block-start\", \"inset-inline\",\n \"inset-inline-end\", \"inset-inline-start\", \"isolation\", \"justify-content\",\n \"justify-items\", \"justify-self\", \"left\", \"letter-spacing\", \"line-break\",\n \"line-height\", \"line-height-step\", \"line-stacking\", \"line-stacking-ruby\",\n \"line-stacking-shift\", \"line-stacking-strategy\", \"list-style\",\n \"list-style-image\", \"list-style-position\", \"list-style-type\", \"margin\",\n \"margin-bottom\", \"margin-left\", \"margin-right\", \"margin-top\", \"marks\",\n \"marquee-direction\", \"marquee-loop\", \"marquee-play-count\", \"marquee-speed\",\n \"marquee-style\", \"mask-clip\", \"mask-composite\", \"mask-image\", \"mask-mode\",\n \"mask-origin\", \"mask-position\", \"mask-repeat\", \"mask-size\",\"mask-type\",\n \"max-block-size\", \"max-height\", \"max-inline-size\",\n \"max-width\", \"min-block-size\", \"min-height\", \"min-inline-size\", \"min-width\",\n \"mix-blend-mode\", \"move-to\", \"nav-down\", \"nav-index\", \"nav-left\", \"nav-right\",\n \"nav-up\", \"object-fit\", \"object-position\", \"offset\", \"offset-anchor\",\n \"offset-distance\", \"offset-path\", \"offset-position\", \"offset-rotate\",\n \"opacity\", \"order\", \"orphans\", \"outline\", \"outline-color\", \"outline-offset\",\n \"outline-style\", \"outline-width\", \"overflow\", \"overflow-style\",\n \"overflow-wrap\", \"overflow-x\", \"overflow-y\", \"padding\", \"padding-bottom\",\n \"padding-left\", \"padding-right\", \"padding-top\", \"page\", \"page-break-after\",\n \"page-break-before\", \"page-break-inside\", \"page-policy\", \"pause\",\n \"pause-after\", \"pause-before\", \"perspective\", \"perspective-origin\", \"pitch\",\n \"pitch-range\", \"place-content\", \"place-items\", \"place-self\", \"play-during\",\n \"position\", \"presentation-level\", \"punctuation-trim\", \"quotes\",\n \"region-break-after\", \"region-break-before\", \"region-break-inside\",\n \"region-fragment\", \"rendering-intent\", \"resize\", \"rest\", \"rest-after\",\n \"rest-before\", \"richness\", \"right\", \"rotate\", \"rotation\", \"rotation-point\",\n \"row-gap\", \"ruby-align\", \"ruby-overhang\", \"ruby-position\", \"ruby-span\",\n \"scale\", \"scroll-behavior\", \"scroll-margin\", \"scroll-margin-block\",\n \"scroll-margin-block-end\", \"scroll-margin-block-start\", \"scroll-margin-bottom\",\n \"scroll-margin-inline\", \"scroll-margin-inline-end\",\n \"scroll-margin-inline-start\", \"scroll-margin-left\", \"scroll-margin-right\",\n \"scroll-margin-top\", \"scroll-padding\", \"scroll-padding-block\",\n \"scroll-padding-block-end\", \"scroll-padding-block-start\",\n \"scroll-padding-bottom\", \"scroll-padding-inline\", \"scroll-padding-inline-end\",\n \"scroll-padding-inline-start\", \"scroll-padding-left\", \"scroll-padding-right\",\n \"scroll-padding-top\", \"scroll-snap-align\", \"scroll-snap-type\",\n \"shape-image-threshold\", \"shape-inside\", \"shape-margin\", \"shape-outside\",\n \"size\", \"speak\", \"speak-as\", \"speak-header\", \"speak-numeral\",\n \"speak-punctuation\", \"speech-rate\", \"stress\", \"string-set\", \"tab-size\",\n \"table-layout\", \"target\", \"target-name\", \"target-new\", \"target-position\",\n \"text-align\", \"text-align-last\", \"text-combine-upright\", \"text-decoration\",\n \"text-decoration-color\", \"text-decoration-line\", \"text-decoration-skip\",\n \"text-decoration-skip-ink\", \"text-decoration-style\", \"text-emphasis\",\n \"text-emphasis-color\", \"text-emphasis-position\", \"text-emphasis-style\",\n \"text-height\", \"text-indent\", \"text-justify\", \"text-orientation\",\n \"text-outline\", \"text-overflow\", \"text-rendering\", \"text-shadow\",\n \"text-size-adjust\", \"text-space-collapse\", \"text-transform\",\n \"text-underline-position\", \"text-wrap\", \"top\", \"touch-action\", \"transform\", \"transform-origin\",\n \"transform-style\", \"transition\", \"transition-delay\", \"transition-duration\",\n \"transition-property\", \"transition-timing-function\", \"translate\",\n \"unicode-bidi\", \"user-select\", \"vertical-align\", \"visibility\", \"voice-balance\",\n \"voice-duration\", \"voice-family\", \"voice-pitch\", \"voice-range\", \"voice-rate\",\n \"voice-stress\", \"voice-volume\", \"volume\", \"white-space\", \"widows\", \"width\",\n \"will-change\", \"word-break\", \"word-spacing\", \"word-wrap\", \"writing-mode\", \"z-index\",\n // SVG-specific\n \"clip-path\", \"clip-rule\", \"mask\", \"enable-background\", \"filter\", \"flood-color\",\n \"flood-opacity\", \"lighting-color\", \"stop-color\", \"stop-opacity\", \"pointer-events\",\n \"color-interpolation\", \"color-interpolation-filters\",\n \"color-rendering\", \"fill\", \"fill-opacity\", \"fill-rule\", \"image-rendering\",\n \"marker\", \"marker-end\", \"marker-mid\", \"marker-start\", \"paint-order\", \"shape-rendering\", \"stroke\",\n \"stroke-dasharray\", \"stroke-dashoffset\", \"stroke-linecap\", \"stroke-linejoin\",\n \"stroke-miterlimit\", \"stroke-opacity\", \"stroke-width\", \"text-rendering\",\n \"baseline-shift\", \"dominant-baseline\", \"glyph-orientation-horizontal\",\n \"glyph-orientation-vertical\", \"text-anchor\", \"writing-mode\",\n], propertyKeywords = keySet(propertyKeywords_);\n\nvar nonStandardPropertyKeywords_ = [\n \"accent-color\", \"aspect-ratio\", \"border-block\", \"border-block-color\", \"border-block-end\",\n \"border-block-end-color\", \"border-block-end-style\", \"border-block-end-width\",\n \"border-block-start\", \"border-block-start-color\", \"border-block-start-style\",\n \"border-block-start-width\", \"border-block-style\", \"border-block-width\",\n \"border-inline\", \"border-inline-color\", \"border-inline-end\",\n \"border-inline-end-color\", \"border-inline-end-style\",\n \"border-inline-end-width\", \"border-inline-start\", \"border-inline-start-color\",\n \"border-inline-start-style\", \"border-inline-start-width\",\n \"border-inline-style\", \"border-inline-width\", \"content-visibility\", \"margin-block\",\n \"margin-block-end\", \"margin-block-start\", \"margin-inline\", \"margin-inline-end\",\n \"margin-inline-start\", \"overflow-anchor\", \"overscroll-behavior\", \"padding-block\", \"padding-block-end\",\n \"padding-block-start\", \"padding-inline\", \"padding-inline-end\",\n \"padding-inline-start\", \"scroll-snap-stop\", \"scrollbar-3d-light-color\",\n \"scrollbar-arrow-color\", \"scrollbar-base-color\", \"scrollbar-dark-shadow-color\",\n \"scrollbar-face-color\", \"scrollbar-highlight-color\", \"scrollbar-shadow-color\",\n \"scrollbar-track-color\", \"searchfield-cancel-button\", \"searchfield-decoration\",\n \"searchfield-results-button\", \"searchfield-results-decoration\", \"shape-inside\", \"zoom\"\n], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_);\n\nvar fontProperties_ = [\n \"font-display\", \"font-family\", \"src\", \"unicode-range\", \"font-variant\",\n \"font-feature-settings\", \"font-stretch\", \"font-weight\", \"font-style\"\n], fontProperties = keySet(fontProperties_);\n\nvar counterDescriptors_ = [\n \"additive-symbols\", \"fallback\", \"negative\", \"pad\", \"prefix\", \"range\",\n \"speak-as\", \"suffix\", \"symbols\", \"system\"\n], counterDescriptors = keySet(counterDescriptors_);\n\nvar colorKeywords_ = [\n \"aliceblue\", \"antiquewhite\", \"aqua\", \"aquamarine\", \"azure\", \"beige\",\n \"bisque\", \"black\", \"blanchedalmond\", \"blue\", \"blueviolet\", \"brown\",\n \"burlywood\", \"cadetblue\", \"chartreuse\", \"chocolate\", \"coral\", \"cornflowerblue\",\n \"cornsilk\", \"crimson\", \"cyan\", \"darkblue\", \"darkcyan\", \"darkgoldenrod\",\n \"darkgray\", \"darkgreen\", \"darkgrey\", \"darkkhaki\", \"darkmagenta\", \"darkolivegreen\",\n \"darkorange\", \"darkorchid\", \"darkred\", \"darksalmon\", \"darkseagreen\",\n \"darkslateblue\", \"darkslategray\", \"darkslategrey\", \"darkturquoise\", \"darkviolet\",\n \"deeppink\", \"deepskyblue\", \"dimgray\", \"dimgrey\", \"dodgerblue\", \"firebrick\",\n \"floralwhite\", \"forestgreen\", \"fuchsia\", \"gainsboro\", \"ghostwhite\",\n \"gold\", \"goldenrod\", \"gray\", \"grey\", \"green\", \"greenyellow\", \"honeydew\",\n \"hotpink\", \"indianred\", \"indigo\", \"ivory\", \"khaki\", \"lavender\",\n \"lavenderblush\", \"lawngreen\", \"lemonchiffon\", \"lightblue\", \"lightcoral\",\n \"lightcyan\", \"lightgoldenrodyellow\", \"lightgray\", \"lightgreen\", \"lightgrey\", \"lightpink\",\n \"lightsalmon\", \"lightseagreen\", \"lightskyblue\", \"lightslategray\", \"lightslategrey\",\n \"lightsteelblue\", \"lightyellow\", \"lime\", \"limegreen\", \"linen\", \"magenta\",\n \"maroon\", \"mediumaquamarine\", \"mediumblue\", \"mediumorchid\", \"mediumpurple\",\n \"mediumseagreen\", \"mediumslateblue\", \"mediumspringgreen\", \"mediumturquoise\",\n \"mediumvioletred\", \"midnightblue\", \"mintcream\", \"mistyrose\", \"moccasin\",\n \"navajowhite\", \"navy\", \"oldlace\", \"olive\", \"olivedrab\", \"orange\", \"orangered\",\n \"orchid\", \"palegoldenrod\", \"palegreen\", \"paleturquoise\", \"palevioletred\",\n \"papayawhip\", \"peachpuff\", \"peru\", \"pink\", \"plum\", \"powderblue\",\n \"purple\", \"rebeccapurple\", \"red\", \"rosybrown\", \"royalblue\", \"saddlebrown\",\n \"salmon\", \"sandybrown\", \"seagreen\", \"seashell\", \"sienna\", \"silver\", \"skyblue\",\n \"slateblue\", \"slategray\", \"slategrey\", \"snow\", \"springgreen\", \"steelblue\", \"tan\",\n \"teal\", \"thistle\", \"tomato\", \"turquoise\", \"violet\", \"wheat\", \"white\",\n \"whitesmoke\", \"yellow\", \"yellowgreen\"\n], colorKeywords = keySet(colorKeywords_);\n\nvar valueKeywords_ = [\n \"above\", \"absolute\", \"activeborder\", \"additive\", \"activecaption\", \"afar\",\n \"after-white-space\", \"ahead\", \"alias\", \"all\", \"all-scroll\", \"alphabetic\", \"alternate\",\n \"always\", \"amharic\", \"amharic-abegede\", \"antialiased\", \"appworkspace\",\n \"arabic-indic\", \"armenian\", \"asterisks\", \"attr\", \"auto\", \"auto-flow\", \"avoid\", \"avoid-column\", \"avoid-page\",\n \"avoid-region\", \"axis-pan\", \"background\", \"backwards\", \"baseline\", \"below\", \"bidi-override\", \"binary\",\n \"bengali\", \"blink\", \"block\", \"block-axis\", \"blur\", \"bold\", \"bolder\", \"border\", \"border-box\",\n \"both\", \"bottom\", \"break\", \"break-all\", \"break-word\", \"brightness\", \"bullets\", \"button\",\n \"buttonface\", \"buttonhighlight\", \"buttonshadow\", \"buttontext\", \"calc\", \"cambodian\",\n \"capitalize\", \"caps-lock-indicator\", \"caption\", \"captiontext\", \"caret\",\n \"cell\", \"center\", \"checkbox\", \"circle\", \"cjk-decimal\", \"cjk-earthly-branch\",\n \"cjk-heavenly-stem\", \"cjk-ideographic\", \"clear\", \"clip\", \"close-quote\",\n \"col-resize\", \"collapse\", \"color\", \"color-burn\", \"color-dodge\", \"column\", \"column-reverse\",\n \"compact\", \"condensed\", \"conic-gradient\", \"contain\", \"content\", \"contents\",\n \"content-box\", \"context-menu\", \"continuous\", \"contrast\", \"copy\", \"counter\", \"counters\", \"cover\", \"crop\",\n \"cross\", \"crosshair\", \"cubic-bezier\", \"currentcolor\", \"cursive\", \"cyclic\", \"darken\", \"dashed\", \"decimal\",\n \"decimal-leading-zero\", \"default\", \"default-button\", \"dense\", \"destination-atop\",\n \"destination-in\", \"destination-out\", \"destination-over\", \"devanagari\", \"difference\",\n \"disc\", \"discard\", \"disclosure-closed\", \"disclosure-open\", \"document\",\n \"dot-dash\", \"dot-dot-dash\",\n \"dotted\", \"double\", \"down\", \"drop-shadow\", \"e-resize\", \"ease\", \"ease-in\", \"ease-in-out\", \"ease-out\",\n \"element\", \"ellipse\", \"ellipsis\", \"embed\", \"end\", \"ethiopic\", \"ethiopic-abegede\",\n \"ethiopic-abegede-am-et\", \"ethiopic-abegede-gez\", \"ethiopic-abegede-ti-er\",\n \"ethiopic-abegede-ti-et\", \"ethiopic-halehame-aa-er\",\n \"ethiopic-halehame-aa-et\", \"ethiopic-halehame-am-et\",\n \"ethiopic-halehame-gez\", \"ethiopic-halehame-om-et\",\n \"ethiopic-halehame-sid-et\", \"ethiopic-halehame-so-et\",\n \"ethiopic-halehame-ti-er\", \"ethiopic-halehame-ti-et\", \"ethiopic-halehame-tig\",\n \"ethiopic-numeric\", \"ew-resize\", \"exclusion\", \"expanded\", \"extends\", \"extra-condensed\",\n \"extra-expanded\", \"fantasy\", \"fast\", \"fill\", \"fill-box\", \"fixed\", \"flat\", \"flex\", \"flex-end\", \"flex-start\", \"footnotes\",\n \"forwards\", \"from\", \"geometricPrecision\", \"georgian\", \"grayscale\", \"graytext\", \"grid\", \"groove\",\n \"gujarati\", \"gurmukhi\", \"hand\", \"hangul\", \"hangul-consonant\", \"hard-light\", \"hebrew\",\n \"help\", \"hidden\", \"hide\", \"higher\", \"highlight\", \"highlighttext\",\n \"hiragana\", \"hiragana-iroha\", \"horizontal\", \"hsl\", \"hsla\", \"hue\", \"hue-rotate\", \"icon\", \"ignore\",\n \"inactiveborder\", \"inactivecaption\", \"inactivecaptiontext\", \"infinite\",\n \"infobackground\", \"infotext\", \"inherit\", \"initial\", \"inline\", \"inline-axis\",\n \"inline-block\", \"inline-flex\", \"inline-grid\", \"inline-table\", \"inset\", \"inside\", \"intrinsic\", \"invert\",\n \"italic\", \"japanese-formal\", \"japanese-informal\", \"justify\", \"kannada\",\n \"katakana\", \"katakana-iroha\", \"keep-all\", \"khmer\",\n \"korean-hangul-formal\", \"korean-hanja-formal\", \"korean-hanja-informal\",\n \"landscape\", \"lao\", \"large\", \"larger\", \"left\", \"level\", \"lighter\", \"lighten\",\n \"line-through\", \"linear\", \"linear-gradient\", \"lines\", \"list-item\", \"listbox\", \"listitem\",\n \"local\", \"logical\", \"loud\", \"lower\", \"lower-alpha\", \"lower-armenian\",\n \"lower-greek\", \"lower-hexadecimal\", \"lower-latin\", \"lower-norwegian\",\n \"lower-roman\", \"lowercase\", \"ltr\", \"luminosity\", \"malayalam\", \"manipulation\", \"match\", \"matrix\", \"matrix3d\",\n \"media-play-button\", \"media-slider\", \"media-sliderthumb\",\n \"media-volume-slider\", \"media-volume-sliderthumb\", \"medium\",\n \"menu\", \"menulist\", \"menulist-button\",\n \"menutext\", \"message-box\", \"middle\", \"min-intrinsic\",\n \"mix\", \"mongolian\", \"monospace\", \"move\", \"multiple\", \"multiple_mask_images\", \"multiply\", \"myanmar\", \"n-resize\",\n \"narrower\", \"ne-resize\", \"nesw-resize\", \"no-close-quote\", \"no-drop\",\n \"no-open-quote\", \"no-repeat\", \"none\", \"normal\", \"not-allowed\", \"nowrap\",\n \"ns-resize\", \"numbers\", \"numeric\", \"nw-resize\", \"nwse-resize\", \"oblique\", \"octal\", \"opacity\", \"open-quote\",\n \"optimizeLegibility\", \"optimizeSpeed\", \"oriya\", \"oromo\", \"outset\",\n \"outside\", \"outside-shape\", \"overlay\", \"overline\", \"padding\", \"padding-box\",\n \"painted\", \"page\", \"paused\", \"persian\", \"perspective\", \"pinch-zoom\", \"plus-darker\", \"plus-lighter\",\n \"pointer\", \"polygon\", \"portrait\", \"pre\", \"pre-line\", \"pre-wrap\", \"preserve-3d\",\n \"progress\", \"push-button\", \"radial-gradient\", \"radio\", \"read-only\",\n \"read-write\", \"read-write-plaintext-only\", \"rectangle\", \"region\",\n \"relative\", \"repeat\", \"repeating-linear-gradient\", \"repeating-radial-gradient\",\n \"repeating-conic-gradient\", \"repeat-x\", \"repeat-y\", \"reset\", \"reverse\",\n \"rgb\", \"rgba\", \"ridge\", \"right\", \"rotate\", \"rotate3d\", \"rotateX\", \"rotateY\",\n \"rotateZ\", \"round\", \"row\", \"row-resize\", \"row-reverse\", \"rtl\", \"run-in\", \"running\",\n \"s-resize\", \"sans-serif\", \"saturate\", \"saturation\", \"scale\", \"scale3d\", \"scaleX\", \"scaleY\", \"scaleZ\", \"screen\",\n \"scroll\", \"scrollbar\", \"scroll-position\", \"se-resize\", \"searchfield\",\n \"searchfield-cancel-button\", \"searchfield-decoration\",\n \"searchfield-results-button\", \"searchfield-results-decoration\", \"self-start\", \"self-end\",\n \"semi-condensed\", \"semi-expanded\", \"separate\", \"sepia\", \"serif\", \"show\", \"sidama\",\n \"simp-chinese-formal\", \"simp-chinese-informal\", \"single\",\n \"skew\", \"skewX\", \"skewY\", \"skip-white-space\", \"slide\", \"slider-horizontal\",\n \"slider-vertical\", \"sliderthumb-horizontal\", \"sliderthumb-vertical\", \"slow\",\n \"small\", \"small-caps\", \"small-caption\", \"smaller\", \"soft-light\", \"solid\", \"somali\",\n \"source-atop\", \"source-in\", \"source-out\", \"source-over\", \"space\", \"space-around\", \"space-between\", \"space-evenly\", \"spell-out\", \"square\",\n \"square-button\", \"start\", \"static\", \"status-bar\", \"stretch\", \"stroke\", \"stroke-box\", \"sub\",\n \"subpixel-antialiased\", \"svg_masks\", \"super\", \"sw-resize\", \"symbolic\", \"symbols\", \"system-ui\", \"table\",\n \"table-caption\", \"table-cell\", \"table-column\", \"table-column-group\",\n \"table-footer-group\", \"table-header-group\", \"table-row\", \"table-row-group\",\n \"tamil\",\n \"telugu\", \"text\", \"text-bottom\", \"text-top\", \"textarea\", \"textfield\", \"thai\",\n \"thick\", \"thin\", \"threeddarkshadow\", \"threedface\", \"threedhighlight\",\n \"threedlightshadow\", \"threedshadow\", \"tibetan\", \"tigre\", \"tigrinya-er\",\n \"tigrinya-er-abegede\", \"tigrinya-et\", \"tigrinya-et-abegede\", \"to\", \"top\",\n \"trad-chinese-formal\", \"trad-chinese-informal\", \"transform\",\n \"translate\", \"translate3d\", \"translateX\", \"translateY\", \"translateZ\",\n \"transparent\", \"ultra-condensed\", \"ultra-expanded\", \"underline\", \"unidirectional-pan\", \"unset\", \"up\",\n \"upper-alpha\", \"upper-armenian\", \"upper-greek\", \"upper-hexadecimal\",\n \"upper-latin\", \"upper-norwegian\", \"upper-roman\", \"uppercase\", \"urdu\", \"url\",\n \"var\", \"vertical\", \"vertical-text\", \"view-box\", \"visible\", \"visibleFill\", \"visiblePainted\",\n \"visibleStroke\", \"visual\", \"w-resize\", \"wait\", \"wave\", \"wider\",\n \"window\", \"windowframe\", \"windowtext\", \"words\", \"wrap\", \"wrap-reverse\", \"x-large\", \"x-small\", \"xor\",\n \"xx-large\", \"xx-small\"\n], valueKeywords = keySet(valueKeywords_);\n\nvar allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_)\n .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_)\n .concat(valueKeywords_);\n\nexport const keywords = {properties: propertyKeywords_, colors: colorKeywords_,\n fonts: fontProperties_, values: valueKeywords_, all: allWords}\n\nconst defaults = {\n documentTypes: documentTypes,\n mediaTypes: mediaTypes,\n mediaFeatures: mediaFeatures,\n mediaValueKeywords: mediaValueKeywords,\n propertyKeywords: propertyKeywords,\n nonStandardPropertyKeywords: nonStandardPropertyKeywords,\n fontProperties: fontProperties,\n counterDescriptors: counterDescriptors,\n colorKeywords: colorKeywords,\n valueKeywords: valueKeywords,\n tokenHooks: {\n \"/\": function(stream, state) {\n if (!stream.eat(\"*\")) return false;\n state.tokenize = tokenCComment;\n return tokenCComment(stream, state);\n }\n }\n}\n\nexport const css = mkCSS({name: \"css\"})\n\nfunction tokenCComment(stream, state) {\n var maybeEnd = false, ch;\n while ((ch = stream.next()) != null) {\n if (maybeEnd && ch == \"/\") {\n state.tokenize = null;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return [\"comment\", \"comment\"];\n}\n\nexport const sCSS = mkCSS({\n name: \"scss\",\n mediaTypes: mediaTypes,\n mediaFeatures: mediaFeatures,\n mediaValueKeywords: mediaValueKeywords,\n propertyKeywords: propertyKeywords,\n nonStandardPropertyKeywords: nonStandardPropertyKeywords,\n colorKeywords: colorKeywords,\n valueKeywords: valueKeywords,\n fontProperties: fontProperties,\n allowNested: true,\n lineComment: \"//\",\n tokenHooks: {\n \"/\": function(stream, state) {\n if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return [\"comment\", \"comment\"];\n } else if (stream.eat(\"*\")) {\n state.tokenize = tokenCComment;\n return tokenCComment(stream, state);\n } else {\n return [\"operator\", \"operator\"];\n }\n },\n \":\": function(stream) {\n if (stream.match(/^\\s*\\{/, false))\n return [null, null]\n return false;\n },\n \"$\": function(stream) {\n stream.match(/^[\\w-]+/);\n if (stream.match(/^\\s*:/, false))\n return [\"def\", \"variable-definition\"];\n return [\"variableName.special\", \"variable\"];\n },\n \"#\": function(stream) {\n if (!stream.eat(\"{\")) return false;\n return [null, \"interpolation\"];\n }\n }\n})\n\nexport const less = mkCSS({\n name: \"less\",\n mediaTypes: mediaTypes,\n mediaFeatures: mediaFeatures,\n mediaValueKeywords: mediaValueKeywords,\n propertyKeywords: propertyKeywords,\n nonStandardPropertyKeywords: nonStandardPropertyKeywords,\n colorKeywords: colorKeywords,\n valueKeywords: valueKeywords,\n fontProperties: fontProperties,\n allowNested: true,\n lineComment: \"//\",\n tokenHooks: {\n \"/\": function(stream, state) {\n if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return [\"comment\", \"comment\"];\n } else if (stream.eat(\"*\")) {\n state.tokenize = tokenCComment;\n return tokenCComment(stream, state);\n } else {\n return [\"operator\", \"operator\"];\n }\n },\n \"@\": function(stream) {\n if (stream.eat(\"{\")) return [null, \"interpolation\"];\n if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\\b/i, false)) return false;\n stream.eatWhile(/[\\w\\\\\\-]/);\n if (stream.match(/^\\s*:/, false))\n return [\"def\", \"variable-definition\"];\n return [\"variableName\", \"variable\"];\n },\n \"&\": function() {\n return [\"atom\", \"atom\"];\n }\n }\n})\n\nexport const gss = mkCSS({\n name: \"gss\",\n documentTypes: documentTypes,\n mediaTypes: mediaTypes,\n mediaFeatures: mediaFeatures,\n propertyKeywords: propertyKeywords,\n nonStandardPropertyKeywords: nonStandardPropertyKeywords,\n fontProperties: fontProperties,\n counterDescriptors: counterDescriptors,\n colorKeywords: colorKeywords,\n valueKeywords: valueKeywords,\n supportsAtComponent: true,\n tokenHooks: {\n \"/\": function(stream, state) {\n if (!stream.eat(\"*\")) return false;\n state.tokenize = tokenCComment;\n return tokenCComment(stream, state);\n }\n }\n})\n"],"names":["mkCSS","parserConfig","type","override","inline","defaults","tokenHooks","documentTypes","mediaTypes","mediaFeatures","mediaValueKeywords","propertyKeywords","nonStandardPropertyKeywords","fontProperties","counterDescriptors","colorKeywords","valueKeywords","allowNested","lineComment","supportsAtComponent","highlightNonStandardPropertyKeywords","ret","style","tp","tokenBase","stream","state","ch","next","result","eatWhile","current","eat","tokenize","tokenString","match","test","tokenParenthesized","peek","quote","escaped","backUp","Context","indent","prev","this","pushContext","context","indentation","indentUnit","popContext","pass","states","popAndPass","n","i","wordAsValue","word","toLowerCase","hasOwnProperty","stateArg","charAt","top","_stream","atBlock","name","startState","token","eatSpace","textAfter","iCx","cx","Math","max","unit","languageData","indentOnInput","commentTokens","line","block","open","close","autocomplete","allWords","keySet","array","keys","length","documentTypes_","mediaTypes_","mediaFeatures_","mediaValueKeywords_","propertyKeywords_","nonStandardPropertyKeywords_","fontProperties_","colorKeywords_","valueKeywords_","concat","keywords","properties","colors","fonts","values","all","tokenCComment","css","maybeEnd","sCSS","skipToEnd","less","gss"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/6047.index.js b/book/_build/html/_static/6047.index.js new file mode 100644 index 0000000..332c308 --- /dev/null +++ b/book/_build/html/_static/6047.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[6047],{36047:(e,t,n)=>{function r(e){return{type:e,style:"keyword"}}n.r(t),n.d(t,{haxe:()=>ae,hxml:()=>ie});var a,i=r("keyword a"),o=r("keyword b"),l=r("keyword c"),u=r("operator"),c={type:"atom",style:"atom"},f={type:"attribute",style:"attribute"},s=r("typedef"),d={if:i,while:i,else:o,do:o,try:o,return:l,break:l,continue:l,new:l,throw:l,var:r("var"),inline:f,static:f,using:r("import"),public:f,private:f,cast:r("cast"),import:r("import"),macro:r("macro"),function:r("function"),catch:r("catch"),untyped:r("untyped"),callback:r("cb"),for:r("for"),switch:r("switch"),case:r("case"),default:r("default"),in:u,never:r("property_access"),trace:r("trace"),class:s,abstract:s,enum:s,interface:s,typedef:s,extends:s,implements:s,dynamic:s,true:c,false:c,null:c},p=/[+\-*&%=<>!?|]/;function m(e,t,n){return t.tokenize=n,n(e,t)}function v(e,t){for(var n,r=!1;null!=(n=e.next());){if(n==t&&!r)return!0;r=!r&&"\\"==n}}function y(e,t,n){return s=e,a=n,t}function h(e,t){var n=e.next();if('"'==n||"'"==n)return m(e,t,(r=n,function(e,t){return v(e,r)&&(t.tokenize=h),y("string","string")}));if(/[\[\]{}\(\),;\:\.]/.test(n))return y(n);if("0"==n&&e.eat(/x/i))return e.eatWhile(/[\da-f]/i),y("number","number");if(/\d/.test(n)||"-"==n&&e.eat(/\d/))return e.match(/^\d*(?:\.\d*(?!\.))?(?:[eE][+\-]?\d+)?/),y("number","number");if(t.reAllowed&&"~"==n&&e.eat(/\//))return v(e,"/"),e.eatWhile(/[gimsu]/),y("regexp","string.special");if("/"==n)return e.eat("*")?m(e,t,b):e.eat("/")?(e.skipToEnd(),y("comment","comment")):(e.eatWhile(p),y("operator",null,e.current()));if("#"==n)return e.skipToEnd(),y("conditional","meta");if("@"==n)return e.eat(/:/),e.eatWhile(/[\w_]/),y("metadata","meta");if(p.test(n))return e.eatWhile(p),y("operator",null,e.current());if(/[A-Z]/.test(n))return e.eatWhile(/[\w_<>]/),y("type","type",a=e.current());e.eatWhile(/[\w_]/);var r,a=e.current(),i=d.propertyIsEnumerable(a)&&d[a];return i&&t.kwAllowed?y(i.type,i.style,a):y("variable","variable",a)}function b(e,t){for(var n,r=!1;n=e.next();){if("/"==n&&r){t.tokenize=h;break}r="*"==n}return y("comment","comment")}var k={atom:!0,number:!0,variable:!0,string:!0,regexp:!0};function x(e,t,n,r,a,i){this.indented=e,this.column=t,this.type=n,this.prev=a,this.info=i,null!=r&&(this.align=r)}function w(e,t){for(var n=e.localVars;n;n=n.next)if(n.name==t)return!0}function g(e,t){if(/[a-z]/.test(t.charAt(0)))return!1;for(var n=e.importedtypes.length,r=0;r=0;e--)V.cc.push(arguments[e])}function W(){return S.apply(null,arguments),!0}function z(e,t){for(var n=t;n;n=n.next)if(n.name==e)return!0;return!1}function T(e){var t=V.state;if(t.context){if(V.marked="def",z(e,t.localVars))return;t.localVars={name:e,next:t.localVars}}else if(t.globalVars){if(z(e,t.globalVars))return;t.globalVars={name:e,next:t.globalVars}}}var E={name:"this",next:null};function D(){V.state.context||(V.state.localVars=E),V.state.context={prev:V.state.context,vars:V.state.localVars}}function O(){V.state.localVars=V.state.context.vars,V.state.context=V.state.context.prev}function Z(e,t){var n=function(){var n=V.state;n.lexical=new x(n.indented,V.stream.column(),e,null,n.lexical,t)};return n.lex=!0,n}function P(){var e=V.state;e.lexical.prev&&(")"==e.lexical.type&&(e.indented=e.lexical.indented),e.lexical=e.lexical.prev)}function _(e){return function t(n){return n==e?W():";"==e?S():W(t)}}function I(e){return"@"==e?W(F):"var"==e?W(Z("vardef"),Q,_(";"),P):"keyword a"==e?W(Z("form"),C,I,P):"keyword b"==e?W(Z("form"),I,P):"{"==e?W(Z("}"),D,M,P,O):";"==e?W():"attribute"==e?W(B):"function"==e?W(Y):"for"==e?W(Z("form"),_("("),Z(")"),U,_(")"),P,I,P):"variable"==e?W(Z("stat"),H):"switch"==e?W(Z("form"),C,Z("}","switch"),_("{"),M,P,P):"case"==e?W(C,_(":")):"default"==e?W(_(":")):"catch"==e?W(Z("form"),D,_("("),re,_(")"),I,P,O):"import"==e?W(q,_(";")):"typedef"==e?W(G):S(Z("stat"),C,_(";"),P)}function C(e){return k.hasOwnProperty(e)||"type"==e?W($):"function"==e?W(Y):"keyword c"==e?W(N):"("==e?W(Z(")"),N,_(")"),P,$):"operator"==e?W(C):"["==e?W(Z("]"),L(N,"]"),P,$):"{"==e?W(Z("}"),L(K,"}"),P,$):W()}function N(e){return e.match(/[;\}\)\],]/)?S():S(C)}function $(e,t){return"operator"==e&&/\+\+|--/.test(t)?W($):"operator"==e||":"==e?W(C):";"!=e?"("==e?W(Z(")"),L(C,")"),P,$):"."==e?W(J,$):"["==e?W(Z("]"),C,_("]"),P,$):void 0:void 0}function B(e){return"attribute"==e?W(B):"function"==e?W(Y):"var"==e?W(Q):void 0}function F(e){return":"==e||"variable"==e?W(F):"("==e?W(Z(")"),L(j,")"),P,I):void 0}function j(e){if("variable"==e)return W()}function q(e,t){return"variable"==e&&/[A-Z]/.test(t.charAt(0))?(A(t),W()):"variable"==e||"property"==e||"."==e||"*"==t?W(q):void 0}function G(e,t){return"variable"==e&&/[A-Z]/.test(t.charAt(0))?(A(t),W()):"type"==e&&/[A-Z]/.test(t.charAt(0))?W():void 0}function H(e){return":"==e?W(P,I):S($,_(";"),P)}function J(e){if("variable"==e)return V.marked="property",W()}function K(e){if("variable"==e&&(V.marked="property"),k.hasOwnProperty(e))return W(_(":"),C)}function L(e,t){function n(r){return","==r?W(e,n):r==t?W():W(_(t))}return function(r){return r==t?W():S(e,n)}}function M(e){return"}"==e?W():S(I,M)}function Q(e,t){return"variable"==e?(T(t),W(ee,R)):W()}function R(e,t){return"="==t?W(C,R):","==e?W(Q):void 0}function U(e,t){return"variable"==e?(T(t),W(X,C)):S()}function X(e,t){if("in"==t)return W()}function Y(e,t){return"variable"==e||"type"==e?(T(t),W(Y)):"new"==t?W(Y):"("==e?W(Z(")"),D,L(re,")"),P,ee,I,O):void 0}function ee(e){if(":"==e)return W(te)}function te(e){return"type"==e||"variable"==e?W():"{"==e?W(Z("}"),L(ne,"}"),P):void 0}function ne(e){if("variable"==e)return W(ee)}function re(e,t){if("variable"==e)return T(t),W(ee)}O.lex=!0,P.lex=!0;const ae={name:"haxe",startState:function(e){return{tokenize:h,reAllowed:!0,kwAllowed:!0,cc:[],lexical:new x(-e,0,"block",!1),importedtypes:["Int","Float","String","Void","Std","Bool","Dynamic","Array"],context:null,indented:0}},token:function(e,t){if(e.sol()&&(t.lexical.hasOwnProperty("align")||(t.lexical.align=!1),t.indented=e.indentation()),e.eatSpace())return null;var n=t.tokenize(e,t);return"comment"==s?n:(t.reAllowed=!("operator"!=s&&"keyword c"!=s&&!s.match(/^[\[{}\(,;:]$/)),t.kwAllowed="."!=s,function(e,t,n,r,a){var i=e.cc;for(V.state=e,V.stream=a,V.marked=null,V.cc=i,e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);;)if((i.length?i.pop():I)(n,r)){for(;i.length&&i[i.length-1].lex;)i.pop()();return V.marked?V.marked:"variable"==n&&w(e,r)?"variableName.local":"variable"==n&&g(e,r)?"variableName.special":t}}(t,n,s,a,e))},indent:function(e,t,n){if(e.tokenize!=h)return 0;var r=t&&t.charAt(0),a=e.lexical;"stat"==a.type&&"}"==r&&(a=a.prev);var i=a.type,o=r==i;return"vardef"==i?a.indented+4:"form"==i&&"{"==r?a.indented:"stat"==i||"form"==i?a.indented+n.unit:"switch"!=a.info||o?a.align?a.column+(o?0:1):a.indented+(o?0:n.unit):a.indented+(/^(?:case|default)\b/.test(t)?n.unit:2*n.unit)},languageData:{indentOnInput:/^\s*[{}]$/,commentTokens:{line:"//",block:{open:"/*",close:"*/"}}}},ie={name:"hxml",startState:function(){return{define:!1,inString:!1}},token:function(e,t){var n=e.peek(),r=e.sol();if("#"==n)return e.skipToEnd(),"comment";if(r&&"-"==n){var a="variable-2";return e.eat(/-/),"-"==e.peek()&&(e.eat(/-/),a="keyword a"),"D"==e.peek()&&(e.eat(/[D]/),a="keyword c",t.define=!0),e.eatWhile(/[A-Z]/i),a}return n=e.peek(),0==t.inString&&"'"==n&&(t.inString=!0,e.next()),1==t.inString?(e.skipTo("'")||e.skipToEnd(),"'"==e.peek()&&(e.next(),t.inString=!1),"string"):(e.next(),null)},languageData:{commentTokens:{line:"#"}}}}}]); +//# sourceMappingURL=6047.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/6047.index.js.map b/book/_build/html/_static/6047.index.js.map new file mode 100644 index 0000000..368ddb8 --- /dev/null +++ b/book/_build/html/_static/6047.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"6047.index.js","mappings":"+FAEA,SAASA,EAAGC,GAAO,MAAO,CAACA,KAAMA,EAAMC,MAAO,UAAW,C,wCACzD,IAiCUC,EAjCNC,EAAIJ,EAAG,aAAcK,EAAIL,EAAG,aAAcM,EAAIN,EAAG,aACjDO,EAAWP,EAAG,YAAaQ,EAAO,CAACP,KAAM,OAAQC,MAAO,QAASO,EAAY,CAACR,KAAK,YAAaC,MAAO,aACvGD,EAAOD,EAAG,WACVU,EAAW,CACb,GAAMN,EAAG,MAASA,EAAG,KAAQC,EAAG,GAAMA,EAAG,IAAOA,EAChD,OAAUC,EAAG,MAASA,EAAG,SAAYA,EAAG,IAAOA,EAAG,MAASA,EAC3D,IAAON,EAAG,OAAQ,OAASS,EAAW,OAAUA,EAAW,MAAQT,EAAG,UACtE,OAAUS,EAAW,QAAWA,EAAW,KAAQT,EAAG,QAAS,OAAUA,EAAG,U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,OACZnB,EAAMzG,EAAOyG,MAGjB,GAAU,KAAN7F,EAEF,OADAZ,EAAOoB,YACA,UAET,GAAIqF,GAAa,KAAN7F,EAAW,CACpB,IAAIvB,EAAQ,aAgBZ,OAdAW,EAAOe,IAAI,KAEU,KAAjBf,EAAO4H,SACT5H,EAAOe,IAAI,KACX1B,EAAQ,aAGW,KAAjBW,EAAO4H,SACT5H,EAAOe,IAAI,OACX1B,EAAQ,YACRY,EAAMyH,QAAS,GAGjB1H,EAAOgB,SAAS,UACT3B,CACT,CASA,OAPIuB,EAAKZ,EAAO4H,OAEM,GAAlB3H,EAAM0H,UAA2B,KAAN/G,IAC7BX,EAAM0H,UAAW,EACjB3H,EAAOM,QAGa,GAAlBL,EAAM0H,UACJ3H,EAAO6H,OAAO,MAGhB7H,EAAOoB,YAGY,KAAjBpB,EAAO4H,SACT5H,EAAOM,OACPL,EAAM0H,UAAW,GAGZ,WAGT3H,EAAOM,OACA,KACT,EACA6G,aAAc,CACZE,cAAe,CAACC,KAAM,M","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/haxe.js"],"sourcesContent":["// Tokenizer\n\nfunction kw(type) {return {type: type, style: \"keyword\"};}\nvar A = kw(\"keyword a\"), B = kw(\"keyword b\"), C = kw(\"keyword c\");\nvar operator = kw(\"operator\"), atom = {type: \"atom\", style: \"atom\"}, attribute = {type:\"attribute\", style: \"attribute\"};\nvar type = kw(\"typedef\");\nvar keywords = {\n \"if\": A, \"while\": A, \"else\": B, \"do\": B, \"try\": B,\n \"return\": C, \"break\": C, \"continue\": C, \"new\": C, \"throw\": C,\n \"var\": kw(\"var\"), \"inline\":attribute, \"static\": attribute, \"using\":kw(\"import\"),\n \"public\": attribute, \"private\": attribute, \"cast\": kw(\"cast\"), \"import\": kw(\"import\"), \"macro\": kw(\"macro\"),\n \"function\": kw(\"function\"), \"catch\": kw(\"catch\"), \"untyped\": kw(\"untyped\"), \"callback\": kw(\"cb\"),\n \"for\": kw(\"for\"), \"switch\": kw(\"switch\"), \"case\": kw(\"case\"), \"default\": kw(\"default\"),\n \"in\": operator, \"never\": kw(\"property_access\"), \"trace\":kw(\"trace\"),\n \"class\": type, \"abstract\":type, \"enum\":type, \"interface\":type, \"typedef\":type, \"extends\":type, \"implements\":type, \"dynamic\":type,\n \"true\": atom, \"false\": atom, \"null\": atom\n};\n\nvar isOperatorChar = /[+\\-*&%=<>!?|]/;\n\nfunction chain(stream, state, f) {\n state.tokenize = f;\n return f(stream, state);\n}\n\nfunction toUnescaped(stream, end) {\n var escaped = false, next;\n while ((next = stream.next()) != null) {\n if (next == end && !escaped)\n return true;\n escaped = !escaped && next == \"\\\\\";\n }\n}\n\n// Used as scratch variables to communicate multiple values without\n// consing up tons of objects.\nvar type, content;\nfunction ret(tp, style, cont) {\n type = tp; content = cont;\n return style;\n}\n\nfunction haxeTokenBase(stream, state) {\n var ch = stream.next();\n if (ch == '\"' || ch == \"'\") {\n return chain(stream, state, haxeTokenString(ch));\n } else if (/[\\[\\]{}\\(\\),;\\:\\.]/.test(ch)) {\n return ret(ch);\n } else if (ch == \"0\" && stream.eat(/x/i)) {\n stream.eatWhile(/[\\da-f]/i);\n return ret(\"number\", \"number\");\n } else if (/\\d/.test(ch) || ch == \"-\" && stream.eat(/\\d/)) {\n stream.match(/^\\d*(?:\\.\\d*(?!\\.))?(?:[eE][+\\-]?\\d+)?/);\n return ret(\"number\", \"number\");\n } else if (state.reAllowed && (ch == \"~\" && stream.eat(/\\//))) {\n toUnescaped(stream, \"/\");\n stream.eatWhile(/[gimsu]/);\n return ret(\"regexp\", \"string.special\");\n } else if (ch == \"/\") {\n if (stream.eat(\"*\")) {\n return chain(stream, state, haxeTokenComment);\n } else if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return ret(\"comment\", \"comment\");\n } else {\n stream.eatWhile(isOperatorChar);\n return ret(\"operator\", null, stream.current());\n }\n } else if (ch == \"#\") {\n stream.skipToEnd();\n return ret(\"conditional\", \"meta\");\n } else if (ch == \"@\") {\n stream.eat(/:/);\n stream.eatWhile(/[\\w_]/);\n return ret (\"metadata\", \"meta\");\n } else if (isOperatorChar.test(ch)) {\n stream.eatWhile(isOperatorChar);\n return ret(\"operator\", null, stream.current());\n } else {\n var word;\n if(/[A-Z]/.test(ch)) {\n stream.eatWhile(/[\\w_<>]/);\n word = stream.current();\n return ret(\"type\", \"type\", word);\n } else {\n stream.eatWhile(/[\\w_]/);\n var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];\n return (known && state.kwAllowed) ? ret(known.type, known.style, word) :\n ret(\"variable\", \"variable\", word);\n }\n }\n}\n\nfunction haxeTokenString(quote) {\n return function(stream, state) {\n if (toUnescaped(stream, quote))\n state.tokenize = haxeTokenBase;\n return ret(\"string\", \"string\");\n };\n}\n\nfunction haxeTokenComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if (ch == \"/\" && maybeEnd) {\n state.tokenize = haxeTokenBase;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return ret(\"comment\", \"comment\");\n}\n\n// Parser\n\nvar atomicTypes = {\"atom\": true, \"number\": true, \"variable\": true, \"string\": true, \"regexp\": true};\n\nfunction HaxeLexical(indented, column, type, align, prev, info) {\n this.indented = indented;\n this.column = column;\n this.type = type;\n this.prev = prev;\n this.info = info;\n if (align != null) this.align = align;\n}\n\nfunction inScope(state, varname) {\n for (var v = state.localVars; v; v = v.next)\n if (v.name == varname) return true;\n}\n\nfunction parseHaxe(state, style, type, content, stream) {\n var cc = state.cc;\n // Communicate our context to the combinators.\n // (Less wasteful than consing up a hundred closures on every call.)\n cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;\n\n if (!state.lexical.hasOwnProperty(\"align\"))\n state.lexical.align = true;\n\n while(true) {\n var combinator = cc.length ? cc.pop() : statement;\n if (combinator(type, content)) {\n while(cc.length && cc[cc.length - 1].lex)\n cc.pop()();\n if (cx.marked) return cx.marked;\n if (type == \"variable\" && inScope(state, content)) return \"variableName.local\";\n if (type == \"variable\" && imported(state, content)) return \"variableName.special\";\n return style;\n }\n }\n}\n\nfunction imported(state, typename) {\n if (/[a-z]/.test(typename.charAt(0)))\n return false;\n var len = state.importedtypes.length;\n for (var i = 0; i= 0; i--) cx.cc.push(arguments[i]);\n}\nfunction cont() {\n pass.apply(null, arguments);\n return true;\n}\nfunction inList(name, list) {\n for (var v = list; v; v = v.next)\n if (v.name == name) return true;\n return false;\n}\nfunction register(varname) {\n var state = cx.state;\n if (state.context) {\n cx.marked = \"def\";\n if (inList(varname, state.localVars)) return;\n state.localVars = {name: varname, next: state.localVars};\n } else if (state.globalVars) {\n if (inList(varname, state.globalVars)) return;\n state.globalVars = {name: varname, next: state.globalVars};\n }\n}\n\n// Combinators\n\nvar defaultVars = {name: \"this\", next: null};\nfunction pushcontext() {\n if (!cx.state.context) cx.state.localVars = defaultVars;\n cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};\n}\nfunction popcontext() {\n cx.state.localVars = cx.state.context.vars;\n cx.state.context = cx.state.context.prev;\n}\npopcontext.lex = true;\nfunction pushlex(type, info) {\n var result = function() {\n var state = cx.state;\n state.lexical = new HaxeLexical(state.indented, cx.stream.column(), type, null, state.lexical, info);\n };\n result.lex = true;\n return result;\n}\nfunction poplex() {\n var state = cx.state;\n if (state.lexical.prev) {\n if (state.lexical.type == \")\")\n state.indented = state.lexical.indented;\n state.lexical = state.lexical.prev;\n }\n}\npoplex.lex = true;\n\nfunction expect(wanted) {\n function f(type) {\n if (type == wanted) return cont();\n else if (wanted == \";\") return pass();\n else return cont(f);\n }\n return f;\n}\n\nfunction statement(type) {\n if (type == \"@\") return cont(metadef);\n if (type == \"var\") return cont(pushlex(\"vardef\"), vardef1, expect(\";\"), poplex);\n if (type == \"keyword a\") return cont(pushlex(\"form\"), expression, statement, poplex);\n if (type == \"keyword b\") return cont(pushlex(\"form\"), statement, poplex);\n if (type == \"{\") return cont(pushlex(\"}\"), pushcontext, block, poplex, popcontext);\n if (type == \";\") return cont();\n if (type == \"attribute\") return cont(maybeattribute);\n if (type == \"function\") return cont(functiondef);\n if (type == \"for\") return cont(pushlex(\"form\"), expect(\"(\"), pushlex(\")\"), forspec1, expect(\")\"),\n poplex, statement, poplex);\n if (type == \"variable\") return cont(pushlex(\"stat\"), maybelabel);\n if (type == \"switch\") return cont(pushlex(\"form\"), expression, pushlex(\"}\", \"switch\"), expect(\"{\"),\n block, poplex, poplex);\n if (type == \"case\") return cont(expression, expect(\":\"));\n if (type == \"default\") return cont(expect(\":\"));\n if (type == \"catch\") return cont(pushlex(\"form\"), pushcontext, expect(\"(\"), funarg, expect(\")\"),\n statement, poplex, popcontext);\n if (type == \"import\") return cont(importdef, expect(\";\"));\n if (type == \"typedef\") return cont(typedef);\n return pass(pushlex(\"stat\"), expression, expect(\";\"), poplex);\n}\nfunction expression(type) {\n if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator);\n if (type == \"type\" ) return cont(maybeoperator);\n if (type == \"function\") return cont(functiondef);\n if (type == \"keyword c\") return cont(maybeexpression);\n if (type == \"(\") return cont(pushlex(\")\"), maybeexpression, expect(\")\"), poplex, maybeoperator);\n if (type == \"operator\") return cont(expression);\n if (type == \"[\") return cont(pushlex(\"]\"), commasep(maybeexpression, \"]\"), poplex, maybeoperator);\n if (type == \"{\") return cont(pushlex(\"}\"), commasep(objprop, \"}\"), poplex, maybeoperator);\n return cont();\n}\nfunction maybeexpression(type) {\n if (type.match(/[;\\}\\)\\],]/)) return pass();\n return pass(expression);\n}\n\nfunction maybeoperator(type, value) {\n if (type == \"operator\" && /\\+\\+|--/.test(value)) return cont(maybeoperator);\n if (type == \"operator\" || type == \":\") return cont(expression);\n if (type == \";\") return;\n if (type == \"(\") return cont(pushlex(\")\"), commasep(expression, \")\"), poplex, maybeoperator);\n if (type == \".\") return cont(property, maybeoperator);\n if (type == \"[\") return cont(pushlex(\"]\"), expression, expect(\"]\"), poplex, maybeoperator);\n}\n\nfunction maybeattribute(type) {\n if (type == \"attribute\") return cont(maybeattribute);\n if (type == \"function\") return cont(functiondef);\n if (type == \"var\") return cont(vardef1);\n}\n\nfunction metadef(type) {\n if(type == \":\") return cont(metadef);\n if(type == \"variable\") return cont(metadef);\n if(type == \"(\") return cont(pushlex(\")\"), commasep(metaargs, \")\"), poplex, statement);\n}\nfunction metaargs(type) {\n if(type == \"variable\") return cont();\n}\n\nfunction importdef (type, value) {\n if(type == \"variable\" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); }\n else if(type == \"variable\" || type == \"property\" || type == \".\" || value == \"*\") return cont(importdef);\n}\n\nfunction typedef (type, value)\n{\n if(type == \"variable\" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); }\n else if (type == \"type\" && /[A-Z]/.test(value.charAt(0))) { return cont(); }\n}\n\nfunction maybelabel(type) {\n if (type == \":\") return cont(poplex, statement);\n return pass(maybeoperator, expect(\";\"), poplex);\n}\nfunction property(type) {\n if (type == \"variable\") {cx.marked = \"property\"; return cont();}\n}\nfunction objprop(type) {\n if (type == \"variable\") cx.marked = \"property\";\n if (atomicTypes.hasOwnProperty(type)) return cont(expect(\":\"), expression);\n}\nfunction commasep(what, end) {\n function proceed(type) {\n if (type == \",\") return cont(what, proceed);\n if (type == end) return cont();\n return cont(expect(end));\n }\n return function(type) {\n if (type == end) return cont();\n else return pass(what, proceed);\n };\n}\nfunction block(type) {\n if (type == \"}\") return cont();\n return pass(statement, block);\n}\nfunction vardef1(type, value) {\n if (type == \"variable\"){register(value); return cont(typeuse, vardef2);}\n return cont();\n}\nfunction vardef2(type, value) {\n if (value == \"=\") return cont(expression, vardef2);\n if (type == \",\") return cont(vardef1);\n}\nfunction forspec1(type, value) {\n if (type == \"variable\") {\n register(value);\n return cont(forin, expression)\n } else {\n return pass()\n }\n}\nfunction forin(_type, value) {\n if (value == \"in\") return cont();\n}\nfunction functiondef(type, value) {\n //function names starting with upper-case letters are recognised as types, so cludging them together here.\n if (type == \"variable\" || type == \"type\") {register(value); return cont(functiondef);}\n if (value == \"new\") return cont(functiondef);\n if (type == \"(\") return cont(pushlex(\")\"), pushcontext, commasep(funarg, \")\"), poplex, typeuse, statement, popcontext);\n}\nfunction typeuse(type) {\n if(type == \":\") return cont(typestring);\n}\nfunction typestring(type) {\n if(type == \"type\") return cont();\n if(type == \"variable\") return cont();\n if(type == \"{\") return cont(pushlex(\"}\"), commasep(typeprop, \"}\"), poplex);\n}\nfunction typeprop(type) {\n if(type == \"variable\") return cont(typeuse);\n}\nfunction funarg(type, value) {\n if (type == \"variable\") {register(value); return cont(typeuse);}\n}\n\n// Interface\nexport const haxe = {\n name: \"haxe\",\n startState: function(indentUnit) {\n var defaulttypes = [\"Int\", \"Float\", \"String\", \"Void\", \"Std\", \"Bool\", \"Dynamic\", \"Array\"];\n var state = {\n tokenize: haxeTokenBase,\n reAllowed: true,\n kwAllowed: true,\n cc: [],\n lexical: new HaxeLexical(-indentUnit, 0, \"block\", false),\n importedtypes: defaulttypes,\n context: null,\n indented: 0\n };\n return state;\n },\n\n token: function(stream, state) {\n if (stream.sol()) {\n if (!state.lexical.hasOwnProperty(\"align\"))\n state.lexical.align = false;\n state.indented = stream.indentation();\n }\n if (stream.eatSpace()) return null;\n var style = state.tokenize(stream, state);\n if (type == \"comment\") return style;\n state.reAllowed = !!(type == \"operator\" || type == \"keyword c\" || type.match(/^[\\[{}\\(,;:]$/));\n state.kwAllowed = type != '.';\n return parseHaxe(state, style, type, content, stream);\n },\n\n indent: function(state, textAfter, cx) {\n if (state.tokenize != haxeTokenBase) return 0;\n var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;\n if (lexical.type == \"stat\" && firstChar == \"}\") lexical = lexical.prev;\n var type = lexical.type, closing = firstChar == type;\n if (type == \"vardef\") return lexical.indented + 4;\n else if (type == \"form\" && firstChar == \"{\") return lexical.indented;\n else if (type == \"stat\" || type == \"form\") return lexical.indented + cx.unit;\n else if (lexical.info == \"switch\" && !closing)\n return lexical.indented + (/^(?:case|default)\\b/.test(textAfter) ? cx.unit : 2 * cx.unit);\n else if (lexical.align) return lexical.column + (closing ? 0 : 1);\n else return lexical.indented + (closing ? 0 : cx.unit);\n },\n\n languageData: {\n indentOnInput: /^\\s*[{}]$/,\n commentTokens: {line: \"//\", block: {open: \"/*\", close: \"*/\"}}\n }\n};\n\nexport const hxml = {\n name: \"hxml\",\n startState: function () {\n return {\n define: false,\n inString: false\n };\n },\n token: function (stream, state) {\n var ch = stream.peek();\n var sol = stream.sol();\n\n ///* comments */\n if (ch == \"#\") {\n stream.skipToEnd();\n return \"comment\";\n }\n if (sol && ch == \"-\") {\n var style = \"variable-2\";\n\n stream.eat(/-/);\n\n if (stream.peek() == \"-\") {\n stream.eat(/-/);\n style = \"keyword a\";\n }\n\n if (stream.peek() == \"D\") {\n stream.eat(/[D]/);\n style = \"keyword c\";\n state.define = true;\n }\n\n stream.eatWhile(/[A-Z]/i);\n return style;\n }\n\n var ch = stream.peek();\n\n if (state.inString == false && ch == \"'\") {\n state.inString = true;\n stream.next();\n }\n\n if (state.inString == true) {\n if (stream.skipTo(\"'\")) {\n\n } else {\n stream.skipToEnd();\n }\n\n if (stream.peek() == \"'\") {\n stream.next();\n state.inString = false;\n }\n\n return \"string\";\n }\n\n stream.next();\n return null;\n },\n languageData: {\n commentTokens: {line: \"#\"}\n }\n}\n"],"names":["kw","type","style","content","A","B","C","operator","atom","attribute","keywords","isOperatorChar","chain","stream","state","f","tokenize","toUnescaped","end","next","escaped","ret","tp","cont","haxeTokenBase","ch","quote","test","eat","eatWhile","match","reAllowed","haxeTokenComment","skipToEnd","current","word","known","propertyIsEnumerable","kwAllowed","maybeEnd","atomicTypes","HaxeLexical","indented","column","align","prev","info","this","inScope","varname","v","localVars","name","imported","typename","charAt","len","importedtypes","length","i","registerimport","importname","cx","t","marked","cc","pass","arguments","push","apply","inList","list","register","context","globalVars","defaultVars","pushcontext","vars","popcontext","pushlex","result","lexical","lex","poplex","expect","wanted","statement","metadef","vardef1","expression","block","maybeattribute","functiondef","forspec1","maybelabel","funarg","importdef","typedef","hasOwnProperty","maybeoperator","maybeexpression","commasep","objprop","value","property","metaargs","what","proceed","typeuse","vardef2","forin","_type","typestring","typeprop","haxe","startState","indentUnit","token","sol","indentation","eatSpace","pop","parseHaxe","indent","textAfter","firstChar","closing","unit","languageData","indentOnInput","commentTokens","line","open","close","hxml","define","inString","peek","skipTo"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/6097.index.js b/book/_build/html/_static/6097.index.js new file mode 100644 index 0000000..8edb4d1 --- /dev/null +++ b/book/_build/html/_static/6097.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[6097],{56097:(O,e,r)=>{r.r(e),r.d(e,{json:()=>c,jsonLanguage:()=>o,jsonParseLinter:()=>Q});var t=r(51392),a=r(86253);const P=(0,a.Gv)({String:a.pJ.string,Number:a.pJ.number,"True False":a.pJ.bool,PropertyName:a.pJ.propertyName,Null:a.pJ.null,",":a.pJ.separator,"[ ]":a.pJ.squareBracket,"{ }":a.pJ.brace}),s=t.WQ.deserialize({version:14,states:"$bOVQPOOOOQO'#Cb'#CbOnQPO'#CeOvQPO'#CjOOQO'#Cp'#CpQOQPOOOOQO'#Cg'#CgO}QPO'#CfO!SQPO'#CrOOQO,59P,59PO![QPO,59PO!aQPO'#CuOOQO,59U,59UO!iQPO,59UOVQPO,59QOqQPO'#CkO!nQPO,59^OOQO1G.k1G.kOVQPO'#ClO!vQPO,59aOOQO1G.p1G.pOOQO1G.l1G.lOOQO,59V,59VOOQO-E6i-E6iOOQO,59W,59WOOQO-E6j-E6j",stateData:"#O~OcOS~OQSORSOSSOTSOWQO]ROePO~OVXOeUO~O[[O~PVOg^O~Oh_OVfX~OVaO~OhbO[iX~O[dO~Oh_OVfa~OhbO[ia~O",goto:"!kjPPPPPPkPPkqwPPk{!RPPP!XP!ePP!hXSOR^bQWQRf_TVQ_Q`WRg`QcZRicQTOQZRQe^RhbRYQR]R",nodeNames:"⚠ JsonText True False Null Number String } { Object Property PropertyName ] [ Array",maxTerm:25,nodeProps:[["openedBy",7,"{",12,"["],["closedBy",8,"}",13,"]"]],propSources:[P],skippedNodes:[0],repeatNodeCount:2,tokenData:"(|~RaXY!WYZ!W]^!Wpq!Wrs!]|}$u}!O$z!Q!R%T!R![&c![!]&t!}#O&y#P#Q'O#Y#Z'T#b#c'r#h#i(Z#o#p(r#q#r(w~!]Oc~~!`Wpq!]qr!]rs!xs#O!]#O#P!}#P;'S!];'S;=`$o<%lO!]~!}Oe~~#QXrs!]!P!Q!]#O#P!]#U#V!]#Y#Z!]#b#c!]#f#g!]#h#i!]#i#j#m~#pR!Q![#y!c!i#y#T#Z#y~#|R!Q![$V!c!i$V#T#Z$V~$YR!Q![$c!c!i$c#T#Z$c~$fR!Q![!]!c!i!]#T#Z!]~$rP;=`<%l!]~$zOh~~$}Q!Q!R%T!R![&c~%YRT~!O!P%c!g!h%w#X#Y%w~%fP!Q![%i~%nRT~!Q![%i!g!h%w#X#Y%w~%zR{|&T}!O&T!Q![&Z~&WP!Q![&Z~&`PT~!Q![&Z~&hST~!O!P%c!Q![&c!g!h%w#X#Y%w~&yOg~~'OO]~~'TO[~~'WP#T#U'Z~'^P#`#a'a~'dP#g#h'g~'jP#X#Y'm~'rOR~~'uP#i#j'x~'{P#`#a(O~(RP#`#a(U~(ZOS~~(^P#f#g(a~(dP#i#j(g~(jP#X#Y(m~(rOQ~~(wOW~~(|OV~",tokenizers:[0],topRules:{JsonText:[0,1]},tokenPrec:0});var n=r(77120);const Q=()=>O=>{try{JSON.parse(O.state.doc.toString())}catch(e){if(!(e instanceof SyntaxError))throw e;const r=function(O,e){let r;return(r=O.message.match(/at position (\d+)/))?Math.min(+r[1],e.length):(r=O.message.match(/at line (\d+) column (\d+)/))?Math.min(e.line(+r[1]).from+ +r[2]-1,e.length):0}(e,O.state.doc);return[{from:r,message:e.message,severity:"error",to:r}]}return[]},o=n.qp.define({name:"json",parser:s.configure({props:[n.uj.add({Object:(0,n.tC)({except:/^\s*\}/}),Array:(0,n.tC)({except:/^\s*\]/})}),n.x0.add({"Object Array":n.Dv})]}),languageData:{closeBrackets:{brackets:["[","{",'"']},indentOnInput:/^\s*[\}\]]$/}});function c(){return new n.ri(o)}}}]); +//# sourceMappingURL=6097.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/6097.index.js.map b/book/_build/html/_static/6097.index.js.map new file mode 100644 index 0000000..43a2c97 --- /dev/null +++ b/book/_build/html/_static/6097.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"6097.index.js","mappings":"6LAGA,MAAMA,GAAmB,QAAU,CACjCC,OAAQ,YACRC,OAAQ,YACR,aAAc,UACdC,aAAc,kBACdC,KAAM,UACN,IAAK,eACL,MAAO,mBACP,MAAO,aAIHC,EAAS,iBAAqB,CAClCC,QAAS,GACTC,OAAQ,mRACRC,UAAW,iGACXC,KAAM,kFACNC,UAAW,sFACXC,QAAS,GACTC,UAAW,CACT,CAAC,WAAY,EAAE,IAAI,GAAG,KACtB,CAAC,WAAY,EAAE,IAAI,GAAG,MAExBC,YAAa,CAACb,GACdc,aAAc,CAAC,GACfC,gBAAiB,EACjBC,UAAW,omBACXC,WAAY,CAAC,GACbC,SAAU,CAAC,SAAW,CAAC,EAAE,IACzBC,UAAW,I,eCvBb,MAAMC,EAAkB,IAAOC,IAC3B,IACIC,KAAKC,MAAMF,EAAKG,MAAMC,IAAIC,WAC9B,CACA,MAAOC,GACH,KAAMA,aAAaC,aACf,MAAMD,EACV,MAAME,EAUd,SAA0BC,EAAOL,GAC7B,IAAIM,EACJ,OAAIA,EAAID,EAAME,QAAQC,MAAM,sBACjBC,KAAKC,KAAKJ,EAAE,GAAIN,EAAIW,SAC3BL,EAAID,EAAME,QAAQC,MAAM,+BACjBC,KAAKC,IAAIV,EAAIY,MAAMN,EAAE,IAAIO,OAASP,EAAE,GAAM,EAAGN,EAAIW,QACrD,CACX,CAjBoBG,CAAiBZ,EAAGN,EAAKG,MAAMC,KAC3C,MAAO,CAAC,CACAa,KAAMT,EACNG,QAASL,EAAEK,QACXQ,SAAU,QACVC,GAAIZ,GAEhB,CACA,MAAO,EAAE,EAcPa,EAA4B,YAAkB,CAChDC,KAAM,OACNtC,OAAqBA,EAAOuC,UAAU,CAClCC,MAAO,CACU,SAAmB,CAC5BC,QAAqB,QAAgB,CAAEC,OAAQ,WAC/CC,OAAoB,QAAgB,CAAED,OAAQ,aAErC,SAAiB,CAC1B,eAAgB,UAI5BE,aAAc,CACVC,cAAe,CAAEC,SAAU,CAAC,IAAK,IAAK,MACtCC,cAAe,iBAMvB,SAASC,IACL,OAAO,IAAI,KAAgBX,EAC/B,C","sources":["webpack://thebe/../../node_modules/@lezer/json/dist/index.js","webpack://thebe/../../node_modules/@codemirror/lang-json/dist/index.js"],"sourcesContent":["import { LRParser } from '@lezer/lr';\nimport { styleTags, tags } from '@lezer/highlight';\n\nconst jsonHighlighting = styleTags({\n String: tags.string,\n Number: tags.number,\n \"True False\": tags.bool,\n PropertyName: tags.propertyName,\n Null: tags.null,\n \",\": tags.separator,\n \"[ ]\": tags.squareBracket,\n \"{ }\": tags.brace\n});\n\n// This file was generated by lezer-generator. You probably shouldn't edit it.\nconst parser = LRParser.deserialize({\n version: 14,\n states: \"$bOVQPOOOOQO'#Cb'#CbOnQPO'#CeOvQPO'#CjOOQO'#Cp'#CpQOQPOOOOQO'#Cg'#CgO}QPO'#CfO!SQPO'#CrOOQO,59P,59PO![QPO,59PO!aQPO'#CuOOQO,59U,59UO!iQPO,59UOVQPO,59QOqQPO'#CkO!nQPO,59^OOQO1G.k1G.kOVQPO'#ClO!vQPO,59aOOQO1G.p1G.pOOQO1G.l1G.lOOQO,59V,59VOOQO-E6i-E6iOOQO,59W,59WOOQO-E6j-E6j\",\n stateData: \"#O~OcOS~OQSORSOSSOTSOWQO]ROePO~OVXOeUO~O[[O~PVOg^O~Oh_OVfX~OVaO~OhbO[iX~O[dO~Oh_OVfa~OhbO[ia~O\",\n goto: \"!kjPPPPPPkPPkqwPPk{!RPPP!XP!ePP!hXSOR^bQWQRf_TVQ_Q`WRg`QcZRicQTOQZRQe^RhbRYQR]R\",\n nodeNames: \"⚠ JsonText True False Null Number String } { Object Property PropertyName ] [ Array\",\n maxTerm: 25,\n nodeProps: [\n [\"openedBy\", 7,\"{\",12,\"[\"],\n [\"closedBy\", 8,\"}\",13,\"]\"]\n ],\n propSources: [jsonHighlighting],\n skippedNodes: [0],\n repeatNodeCount: 2,\n tokenData: \"(|~RaXY!WYZ!W]^!Wpq!Wrs!]|}$u}!O$z!Q!R%T!R![&c![!]&t!}#O&y#P#Q'O#Y#Z'T#b#c'r#h#i(Z#o#p(r#q#r(w~!]Oc~~!`Wpq!]qr!]rs!xs#O!]#O#P!}#P;'S!];'S;=`$o<%lO!]~!}Oe~~#QXrs!]!P!Q!]#O#P!]#U#V!]#Y#Z!]#b#c!]#f#g!]#h#i!]#i#j#m~#pR!Q![#y!c!i#y#T#Z#y~#|R!Q![$V!c!i$V#T#Z$V~$YR!Q![$c!c!i$c#T#Z$c~$fR!Q![!]!c!i!]#T#Z!]~$rP;=`<%l!]~$zOh~~$}Q!Q!R%T!R![&c~%YRT~!O!P%c!g!h%w#X#Y%w~%fP!Q![%i~%nRT~!Q![%i!g!h%w#X#Y%w~%zR{|&T}!O&T!Q![&Z~&WP!Q![&Z~&`PT~!Q![&Z~&hST~!O!P%c!Q![&c!g!h%w#X#Y%w~&yOg~~'OO]~~'TO[~~'WP#T#U'Z~'^P#`#a'a~'dP#g#h'g~'jP#X#Y'm~'rOR~~'uP#i#j'x~'{P#`#a(O~(RP#`#a(U~(ZOS~~(^P#f#g(a~(dP#i#j(g~(jP#X#Y(m~(rOQ~~(wOW~~(|OV~\",\n tokenizers: [0],\n topRules: {\"JsonText\":[0,1]},\n tokenPrec: 0\n});\n\nexport { parser };\n","import { parser } from '@lezer/json';\nimport { LRLanguage, indentNodeProp, continuedIndent, foldNodeProp, foldInside, LanguageSupport } from '@codemirror/language';\n\n/**\nCalls\n[`JSON.parse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)\non the document and, if that throws an error, reports it as a\nsingle diagnostic.\n*/\nconst jsonParseLinter = () => (view) => {\n try {\n JSON.parse(view.state.doc.toString());\n }\n catch (e) {\n if (!(e instanceof SyntaxError))\n throw e;\n const pos = getErrorPosition(e, view.state.doc);\n return [{\n from: pos,\n message: e.message,\n severity: 'error',\n to: pos\n }];\n }\n return [];\n};\nfunction getErrorPosition(error, doc) {\n let m;\n if (m = error.message.match(/at position (\\d+)/))\n return Math.min(+m[1], doc.length);\n if (m = error.message.match(/at line (\\d+) column (\\d+)/))\n return Math.min(doc.line(+m[1]).from + (+m[2]) - 1, doc.length);\n return 0;\n}\n\n/**\nA language provider that provides JSON parsing.\n*/\nconst jsonLanguage = /*@__PURE__*/LRLanguage.define({\n name: \"json\",\n parser: /*@__PURE__*/parser.configure({\n props: [\n /*@__PURE__*/indentNodeProp.add({\n Object: /*@__PURE__*/continuedIndent({ except: /^\\s*\\}/ }),\n Array: /*@__PURE__*/continuedIndent({ except: /^\\s*\\]/ })\n }),\n /*@__PURE__*/foldNodeProp.add({\n \"Object Array\": foldInside\n })\n ]\n }),\n languageData: {\n closeBrackets: { brackets: [\"[\", \"{\", '\"'] },\n indentOnInput: /^\\s*[\\}\\]]$/\n }\n});\n/**\nJSON language support.\n*/\nfunction json() {\n return new LanguageSupport(jsonLanguage);\n}\n\nexport { json, jsonLanguage, jsonParseLinter };\n"],"names":["jsonHighlighting","String","Number","PropertyName","Null","parser","version","states","stateData","goto","nodeNames","maxTerm","nodeProps","propSources","skippedNodes","repeatNodeCount","tokenData","tokenizers","topRules","tokenPrec","jsonParseLinter","view","JSON","parse","state","doc","toString","e","SyntaxError","pos","error","m","message","match","Math","min","length","line","from","getErrorPosition","severity","to","jsonLanguage","name","configure","props","Object","except","Array","languageData","closeBrackets","brackets","indentOnInput","json"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/6208.index.js b/book/_build/html/_static/6208.index.js new file mode 100644 index 0000000..25e3619 --- /dev/null +++ b/book/_build/html/_static/6208.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[6208],{46208:(O,Q,P)=>{P.r(Q),P.d(Q,{rust:()=>z,rustLanguage:()=>Y});var $=P(51392),X=P(86253);function i(O){return O>=48&&O<=57}function e(O){return i(O)||95==O}const n=new $.Jq(((O,Q)=>{if(i(O.next)){let Q=!1;do{O.advance()}while(e(O.next));if(46==O.next)if(Q=!0,O.advance(),i(O.next))do{O.advance()}while(e(O.next));else if(46==O.next||O.next>127||/\w/.test(String.fromCharCode(O.next)))return;if(101==O.next||69==O.next){if(Q=!0,O.advance(),43!=O.next&&45!=O.next||O.advance(),!e(O.next))return;do{O.advance()}while(e(O.next))}if(102==O.next){let P=O.peek(1);if(!(51==P&&50==O.peek(2)||54==P&&52==O.peek(2)))return;O.advance(3),Q=!0}Q&&O.acceptToken(5)}else if(98==O.next||114==O.next){if(98==O.next&&O.advance(),114!=O.next)return;O.advance();let Q=0;for(;35==O.next;)Q++,O.advance();if(34!=O.next)return;O.advance();O:for(;;){if(O.next<0)return;let P=34==O.next;if(O.advance(),P){for(let P=0;P{124==O.next&&O.acceptToken(1,1)})),S=new $.Jq((O=>{60==O.next?O.acceptToken(2,1):62==O.next&&O.acceptToken(3,1)})),r=(0,X.Gv)({"const macro_rules struct union enum type fn impl trait let static":X.pJ.definitionKeyword,"mod use crate":X.pJ.moduleKeyword,"pub unsafe async mut extern default move":X.pJ.modifier,"for if else loop while match continue break return await":X.pJ.controlKeyword,"as in ref":X.pJ.operatorKeyword,"where _ crate super dyn":X.pJ.keyword,self:X.pJ.self,String:X.pJ.string,Char:X.pJ.character,RawString:X.pJ.special(X.pJ.string),Boolean:X.pJ.bool,Identifier:X.pJ.variableName,"CallExpression/Identifier":X.pJ.function(X.pJ.variableName),BoundIdentifier:X.pJ.definition(X.pJ.variableName),"FunctionItem/BoundIdentifier":X.pJ.function(X.pJ.definition(X.pJ.variableName)),LoopLabel:X.pJ.labelName,FieldIdentifier:X.pJ.propertyName,"CallExpression/FieldExpression/FieldIdentifier":X.pJ.function(X.pJ.propertyName),Lifetime:X.pJ.special(X.pJ.variableName),ScopeIdentifier:X.pJ.namespace,TypeIdentifier:X.pJ.typeName,"MacroInvocation/Identifier MacroInvocation/ScopedIdentifier/Identifier":X.pJ.macroName,"MacroInvocation/TypeIdentifier MacroInvocation/ScopedIdentifier/TypeIdentifier":X.pJ.macroName,'"!"':X.pJ.macroName,UpdateOp:X.pJ.updateOperator,LineComment:X.pJ.lineComment,BlockComment:X.pJ.blockComment,Integer:X.pJ.integer,Float:X.pJ.float,ArithOp:X.pJ.arithmeticOperator,LogicOp:X.pJ.logicOperator,BitOp:X.pJ.bitwiseOperator,CompareOp:X.pJ.compareOperator,"=":X.pJ.definitionOperator,".. ... => ->":X.pJ.punctuation,"( )":X.pJ.paren,"[ ]":X.pJ.squareBracket,"{ }":X.pJ.brace,". DerefOp":X.pJ.derefOperator,"&":X.pJ.operator,", ; ::":X.pJ.separator,"Attribute/...":X.pJ.meta}),s={__proto__:null,self:28,super:32,crate:34,impl:46,true:72,false:72,pub:88,in:92,const:96,unsafe:104,async:108,move:110,if:114,let:118,ref:142,mut:144,_:198,else:200,match:204,as:248,return:252,await:262,break:270,continue:276,while:312,loop:316,for:320,macro_rules:327,mod:334,extern:342,struct:346,where:364,union:379,enum:382,type:390,default:395,fn:396,trait:412,use:420,static:438,dyn:476},t=$.WQ.deserialize({version:14,states:"$2xQ]Q_OOP$wOWOOO&sQWO'#CnO)WQWO'#I`OOQP'#I`'#I`OOQQ'#Ie'#IeO)hO`O'#C}OOQR'#Ih'#IhO)sQWO'#IuOOQO'#Hk'#HkO)xQWO'#DpOOQR'#Iw'#IwO)xQWO'#DpO*ZQWO'#DpOOQO'#Iv'#IvO,SQWO'#J`O,ZQWO'#EiOOQV'#Hp'#HpO,cQYO'#F{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_4e4t5`5d5v6R6Y6p6v6x7c7r8gR0k+ZR0j+ZQ'R!qQ)c%XQ+w&|R4y1PX'Q!q%X&|1PR+y&|R+x&|T/S*S4TT/R*S4TR.o)sR.n)sR){%p",nodeNames:"⚠ | < > RawString Float LineComment BlockComment SourceFile ] InnerAttribute ! [ MetaItem self Metavariable super crate Identifier ScopedIdentifier :: QualifiedScope AbstractType impl SelfType MetaType TypeIdentifier ScopedTypeIdentifier ScopeIdentifier TypeArgList TypeBinding = Lifetime String Escape Char Boolean Integer } { Block ; ConstItem Vis pub ( in ) const BoundIdentifier : UnsafeBlock unsafe AsyncBlock async move IfExpression if LetDeclaration let LiteralPattern ArithOp MetaPattern SelfPattern ScopedIdentifier TuplePattern ScopedTypeIdentifier , StructPattern FieldPatternList FieldPattern ref mut FieldIdentifier .. RefPattern SlicePattern CapturedPattern ReferencePattern & MutPattern RangePattern ... OrPattern MacroPattern ParenthesizedTokens TokenBinding Identifier TokenRepetition ArithOp BitOp LogicOp UpdateOp CompareOp -> => ArithOp BracketedTokens BracedTokens _ else MatchExpression match MatchBlock MatchArm Attribute Guard UnaryExpression ArithOp DerefOp LogicOp ReferenceExpression TryExpression BinaryExpression ArithOp ArithOp BitOp BitOp BitOp BitOp LogicOp LogicOp AssignmentExpression TypeCastExpression as ReturnExpression return RangeExpression CallExpression ArgList AwaitExpression await FieldExpression GenericFunction BreakExpression break LoopLabel ContinueExpression continue IndexExpression ArrayExpression TupleExpression MacroInvocation UnitExpression ClosureExpression ParamList Parameter Parameter ParenthesizedExpression StructExpression FieldInitializerList ShorthandFieldInitializer FieldInitializer BaseFieldInitializer MatchArm WhileExpression while LoopExpression loop ForExpression for MacroInvocation MacroDefinition macro_rules MacroRule EmptyStatement ModItem mod DeclarationList AttributeItem ForeignModItem extern StructItem struct TypeParamList ConstrainedTypeParameter TraitBounds HigherRankedTraitBound RemovedTraitBound OptionalTypeParameter ConstParameter WhereClause where LifetimeClause TypeBoundClause FieldDeclarationList FieldDeclaration OrderedFieldDeclarationList UnionItem union EnumItem enum EnumVariantList EnumVariant TypeItem type FunctionItem default fn ParamList Parameter SelfParameter VariadicParameter VariadicParameter ImplItem TraitItem trait AssociatedType LetDeclaration UseDeclaration use ScopedIdentifier UseAsClause ScopedIdentifier UseList ScopedUseList UseWildcard ExternCrateDeclaration StaticItem static ExpressionStatement ExpressionStatement GenericType FunctionType ForLifetimes ParamList VariadicParameter Parameter VariadicParameter Parameter ReferenceType PointerType TupleType UnitType ArrayType MacroInvocation EmptyType DynamicType dyn BoundedType",maxTerm:359,nodeProps:[["group",-42,4,5,14,15,16,17,18,19,33,35,36,37,40,51,53,56,101,107,111,112,113,122,123,125,127,128,130,132,133,134,137,139,140,141,142,143,144,148,149,155,157,159,"Expression",-16,22,24,25,26,27,222,223,230,231,232,233,234,235,236,237,239,"Type",-20,42,161,162,165,166,169,170,172,188,190,194,196,204,205,207,208,209,217,218,220,"Statement",-17,49,60,62,63,64,65,68,74,75,76,77,78,80,81,83,84,99,"Pattern"],["openedBy",9,"[",38,"{",47,"("],["closedBy",12,"]",39,"}",45,")"]],propSources:[r],skippedNodes:[0,6,7,240],repeatNodeCount:32,tokenData:"$%h_R!XOX$nXY5gYZ6iZ]$n]^5g^p$npq5gqr7Xrs9cst:Rtu;Tuv>vvwAQwxCbxy!+Tyz!,Vz{!-X{|!/_|}!0g}!O!1i!O!P!3v!P!Q!8[!Q!R!Bw!R![!Dr![!]#+q!]!^#-{!^!_#.}!_!`#1b!`!a#3o!a!b#6S!b!c#7U!c!}#8W!}#O#:T#O#P#;V#P#Q#Cb#Q#R#Dd#R#S#8W#S#T$n#T#U#8W#U#V#El#V#f#8W#f#g#Ic#g#o#8W#o#p$ S#p#q$!U#q#r$$f#r${$n${$|#8W$|4w$n4w5b#8W5b5i$n5i6S#8W6S;'S$n;'S;=`4s<%lO$nU$u]'_Q'OSOY$nYZ%nZr$nrs&[sz$nz{+O{!P$n!P!Q,z!Q#O$n#O#P&[#P;'S$n;'S;=`4s<%l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.define({name:"rust",parser:t.configure({props:[W.uj.add({IfExpression:(0,W.tC)({except:/^\s*({|else\b)/}),"String BlockComment":()=>null,AttributeItem:O=>O.continue(),"Statement MatchArm":(0,W.tC)()}),W.x0.add((O=>/(Block|edTokens|List)$/.test(O.name)?W.Dv:"BlockComment"==O.name?O=>({from:O.from+2,to:O.to-2}):void 0))]}),languageData:{commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:\{|\})$/,closeBrackets:{stringPrefixes:["b","r","br"]}}});function z(){return new W.ri(Y)}}}]); +//# sourceMappingURL=6208.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/6208.index.js.map b/book/_build/html/_static/6208.index.js.map new file mode 100644 index 0000000..781306f --- /dev/null +++ b/book/_build/html/_static/6208.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"6208.index.js","mappings":"uKAaA,SAASA,EAAMC,GAAM,OAAOA,GAAM,IAAMA,GAAM,EAAG,CACjD,SAASC,EAAOD,GAAM,OAAOD,EAAMC,IAAa,IAANA,CAAS,CAEnD,MAAME,EAAgB,IAAI,MAAkB,CAACC,EAAOC,KAClD,GAAIL,EAAMI,EAAME,MAAO,CACrB,IAAIC,GAAU,EACd,GAAKH,EAAMI,gBAAoBN,EAAOE,EAAME,OAC5C,GATQ,IASJF,EAAME,KAGR,GAFAC,GAAU,EACVH,EAAMI,UACFR,EAAMI,EAAME,MACd,GAAKF,EAAMI,gBAAoBN,EAAOE,EAAME,YACvC,GAdD,IAcKF,EAAME,MAAeF,EAAME,KAAO,KAAQ,KAAKG,KAAKC,OAAOC,aAAaP,EAAME,OACvF,OAGJ,GAnBgB,KAmBZF,EAAME,MAnBoC,IAmBtBF,EAAME,KAAY,CAIxC,GAHAC,GAAU,EACVH,EAAMI,UApBW,IAqBbJ,EAAME,MArBmB,IAqBHF,EAAME,MAAeF,EAAMI,WAChDN,EAAOE,EAAME,MAAO,OACzB,GAAKF,EAAMI,gBAAoBN,EAAOE,EAAME,MAC9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GC,GAAIF,EAAKE,GAAK,SADzD,OAMZC,aAAc,CACVC,cAAe,CAAEC,KAAM,KAAMC,MAAO,CAAEC,KAAM,KAAMC,MAAO,OACzDC,cAAe,iBACfC,cAAe,CAAEC,eAAgB,CAAC,IAAK,IAAK,UAMpD,SAASC,IACL,OAAO,IAAI,KAAgBnB,EAC/B,C","sources":["webpack://thebe/../../node_modules/@lezer/rust/dist/index.js","webpack://thebe/../../node_modules/@codemirror/lang-rust/dist/index.js"],"sourcesContent":["import { ExternalTokenizer, LRParser } from '@lezer/lr';\nimport { styleTags, tags } from '@lezer/highlight';\n\n// This file was generated by lezer-generator. You probably shouldn't edit it.\nconst closureParamDelim = 1,\n tpOpen = 2,\n tpClose = 3,\n RawString = 4,\n Float = 5;\n\nconst _b = 98, _e = 101, _f = 102, _r = 114, _E = 69, Zero = 48,\n Dot = 46, Plus = 43, Minus = 45, Hash = 35, Quote = 34, Pipe = 124, LessThan = 60, GreaterThan = 62;\n\nfunction isNum(ch) { return ch >= 48 && ch <= 57 }\nfunction isNum_(ch) { return isNum(ch) || ch == 95 }\n\nconst literalTokens = new ExternalTokenizer((input, stack) => {\n if (isNum(input.next)) {\n let isFloat = false;\n do { input.advance(); } while (isNum_(input.next))\n if (input.next == Dot) {\n isFloat = true;\n input.advance();\n if (isNum(input.next)) {\n do { input.advance(); } while (isNum_(input.next))\n } else if (input.next == Dot || input.next > 0x7f || /\\w/.test(String.fromCharCode(input.next))) {\n return\n }\n }\n if (input.next == _e || input.next == _E) {\n isFloat = true;\n input.advance();\n if (input.next == Plus || input.next == Minus) input.advance();\n if (!isNum_(input.next)) return\n do { input.advance(); } while (isNum_(input.next))\n }\n if (input.next == _f) {\n let after = input.peek(1);\n if (after == Zero + 3 && input.peek(2) == Zero + 2 ||\n after == Zero + 6 && input.peek(2) == Zero + 4) {\n input.advance(3);\n isFloat = true;\n } else {\n return\n }\n }\n if (isFloat) input.acceptToken(Float);\n } else if (input.next == _b || input.next == _r) {\n if (input.next == _b) input.advance();\n if (input.next != _r) return\n input.advance();\n let count = 0;\n while (input.next == Hash) { count++; input.advance(); }\n if (input.next != Quote) return\n input.advance();\n content: for (;;) {\n if (input.next < 0) return\n let isQuote = input.next == Quote;\n input.advance();\n if (isQuote) {\n for (let i = 0; i < count; i++) {\n if (input.next != Hash) continue content\n input.advance();\n }\n input.acceptToken(RawString);\n return\n }\n }\n }\n});\n\nconst closureParam = new ExternalTokenizer(input => {\n if (input.next == Pipe) input.acceptToken(closureParamDelim, 1);\n});\n\nconst tpDelim = new ExternalTokenizer(input => {\n if (input.next == LessThan) input.acceptToken(tpOpen, 1);\n else if (input.next == GreaterThan) input.acceptToken(tpClose, 1);\n});\n\nconst rustHighlighting = styleTags({\n \"const macro_rules struct union enum type fn impl trait let static\": tags.definitionKeyword,\n \"mod use crate\": tags.moduleKeyword,\n \"pub unsafe async mut extern default move\": tags.modifier,\n \"for if else loop while match continue break return await\": tags.controlKeyword,\n \"as in ref\": tags.operatorKeyword,\n \"where _ crate super dyn\": tags.keyword,\n \"self\": tags.self,\n String: tags.string,\n Char: tags.character,\n RawString: tags.special(tags.string),\n Boolean: tags.bool,\n Identifier: tags.variableName,\n \"CallExpression/Identifier\": tags.function(tags.variableName),\n BoundIdentifier: tags.definition(tags.variableName),\n \"FunctionItem/BoundIdentifier\": tags.function(tags.definition(tags.variableName)),\n LoopLabel: tags.labelName,\n FieldIdentifier: tags.propertyName,\n \"CallExpression/FieldExpression/FieldIdentifier\": tags.function(tags.propertyName),\n Lifetime: tags.special(tags.variableName),\n ScopeIdentifier: tags.namespace,\n TypeIdentifier: tags.typeName,\n \"MacroInvocation/Identifier MacroInvocation/ScopedIdentifier/Identifier\": tags.macroName,\n \"MacroInvocation/TypeIdentifier MacroInvocation/ScopedIdentifier/TypeIdentifier\": tags.macroName,\n \"\\\"!\\\"\": tags.macroName,\n UpdateOp: tags.updateOperator,\n LineComment: tags.lineComment,\n BlockComment: tags.blockComment,\n Integer: tags.integer,\n Float: tags.float,\n ArithOp: tags.arithmeticOperator,\n LogicOp: tags.logicOperator,\n BitOp: tags.bitwiseOperator,\n CompareOp: tags.compareOperator,\n \"=\": tags.definitionOperator,\n \".. ... => ->\": tags.punctuation,\n \"( )\": tags.paren,\n \"[ ]\": tags.squareBracket,\n \"{ }\": tags.brace,\n \". DerefOp\": tags.derefOperator,\n \"&\": tags.operator,\n \", ; ::\": tags.separator,\n \"Attribute/...\": tags.meta,\n});\n\n// This file was generated by lezer-generator. You probably shouldn't edit it.\nconst spec_identifier = {__proto__:null,self:28, super:32, crate:34, impl:46, true:72, false:72, pub:88, in:92, const:96, unsafe:104, async:108, move:110, if:114, let:118, ref:142, mut:144, _:198, else:200, match:204, as:248, return:252, await:262, break:270, continue:276, while:312, loop:316, for:320, macro_rules:327, mod:334, extern:342, struct:346, where:364, union:379, enum:382, type:390, default:395, fn:396, trait:412, use:420, static:438, dyn:476};\nconst parser = LRParser.deserialize({\n version: 14,\n states: \"$2xQ]Q_OOP$wOWOOO&sQWO'#CnO)WQWO'#I`OOQP'#I`'#I`OOQQ'#Ie'#IeO)hO`O'#C}OOQR'#Ih'#IhO)sQWO'#IuOOQO'#Hk'#HkO)xQWO'#DpOOQR'#Iw'#IwO)xQWO'#DpO*ZQWO'#DpOOQO'#Iv'#IvO,SQWO'#J`O,ZQWO'#EiOOQV'#Hp'#HpO,cQYO'#F{OOQV'#El'#ElOOQV'#Em'#EmOOQV'#En'#EnO.YQ_O'#EkO0_Q_O'#EoO2gQWOOO4QQ_O'#FPO7hQWO'#J`OOQV'#FY'#FYO7{Q_O'#F^O:WQ_O'#FaOOQO'#F`'#F`O=sQ_O'#FcO=}Q_O'#FbO@VQWO'#FgOOQO'#J`'#J`OOQV'#Io'#IoOA]Q_O'#InOEPQWO'#InOOQV'#Fw'#FwOF[QWO'#JuOFcQWO'#F|OOQO'#IO'#IOOGrQWO'#GhOOQV'#Im'#ImOOQV'#Il'#IlOOQV'#Hj'#HjQGyQ_OOOKeQ_O'#DUOKlQYO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f,h,l/m/n1_3n3q5UQ7j5TR8s7k^uO!O!P!T%_%b)i$`#afgilmp!Y!Z![!_!`#e#o#p#q#r#s#t#u#v#w#x#y#z#}$T$W&Y&['}(W(Y(|*i*l+n,s,z-m.}/^0}1h1|3a3h3k4W4v4|5g5t7S7g7{8k8|9u9v9w9x9z9{:O:P:Q:R:S:T:U:V:W:X:Y:Z:e:fQ6Z3_Q8U6]Q9Q8WQ9S8XQ9f9UR9l9hR(Q#zR(P#zQ$SlR(]$TR$ooR$noR)Q$vR)P$vQ)O$vR2O-ohwOb!O!P!T$y%_%b)S)U)i-t$l!lz!Q!n$O$u$|%f%n%o%p%q%y%{&P&o&p&r'](q)s)v)x)y*O*P*R*V*[*^*e*n*w*x+U+V+h+o+}-i-v.U.`.p.t.x.y/Z/[/{/}0`0r0w1O1Y1Z1y2a2h2j2m2s2v3V3u3{3|4R4U4_4e4t5`5d5v6R6Y6p6v6x7c7r8gR${xR0b+UR0W*xR0U*xR6{4PR/y*vR/x*vR0P*wR0O*wR0_+QR0^+Q%XyObxz!O!P!Q!T!n$O$u$y$|%_%b%f%n%o%p%q%y%{&P&o&p&r'](q)S)U)i)s)v)x)y*O*P*R*V*[*^*e*n*w*x+U+V+h+o+}-i-t-v.U.`.p.t.x.y/Z/[/{/}0`0r0w1O1Y1Z1y2a2h2j2m2s2v3V3u3{3|4R4U4_4e4t5`5d5v6R6Y6p6v6x7c7r8gR0k+ZR0j+ZQ'R!qQ)c%XQ+w&|R4y1PX'Q!q%X&|1PR+y&|R+x&|T/S*S4TT/R*S4TR.o)sR.n)sR){%p\",\n nodeNames: \"⚠ | < > RawString Float LineComment BlockComment SourceFile ] InnerAttribute ! [ MetaItem self Metavariable super crate Identifier ScopedIdentifier :: QualifiedScope AbstractType impl SelfType MetaType TypeIdentifier ScopedTypeIdentifier ScopeIdentifier TypeArgList TypeBinding = Lifetime String Escape Char Boolean Integer } { Block ; ConstItem Vis pub ( in ) const BoundIdentifier : UnsafeBlock unsafe AsyncBlock async move IfExpression if LetDeclaration let LiteralPattern ArithOp MetaPattern SelfPattern ScopedIdentifier TuplePattern ScopedTypeIdentifier , StructPattern FieldPatternList FieldPattern ref mut FieldIdentifier .. RefPattern SlicePattern CapturedPattern ReferencePattern & MutPattern RangePattern ... OrPattern MacroPattern ParenthesizedTokens TokenBinding Identifier TokenRepetition ArithOp BitOp LogicOp UpdateOp CompareOp -> => ArithOp BracketedTokens BracedTokens _ else MatchExpression match MatchBlock MatchArm Attribute Guard UnaryExpression ArithOp DerefOp LogicOp ReferenceExpression TryExpression BinaryExpression ArithOp ArithOp BitOp BitOp BitOp BitOp LogicOp LogicOp AssignmentExpression TypeCastExpression as ReturnExpression return RangeExpression CallExpression ArgList AwaitExpression await FieldExpression GenericFunction BreakExpression break LoopLabel ContinueExpression continue IndexExpression ArrayExpression TupleExpression MacroInvocation UnitExpression ClosureExpression ParamList Parameter Parameter ParenthesizedExpression StructExpression FieldInitializerList ShorthandFieldInitializer FieldInitializer BaseFieldInitializer MatchArm WhileExpression while LoopExpression loop ForExpression for MacroInvocation MacroDefinition macro_rules MacroRule EmptyStatement ModItem mod DeclarationList AttributeItem ForeignModItem extern StructItem struct TypeParamList ConstrainedTypeParameter TraitBounds HigherRankedTraitBound RemovedTraitBound OptionalTypeParameter ConstParameter WhereClause where LifetimeClause TypeBoundClause FieldDeclarationList FieldDeclaration OrderedFieldDeclarationList UnionItem union EnumItem enum EnumVariantList EnumVariant TypeItem type FunctionItem default fn ParamList Parameter SelfParameter VariadicParameter VariadicParameter ImplItem TraitItem trait AssociatedType LetDeclaration UseDeclaration use ScopedIdentifier UseAsClause ScopedIdentifier UseList ScopedUseList UseWildcard ExternCrateDeclaration StaticItem static ExpressionStatement ExpressionStatement GenericType FunctionType ForLifetimes ParamList VariadicParameter Parameter VariadicParameter Parameter ReferenceType PointerType TupleType UnitType ArrayType MacroInvocation EmptyType DynamicType dyn BoundedType\",\n maxTerm: 359,\n nodeProps: [\n [\"group\", -42,4,5,14,15,16,17,18,19,33,35,36,37,40,51,53,56,101,107,111,112,113,122,123,125,127,128,130,132,133,134,137,139,140,141,142,143,144,148,149,155,157,159,\"Expression\",-16,22,24,25,26,27,222,223,230,231,232,233,234,235,236,237,239,\"Type\",-20,42,161,162,165,166,169,170,172,188,190,194,196,204,205,207,208,209,217,218,220,\"Statement\",-17,49,60,62,63,64,65,68,74,75,76,77,78,80,81,83,84,99,\"Pattern\"],\n [\"openedBy\", 9,\"[\",38,\"{\",47,\"(\"],\n [\"closedBy\", 12,\"]\",39,\"}\",45,\")\"]\n ],\n propSources: [rustHighlighting],\n skippedNodes: [0,6,7,240],\n repeatNodeCount: 32,\n tokenData: \"$%h_R!XOX$nXY5gYZ6iZ]$n]^5g^p$npq5gqr7Xrs9cst:Rtu;Tuv>vvwAQwxCbxy!+Tyz!,Vz{!-X{|!/_|}!0g}!O!1i!O!P!3v!P!Q!8[!Q!R!Bw!R![!Dr![!]#+q!]!^#-{!^!_#.}!_!`#1b!`!a#3o!a!b#6S!b!c#7U!c!}#8W!}#O#:T#O#P#;V#P#Q#Cb#Q#R#Dd#R#S#8W#S#T$n#T#U#8W#U#V#El#V#f#8W#f#g#Ic#g#o#8W#o#p$ S#p#q$!U#q#r$$f#r${$n${$|#8W$|4w$n4w5b#8W5b5i$n5i6S#8W6S;'S$n;'S;=`4s<%lO$nU$u]'_Q'OSOY$nYZ%nZr$nrs&[sz$nz{+O{!P$n!P!Q,z!Q#O$n#O#P&[#P;'S$n;'S;=`4s<%lO$nU%uV'_Q'OSOz&[z{&v{!P&[!P!Q'x!Q;'S&[;'S;=`*s<%lO&[S&aV'OSOz&[z{&v{!P&[!P!Q'x!Q;'S&[;'S;=`*s<%lO&[S&yVOz'`z{&v{!P'`!P!Q*y!Q;'S'`;'S;=`*m<%lO'`S'cVOz&[z{&v{!P&[!P!Q'x!Q;'S&[;'S;=`*s<%lO&[S'{UOz'`{!P'`!P!Q(_!Q;'S'`;'S;=`*m<%lO'`S(bUOz(t{!P(t!P!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nYZ%nZr$nrs&[sz$nz{+O{!P$n!P!Q,z!Q!c$n!c!}#MX!}#O$n#O#P&[#P#R$n#R#S#MX#S#T$n#T#o#MX#o${$n${$|#MX$|4w$n4w5b#MX5b5i$n5i6S#MX6S;'S$n;'S;=`4s<%lO$nV#Mbj'_Q'OS'TPOY$nYZ%nZr$nrs&[sz$nz{+O{!P$n!P!Q,z!Q![#MX![!c$n!c!}#MX!}#O$n#O#P&[#P#R$n#R#S#MX#S#T$n#T#o#MX#o${$n${$|#MX$|4w$n4w5b#MX5b5i$n5i6S#MX6S;'S$n;'S;=`4s<%lO$n_$ ]]wX'_Q'OSOY$nYZ%nZr$nrs&[sz$nz{+O{!P$n!P!Q,z!Q#O$n#O#P&[#P;'S$n;'S;=`4s<%lO$n_$!_a'rX'_Q'OSOY$nYZ%nZr$nrs&[sz$nz{+O{!P$n!P!Q,z!Q!_$n!_!`@O!`#O$n#O#P&[#P#p$n#p#q$#d#q;'S$n;'S;=`4s<%lO$n_$#m]'|X'_Q'OSOY$nYZ%nZr$nrs&[sz$nz{+O{!P$n!P!Q,z!Q#O$n#O#P&[#P;'S$n;'S;=`4s<%lO$n_$$o]vX'_Q'OSOY$nYZ%nZr$nrs&[sz$nz{+O{!P$n!P!Q,z!Q#O$n#O#P&[#P;'S$n;'S;=`4s<%lO$n\",\n tokenizers: [closureParam, tpDelim, literalTokens, 0, 1, 2, 3],\n topRules: {\"SourceFile\":[0,8]},\n specialized: [{term: 281, get: value => spec_identifier[value] || -1}],\n tokenPrec: 15596\n});\n\nexport { parser };\n","import { parser } from '@lezer/rust';\nimport { LRLanguage, indentNodeProp, continuedIndent, foldNodeProp, foldInside, LanguageSupport } from '@codemirror/language';\n\n/**\nA syntax provider based on the [Lezer Rust\nparser](https://github.com/lezer-parser/rust), extended with\nhighlighting and indentation information.\n*/\nconst rustLanguage = /*@__PURE__*/LRLanguage.define({\n name: \"rust\",\n parser: /*@__PURE__*/parser.configure({\n props: [\n /*@__PURE__*/indentNodeProp.add({\n IfExpression: /*@__PURE__*/continuedIndent({ except: /^\\s*({|else\\b)/ }),\n \"String BlockComment\": () => null,\n \"AttributeItem\": cx => cx.continue(),\n \"Statement MatchArm\": /*@__PURE__*/continuedIndent()\n }),\n /*@__PURE__*/foldNodeProp.add(type => {\n if (/(Block|edTokens|List)$/.test(type.name))\n return foldInside;\n if (type.name == \"BlockComment\")\n return tree => ({ from: tree.from + 2, to: tree.to - 2 });\n return undefined;\n })\n ]\n }),\n languageData: {\n commentTokens: { line: \"//\", block: { open: \"/*\", close: \"*/\" } },\n indentOnInput: /^\\s*(?:\\{|\\})$/,\n closeBrackets: { stringPrefixes: [\"b\", \"r\", \"br\"] }\n }\n});\n/**\nRust language support\n*/\nfunction rust() {\n return new LanguageSupport(rustLanguage);\n}\n\nexport { rust, rustLanguage };\n"],"names":["isNum","ch","isNum_","literalTokens","input","stack","next","isFloat","advance","test","String","fromCharCode","after","peek","Zero","acceptToken","count","content","isQuote","i","closureParam","tpDelim","rustHighlighting","Char","RawString","Boolean","Identifier","BoundIdentifier","LoopLabel","FieldIdentifier","Lifetime","ScopeIdentifier","TypeIdentifier","UpdateOp","LineComment","BlockComment","Integer","Float","ArithOp","LogicOp","BitOp","CompareOp","spec_identifier","__proto__","self","super","crate","impl","true","false","pub","in","const","unsafe","async","move","if","let","ref","mut","_","else","match","as","return","await","break","continue","while","loop","for","macro_rules","mod","extern","struct","where","union","enum","type","default","fn","trait","use","static","dyn","parser","version","states","stateData","goto","nodeNames","maxTerm","nodeProps","propSources","skippedNodes","repeatNodeCount","tokenData","tokenizers","topRules","specialized","term","get","value","tokenPrec","rustLanguage","name","configure","props","IfExpression","except","cx","tree","from","to","languageData","commentTokens","line","block","open","close","indentOnInput","closeBrackets","stringPrefixes","rust"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/6388.index.js b/book/_build/html/_static/6388.index.js new file mode 100644 index 0000000..45b4cf9 --- /dev/null +++ b/book/_build/html/_static/6388.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[6388],{76388:(O,Q,$)=>{$.r(Q),$.d(Q,{cpp:()=>W,cppLanguage:()=>n});var X=$(51392),e=$(86253);const i=new X.Jq((O=>{if(76==O.next||85==O.next?O.advance():117==O.next&&(O.advance(),56==O.next&&O.advance()),82!=O.next)return;if(O.advance(),34!=O.next)return;O.advance();let Q="";for(;40!=O.next;){if(32==O.next||O.next<=13||41==O.next)return;Q+=String.fromCharCode(O.next),O.advance()}for(O.advance();;){if(O.next<0)return O.acceptToken(1);if(41==O.next){let $=!0;for(let X=0;$&&X{if(62==O.next)62==O.peek(1)&&O.acceptToken(2,1);else{let Q=!1,$=0;for(;;$++){if(O.next>=65&&O.next<=90)Q=!0;else{if(O.next>=97&&O.next<=122)return;if(95!=O.next&&!(O.next>=48&&O.next<=57))break}O.advance()}Q&&$>1&&O.acceptToken(3)}}),{extend:!0}),r=(0,e.Gv)({"typedef struct union enum class typename decltype auto template operator friend noexcept namespace using requires concept import export module __attribute__ __declspec __based":e.pJ.definitionKeyword,"extern MsCallModifier MsPointerModifier extern static register thread_local inline const volatile restrict _Atomic mutable constexpr constinit consteval virtual explicit VirtualSpecifier Access":e.pJ.modifier,"if else switch for while do case default return break continue goto throw try catch":e.pJ.controlKeyword,"co_return co_yield co_await":e.pJ.controlKeyword,"new sizeof delete static_assert":e.pJ.operatorKeyword,"NULL nullptr":e.pJ.null,this:e.pJ.self,"True False":e.pJ.bool,"TypeSize PrimitiveType":e.pJ.standard(e.pJ.typeName),TypeIdentifier:e.pJ.typeName,FieldIdentifier:e.pJ.propertyName,"CallExpression/FieldExpression/FieldIdentifier":e.pJ.function(e.pJ.propertyName),"ModuleName/Identifier":e.pJ.namespace,PartitionName:e.pJ.labelName,StatementIdentifier:e.pJ.labelName,"Identifier DestructorName":e.pJ.variableName,"CallExpression/Identifier":e.pJ.function(e.pJ.variableName),"CallExpression/ScopedIdentifier/Identifier":e.pJ.function(e.pJ.variableName),"FunctionDeclarator/Identifier FunctionDeclarator/DestructorName":e.pJ.function(e.pJ.definition(e.pJ.variableName)),NamespaceIdentifier:e.pJ.namespace,OperatorName:e.pJ.operator,ArithOp:e.pJ.arithmeticOperator,LogicOp:e.pJ.logicOperator,BitOp:e.pJ.bitwiseOperator,CompareOp:e.pJ.compareOperator,AssignOp:e.pJ.definitionOperator,UpdateOp:e.pJ.updateOperator,LineComment:e.pJ.lineComment,BlockComment:e.pJ.blockComment,Number:e.pJ.number,String:e.pJ.string,"RawString SystemLibString":e.pJ.special(e.pJ.string),CharLiteral:e.pJ.character,EscapeSequence:e.pJ.escape,"UserDefinedLiteral/Identifier":e.pJ.literal,PreProcArg:e.pJ.meta,"PreprocDirectiveName #include #ifdef #ifndef #if #define #else #endif #elif":e.pJ.processingInstruction,MacroName:e.pJ.special(e.pJ.name),"( )":e.pJ.paren,"[ ]":e.pJ.squareBracket,"{ }":e.pJ.brace,"< >":e.pJ.angleBracket,". ->":e.pJ.derefOperator,", ;":e.pJ.separator}),P={__proto__:null,bool:34,char:34,int:34,float:34,double:34,void:34,size_t:34,ssize_t:34,intptr_t:34,uintptr_t:34,charptr_t:34,int8_t:34,int16_t:34,int32_t:34,int64_t:34,uint8_t:34,uint16_t:34,uint32_t:34,uint64_t:34,char8_t:34,char16_t:34,char32_t:34,char64_t:34,const:68,volatile:70,restrict:72,_Atomic:74,mutable:76,constexpr:78,constinit:80,consteval:82,struct:86,__declspec:90,final:148,override:148,public:152,private:152,protected:152,virtual:154,extern:160,static:162,register:164,inline:166,thread_local:168,__attribute__:172,__based:178,__restrict:180,__uptr:180,__sptr:180,_unaligned:180,__unaligned:180,noexcept:194,requires:198,TRUE:784,true:784,FALSE:786,false:786,typename:218,class:220,template:234,throw:248,__cdecl:256,__clrcall:256,__stdcall:256,__fastcall:256,__thiscall:256,__vectorcall:256,try:260,catch:264,export:282,import:286,case:296,default:298,if:308,else:314,switch:318,do:322,while:324,for:330,return:334,break:338,continue:342,goto:346,co_return:350,co_yield:354,using:362,typedef:366,namespace:380,new:398,delete:400,co_await:402,concept:406,enum:410,static_assert:414,friend:422,union:424,explicit:430,operator:444,module:456,signed:518,unsigned:518,long:518,short:518,decltype:528,auto:530,sizeof:566,NULL:572,nullptr:586,this:588},U={__proto__:null,"<":131},t={__proto__:null,">":135},Y={__proto__:null,operator:388,new:576,delete:582},S=X.WQ.deserialize({version:14,states:"$:|Q!QQVOOP'gOUOOO(XOWO'#CdO,RQUO'#CgO,]QUO'#FjO-sQbO'#CwO.UQUO'#CwO0TQUO'#KZO0[QUO'#CvO0gOpO'#DvO0oQ!dO'#D]OOQR'#JO'#JOO5XQVO'#GUO5fQUO'#JVOOQQ'#JV'#JVO8zQUO'#KmO{QVO'#E^O?]QUO'#E^OOQQ'#Ed'#EdOOQQ'#Ee'#EeO?bQVO'#EfO@XQVO'#EiOBUQUO'#FPOBvQUO'#FhOOQR'#Fj'#FjOB{QUO'#FjOOQR'#LQ'#LQOOQR'#LP'#LPOETQVO'#KQOFxQUO'#LVOGVQUO'#KqOGkQUO'#LVOH]QUO'#LXOOQR'#HU'#HUOOQR'#HV'#HVOOQR'#HW'#HWOOQR'#K|'#K|OOQR'#J_'#J_Q!QQVOOOHkQVO'#FOOIWQUO'#EhOI_QUOOOKZQVO'#HgOKkQUO'#HgONVQUO'#KqONaQUO'#KqOOQQ'#Kq'#KqO!!_QUO'#KqOOQQ'#Jq'#JqO!!lQUO'#HxOOQQ'#KZ'#KZO!&^QUO'#KZO!&zQUO'#KQO!(zQVO'#I]O!(zQVO'#I`OCQQUO'#KQOOQQ'#Ip'#IpOOQQ'#KQ'#KQO!,}QUO'#KZOOQR'#KY'#KYO!-UQUO'#DYO!/mQUO'#KnOOQQ'#Kn'#KnO!/tQUO'#KnO!/{QUO'#ETO!0QQUO'#EWO!0VQUO'#FRO8zQUO'#FPO!QQVO'#F^O!0[Q#vO'#F`O!0gQUO'#FkO!0oQUO'#FpO!0tQVO'#FrO!0oQUO'#FuO!3sQU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}3i4O4R4W4a5Y5e5q6_6c6f6h6j6t6v6{7b7j7m8e8g8m8s8t9R9V9]9_9l9o9p9{:O:U:W:]:b:fS%`f0h#d%jgnp|#O$g$|$}%S%d%h%i%w&s't'u(Q*Y*`*b*t+],l,v-_-p-w.f.m.o0]0y0z1O1S2_2j5a6g;W;X;Y;`;a;b;o;p;q;r;v;w;x;y MacroName LineComment BlockComment PreprocDirective #include String EscapeSequence SystemLibString Identifier ArgumentList ( ConditionalExpression AssignmentExpression CallExpression PrimitiveType FieldExpression FieldIdentifier DestructorName TemplateMethod ScopedFieldIdentifier NamespaceIdentifier TemplateType TypeIdentifier ScopedTypeIdentifier ScopedNamespaceIdentifier :: NamespaceIdentifier TypeIdentifier TemplateArgumentList < TypeDescriptor const volatile restrict _Atomic mutable constexpr constinit consteval StructSpecifier struct MsDeclspecModifier __declspec ) Attribute AttributeName Identifier AttributeArgs { } [ ] UpdateOp ArithOp ArithOp ArithOp LogicOp BitOp BitOp BitOp CompareOp CompareOp CompareOp > CompareOp BitOp UpdateOp , Number CharLiteral AttributeArgs VirtualSpecifier BaseClassClause Access virtual FieldDeclarationList FieldDeclaration extern static register inline thread_local AttributeSpecifier __attribute__ PointerDeclarator MsBasedModifier __based MsPointerModifier FunctionDeclarator ParameterList ParameterDeclaration PointerDeclarator FunctionDeclarator Noexcept noexcept RequiresClause requires True False ParenthesizedExpression CommaExpression LambdaExpression LambdaCaptureSpecifier TemplateParameterList OptionalParameterDeclaration TypeParameterDeclaration typename class VariadicParameterDeclaration VariadicDeclarator ReferenceDeclarator OptionalTypeParameterDeclaration VariadicTypeParameterDeclaration TemplateTemplateParameterDeclaration template AbstractFunctionDeclarator AbstractPointerDeclarator AbstractArrayDeclarator AbstractParenthesizedDeclarator AbstractReferenceDeclarator ThrowSpecifier throw TrailingReturnType CompoundStatement FunctionDefinition MsCallModifier TryStatement try CatchClause catch LinkageSpecification Declaration InitDeclarator InitializerList InitializerPair SubscriptDesignator FieldDesignator ExportDeclaration export ImportDeclaration import ModuleName PartitionName HeaderName CaseStatement case default LabeledStatement StatementIdentifier ExpressionStatement IfStatement if ConditionClause Declaration else SwitchStatement switch DoStatement do while WhileStatement ForStatement for ReturnStatement return BreakStatement break ContinueStatement continue GotoStatement goto CoReturnStatement co_return CoYieldStatement co_yield AttributeStatement ForRangeLoop AliasDeclaration using TypeDefinition typedef PointerDeclarator FunctionDeclarator ArrayDeclarator ParenthesizedDeclarator ThrowStatement NamespaceDefinition namespace ScopedIdentifier Identifier OperatorName operator ArithOp BitOp CompareOp LogicOp new delete co_await ConceptDefinition concept UsingDeclaration enum StaticAssertDeclaration static_assert ConcatenatedString TemplateDeclaration FriendDeclaration friend union FunctionDefinition ExplicitFunctionSpecifier explicit FieldInitializerList FieldInitializer DefaultMethodClause DeleteMethodClause FunctionDefinition OperatorCast operator TemplateInstantiation FunctionDefinition FunctionDefinition Declaration ModuleDeclaration module RequiresExpression RequirementList SimpleRequirement TypeRequirement CompoundRequirement ReturnTypeRequirement ConstraintConjuction LogicOp ConstraintDisjunction LogicOp ArrayDeclarator ParenthesizedDeclarator ReferenceDeclarator TemplateFunction OperatorName StructuredBindingDeclarator ArrayDeclarator ParenthesizedDeclarator ReferenceDeclarator BitfieldClause FunctionDefinition FunctionDefinition Declaration FunctionDefinition Declaration AccessSpecifier UnionSpecifier ClassSpecifier EnumSpecifier SizedTypeSpecifier TypeSize EnumeratorList Enumerator DependentType Decltype decltype auto PlaceholderTypeSpecifier ParameterPackExpansion ParameterPackExpansion FieldIdentifier PointerExpression SubscriptExpression BinaryExpression ArithOp LogicOp LogicOp BitOp UnaryExpression LogicOp BitOp UpdateExpression CastExpression SizeofExpression sizeof CoAwaitExpression CompoundLiteralExpression NULL NewExpression new NewDeclarator DeleteExpression delete ParameterPackExpansion nullptr this UserDefinedLiteral ParamPack #define PreprocArg #if #ifdef #ifndef #else #endif #elif PreprocDirectiveName Macro Program",maxTerm:425,nodeProps:[["group",-35,1,8,11,14,15,16,18,71,72,100,101,102,104,191,208,229,242,243,270,271,272,277,280,281,282,284,285,286,287,290,292,293,294,295,296,"Expression",-13,17,24,25,26,42,255,256,257,258,262,263,265,266,"Type",-19,126,129,147,150,152,153,158,160,163,164,166,168,170,172,174,176,178,179,188,"Statement"]],propSources:[r],skippedNodes:[0,3,4,5,6,7,10,297,298,299,300,301,302,303,304,305,306,347,348],repeatNodeCount:41,tokenData:"&*r7ZR!UOX$eXY({YZ.gZ]$e]^+P^p$epq({qr.}rs0}st2ktu$euv!7dvw!9bwx!;exy!O{|!?R|}!AV}!O!BQ!O!P!DX!P!Q#+y!Q!R#Az!R![$(x![!]$Ag!]!^$Cc!^!_$D^!_!`%1W!`!a%2X!a!b%5_!b!c$e!c!n%6Y!n!o%7q!o!w%6Y!w!x%7q!x!}%6Y!}#O%:n#O#P%u#Y#]4Y#]#^NZ#^#o4Y#o;'S$e;'S;=`(u<%lO$e4e4eb)ZW(pQ'f&j'm.oOY$eZr$ers%^sw$ewx(Ox!Q$e!Q![4Y![!c$e!c!}4Y!}#O$e#O#P&f#P#R$e#R#S4Y#S#T$e#T#o4Y#o;'S$e;'S;=`(u<%lO$e4e5xd)ZW(pQ'f&j'm.oOY$eZr$ers%^sw$ewx(Ox!Q$e!Q![4Y![!c$e!c!}4Y!}#O$e#O#P&f#P#R$e#R#S4Y#S#T$e#T#X4Y#X#Y7W#Y#o4Y#o;'S$e;'S;=`(u<%lO$e4e7cd)ZW(pQ'f&j'm.oOY$eZr$ers%^sw$ewx(Ox!Q$e!Q![4Y![!c$e!c!}4Y!}#O$e#O#P&f#P#R$e#R#S4Y#S#T$e#T#Y4Y#Y#Z8q#Z#o4Y#o;'S$e;'S;=`(u<%lO$e4e8|d)ZW(pQ'f&j'm.oOY$eZr$ers%^sw$ewx(Ox!Q$e!Q![4Y![!c$e!c!}4Y!}#O$e#O#P&f#P#R$e#R#S4Y#S#T$e#T#]4Y#]#^:[#^#o4Y#o;'S$e;'S;=`(u<%lO$e4e:gd)ZW(pQ'f&j'm.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!c!}%6Y!}#O$e#O#P&f#P#R$e#R#S%6Y#S#T$e#T#o%6Y#o;'S$e;'S;=`(u<%lO$e2]&!pY!T,g)ZW(pQ'f&jOY$eZr$ers%^sw$ewx(Ox#O$e#O#P&f#P;'S$e;'S;=`(u<%lO$e3o&#m^)ZW(pQ%[!b'f&j!^,gOY$eZr$ers%^sw$ewx(Ox!_$e!_!`!8g!`#O$e#O#P&f#P#p$e#p#q&$i#q;'S$e;'S;=`(u<%lO$e3o&$vY)T,g%^!b)ZW(pQ'f&jOY$eZr$ers%^sw$ewx(Ox#O$e#O#P&f#P;'S$e;'S;=`(u<%lO$e'V&%qY!Ua)ZW(pQ'f&jOY$eZr$ers%^sw$ewx(Ox#O$e#O#P&f#P;'S$e;'S;=`(u<%lO$e(]&&nc)ZW(pQ%[!b'RP'f&jOX$eXY&'yZp$epq&'yqr$ers%^sw$ewx(Ox!c$e!c!}&)_!}#O$e#O#P&f#P#R$e#R#S&)_#S#T$e#T#o&)_#o;'S$e;'S;=`(u<%lO$e&y&(Sc)ZW(pQ'f&jOX$eXY&'yZp$epq&'yqr$ers%^sw$ewx(Ox!c$e!c!}&)_!}#O$e#O#P&f#P#R$e#R#S&)_#S#T$e#T#o&)_#o;'S$e;'S;=`(u<%lO$e&y&)jb)ZW(pQdT'f&jOY$eZr$ers%^sw$ewx(Ox!Q$e!Q![&)_![!c$e!c!}&)_!}#O$e#O#P&f#P#R$e#R#S&)_#S#T$e#T#o&)_#o;'S$e;'S;=`(u<%lO$e",tokenizers:[i,a,0,1,2,3,4,5,6,7,8,9],topRules:{Program:[0,307]},dynamicPrecedences:{87:1,94:1,119:1,184:1,187:-10,240:-10,241:1,244:-1,246:-10,247:1,262:-1,267:2,268:2,306:-10,365:3,417:1,418:3,419:1,420:1},specialized:[{term:356,get:O=>P[O]||-1},{term:32,get:O=>U[O]||-1},{term:66,get:O=>t[O]||-1},{term:363,get:O=>Y[O]||-1}],tokenPrec:24891});var l=$(77120);const n=l.qp.define({name:"cpp",parser:S.configure({props:[l.uj.add({IfStatement:(0,l.tC)({except:/^\s*({|else\b)/}),TryStatement:(0,l.tC)({except:/^\s*({|catch)\b/}),LabeledStatement:l.ze,CaseStatement:O=>O.baseIndent+O.unit,BlockComment:()=>null,CompoundStatement:(0,l.vw)({closing:"}"}),Statement:(0,l.tC)({except:/^{/})}),l.x0.add({"DeclarationList CompoundStatement EnumeratorList FieldDeclarationList InitializerList":l.Dv,BlockComment:O=>({from:O.from+2,to:O.to-2})})]}),languageData:{commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\})$/,closeBrackets:{stringPrefixes:["L","u","U","u8","LR","UR","uR","u8R","R"]}}});function W(){return new l.ri(n)}}}]); +//# sourceMappingURL=6388.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/6388.index.js.map b/book/_build/html/_static/6388.index.js.map new file mode 100644 index 0000000..520fdd2 --- /dev/null +++ b/book/_build/html/_static/6388.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"6388.index.js","mappings":"qKAIA,MAWMA,EAAY,IAAI,MAAkBC,IAQtC,GAfgB,IASZA,EAAMC,MATuB,IASVD,EAAMC,KAC3BD,EAAME,UAVgB,KAWbF,EAAMC,OACfD,EAAME,UACYC,IAAdH,EAAMC,MAAkBD,EAAME,WAb5B,IAeJF,EAAMC,KAAW,OAErB,GADAD,EAAME,UAbM,IAcRF,EAAMC,KAAe,OACzBD,EAAME,UAEN,IAAIE,EAAS,GACb,KAjBa,IAiBNJ,EAAMC,MAAgB,CAC3B,GAjBU,IAiBND,EAAMC,MAAiBD,EAAMC,MAAQ,IAlBjB,IAkBuBD,EAAMC,KAAgB,OACrEG,GAAUC,OAAOC,aAAaN,EAAMC,MACpCD,EAAME,SACR,CAGA,IAFAF,EAAME,YAEG,CACP,GAAIF,EAAMC,KAAO,EACf,OAAOD,EAAMO,YAlCD,GAmCd,GA3BwB,IA2BpBP,EAAMC,KAAgB,CACxB,IAAIO,GAAQ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,CAAEC,KAAM,KAAMC,MAAO,OACzDC,cAAe,gCACfC,cAAe,CAAEC,eAAgB,CAAC,IAAK,IAAK,IAAK,KAAM,KAAM,KAAM,KAAM,MAAO,SAMxF,SAASC,IACL,OAAO,IAAI,KAAgB3B,EAC/B,C","sources":["webpack://thebe/../../node_modules/@lezer/cpp/dist/index.js","webpack://thebe/../../node_modules/@codemirror/lang-cpp/dist/index.js"],"sourcesContent":["import { ExternalTokenizer, LRParser } from '@lezer/lr';\nimport { styleTags, tags } from '@lezer/highlight';\n\n// This file was generated by lezer-generator. You probably shouldn't edit it.\nconst RawString = 1,\n templateArgsEndFallback = 2,\n MacroName = 3;\n\nconst R = 82, L = 76, u = 117, U = 85,\n a = 97, z = 122, A = 65, Z = 90, Underscore = 95,\n Zero = 48,\n Quote = 34,\n ParenL = 40, ParenR = 41,\n Space = 32, GreaterThan = 62;\n\nconst rawString = new ExternalTokenizer(input => {\n // Raw string literals can start with: R, LR, uR, UR, u8R\n if (input.next == L || input.next == U) {\n input.advance();\n } else if (input.next == u) {\n input.advance();\n if (input.next == Zero + 8) input.advance();\n }\n if (input.next != R) return\n input.advance();\n if (input.next != Quote) return\n input.advance();\n\n let marker = \"\";\n while (input.next != ParenL) {\n if (input.next == Space || input.next <= 13 || input.next == ParenR) return\n marker += String.fromCharCode(input.next);\n input.advance();\n }\n input.advance();\n\n for (;;) {\n if (input.next < 0)\n return input.acceptToken(RawString)\n if (input.next == ParenR) {\n let match = true;\n for (let i = 0; match && i < marker.length; i++)\n if (input.peek(i + 1) != marker.charCodeAt(i)) match = false;\n if (match && input.peek(marker.length + 1) == Quote)\n return input.acceptToken(RawString, 2 + marker.length)\n }\n input.advance();\n }\n});\n\nconst fallback = new ExternalTokenizer(input => {\n if (input.next == GreaterThan) {\n // Provide a template-args-closing token when the next characters\n // are \">>\", in which case the regular tokenizer will only see a\n // bit shift op.\n if (input.peek(1) == GreaterThan)\n input.acceptToken(templateArgsEndFallback, 1);\n } else {\n // Notice all-uppercase identifiers\n let sawLetter = false, i = 0;\n for (;; i++) {\n if (input.next >= A && input.next <= Z) sawLetter = true;\n else if (input.next >= a && input.next <= z) return\n else if (input.next != Underscore && !(input.next >= Zero && input.next <= Zero + 9)) break\n input.advance();\n }\n if (sawLetter && i > 1) input.acceptToken(MacroName);\n }\n}, {extend: true});\n\nconst cppHighlighting = styleTags({\n \"typedef struct union enum class typename decltype auto template operator friend noexcept namespace using requires concept import export module __attribute__ __declspec __based\": tags.definitionKeyword,\n \"extern MsCallModifier MsPointerModifier extern static register thread_local inline const volatile restrict _Atomic mutable constexpr constinit consteval virtual explicit VirtualSpecifier Access\": tags.modifier,\n \"if else switch for while do case default return break continue goto throw try catch\": tags.controlKeyword,\n \"co_return co_yield co_await\": tags.controlKeyword,\n \"new sizeof delete static_assert\": tags.operatorKeyword,\n \"NULL nullptr\": tags.null,\n this: tags.self,\n \"True False\": tags.bool,\n \"TypeSize PrimitiveType\": tags.standard(tags.typeName),\n TypeIdentifier: tags.typeName,\n FieldIdentifier: tags.propertyName,\n \"CallExpression/FieldExpression/FieldIdentifier\": tags.function(tags.propertyName),\n \"ModuleName/Identifier\": tags.namespace,\n \"PartitionName\": tags.labelName,\n StatementIdentifier: tags.labelName,\n \"Identifier DestructorName\": tags.variableName,\n \"CallExpression/Identifier\": tags.function(tags.variableName),\n \"CallExpression/ScopedIdentifier/Identifier\": tags.function(tags.variableName),\n \"FunctionDeclarator/Identifier FunctionDeclarator/DestructorName\": tags.function(tags.definition(tags.variableName)),\n NamespaceIdentifier: tags.namespace,\n OperatorName: tags.operator,\n ArithOp: tags.arithmeticOperator,\n LogicOp: tags.logicOperator,\n BitOp: tags.bitwiseOperator,\n CompareOp: tags.compareOperator,\n AssignOp: tags.definitionOperator,\n UpdateOp: tags.updateOperator,\n LineComment: tags.lineComment,\n BlockComment: tags.blockComment,\n Number: tags.number,\n String: tags.string,\n \"RawString SystemLibString\": tags.special(tags.string),\n CharLiteral: tags.character,\n EscapeSequence: tags.escape,\n \"UserDefinedLiteral/Identifier\": tags.literal,\n PreProcArg: tags.meta,\n \"PreprocDirectiveName #include #ifdef #ifndef #if #define #else #endif #elif\": tags.processingInstruction,\n MacroName: tags.special(tags.name),\n \"( )\": tags.paren,\n \"[ ]\": tags.squareBracket,\n \"{ }\": tags.brace,\n \"< >\": tags.angleBracket,\n \". ->\": tags.derefOperator,\n \", ;\": tags.separator\n});\n\n// This file was generated by lezer-generator. You probably shouldn't edit it.\nconst spec_identifier = {__proto__:null,bool:34, char:34, int:34, float:34, double:34, void:34, size_t:34, ssize_t:34, intptr_t:34, uintptr_t:34, charptr_t:34, int8_t:34, int16_t:34, int32_t:34, int64_t:34, uint8_t:34, uint16_t:34, uint32_t:34, uint64_t:34, char8_t:34, char16_t:34, char32_t:34, char64_t:34, const:68, volatile:70, restrict:72, _Atomic:74, mutable:76, constexpr:78, constinit:80, consteval:82, struct:86, __declspec:90, final:148, override:148, public:152, private:152, protected:152, virtual:154, extern:160, static:162, register:164, inline:166, thread_local:168, __attribute__:172, __based:178, __restrict:180, __uptr:180, __sptr:180, _unaligned:180, __unaligned:180, noexcept:194, requires:198, TRUE:784, true:784, FALSE:786, false:786, typename:218, class:220, template:234, throw:248, __cdecl:256, __clrcall:256, __stdcall:256, __fastcall:256, __thiscall:256, __vectorcall:256, try:260, catch:264, export:282, import:286, case:296, default:298, if:308, else:314, switch:318, do:322, while:324, for:330, return:334, break:338, continue:342, goto:346, co_return:350, co_yield:354, using:362, typedef:366, namespace:380, new:398, delete:400, co_await:402, concept:406, enum:410, static_assert:414, friend:422, union:424, explicit:430, operator:444, module:456, signed:518, unsigned:518, long:518, short:518, decltype:528, auto:530, sizeof:566, NULL:572, nullptr:586, this:588};\nconst spec_ = {__proto__:null,\"<\":131};\nconst spec_templateArgsEnd = {__proto__:null,\">\":135};\nconst spec_scopedIdentifier = {__proto__:null,operator:388, new:576, delete:582};\nconst parser = LRParser.deserialize({\n version: 14,\n states: \"$:|Q!QQVOOP'gOUOOO(XOW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gumentList ( ConditionalExpression AssignmentExpression CallExpression PrimitiveType FieldExpression FieldIdentifier DestructorName TemplateMethod ScopedFieldIdentifier NamespaceIdentifier TemplateType TypeIdentifier ScopedTypeIdentifier ScopedNamespaceIdentifier :: NamespaceIdentifier TypeIdentifier TemplateArgumentList < TypeDescriptor const volatile restrict _Atomic mutable constexpr constinit consteval StructSpecifier struct MsDeclspecModifier __declspec ) Attribute AttributeName Identifier AttributeArgs { } [ ] UpdateOp ArithOp ArithOp ArithOp LogicOp BitOp BitOp BitOp CompareOp CompareOp CompareOp > CompareOp BitOp UpdateOp , Number CharLiteral AttributeArgs VirtualSpecifier BaseClassClause Access virtual FieldDeclarationList FieldDeclaration extern static register inline thread_local AttributeSpecifier __attribute__ PointerDeclarator MsBasedModifier __based MsPointerModifier FunctionDeclarator ParameterList ParameterDeclaration PointerDeclarator FunctionDeclarator Noexcept noexcept RequiresClause requires True False ParenthesizedExpression CommaExpression LambdaExpression LambdaCaptureSpecifier TemplateParameterList OptionalParameterDeclaration TypeParameterDeclaration typename class VariadicParameterDeclaration VariadicDeclarator ReferenceDeclarator OptionalTypeParameterDeclaration VariadicTypeParameterDeclaration TemplateTemplateParameterDeclaration template AbstractFunctionDeclarator AbstractPointerDeclarator AbstractArrayDeclarator AbstractParenthesizedDeclarator AbstractReferenceDeclarator ThrowSpecifier throw TrailingReturnType CompoundStatement FunctionDefinition MsCallModifier TryStatement try CatchClause catch LinkageSpecification Declaration InitDeclarator InitializerList InitializerPair SubscriptDesignator FieldDesignator ExportDeclaration export ImportDeclaration import ModuleName PartitionName HeaderName CaseStatement case default LabeledStatement StatementIdentifier ExpressionStatement IfStatement if ConditionClause Declaration else SwitchStatement switch DoStatement do while WhileStatement ForStatement for ReturnStatement return BreakStatement break ContinueStatement continue GotoStatement goto CoReturnStatement co_return CoYieldStatement co_yield AttributeStatement ForRangeLoop AliasDeclaration using TypeDefinition typedef PointerDeclarator FunctionDeclarator ArrayDeclarator ParenthesizedDeclarator ThrowStatement NamespaceDefinition namespace ScopedIdentifier Identifier OperatorName operator ArithOp BitOp CompareOp LogicOp new delete co_await ConceptDefinition concept UsingDeclaration enum StaticAssertDeclaration static_assert ConcatenatedString TemplateDeclaration FriendDeclaration friend union FunctionDefinition ExplicitFunctionSpecifier explicit FieldInitializerList FieldInitializer DefaultMethodClause DeleteMethodClause FunctionDefinition OperatorCast operator TemplateInstantiation FunctionDefinition FunctionDefinition Declaration ModuleDeclaration module RequiresExpression RequirementList SimpleRequirement TypeRequirement CompoundRequirement ReturnTypeRequirement ConstraintConjuction LogicOp ConstraintDisjunction LogicOp ArrayDeclarator ParenthesizedDeclarator ReferenceDeclarator TemplateFunction OperatorName StructuredBindingDeclarator ArrayDeclarator ParenthesizedDeclarator ReferenceDeclarator BitfieldClause FunctionDefinition FunctionDefinition Declaration FunctionDefinition Declaration AccessSpecifier UnionSpecifier ClassSpecifier EnumSpecifier SizedTypeSpecifier TypeSize EnumeratorList Enumerator DependentType Decltype decltype auto PlaceholderTypeSpecifier ParameterPackExpansion ParameterPackExpansion FieldIdentifier PointerExpression SubscriptExpression BinaryExpression ArithOp LogicOp LogicOp BitOp UnaryExpression LogicOp BitOp UpdateExpression CastExpression SizeofExpression sizeof CoAwaitExpression CompoundLiteralExpression NULL NewExpression new NewDeclarator DeleteExpression delete ParameterPackExpansion nullptr this UserDefinedLiteral ParamPack #define PreprocArg #if #ifdef #ifndef #else #endif #elif PreprocDirectiveName Macro Program\",\n maxTerm: 425,\n nodeProps: [\n [\"group\", -35,1,8,11,14,15,16,18,71,72,100,101,102,104,191,208,229,242,243,270,271,272,277,280,281,282,284,285,286,287,290,292,293,294,295,296,\"Expression\",-13,17,24,25,26,42,255,256,257,258,262,263,265,266,\"Type\",-19,126,129,147,150,152,153,158,160,163,164,166,168,170,172,174,176,178,179,188,\"Statement\"]\n ],\n propSources: [cppHighlighting],\n skippedNodes: [0,3,4,5,6,7,10,297,298,299,300,301,302,303,304,305,306,347,348],\n repeatNodeCount: 41,\n tok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`!8g!`#O$e#O#P&f#P#p$e#p#q&$i#q;'S$e;'S;=`(u<%lO$e3o&$vY)T,g%^!b)ZW(pQ'f&jOY$eZr$ers%^sw$ewx(Ox#O$e#O#P&f#P;'S$e;'S;=`(u<%lO$e'V&%qY!Ua)ZW(pQ'f&jOY$eZr$ers%^sw$ewx(Ox#O$e#O#P&f#P;'S$e;'S;=`(u<%lO$e(]&&nc)ZW(pQ%[!b'RP'f&jOX$eXY&'yZp$epq&'yqr$ers%^sw$ewx(Ox!c$e!c!}&)_!}#O$e#O#P&f#P#R$e#R#S&)_#S#T$e#T#o&)_#o;'S$e;'S;=`(u<%lO$e&y&(Sc)ZW(pQ'f&jOX$eXY&'yZp$epq&'yqr$ers%^sw$ewx(Ox!c$e!c!}&)_!}#O$e#O#P&f#P#R$e#R#S&)_#S#T$e#T#o&)_#o;'S$e;'S;=`(u<%lO$e&y&)jb)ZW(pQdT'f&jOY$eZr$ers%^sw$ewx(Ox!Q$e!Q![&)_![!c$e!c!}&)_!}#O$e#O#P&f#P#R$e#R#S&)_#S#T$e#T#o&)_#o;'S$e;'S;=`(u<%lO$e\",\n tokenizers: [rawString, fallback, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n topRules: {\"Program\":[0,307]},\n dynamicPrecedences: {\"87\":1,\"94\":1,\"119\":1,\"184\":1,\"187\":-10,\"240\":-10,\"241\":1,\"244\":-1,\"246\":-10,\"247\":1,\"262\":-1,\"267\":2,\"268\":2,\"306\":-10,\"365\":3,\"417\":1,\"418\":3,\"419\":1,\"420\":1},\n specialized: [{term: 356, get: value => spec_identifier[value] || -1},{term: 32, get: value => spec_[value] || -1},{term: 66, get: value => spec_templateArgsEnd[value] || -1},{term: 363, get: value => spec_scopedIdentifier[value] || -1}],\n tokenPrec: 24891\n});\n\nexport { parser };\n","import { parser } from '@lezer/cpp';\nimport { LRLanguage, indentNodeProp, continuedIndent, flatIndent, delimitedIndent, foldNodeProp, foldInside, LanguageSupport } from '@codemirror/language';\n\n/**\nA language provider based on the [Lezer C++\nparser](https://github.com/lezer-parser/cpp), extended with\nhighlighting and indentation information.\n*/\nconst cppLanguage = /*@__PURE__*/LRLanguage.define({\n name: \"cpp\",\n parser: /*@__PURE__*/parser.configure({\n props: [\n /*@__PURE__*/indentNodeProp.add({\n IfStatement: /*@__PURE__*/continuedIndent({ except: /^\\s*({|else\\b)/ }),\n TryStatement: /*@__PURE__*/continuedIndent({ except: /^\\s*({|catch)\\b/ }),\n LabeledStatement: flatIndent,\n CaseStatement: context => context.baseIndent + context.unit,\n BlockComment: () => null,\n CompoundStatement: /*@__PURE__*/delimitedIndent({ closing: \"}\" }),\n Statement: /*@__PURE__*/continuedIndent({ except: /^{/ })\n }),\n /*@__PURE__*/foldNodeProp.add({\n \"DeclarationList CompoundStatement EnumeratorList FieldDeclarationList InitializerList\": foldInside,\n BlockComment(tree) { return { from: tree.from + 2, to: tree.to - 2 }; }\n })\n ]\n }),\n languageData: {\n commentTokens: { line: \"//\", block: { open: \"/*\", close: \"*/\" } },\n indentOnInput: /^\\s*(?:case |default:|\\{|\\})$/,\n closeBrackets: { stringPrefixes: [\"L\", \"u\", \"U\", \"u8\", \"LR\", \"UR\", \"uR\", \"u8R\", \"R\"] }\n }\n});\n/**\nLanguage support for C++.\n*/\nfunction cpp() {\n return new LanguageSupport(cppLanguage);\n}\n\nexport { cpp, cppLanguage };\n"],"names":["rawString","input","next","advance","Zero","marker","String","fromCharCode","acceptToken","match","i","length","peek","charCodeAt","fallback","sawLetter","extend","cppHighlighting","this","TypeIdentifier","FieldIdentifier","StatementIdentifier","NamespaceIdentifier","OperatorName","ArithOp","LogicOp","BitOp","CompareOp","AssignOp","UpdateOp","LineComment","BlockComment","Number","CharLiteral","EscapeSequence","PreProcArg","MacroName","spec_identifier","__proto__","bool","char","int","float","double","void","size_t","ssize_t","intptr_t","uintptr_t","charptr_t","int8_t","int16_t","int32_t","int64_t","uint8_t","uint16_t","uint32_t","uint64_t","char8_t","char16_t","char32_t","char64_t","const","volatile","restrict","_Atomic","mutable","constexpr","constinit","consteval","struct","__declspec","final","override","public","private","protected","virtual","extern","static","register","inline","thread_local","__attribute__","__based","__restrict","__uptr","__sptr","_unaligned","__unaligned","noexcept","requires","TRUE","true","FALSE","false","typename","class","template","throw","__cdecl","__clrcall","__stdcall","__fastcall","__thiscall","__vectorcall","try","catch","export","import","case","default","if","else","switch","do","while","for","return","break","continue","goto","co_return","co_yield","using","typedef","namespace","new","delete","co_await","concept","enum","static_assert","friend","union","explicit","operator","module","signed","unsigned","long","short","decltype","auto","sizeof","NULL","nullptr","spec_","spec_templateArgsEnd","spec_scopedIdentifier","parser","version","states","stateData","nodeNames","maxTerm","nodeProps","propSources","skippedNodes","repeatNodeCount","tokenData","tokenizers","topRules","dynamicPrecedences","specialized","term","get","value","tokenPrec","cppLanguage","name","configure","props","IfStatement","except","TryStatement","LabeledStatement","CaseStatement","context","baseIndent","unit","CompoundStatement","closing","Statement","tree","from","to","languageData","commentTokens","line","block","open","close","indentOnInput","closeBrackets","stringPrefixes","cpp"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/6475.index.js b/book/_build/html/_static/6475.index.js new file mode 100644 index 0000000..f667c24 --- /dev/null +++ b/book/_build/html/_static/6475.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[6475],{36475:(e,t,r)=>{function n(e,t){for(var r=void 0!==(t=t||{}).prefix?t.prefix:"^",n=void 0!==t.suffix?t.suffix:"\\b",o=0;oh});var o="(?=[^A-Za-z\\d\\-_]|$)",i=/[\w\-:]/,a=n([/begin|break|catch|continue|data|default|do|dynamicparam/,/else|elseif|end|exit|filter|finally|for|foreach|from|function|if|in/,/param|process|return|switch|throw|trap|try|until|where|while/],{suffix:o}),s=n(["f",/b?not/,/[ic]?split/,"join",/is(not)?/,"as",/[ic]?(eq|ne|[gl][te])/,/[ic]?(not)?(like|match|contains)/,/[ic]?replace/,/b?(and|or|xor)/],{prefix:"-"}),u=n([s,/[+\-*\/%]=|\+\+|--|\.\.|[+\-*&^%:=!|\/]|<(?!#)|(?!#)>/],{suffix:""}),c=n([/Add-(Computer|Content|History|Member|PSSnapin|Type)/,/Checkpoint-Computer/,/Clear-(Content|EventLog|History|Host|Item(Property)?|Variable)/,/Compare-Object/,/Complete-Transaction/,/Connect-PSSession/,/ConvertFrom-(Csv|Json|SecureString|StringData)/,/Convert-Path/,/ConvertTo-(Csv|Html|Json|SecureString|Xml)/,/Copy-Item(Property)?/,/Debug-Process/,/Disable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)/,/Disconnect-PSSession/,/Enable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)/,/(Enter|Exit)-PSSession/,/Export-(Alias|Clixml|Console|Counter|Csv|FormatData|ModuleMember|PSSession)/,/ForEach-Object/,/Format-(Custom|List|Table|Wide)/,new RegExp("Get-(Acl|Alias|AuthenticodeSignature|ChildItem|Command|ComputerRestorePoint|Content|ControlPanelItem|Counter|Credential|Culture|Date|Event|EventLog|EventSubscriber|ExecutionPolicy|FormatData|Help|History|Host|HotFix|Item|ItemProperty|Job|Location|Member|Module|PfxCertificate|Process|PSBreakpoint|PSCallStack|PSDrive|PSProvider|PSSession|PSSessionConfiguration|PSSnapin|Random|Service|TraceSource|Transaction|TypeData|UICulture|Unique|Variable|Verb|WinEvent|WmiObject)"),/Group-Object/,/Import-(Alias|Clixml|Counter|Csv|LocalizedData|Module|PSSession)/,/ImportSystemModules/,/Invoke-(Command|Expression|History|Item|RestMethod|WebRequest|WmiMethod)/,/Join-Path/,/Limit-EventLog/,/Measure-(Command|Object)/,/Move-Item(Property)?/,new RegExp("New-(Alias|Event|EventLog|Item(Property)?|Module|ModuleManifest|Object|PSDrive|PSSession|PSSessionConfigurationFile|PSSessionOption|PSTransportOption|Service|TimeSpan|Variable|WebServiceProxy|WinEvent)"),/Out-(Default|File|GridView|Host|Null|Printer|String)/,/Pause/,/(Pop|Push)-Location/,/Read-Host/,/Receive-(Job|PSSession)/,/Register-(EngineEvent|ObjectEvent|PSSessionConfiguration|WmiEvent)/,/Remove-(Computer|Event|EventLog|Item(Property)?|Job|Module|PSBreakpoint|PSDrive|PSSession|PSSnapin|TypeData|Variable|WmiObject)/,/Rename-(Computer|Item(Property)?)/,/Reset-ComputerMachinePassword/,/Resolve-Path/,/Restart-(Computer|Service)/,/Restore-Computer/,/Resume-(Job|Service)/,/Save-Help/,/Select-(Object|String|Xml)/,/Send-MailMessage/,new RegExp("Set-(Acl|Alias|AuthenticodeSignature|Content|Date|ExecutionPolicy|Item(Property)?|Location|PSBreakpoint|PSDebug|PSSessionConfiguration|Service|StrictMode|TraceSource|Variable|WmiInstance)"),/Show-(Command|ControlPanelItem|EventLog)/,/Sort-Object/,/Split-Path/,/Start-(Job|Process|Service|Sleep|Transaction|Transcript)/,/Stop-(Computer|Job|Process|Service|Transcript)/,/Suspend-(Job|Service)/,/TabExpansion2/,/Tee-Object/,/Test-(ComputerSecureChannel|Connection|ModuleManifest|Path|PSSessionConfigurationFile)/,/Trace-Command/,/Unblock-File/,/Undo-Transaction/,/Unregister-(Event|PSSessionConfiguration)/,/Update-(FormatData|Help|List|TypeData)/,/Use-Transaction/,/Wait-(Event|Job|Process)/,/Where-Object/,/Write-(Debug|Error|EventLog|Host|Output|Progress|Verbose|Warning)/,/cd|help|mkdir|more|oss|prompt/,/ac|asnp|cat|cd|chdir|clc|clear|clhy|cli|clp|cls|clv|cnsn|compare|copy|cp|cpi|cpp|cvpa|dbp|del|diff|dir|dnsn|ebp/,/echo|epal|epcsv|epsn|erase|etsn|exsn|fc|fl|foreach|ft|fw|gal|gbp|gc|gci|gcm|gcs|gdr|ghy|gi|gjb|gl|gm|gmo|gp|gps/,/group|gsn|gsnp|gsv|gu|gv|gwmi|h|history|icm|iex|ihy|ii|ipal|ipcsv|ipmo|ipsn|irm|ise|iwmi|iwr|kill|lp|ls|man|md/,/measure|mi|mount|move|mp|mv|nal|ndr|ni|nmo|npssc|nsn|nv|ogv|oh|popd|ps|pushd|pwd|r|rbp|rcjb|rcsn|rd|rdr|ren|ri/,/rjb|rm|rmdir|rmo|rni|rnp|rp|rsn|rsnp|rujb|rv|rvpa|rwmi|sajb|sal|saps|sasv|sbp|sc|select|set|shcm|si|sl|sleep|sls/,/sort|sp|spjb|spps|spsv|start|sujb|sv|swmi|tee|trcm|type|where|wjb|write/],{prefix:"",suffix:""}),l=n([/[$?^_]|Args|ConfirmPreference|ConsoleFileName|DebugPreference|Error|ErrorActionPreference|ErrorView|ExecutionContext/,/FormatEnumerationLimit|Home|Host|Input|MaximumAliasCount|MaximumDriveCount|MaximumErrorCount|MaximumFunctionCount/,/MaximumHistoryCount|MaximumVariableCount|MyInvocation|NestedPromptLevel|OutputEncoding|Pid|Profile|ProgressPreference/,/PSBoundParameters|PSCommandPath|PSCulture|PSDefaultParameterValues|PSEmailServer|PSHome|PSScriptRoot|PSSessionApplicationName/,/PSSessionConfigurationName|PSSessionOption|PSUICulture|PSVersionTable|Pwd|ShellId|StackTrace|VerbosePreference/,/WarningPreference|WhatIfPreference/,/Event|EventArgs|EventSubscriber|Sender/,/Matches|Ofs|ForEach|LastExitCode|PSCmdlet|PSItem|PSSenderInfo|This/,/true|false|null/],{prefix:"\\$",suffix:""}),p={keyword:a,number:/^((0x[\da-f]+)|((\d+\.\d+|\d\.|\.\d+|\d+)(e[\+\-]?\d+)?))[ld]?([kmgtp]b)?/i,operator:u,builtin:n([/[A-Z]:|%|\?/i,c,l],{suffix:o}),punctuation:/[\[\]{},;`\\\.]|@[({]/,variable:/^[A-Za-z\_][A-Za-z\-\_\d]*\b/};function m(e,t){var r=t.returnStack[t.returnStack.length-1];if(r&&r.shouldReturnFrom(t))return t.tokenize=r.tokenize,t.returnStack.pop(),t.tokenize(e,t);if(e.eatSpace())return null;if(e.eat("("))return t.bracketNesting+=1,"punctuation";if(e.eat(")"))return t.bracketNesting-=1,"punctuation";for(var n in p)if(e.match(p[n]))return n;var o=e.next();if("'"===o)return function(e,t){for(var r;null!=(r=e.peek());)if(e.next(),"'"===r&&!e.eat("'"))return t.tokenize=m,"string";return"error"}(e,t);if("$"===o)return v(e,t);if('"'===o)return S(e,t);if("<"===o&&e.eat("#"))return t.tokenize=b,b(e,t);if("#"===o)return e.skipToEnd(),"comment";if("@"===o){var a=e.eat(/["']/);if(a&&e.eol())return t.tokenize=k,t.startQuote=a[0],k(e,t);if(e.eol())return"error";if(e.peek().match(/[({]/))return"punctuation";if(e.peek().match(i))return v(e,t)}return"error"}function S(e,t){for(var r;null!=(r=e.peek());){if("$"===r)return t.tokenize=f,"string";if(e.next(),"`"!==r){if('"'===r&&!e.eat('"'))return t.tokenize=m,"string"}else e.next()}return"error"}function f(e,t){return d(e,t,S)}function P(e,t){return t.tokenize=k,t.startQuote='"',k(e,t)}function g(e,t){return d(e,t,P)}function d(e,t,r){if(e.match("$(")){var n=t.bracketNesting;return t.returnStack.push({shouldReturnFrom:function(e){return e.bracketNesting===n},tokenize:r}),t.tokenize=m,t.bracketNesting+=1,"punctuation"}return e.next(),t.returnStack.push({shouldReturnFrom:function(){return!0},tokenize:r}),t.tokenize=v,t.tokenize(e,t)}function b(e,t){for(var r,n=!1;null!=(r=e.next());){if(n&&">"==r){t.tokenize=m;break}n="#"===r}return"comment"}function v(e,t){var r=e.peek();return e.eat("{")?(t.tokenize=C,C(e,t)):null!=r&&r.match(i)?(e.eatWhile(i),t.tokenize=m,"variable"):(t.tokenize=m,"error")}function C(e,t){for(var r;null!=(r=e.next());)if("}"===r){t.tokenize=m;break}return"variable"}function k(e,t){var r=t.startQuote;if(e.sol()&&e.match(new RegExp(r+"@")))t.tokenize=m;else if('"'===r)for(;!e.eol();){var n=e.peek();if("$"===n)return t.tokenize=g,"string";e.next(),"`"===n&&e.next()}else e.skipToEnd();return"string"}const h={name:"powershell",startState:function(){return{returnStack:[],bracketNesting:0,tokenize:m}},token:function(e,t){return t.tokenize(e,t)},languageData:{commentTokens:{line:"#",block:{open:"<#",close:"#>"}}}}}}]); +//# sourceMappingURL=6475.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/6475.index.js.map b/book/_build/html/_static/6475.index.js.map new file mode 100644 index 0000000..b2a7b33 --- /dev/null +++ b/book/_build/html/_static/6475.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"6475.index.js","mappings":"+FAAA,SAASA,EAAYC,EAAUC,GAK7B,IAHA,IAAIC,OAA4BC,KADhCF,EAAUA,GAAW,CAAC,GACDC,OAAuBD,EAAQC,OAAS,IACzDE,OAA4BD,IAAnBF,EAAQG,OAAuBH,EAAQG,OAAS,MAEpDC,EAAI,EAAGA,EAAIL,EAASM,OAAQD,IAC/BL,EAASK,aAAcE,OACzBP,EAASK,GAAKL,EAASK,GAAGG,OAG1BR,EAASK,GAAKL,EAASK,GAAGI,QAAQ,yBAA0B,QAIhE,OAAO,IAAIF,OAAOL,EAAS,IAAMF,EAASU,KAAK,KAAO,IAAMN,EAAQ,IACtE,C,iCAEA,IAAIO,EAAqB,yBACrBC,EAAW,UACXC,EAAWd,EAAY,CACzB,0DACA,sEACA,gEACC,CAAEK,OAAQO,IAGTG,EAAgBf,EAAY,CAC9B,IACA,QACA,aAAc,OACd,WAAY,KACZ,wBACA,mCACA,eACA,kBACC,CAAEG,OAAQ,MAETa,EAAYhB,EAAY,CAACe,EADP,yDACwC,CAAEV,OAAQ,KAOpEY,EAAgBjB,EAAY,CAC9B,sDACA,sBACA,iEACA,iBACA,uBACA,oBACA,iDACA,eACA,6CACA,uBACA,gBACA,2EACA,uBACA,0EACA,yBACA,8EACA,iBACA,kCACA,IAAIQ,OAAO,wdAIX,eACA,mEACA,sBACA,2EACA,YACA,iBACA,2BACA,uBACA,IAAIA,OAAO,6MAEX,uDACA,QACA,sBACA,YACA,0BACA,qEACA,kIACA,oCACA,gCACA,eACA,6BACA,mBACA,uBACA,YACA,6BACA,mBACA,IAAIA,OAAO,+LAEX,2CACA,cACA,aACA,2DACA,iDACA,wBACA,gBACA,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O,CACLnC,YAAa,GACbM,eAAgB,EAChBJ,SAAUN,EAEd,EAEAwC,MAAO,SAASvC,EAAQC,GACtB,OAAOA,EAAMI,SAASL,EAAQC,EAChC,EAEAuC,aAAc,CACZC,cAAe,CAACC,KAAM,IAAKC,MAAO,CAACC,KAAM,KAAMC,MAAO,Q","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/powershell.js"],"sourcesContent":["function buildRegexp(patterns, options) {\n options = options || {};\n var prefix = options.prefix !== undefined ? options.prefix : '^';\n var suffix = options.suffix !== undefined ? options.suffix : '\\\\b';\n\n for (var i = 0; i < patterns.length; i++) {\n if (patterns[i] instanceof RegExp) {\n patterns[i] = patterns[i].source;\n }\n else {\n patterns[i] = patterns[i].replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&');\n }\n }\n\n return new RegExp(prefix + '(' + patterns.join('|') + ')' + suffix, 'i');\n}\n\nvar notCharacterOrDash = '(?=[^A-Za-z\\\\d\\\\-_]|$)';\nvar varNames = /[\\w\\-:]/\nvar keywords = buildRegexp([\n /begin|break|catch|continue|data|default|do|dynamicparam/,\n /else|elseif|end|exit|filter|finally|for|foreach|from|function|if|in/,\n /param|process|return|switch|throw|trap|try|until|where|while/\n], { suffix: notCharacterOrDash });\n\nvar punctuation = /[\\[\\]{},;`\\\\\\.]|@[({]/;\nvar wordOperators = buildRegexp([\n 'f',\n /b?not/,\n /[ic]?split/, 'join',\n /is(not)?/, 'as',\n /[ic]?(eq|ne|[gl][te])/,\n /[ic]?(not)?(like|match|contains)/,\n /[ic]?replace/,\n /b?(and|or|xor)/\n], { prefix: '-' });\nvar symbolOperators = /[+\\-*\\/%]=|\\+\\+|--|\\.\\.|[+\\-*&^%:=!|\\/]|<(?!#)|(?!#)>/;\nvar operators = buildRegexp([wordOperators, symbolOperators], { suffix: '' });\n\nvar numbers = /^((0x[\\da-f]+)|((\\d+\\.\\d+|\\d\\.|\\.\\d+|\\d+)(e[\\+\\-]?\\d+)?))[ld]?([kmgtp]b)?/i;\n\nvar identifiers = /^[A-Za-z\\_][A-Za-z\\-\\_\\d]*\\b/;\n\nvar symbolBuiltins = /[A-Z]:|%|\\?/i;\nvar namedBuiltins = buildRegexp([\n /Add-(Computer|Content|History|Member|PSSnapin|Type)/,\n /Checkpoint-Computer/,\n /Clear-(Content|EventLog|History|Host|Item(Property)?|Variable)/,\n /Compare-Object/,\n /Complete-Transaction/,\n /Connect-PSSession/,\n /ConvertFrom-(Csv|Json|SecureString|StringData)/,\n /Convert-Path/,\n /ConvertTo-(Csv|Html|Json|SecureString|Xml)/,\n /Copy-Item(Property)?/,\n /Debug-Process/,\n /Disable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)/,\n /Disconnect-PSSession/,\n /Enable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)/,\n /(Enter|Exit)-PSSession/,\n /Export-(Alias|Clixml|Console|Counter|Csv|FormatData|ModuleMember|PSSession)/,\n /ForEach-Object/,\n /Format-(Custom|List|Table|Wide)/,\n new RegExp('Get-(Acl|Alias|AuthenticodeSignature|ChildItem|Command|ComputerRestorePoint|Content|ControlPanelItem|Counter|Credential'\n + '|Culture|Date|Event|EventLog|EventSubscriber|ExecutionPolicy|FormatData|Help|History|Host|HotFix|Item|ItemProperty|Job'\n + '|Location|Member|Module|PfxCertificate|Process|PSBreakpoint|PSCallStack|PSDrive|PSProvider|PSSession|PSSessionConfiguration'\n + '|PSSnapin|Random|Service|TraceSource|Transaction|TypeData|UICulture|Unique|Variable|Verb|WinEvent|WmiObject)'),\n /Group-Object/,\n /Import-(Alias|Clixml|Counter|Csv|LocalizedData|Module|PSSession)/,\n /ImportSystemModules/,\n /Invoke-(Command|Expression|History|Item|RestMethod|WebRequest|WmiMethod)/,\n /Join-Path/,\n /Limit-EventLog/,\n /Measure-(Command|Object)/,\n /Move-Item(Property)?/,\n new RegExp('New-(Alias|Event|EventLog|Item(Property)?|Module|ModuleManifest|Object|PSDrive|PSSession|PSSessionConfigurationFile'\n + '|PSSessionOption|PSTransportOption|Service|TimeSpan|Variable|WebServiceProxy|WinEvent)'),\n /Out-(Default|File|GridView|Host|Null|Printer|String)/,\n /Pause/,\n /(Pop|Push)-Location/,\n /Read-Host/,\n /Receive-(Job|PSSession)/,\n /Register-(EngineEvent|ObjectEvent|PSSessionConfiguration|WmiEvent)/,\n /Remove-(Computer|Event|EventLog|Item(Property)?|Job|Module|PSBreakpoint|PSDrive|PSSession|PSSnapin|TypeData|Variable|WmiObject)/,\n /Rename-(Computer|Item(Property)?)/,\n /Reset-ComputerMachinePassword/,\n /Resolve-Path/,\n /Restart-(Computer|Service)/,\n /Restore-Computer/,\n /Resume-(Job|Service)/,\n /Save-Help/,\n /Select-(Object|String|Xml)/,\n /Send-MailMessage/,\n new RegExp('Set-(Acl|Alias|AuthenticodeSignature|Content|Date|ExecutionPolicy|Item(Property)?|Location|PSBreakpoint|PSDebug' +\n '|PSSessionConfiguration|Service|StrictMode|TraceSource|Variable|WmiInstance)'),\n /Show-(Command|ControlPanelItem|EventLog)/,\n /Sort-Object/,\n /Split-Path/,\n /Start-(Job|Process|Service|Sleep|Transaction|Transcript)/,\n /Stop-(Computer|Job|Process|Service|Transcript)/,\n /Suspend-(Job|Service)/,\n /TabExpansion2/,\n /Tee-Object/,\n /Test-(ComputerSecureChannel|Connection|ModuleManifest|Path|PSSessionConfigurationFile)/,\n /Trace-Command/,\n /Unblock-File/,\n /Undo-Transaction/,\n /Unregister-(Event|PSSessionConfiguration)/,\n /Update-(FormatData|Help|List|TypeData)/,\n /Use-Transaction/,\n /Wait-(Event|Job|Process)/,\n /Where-Object/,\n /Write-(Debug|Error|EventLog|Host|Output|Progress|Verbose|Warning)/,\n /cd|help|mkdir|more|oss|prompt/,\n /ac|asnp|cat|cd|chdir|clc|clear|clhy|cli|clp|cls|clv|cnsn|compare|copy|cp|cpi|cpp|cvpa|dbp|del|diff|dir|dnsn|ebp/,\n /echo|epal|epcsv|epsn|erase|etsn|exsn|fc|fl|foreach|ft|fw|gal|gbp|gc|gci|gcm|gcs|gdr|ghy|gi|gjb|gl|gm|gmo|gp|gps/,\n /group|gsn|gsnp|gsv|gu|gv|gwmi|h|history|icm|iex|ihy|ii|ipal|ipcsv|ipmo|ipsn|irm|ise|iwmi|iwr|kill|lp|ls|man|md/,\n /measure|mi|mount|move|mp|mv|nal|ndr|ni|nmo|npssc|nsn|nv|ogv|oh|popd|ps|pushd|pwd|r|rbp|rcjb|rcsn|rd|rdr|ren|ri/,\n /rjb|rm|rmdir|rmo|rni|rnp|rp|rsn|rsnp|rujb|rv|rvpa|rwmi|sajb|sal|saps|sasv|sbp|sc|select|set|shcm|si|sl|sleep|sls/,\n /sort|sp|spjb|spps|spsv|start|sujb|sv|swmi|tee|trcm|type|where|wjb|write/\n], { prefix: '', suffix: '' });\nvar variableBuiltins = buildRegexp([\n /[$?^_]|Args|ConfirmPreference|ConsoleFileName|DebugPreference|Error|ErrorActionPreference|ErrorView|ExecutionContext/,\n /FormatEnumerationLimit|Home|Host|Input|MaximumAliasCount|MaximumDriveCount|MaximumErrorCount|MaximumFunctionCount/,\n /MaximumHistoryCount|MaximumVariableCount|MyInvocation|NestedPromptLevel|OutputEncoding|Pid|Profile|ProgressPreference/,\n /PSBoundParameters|PSCommandPath|PSCulture|PSDefaultParameterValues|PSEmailServer|PSHome|PSScriptRoot|PSSessionApplicationName/,\n /PSSessionConfigurationName|PSSessionOption|PSUICulture|PSVersionTable|Pwd|ShellId|StackTrace|VerbosePreference/,\n /WarningPreference|WhatIfPreference/,\n\n /Event|EventArgs|EventSubscriber|Sender/,\n /Matches|Ofs|ForEach|LastExitCode|PSCmdlet|PSItem|PSSenderInfo|This/,\n /true|false|null/\n], { prefix: '\\\\$', suffix: '' });\n\nvar builtins = buildRegexp([symbolBuiltins, namedBuiltins, variableBuiltins], { suffix: notCharacterOrDash });\n\nvar grammar = {\n keyword: keywords,\n number: numbers,\n operator: operators,\n builtin: builtins,\n punctuation: punctuation,\n variable: identifiers\n};\n\n// tokenizers\nfunction tokenBase(stream, state) {\n // Handle Comments\n //var ch = stream.peek();\n\n var parent = state.returnStack[state.returnStack.length - 1];\n if (parent && parent.shouldReturnFrom(state)) {\n state.tokenize = parent.tokenize;\n state.returnStack.pop();\n return state.tokenize(stream, state);\n }\n\n if (stream.eatSpace()) {\n return null;\n }\n\n if (stream.eat('(')) {\n state.bracketNesting += 1;\n return 'punctuation';\n }\n\n if (stream.eat(')')) {\n state.bracketNesting -= 1;\n return 'punctuation';\n }\n\n for (var key in grammar) {\n if (stream.match(grammar[key])) {\n return key;\n }\n }\n\n var ch = stream.next();\n\n // single-quote string\n if (ch === \"'\") {\n return tokenSingleQuoteString(stream, state);\n }\n\n if (ch === '$') {\n return tokenVariable(stream, state);\n }\n\n // double-quote string\n if (ch === '\"') {\n return tokenDoubleQuoteString(stream, state);\n }\n\n if (ch === '<' && stream.eat('#')) {\n state.tokenize = tokenComment;\n return tokenComment(stream, state);\n }\n\n if (ch === '#') {\n stream.skipToEnd();\n return 'comment';\n }\n\n if (ch === '@') {\n var quoteMatch = stream.eat(/[\"']/);\n if (quoteMatch && stream.eol()) {\n state.tokenize = tokenMultiString;\n state.startQuote = quoteMatch[0];\n return tokenMultiString(stream, state);\n } else if (stream.eol()) {\n return 'error';\n } else if (stream.peek().match(/[({]/)) {\n return 'punctuation';\n } else if (stream.peek().match(varNames)) {\n // splatted variable\n return tokenVariable(stream, state);\n }\n }\n return 'error';\n}\n\nfunction tokenSingleQuoteString(stream, state) {\n var ch;\n while ((ch = stream.peek()) != null) {\n stream.next();\n\n if (ch === \"'\" && !stream.eat(\"'\")) {\n state.tokenize = tokenBase;\n return 'string';\n }\n }\n\n return 'error';\n}\n\nfunction tokenDoubleQuoteString(stream, state) {\n var ch;\n while ((ch = stream.peek()) != null) {\n if (ch === '$') {\n state.tokenize = tokenStringInterpolation;\n return 'string';\n }\n\n stream.next();\n if (ch === '`') {\n stream.next();\n continue;\n }\n\n if (ch === '\"' && !stream.eat('\"')) {\n state.tokenize = tokenBase;\n return 'string';\n }\n }\n\n return 'error';\n}\n\nfunction tokenStringInterpolation(stream, state) {\n return tokenInterpolation(stream, state, tokenDoubleQuoteString);\n}\n\nfunction tokenMultiStringReturn(stream, state) {\n state.tokenize = tokenMultiString;\n state.startQuote = '\"'\n return tokenMultiString(stream, state);\n}\n\nfunction tokenHereStringInterpolation(stream, state) {\n return tokenInterpolation(stream, state, tokenMultiStringReturn);\n}\n\nfunction tokenInterpolation(stream, state, parentTokenize) {\n if (stream.match('$(')) {\n var savedBracketNesting = state.bracketNesting;\n state.returnStack.push({\n /*jshint loopfunc:true */\n shouldReturnFrom: function(state) {\n return state.bracketNesting === savedBracketNesting;\n },\n tokenize: parentTokenize\n });\n state.tokenize = tokenBase;\n state.bracketNesting += 1;\n return 'punctuation';\n } else {\n stream.next();\n state.returnStack.push({\n shouldReturnFrom: function() { return true; },\n tokenize: parentTokenize\n });\n state.tokenize = tokenVariable;\n return state.tokenize(stream, state);\n }\n}\n\nfunction tokenComment(stream, state) {\n var maybeEnd = false, ch;\n while ((ch = stream.next()) != null) {\n if (maybeEnd && ch == '>') {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch === '#');\n }\n return 'comment';\n}\n\nfunction tokenVariable(stream, state) {\n var ch = stream.peek();\n if (stream.eat('{')) {\n state.tokenize = tokenVariableWithBraces;\n return tokenVariableWithBraces(stream, state);\n } else if (ch != undefined && ch.match(varNames)) {\n stream.eatWhile(varNames);\n state.tokenize = tokenBase;\n return 'variable';\n } else {\n state.tokenize = tokenBase;\n return 'error';\n }\n}\n\nfunction tokenVariableWithBraces(stream, state) {\n var ch;\n while ((ch = stream.next()) != null) {\n if (ch === '}') {\n state.tokenize = tokenBase;\n break;\n }\n }\n return 'variable';\n}\n\nfunction tokenMultiString(stream, state) {\n var quote = state.startQuote;\n if (stream.sol() && stream.match(new RegExp(quote + '@'))) {\n state.tokenize = tokenBase;\n }\n else if (quote === '\"') {\n while (!stream.eol()) {\n var ch = stream.peek();\n if (ch === '$') {\n state.tokenize = tokenHereStringInterpolation;\n return 'string';\n }\n\n stream.next();\n if (ch === '`') {\n stream.next();\n }\n }\n }\n else {\n stream.skipToEnd();\n }\n\n return 'string';\n}\n\nexport const powerShell = {\n name: \"powershell\",\n\n startState: function() {\n return {\n returnStack: [],\n bracketNesting: 0,\n tokenize: tokenBase\n };\n },\n\n token: function(stream, state) {\n return state.tokenize(stream, state);\n },\n\n languageData: {\n commentTokens: {line: \"#\", block: {open: \"<#\", close: \"#>\"}}\n }\n};\n"],"names":["buildRegexp","patterns","options","prefix","undefined","suffix","i","length","RegExp","source","replace","join","notCharacterOrDash","varNames","keywords","wordOperators","operators","namedBuiltins","variableBuiltins","grammar","keyword","number","operator","builtin","punctuation","variable","tokenBase","stream","state","parent","returnStack","shouldReturnFrom","tokenize","pop","eatSpace","eat","bracketNesting","key","match","ch","next","peek","tokenSingleQuoteString","tokenVariable","tokenDoubleQuoteString","tokenComment","skipToEnd","quoteMatch","eol","tokenMultiString","startQuote","tokenStringInterpolation","tokenInterpolation","tokenMultiStringReturn","tokenHereStringInterpolation","parentTokenize","savedBracketNesting","push","maybeEnd","tokenVariableWithBraces","eatWhile","quote","sol","powerShell","name","startState","token","languageData","commentTokens","line","block","open","close"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/6526.index.js b/book/_build/html/_static/6526.index.js new file mode 100644 index 0000000..46b9568 --- /dev/null +++ b/book/_build/html/_static/6526.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[6526],{26526:(e,t,n)=>{function i(e){var t=e.statementIndentUnit,n=e.dontAlignCalls,i=e.noIndentKeywords||[],r=e.multiLineStrings,a=e.hooks||{};function o(e){for(var t={},n=e.split(" "),i=0;i=0)return o}var l=e.context,s=i&&i.charAt(0);"statement"==l.type&&"}"==s&&(l=l.prev);var c=!1,d=i.match(k);return d&&(c=$(d[0],l.type)),"statement"==l.type?l.indented+("{"==s?0:t||r.unit):y.test(l.type)&&l.align&&!n?l.column+(c?0:1):")"!=l.type||c?l.indented+(c?0:r.unit):l.indented+(t||r.unit)},languageData:{indentOnInput:function(){var e=[];for(var t in w)if(w[t]){var n=w[t].split(";");for(var i in n)e.push(n[i])}return new RegExp("[{}()\\[\\]]|("+e.join("|")+")$")}(),commentTokens:{line:"//",block:{open:"/*",close:"*/"}}}}}n.r(t),n.d(t,{tlv:()=>d,verilog:()=>r});const r=i({});var a={"|":"link",">":"property",$:"variable",$$:"variable","?$":"qualifier","?*":"qualifier","-":"contentSeparator","/":"property","/-":"property","@":"variableName.special","@-":"variableName.special","@++":"variableName.special","@+=":"variableName.special","@+=-":"variableName.special","@--":"variableName.special","@-=":"variableName.special","%+":"tag","%-":"tag","%":"tag",">>":"tag","<<":"tag","<>":"tag","#":"tag","^":"attribute","^^":"attribute","^!":"attribute","*":"variable","**":"variable","\\":"keyword",'"':"comment"},o={"/":"beh-hier",">":"beh-hier","-":"phys-hier","|":"pipe","?":"when","@":"stage","\\":"keyword"},l=/^([~!@#\$%\^&\*-\+=\?\/\\\|'"<>]+)([\d\w_]*)/,s=/^[! ] */,c=/^\/[\/\*]/;const d=i({hooks:{electricInput:!1,token:function(e,t){var n,i=void 0;if(e.sol()&&!t.tlvInBlockComment){"\\"==e.peek()&&(i="def",e.skipToEnd(),e.string.match(/\\SV/)?t.tlvCodeActive=!1:e.string.match(/\\TLV/)&&(t.tlvCodeActive=!0)),t.tlvCodeActive&&0==e.pos&&0==t.indented&&(n=e.match(s,!1))&&(t.indented=n[0].length);var r=t.indented,d=r/3;if(d<=t.tlvIndentationStyle.length){var u=e.string.length==r,f=3*d;if(f0||(t.tlvIndentationStyle[d]=o[m],d++))}if(!u)for(;t.tlvIndentationStyle.length>d;)t.tlvIndentationStyle.pop()}t.tlvNextIndent=r}if(t.tlvCodeActive)if(void 0!==i);else if(t.tlvInBlockComment)e.match(/^.*?\*\//)?t.tlvInBlockComment=!1:e.skipToEnd(),i="comment";else if((n=e.match(c))&&!t.tlvInBlockComment)"//"==n[0]?e.skipToEnd():t.tlvInBlockComment=!0,i="comment";else if(n=e.match(l)){var v=n[1],g=n[2];a.hasOwnProperty(v)&&(g.length>0||e.eol())?i=a[v]:e.backUp(e.current().length-1)}else e.match(/^\t+/)?i="invalid":e.match(/^[\[\]{}\(\);\:]+/)?i="meta":(n=e.match(/^[mM]4([\+_])?[\w\d_]*/))?i="+"==n[1]?"keyword.special":"keyword":e.match(/^ +/)?e.eol()&&(i="error"):e.match(/^[\w\d_]+/)?i="number":e.next();else e.match(/^[mM]4([\w\d_]*)/)&&(i="keyword");return i},indent:function(e){return 1==e.tlvCodeActive?e.tlvNextIndent:-1},startState:function(e){e.tlvIndentationStyle=[],e.tlvCodeActive=!0,e.tlvNextIndent=-1,e.tlvInBlockComment=!1}}})}}]); +//# sourceMappingURL=6526.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/6526.index.js.map b/book/_build/html/_static/6526.index.js.map new file mode 100644 index 0000000..cf4f3b9 --- /dev/null +++ b/book/_build/html/_static/6526.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"6526.index.js","mappings":"+FAAA,SAASA,EAAUC,GAEjB,IAAIC,EAAsBD,EAAaC,oBACnCC,EAAiBF,EAAaE,eAC9BC,EAAmBH,EAAaG,kBAAoB,GACpDC,EAAmBJ,EAAaI,iBAChCC,EAAQL,EAAaK,OAAS,CAAC,EAEnC,SAASC,EAAMC,GAEb,IADA,IAAIC,EAAM,CAAC,EAAGF,EAAQC,EAAIE,MAAM,KACvBC,EAAI,EAAGA,EAAIJ,EAAMK,SAAUD,EAAGF,EAAIF,EAAMI,KAAM,EACvD,OAAOF,CACT,CAKA,IA8CII,EACAC,EA/CAC,EAAWR,EACb,g4DAgCES,EAAiB,sBACjBC,EAAgB,aAEhBC,EAAiB,YACjBC,EAAiB,0BACjBC,EAAgB,+BAChBC,EAAa,iCACbC,EAAa,yCACbC,EAAc,yDAEdC,EA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qB,eAAeF,KAEjCC,EAAS9G,OAAS,GAAKoB,EAAO4F,OAC/B1F,EAAQoE,EAAmBmB,GAM3BzF,EAAOe,OAAOf,EAAOkB,UAAUtC,OAAS,EAE5C,MAAWoB,EAAOgB,MAAM,QAEtBd,EAAQ,UACCF,EAAOgB,MAAM,qBAEtBd,EAAQ,QACCc,EAAQhB,EAAOgB,MAAM,2BAE9Bd,EAAqB,KAAZc,EAAM,GAAa,kBAAoB,UACvChB,EAAOgB,MAAM,OAElBhB,EAAO4F,QAET1F,EAAQ,SAEDF,EAAOgB,MAAM,aAEtBd,EAAQ,SAGRF,EAAOO,YAGLP,EAAOgB,MAAM,sBAEfd,EAAQ,WAGZ,OAAOA,CACT,EAEA6C,OAAQ,SAAS9C,GACf,OAA+B,GAAvBA,EAAM8E,cAAyB9E,EAAMuF,eAAiB,CAChE,EAEAlD,WAAY,SAASrC,GACnBA,EAAMiF,oBAAsB,GAC5BjF,EAAM8E,eAAgB,EACtB9E,EAAMuF,eAAiB,EACvBvF,EAAM4E,mBAAoB,CAI5B,I","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/verilog.js"],"sourcesContent":["function mkVerilog(parserConfig) {\n\n var statementIndentUnit = parserConfig.statementIndentUnit,\n dontAlignCalls = parserConfig.dontAlignCalls,\n noIndentKeywords = parserConfig.noIndentKeywords || [],\n multiLineStrings = parserConfig.multiLineStrings,\n hooks = parserConfig.hooks || {};\n\n function words(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n }\n\n /**\n * Keywords from IEEE 1800-2012\n */\n var keywords = words(\n \"accept_on alias always always_comb always_ff always_latch and assert assign assume automatic before begin bind \" +\n \"bins binsof bit break buf bufif0 bufif1 byte case casex casez cell chandle checker class clocking cmos config \" +\n \"const constraint context continue cover covergroup coverpoint cross deassign default defparam design disable \" +\n \"dist do edge else end endcase endchecker endclass endclocking endconfig endfunction endgenerate endgroup \" +\n \"endinterface endmodule endpackage endprimitive endprogram endproperty endspecify endsequence endtable endtask \" +\n \"enum event eventually expect export extends extern final first_match for force foreach forever fork forkjoin \" +\n \"function generate genvar global highz0 highz1 if iff ifnone ignore_bins illegal_bins implements implies import \" +\n \"incdir include initial inout input inside instance int integer interconnect interface intersect join join_any \" +\n \"join_none large let liblist library local localparam logic longint macromodule matches medium modport module \" +\n \"nand negedge nettype new nexttime nmos nor noshowcancelled not notif0 notif1 null or output package packed \" +\n \"parameter pmos posedge primitive priority program property protected pull0 pull1 pulldown pullup \" +\n \"pulsestyle_ondetect pulsestyle_onevent pure rand randc randcase randsequence rcmos real realtime ref reg \" +\n \"reject_on release repeat restrict return rnmos rpmos rtran rtranif0 rtranif1 s_always s_eventually s_nexttime \" +\n \"s_until s_until_with scalared sequence shortint shortreal showcancelled signed small soft solve specify \" +\n \"specparam static string strong strong0 strong1 struct super supply0 supply1 sync_accept_on sync_reject_on \" +\n \"table tagged task this throughout time timeprecision timeunit tran tranif0 tranif1 tri tri0 tri1 triand trior \" +\n \"trireg type typedef union unique unique0 unsigned until until_with untyped use uwire var vectored virtual void \" +\n \"wait wait_order wand weak weak0 weak1 while wildcard wire with within wor xnor xor\");\n\n /** Operators from IEEE 1800-2012\n unary_operator ::=\n + | - | ! | ~ | & | ~& | | | ~| | ^ | ~^ | ^~\n binary_operator ::=\n + | - | * | / | % | == | != | === | !== | ==? | !=? | && | || | **\n | < | <= | > | >= | & | | | ^ | ^~ | ~^ | >> | << | >>> | <<<\n | -> | <->\n inc_or_dec_operator ::= ++ | --\n unary_module_path_operator ::=\n ! | ~ | & | ~& | | | ~| | ^ | ~^ | ^~\n binary_module_path_operator ::=\n == | != | && | || | & | | | ^ | ^~ | ~^\n */\n var isOperatorChar = /[\\+\\-\\*\\/!~&|^%=?:]/;\n var isBracketChar = /[\\[\\]{}()]/;\n\n var unsignedNumber = /\\d[0-9_]*/;\n var decimalLiteral = /\\d*\\s*'s?d\\s*\\d[0-9_]*/i;\n var binaryLiteral = /\\d*\\s*'s?b\\s*[xz01][xz01_]*/i;\n var octLiteral = /\\d*\\s*'s?o\\s*[xz0-7][xz0-7_]*/i;\n var hexLiteral = /\\d*\\s*'s?h\\s*[0-9a-fxz?][0-9a-fxz?_]*/i;\n var realLiteral = /(\\d[\\d_]*(\\.\\d[\\d_]*)?E-?[\\d_]+)|(\\d[\\d_]*\\.\\d[\\d_]*)/i;\n\n var closingBracketOrWord = /^((\\w+)|[)}\\]])/;\n var closingBracket = /[)}\\]]/;\n\n var curPunc;\n var curKeyword;\n\n // Block openings which are closed by a matching keyword in the form of (\"end\" + keyword)\n // E.g. \"task\" => \"endtask\"\n var blockKeywords = words(\n \"case checker class clocking config function generate interface module package \" +\n \"primitive program property specify sequence table task\"\n );\n\n // Opening/closing pairs\n var openClose = {};\n for (var keyword in blockKeywords) {\n openClose[keyword] = \"end\" + keyword;\n }\n openClose[\"begin\"] = \"end\";\n openClose[\"casex\"] = \"endcase\";\n openClose[\"casez\"] = \"endcase\";\n openClose[\"do\" ] = \"while\";\n openClose[\"fork\" ] = \"join;join_any;join_none\";\n openClose[\"covergroup\"] = \"endgroup\";\n\n for (var i in noIndentKeywords) {\n var keyword = noIndentKeywords[i];\n if (openClose[keyword]) {\n openClose[keyword] = undefined;\n }\n }\n\n // Keywords which open statements that are ended with a semi-colon\n var statementKeywords = words(\"always always_comb always_ff always_latch assert assign assume else export for foreach forever if import initial repeat while\");\n\n function tokenBase(stream, state) {\n var ch = stream.peek(), style;\n if (hooks[ch] && (style = hooks[ch](stream, state)) != false) return style;\n if (hooks.tokenBase && (style = hooks.tokenBase(stream, state)) != false)\n return style;\n\n if (/[,;:\\.]/.test(ch)) {\n curPunc = stream.next();\n return null;\n }\n if (isBracketChar.test(ch)) {\n curPunc = stream.next();\n return \"bracket\";\n }\n // Macros (tick-defines)\n if (ch == '`') {\n stream.next();\n if (stream.eatWhile(/[\\w\\$_]/)) {\n return \"def\";\n } else {\n return null;\n }\n }\n // System calls\n if (ch == '$') {\n stream.next();\n if (stream.eatWhile(/[\\w\\$_]/)) {\n return \"meta\";\n } else {\n return null;\n }\n }\n // Time literals\n if (ch == '#') {\n stream.next();\n stream.eatWhile(/[\\d_.]/);\n return \"def\";\n }\n // Strings\n if (ch == '\"') {\n stream.next();\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n }\n // Comments\n if (ch == \"/\") {\n stream.next();\n if (stream.eat(\"*\")) {\n state.tokenize = tokenComment;\n return tokenComment(stream, state);\n }\n if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return \"comment\";\n }\n stream.backUp(1);\n }\n\n // Numeric literals\n if (stream.match(realLiteral) ||\n stream.match(decimalLiteral) ||\n stream.match(binaryLiteral) ||\n stream.match(octLiteral) ||\n stream.match(hexLiteral) ||\n stream.match(unsignedNumber) ||\n stream.match(realLiteral)) {\n return \"number\";\n }\n\n // Operators\n if (stream.eatWhile(isOperatorChar)) {\n return \"meta\";\n }\n\n // Keywords / plain variables\n if (stream.eatWhile(/[\\w\\$_]/)) {\n var cur = stream.current();\n if (keywords[cur]) {\n if (openClose[cur]) {\n curPunc = \"newblock\";\n }\n if (statementKeywords[cur]) {\n curPunc = \"newstatement\";\n }\n curKeyword = cur;\n return \"keyword\";\n }\n return \"variable\";\n }\n\n stream.next();\n return null;\n }\n\n function tokenString(quote) {\n return function(stream, state) {\n var escaped = false, next, end = false;\n while ((next = stream.next()) != null) {\n if (next == quote && !escaped) {end = true; break;}\n escaped = !escaped && next == \"\\\\\";\n }\n if (end || !(escaped || multiLineStrings))\n state.tokenize = tokenBase;\n return \"string\";\n };\n }\n\n function tokenComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if (ch == \"/\" && maybeEnd) {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return \"comment\";\n }\n\n function Context(indented, column, type, align, prev) {\n this.indented = indented;\n this.column = column;\n this.type = type;\n this.align = align;\n this.prev = prev;\n }\n function pushContext(state, col, type) {\n var indent = state.indented;\n var c = new Context(indent, col, type, null, state.context);\n return state.context = c;\n }\n function popContext(state) {\n var t = state.context.type;\n if (t == \")\" || t == \"]\" || t == \"}\") {\n state.indented = state.context.indented;\n }\n return state.context = state.context.prev;\n }\n\n function isClosing(text, contextClosing) {\n if (text == contextClosing) {\n return true;\n } else {\n // contextClosing may be multiple keywords separated by ;\n var closingKeywords = contextClosing.split(\";\");\n for (var i in closingKeywords) {\n if (text == closingKeywords[i]) {\n return true;\n }\n }\n return false;\n }\n }\n\n function buildElectricInputRegEx() {\n // Reindentation should occur on any bracket char: {}()[]\n // or on a match of any of the block closing keywords, at\n // the end of a line\n var allClosings = [];\n for (var i in openClose) {\n if (openClose[i]) {\n var closings = openClose[i].split(\";\");\n for (var j in closings) {\n allClosings.push(closings[j]);\n }\n }\n }\n var re = new RegExp(\"[{}()\\\\[\\\\]]|(\" + allClosings.join(\"|\") + \")$\");\n return re;\n }\n\n // Interface\n return {\n name: \"verilog\",\n\n startState: function(indentUnit) {\n var state = {\n tokenize: null,\n context: new Context(-indentUnit, 0, \"top\", false),\n indented: 0,\n startOfLine: true\n };\n if (hooks.startState) hooks.startState(state);\n return state;\n },\n\n token: function(stream, state) {\n var ctx = state.context;\n if (stream.sol()) {\n if (ctx.align == null) ctx.align = false;\n state.indented = stream.indentation();\n state.startOfLine = true;\n }\n if (hooks.token) {\n // Call hook, with an optional return value of a style to override verilog styling.\n var style = hooks.token(stream, state);\n if (style !== undefined) {\n return style;\n }\n }\n if (stream.eatSpace()) return null;\n curPunc = null;\n curKeyword = null;\n var style = (state.tokenize || tokenBase)(stream, state);\n if (style == \"comment\" || style == \"meta\" || style == \"variable\") return style;\n if (ctx.align == null) ctx.align = true;\n\n if (curPunc == ctx.type) {\n popContext(state);\n } else if ((curPunc == \";\" && ctx.type == \"statement\") ||\n (ctx.type && isClosing(curKeyword, ctx.type))) {\n ctx = popContext(state);\n while (ctx && ctx.type == \"statement\") ctx = popContext(state);\n } else if (curPunc == \"{\") {\n pushContext(state, stream.column(), \"}\");\n } else if (curPunc == \"[\") {\n pushContext(state, stream.column(), \"]\");\n } else if (curPunc == \"(\") {\n pushContext(state, stream.column(), \")\");\n } else if (ctx && ctx.type == \"endcase\" && curPunc == \":\") {\n pushContext(state, stream.column(), \"statement\");\n } else if (curPunc == \"newstatement\") {\n pushContext(state, stream.column(), \"statement\");\n } else if (curPunc == \"newblock\") {\n if (curKeyword == \"function\" && ctx && (ctx.type == \"statement\" || ctx.type == \"endgroup\")) {\n // The 'function' keyword can appear in some other contexts where it actually does not\n // indicate a function (import/export DPI and covergroup definitions).\n // Do nothing in this case\n } else if (curKeyword == \"task\" && ctx && ctx.type == \"statement\") {\n // Same thing for task\n } else {\n var close = openClose[curKeyword];\n pushContext(state, stream.column(), close);\n }\n }\n\n state.startOfLine = false;\n return style;\n },\n\n indent: function(state, textAfter, cx) {\n if (state.tokenize != tokenBase && state.tokenize != null) return null;\n if (hooks.indent) {\n var fromHook = hooks.indent(state);\n if (fromHook >= 0) return fromHook;\n }\n var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);\n if (ctx.type == \"statement\" && firstChar == \"}\") ctx = ctx.prev;\n var closing = false;\n var possibleClosing = textAfter.match(closingBracketOrWord);\n if (possibleClosing)\n closing = isClosing(possibleClosing[0], ctx.type);\n if (ctx.type == \"statement\") return ctx.indented + (firstChar == \"{\" ? 0 : statementIndentUnit || cx.unit);\n else if (closingBracket.test(ctx.type) && ctx.align && !dontAlignCalls) return ctx.column + (closing ? 0 : 1);\n else if (ctx.type == \")\" && !closing) return ctx.indented + (statementIndentUnit || cx.unit);\n else return ctx.indented + (closing ? 0 : cx.unit);\n },\n\n languageData: {\n indentOnInput: buildElectricInputRegEx(),\n commentTokens: {line: \"//\", block: {open: \"/*\", close: \"*/\"}}\n }\n };\n};\n\nexport const verilog = mkVerilog({})\n\n// TL-Verilog mode.\n// See tl-x.org for language spec.\n// See the mode in action at makerchip.com.\n// Contact: steve.hoover@redwoodeda.com\n\n// TLV Identifier prefixes.\n// Note that sign is not treated separately, so \"+/-\" versions of numeric identifiers\n// are included.\nvar tlvIdentifierStyle = {\n \"|\": \"link\",\n \">\": \"property\", // Should condition this off for > TLV 1c.\n \"$\": \"variable\",\n \"$$\": \"variable\",\n \"?$\": \"qualifier\",\n \"?*\": \"qualifier\",\n \"-\": \"contentSeparator\",\n \"/\": \"property\",\n \"/-\": \"property\",\n \"@\": \"variableName.special\",\n \"@-\": \"variableName.special\",\n \"@++\": \"variableName.special\",\n \"@+=\": \"variableName.special\",\n \"@+=-\": \"variableName.special\",\n \"@--\": \"variableName.special\",\n \"@-=\": \"variableName.special\",\n \"%+\": \"tag\",\n \"%-\": \"tag\",\n \"%\": \"tag\",\n \">>\": \"tag\",\n \"<<\": \"tag\",\n \"<>\": \"tag\",\n \"#\": \"tag\", // Need to choose a style for this.\n \"^\": \"attribute\",\n \"^^\": \"attribute\",\n \"^!\": \"attribute\",\n \"*\": \"variable\",\n \"**\": \"variable\",\n \"\\\\\": \"keyword\",\n \"\\\"\": \"comment\"\n};\n\n// Lines starting with these characters define scope (result in indentation).\nvar tlvScopePrefixChars = {\n \"/\": \"beh-hier\",\n \">\": \"beh-hier\",\n \"-\": \"phys-hier\",\n \"|\": \"pipe\",\n \"?\": \"when\",\n \"@\": \"stage\",\n \"\\\\\": \"keyword\"\n};\nvar tlvIndentUnit = 3;\nvar tlvTrackStatements = false;\nvar tlvIdentMatch = /^([~!@#\\$%\\^&\\*-\\+=\\?\\/\\\\\\|'\"<>]+)([\\d\\w_]*)/; // Matches an identifier.\n// Note that ':' is excluded, because of it's use in [:].\nvar tlvLineIndentationMatch = /^[! ] */;\nvar tlvCommentMatch = /^\\/[\\/\\*]/;\n\nexport const tlv = mkVerilog({\n hooks: {\n electricInput: false,\n\n // Return undefined for verilog tokenizing, or style for TLV token (null not used).\n // Standard CM styles are used for most formatting, but some TL-Verilog-specific highlighting\n // can be enabled with the definition of cm-tlv-* styles, including highlighting for:\n // - M4 tokens\n // - TLV scope indentation\n // - Statement delimitation (enabled by tlvTrackStatements)\n token: function(stream, state) {\n var style = undefined;\n var match; // Return value of pattern matches.\n\n // Set highlighting mode based on code region (TLV or SV).\n if (stream.sol() && ! state.tlvInBlockComment) {\n // Process region.\n if (stream.peek() == '\\\\') {\n style = \"def\";\n stream.skipToEnd();\n if (stream.string.match(/\\\\SV/)) {\n state.tlvCodeActive = false;\n } else if (stream.string.match(/\\\\TLV/)){\n state.tlvCodeActive = true;\n }\n }\n // Correct indentation in the face of a line prefix char.\n if (state.tlvCodeActive && stream.pos == 0 &&\n (state.indented == 0) && (match = stream.match(tlvLineIndentationMatch, false))) {\n state.indented = match[0].length;\n }\n\n // Compute indentation state:\n // o Auto indentation on next line\n // o Indentation scope styles\n var indented = state.indented;\n var depth = indented / tlvIndentUnit;\n if (depth <= state.tlvIndentationStyle.length) {\n // not deeper than current scope\n\n var blankline = stream.string.length == indented;\n var chPos = depth * tlvIndentUnit;\n if (chPos < stream.string.length) {\n var bodyString = stream.string.slice(chPos);\n var ch = bodyString[0];\n if (tlvScopePrefixChars[ch] && ((match = bodyString.match(tlvIdentMatch)) &&\n tlvIdentifierStyle[match[1]])) {\n // This line begins scope.\n // Next line gets indented one level.\n indented += tlvIndentUnit;\n // Style the next level of indentation (except non-region keyword identifiers,\n // which are statements themselves)\n if (!(ch == \"\\\\\" && chPos > 0)) {\n state.tlvIndentationStyle[depth] = tlvScopePrefixChars[ch];\n if (tlvTrackStatements) {state.statementComment = false;}\n depth++;\n }\n }\n }\n // Clear out deeper indentation levels unless line is blank.\n if (!blankline) {\n while (state.tlvIndentationStyle.length > depth) {\n state.tlvIndentationStyle.pop();\n }\n }\n }\n // Set next level of indentation.\n state.tlvNextIndent = indented;\n }\n\n if (state.tlvCodeActive) {\n // Highlight as TLV.\n\n var beginStatement = false;\n if (tlvTrackStatements) {\n // This starts a statement if the position is at the scope level\n // and we're not within a statement leading comment.\n beginStatement =\n (stream.peek() != \" \") && // not a space\n (style === undefined) && // not a region identifier\n !state.tlvInBlockComment && // not in block comment\n //!stream.match(tlvCommentMatch, false) && // not comment start\n (stream.column() == state.tlvIndentationStyle.length * tlvIndentUnit); // at scope level\n if (beginStatement) {\n if (state.statementComment) {\n // statement already started by comment\n beginStatement = false;\n }\n state.statementComment =\n stream.match(tlvCommentMatch, false); // comment start\n }\n }\n\n var match;\n if (style !== undefined) {\n } else if (state.tlvInBlockComment) {\n // In a block comment.\n if (stream.match(/^.*?\\*\\//)) {\n // Exit block comment.\n state.tlvInBlockComment = false;\n if (tlvTrackStatements && !stream.eol()) {\n // Anything after comment is assumed to be real statement content.\n state.statementComment = false;\n }\n } else {\n stream.skipToEnd();\n }\n style = \"comment\";\n } else if ((match = stream.match(tlvCommentMatch)) && !state.tlvInBlockComment) {\n // Start comment.\n if (match[0] == \"//\") {\n // Line comment.\n stream.skipToEnd();\n } else {\n // Block comment.\n state.tlvInBlockComment = true;\n }\n style = \"comment\";\n } else if (match = stream.match(tlvIdentMatch)) {\n // looks like an identifier (or identifier prefix)\n var prefix = match[1];\n var mnemonic = match[2];\n if (// is identifier prefix\n tlvIdentifierStyle.hasOwnProperty(prefix) &&\n // has mnemonic or we're at the end of the line (maybe it hasn't been typed yet)\n (mnemonic.length > 0 || stream.eol())) {\n style = tlvIdentifierStyle[prefix];\n } else {\n // Just swallow one character and try again.\n // This enables subsequent identifier match with preceding symbol character, which\n // is legal within a statement. (Eg, !$reset). It also enables detection of\n // comment start with preceding symbols.\n stream.backUp(stream.current().length - 1);\n }\n } else if (stream.match(/^\\t+/)) {\n // Highlight tabs, which are illegal.\n style = \"invalid\";\n } else if (stream.match(/^[\\[\\]{}\\(\\);\\:]+/)) {\n // [:], (), {}, ;.\n style = \"meta\";\n } else if (match = stream.match(/^[mM]4([\\+_])?[\\w\\d_]*/)) {\n // m4 pre proc\n style = (match[1] == \"+\") ? \"keyword.special\" : \"keyword\";\n } else if (stream.match(/^ +/)){\n // Skip over spaces.\n if (stream.eol()) {\n // Trailing spaces.\n style = \"error\";\n }\n } else if (stream.match(/^[\\w\\d_]+/)) {\n // alpha-numeric token.\n style = \"number\";\n } else {\n // Eat the next char w/ no formatting.\n stream.next();\n }\n } else {\n if (stream.match(/^[mM]4([\\w\\d_]*)/)) {\n // m4 pre proc\n style = \"keyword\";\n }\n }\n return style;\n },\n\n indent: function(state) {\n return (state.tlvCodeActive == true) ? state.tlvNextIndent : -1;\n },\n\n startState: function(state) {\n state.tlvIndentationStyle = []; // Styles to use for each level of indentation.\n state.tlvCodeActive = true; // True when we're in a TLV region (and at beginning of file).\n state.tlvNextIndent = -1; // The number of spaces to autoindent the next line if tlvCodeActive.\n state.tlvInBlockComment = false; // True inside /**/ comment.\n if (tlvTrackStatements) {\n state.statementComment = false; // True inside a statement's header comment.\n }\n }\n\n }\n});\n"],"names":["mkVerilog","parserConfig","statementIndentUnit","dontAlignCalls","noIndentKeywords","multiLineStrings","hooks","words","str","obj","split","i","length","curPunc","curKeyword","keywords","isOperatorChar","isBracketChar","unsignedNumber","decimalLiteral","binaryLiteral","octLiteral","hexLiteral","realLiteral","closingBracketOrWord","closingBracket","blockKeywords","openClose","keyword","undefined","statementKeywords","tokenBase","stream","state","style","quote","ch","peek","test","next","eatWhile","tokenize","escaped","end","eat","tokenComment","skipToEnd","backUp","match","cur","current","maybeEnd","Context","indented","column","type","align","prev","this","pushContext","col","c","context","popContext","t","isClosing","text","contextClosing","closingKeywords","name","startState","indentUnit","startOfLine","token","ctx","sol","indentation","eatSpace","close","indent","textAfter","cx","fromHook","firstChar","charAt","closing","possibleClosing","unit","languageData","indentOnInput","allClosings","closings","j","push","RegExp","join","buildElectricInputRegEx","commentTokens","line","block","open","verilog","tlvIdentifierStyle","tlvScopePrefixChars","tlvIdentMatch","tlvLineIndentationMatch","tlvCommentMatch","tlv","electricInput","tlvInBlockComment","string","tlvCodeActive","pos","depth","tlvIndentationStyle","blankline","chPos","bodyString","slice","pop","tlvNextIndent","prefix","mnemonic","hasOwnProperty","eol"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/6535.index.js b/book/_build/html/_static/6535.index.js new file mode 100644 index 0000000..0f71356 --- /dev/null +++ b/book/_build/html/_static/6535.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[6535],{6535:(e,t,a)=>{function n(e){return new RegExp("^(?:"+e.join("|")+")$","i")}a.r(t),a.d(t,{lua:()=>m});var r=n(["_G","_VERSION","assert","collectgarbage","dofile","error","getfenv","getmetatable","ipairs","load","loadfile","loadstring","module","next","pairs","pcall","print","rawequal","rawget","rawset","require","select","setfenv","setmetatable","tonumber","tostring","type","unpack","xpcall","coroutine.create","coroutine.resume","coroutine.running","coroutine.status","coroutine.wrap","coroutine.yield","debug.debug","debug.getfenv","debug.gethook","debug.getinfo","debug.getlocal","debug.getmetatable","debug.getregistry","debug.getupvalue","debug.setfenv","debug.sethook","debug.setlocal","debug.setmetatable","debug.setupvalue","debug.traceback","close","flush","lines","read","seek","setvbuf","write","io.close","io.flush","io.input","io.lines","io.open","io.output","io.popen","io.read","io.stderr","io.stdin","io.stdout","io.tmpfile","io.type","io.write","math.abs","math.acos","math.asin","math.atan","math.atan2","math.ceil","math.cos","math.cosh","math.deg","math.exp","math.floor","math.fmod","math.frexp","math.huge","math.ldexp","math.log","math.log10","math.max","math.min","math.modf","math.pi","math.pow","math.rad","math.random","math.randomseed","math.sin","math.sinh","math.sqrt","math.tan","math.tanh","os.clock","os.date","os.difftime","os.execute","os.exit","os.getenv","os.remove","os.rename","os.setlocale","os.time","os.tmpname","package.cpath","package.loaded","package.loaders","package.loadlib","package.path","package.preload","package.seeall","string.byte","string.char","string.dump","string.find","string.format","string.gmatch","string.gsub","string.len","string.lower","string.match","string.rep","string.reverse","string.sub","string.upper","table.concat","table.insert","table.maxn","table.remove","table.sort"]),o=n(["and","break","elseif","false","nil","not","or","return","true","function","end","if","then","else","do","while","repeat","until","for","in","local"]),i=n(["function","if","repeat","do","\\(","{"]),s=n(["end","until","\\)","}"]),l=new RegExp("^(?:"+["end","until","\\)","}","else","elseif"].join("|")+")","i");function u(e){for(var t=0;e.eat("=");)++t;return e.eat("["),t}function c(e,t){var a,n=e.next();return"-"==n&&e.eat("-")?e.eat("[")&&e.eat("[")?(t.cur=g(u(e),"comment"))(e,t):(e.skipToEnd(),"comment"):'"'==n||"'"==n?(t.cur=(a=n,function(e,t){for(var n,r=!1;null!=(n=e.next())&&(n!=a||r);)r=!r&&"\\"==n;return r||(t.cur=c),"string"}))(e,t):"["==n&&/[\[=]/.test(e.peek())?(t.cur=g(u(e),"string"))(e,t):/\d/.test(n)?(e.eatWhile(/[\w.%]/),"number"):/[\w_]/.test(n)?(e.eatWhile(/[\w\\\-_.]/),"variable"):null}function g(e,t){return function(a,n){for(var r,o=null;null!=(r=a.next());)if(null==o)"]"==r&&(o=0);else if("="==r)++o;else{if("]"==r&&o==e){n.cur=c;break}o=null}return t}}const m={name:"lua",startState:function(){return{basecol:0,indentDepth:0,cur:c}},token:function(e,t){if(e.eatSpace())return null;var a=t.cur(e,t),n=e.current();return"variable"==a&&(o.test(n)?a="keyword":r.test(n)&&(a="builtin")),"comment"!=a&&"string"!=a&&(i.test(n)?++t.indentDepth:s.test(n)&&--t.indentDepth),a},indent:function(e,t,a){var n=l.test(t);return e.basecol+a.unit*(e.indentDepth-(n?1:0))},languageData:{indentOnInput:/^\s*(?:end|until|else|\)|\})$/,commentTokens:{line:"--",block:{open:"--[[",close:"]]--"}}}}}}]); +//# sourceMappingURL=6535.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/6535.index.js.map b/book/_build/html/_static/6535.index.js.map new file mode 100644 index 0000000..7e579d5 --- /dev/null +++ b/book/_build/html/_static/6535.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"6535.index.js","mappings":"8FAGA,SAASA,EAAOC,GACd,OAAO,IAAIC,OAAO,OAASD,EAAME,KAAK,KAAO,KAAM,IACrD,C,0BAGA,IAAIC,EAAWJ,EAAO,CACpB,K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B,EAAQI,GACtB,GAAIJ,EAAOuB,WAAY,OAAO,KAC9B,IAAIR,EAAQX,EAAMI,IAAIR,EAAQI,GAC1BoB,EAAOxB,EAAOyB,UASlB,MARa,YAATV,IACEpB,EAASiB,KAAKY,GAAOT,EAAQ,UACxBrB,EAASkB,KAAKY,KAAOT,EAAQ,YAE1B,WAATA,GAAiC,UAATA,IACvBnB,EAAagB,KAAKY,KAASpB,EAAMiB,YAC5BxB,EAAae,KAAKY,MAASpB,EAAMiB,aAErCN,CACT,EAEAW,OAAQ,SAAStB,EAAOuB,EAAWC,GACjC,IAAIC,EAAU/B,EAAcc,KAAKe,GACjC,OAAOvB,EAAMgB,QAAUQ,EAAGE,MAAQ1B,EAAMiB,aAAeQ,EAAU,EAAI,GACvE,EAEAE,aAAc,CACZC,cAAe,gCACfC,cAAe,CAACC,KAAM,KAAMC,MAAO,CAACC,KAAM,OAAQC,MAAO,U","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/lua.js"],"sourcesContent":["function prefixRE(words) {\n return new RegExp(\"^(?:\" + words.join(\"|\") + \")\", \"i\");\n}\nfunction wordRE(words) {\n return new RegExp(\"^(?:\" + words.join(\"|\") + \")$\", \"i\");\n}\n\n// long list of standard functions from lua manual\nvar builtins = wordRE([\n \"_G\",\"_VERSION\",\"assert\",\"collectgarbage\",\"dofile\",\"error\",\"getfenv\",\"getmetatable\",\"ipairs\",\"load\",\n \"loadfile\",\"loadstring\",\"module\",\"next\",\"pairs\",\"pcall\",\"print\",\"rawequal\",\"rawget\",\"rawset\",\"require\",\n \"select\",\"setfenv\",\"setmetatable\",\"tonumber\",\"tostring\",\"type\",\"unpack\",\"xpcall\",\n\n \"coroutine.create\",\"coroutine.resume\",\"coroutine.running\",\"coroutine.status\",\"coroutine.wrap\",\"coroutine.yield\",\n\n \"debug.debug\",\"debug.getfenv\",\"debug.gethook\",\"debug.getinfo\",\"debug.getlocal\",\"debug.getmetatable\",\n \"debug.getregistry\",\"debug.getupvalue\",\"debug.setfenv\",\"debug.sethook\",\"debug.setlocal\",\"debug.setmetatable\",\n \"debug.setupvalue\",\"debug.traceback\",\n\n \"close\",\"flush\",\"lines\",\"read\",\"seek\",\"setvbuf\",\"write\",\n\n \"io.close\",\"io.flush\",\"io.input\",\"io.lines\",\"io.open\",\"io.output\",\"io.popen\",\"io.read\",\"io.stderr\",\"io.stdin\",\n \"io.stdout\",\"io.tmpfile\",\"io.type\",\"io.write\",\n\n \"math.abs\",\"math.acos\",\"math.asin\",\"math.atan\",\"math.atan2\",\"math.ceil\",\"math.cos\",\"math.cosh\",\"math.deg\",\n \"math.exp\",\"math.floor\",\"math.fmod\",\"math.frexp\",\"math.huge\",\"math.ldexp\",\"math.log\",\"math.log10\",\"math.max\",\n \"math.min\",\"math.modf\",\"math.pi\",\"math.pow\",\"math.rad\",\"math.random\",\"math.randomseed\",\"math.sin\",\"math.sinh\",\n \"math.sqrt\",\"math.tan\",\"math.tanh\",\n\n \"os.clock\",\"os.date\",\"os.difftime\",\"os.execute\",\"os.exit\",\"os.getenv\",\"os.remove\",\"os.rename\",\"os.setlocale\",\n \"os.time\",\"os.tmpname\",\n\n \"package.cpath\",\"package.loaded\",\"package.loaders\",\"package.loadlib\",\"package.path\",\"package.preload\",\n \"package.seeall\",\n\n \"string.byte\",\"string.char\",\"string.dump\",\"string.find\",\"string.format\",\"string.gmatch\",\"string.gsub\",\n \"string.len\",\"string.lower\",\"string.match\",\"string.rep\",\"string.reverse\",\"string.sub\",\"string.upper\",\n\n \"table.concat\",\"table.insert\",\"table.maxn\",\"table.remove\",\"table.sort\"\n]);\nvar keywords = wordRE([\"and\",\"break\",\"elseif\",\"false\",\"nil\",\"not\",\"or\",\"return\",\n \"true\",\"function\", \"end\", \"if\", \"then\", \"else\", \"do\",\n \"while\", \"repeat\", \"until\", \"for\", \"in\", \"local\" ]);\n\nvar indentTokens = wordRE([\"function\", \"if\",\"repeat\",\"do\", \"\\\\(\", \"{\"]);\nvar dedentTokens = wordRE([\"end\", \"until\", \"\\\\)\", \"}\"]);\nvar dedentPartial = prefixRE([\"end\", \"until\", \"\\\\)\", \"}\", \"else\", \"elseif\"]);\n\nfunction readBracket(stream) {\n var level = 0;\n while (stream.eat(\"=\")) ++level;\n stream.eat(\"[\");\n return level;\n}\n\nfunction normal(stream, state) {\n var ch = stream.next();\n if (ch == \"-\" && stream.eat(\"-\")) {\n if (stream.eat(\"[\") && stream.eat(\"[\"))\n return (state.cur = bracketed(readBracket(stream), \"comment\"))(stream, state);\n stream.skipToEnd();\n return \"comment\";\n }\n if (ch == \"\\\"\" || ch == \"'\")\n return (state.cur = string(ch))(stream, state);\n if (ch == \"[\" && /[\\[=]/.test(stream.peek()))\n return (state.cur = bracketed(readBracket(stream), \"string\"))(stream, state);\n if (/\\d/.test(ch)) {\n stream.eatWhile(/[\\w.%]/);\n return \"number\";\n }\n if (/[\\w_]/.test(ch)) {\n stream.eatWhile(/[\\w\\\\\\-_.]/);\n return \"variable\";\n }\n return null;\n}\n\nfunction bracketed(level, style) {\n return function(stream, state) {\n var curlev = null, ch;\n while ((ch = stream.next()) != null) {\n if (curlev == null) {if (ch == \"]\") curlev = 0;}\n else if (ch == \"=\") ++curlev;\n else if (ch == \"]\" && curlev == level) { state.cur = normal; break; }\n else curlev = null;\n }\n return style;\n };\n}\n\nfunction string(quote) {\n return function(stream, state) {\n var escaped = false, ch;\n while ((ch = stream.next()) != null) {\n if (ch == quote && !escaped) break;\n escaped = !escaped && ch == \"\\\\\";\n }\n if (!escaped) state.cur = normal;\n return \"string\";\n };\n}\n\nexport const lua = {\n name: \"lua\",\n\n startState: function() {\n return {basecol: 0, indentDepth: 0, cur: normal};\n },\n\n token: function(stream, state) {\n if (stream.eatSpace()) return null;\n var style = state.cur(stream, state);\n var word = stream.current();\n if (style == \"variable\") {\n if (keywords.test(word)) style = \"keyword\";\n else if (builtins.test(word)) style = \"builtin\";\n }\n if ((style != \"comment\") && (style != \"string\")){\n if (indentTokens.test(word)) ++state.indentDepth;\n else if (dedentTokens.test(word)) --state.indentDepth;\n }\n return style;\n },\n\n indent: function(state, textAfter, cx) {\n var closing = dedentPartial.test(textAfter);\n return state.basecol + cx.unit * (state.indentDepth - (closing ? 1 : 0));\n },\n\n languageData: {\n indentOnInput: /^\\s*(?:end|until|else|\\)|\\})$/,\n commentTokens: {line: \"--\", block: {open: \"--[[\", close: \"]]--\"}}\n }\n};\n"],"names":["wordRE","words","RegExp","join","builtins","keywords","indentTokens","dedentTokens","dedentPartial","readBracket","stream","level","eat","normal","state","quote","ch","next","cur","bracketed","skipToEnd","escaped","test","peek","eatWhile","style","curlev","lua","name","startState","basecol","indentDepth","token","eatSpace","word","current","indent","textAfter","cx","closing","unit","languageData","indentOnInput","commentTokens","line","block","open","close"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/6551.index.js b/book/_build/html/_static/6551.index.js new file mode 100644 index 0000000..c3b03ce --- /dev/null +++ b/book/_build/html/_static/6551.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[6551],{91757:(t,e,n)=>{var o;function r(t){return new RegExp("^(?:"+t.join("|")+")$","i")}n.r(e),n.d(e,{turtle:()=>p}),r([]);var c=r(["@prefix","@base","a"]),i=/[*+\-<>=&|]/;function a(t,e){var n,r=t.next();if(o=null,"<"!=r||t.match(/^[\s\u00a0=]/,!1)){if('"'==r||"'"==r)return e.tokenize=(n=r,function(t,e){for(var o,r=!1;null!=(o=t.next());){if(o==n&&!r){e.tokenize=a;break}r=!r&&"\\"==o}return"string"}),e.tokenize(t,e);if(/[{}\(\),\.;\[\]]/.test(r))return o=r,null;if("#"==r)return t.skipToEnd(),"comment";if(i.test(r))return t.eatWhile(i),null;if(":"==r)return"operator";if(t.eatWhile(/[_\w\d]/),":"==t.peek())return"variableName.special";var l=t.current();return c.test(l)?"meta":r>="A"&&r<="Z"?"comment":"keyword"}return t.match(/^[^\s\u00a0>]*>?/),"atom"}function l(t,e,n){t.context={prev:t.context,indent:t.indent,col:n,type:e}}function u(t){t.indent=t.context.indent,t.context=t.context.prev}const p={name:"turtle",startState:function(){return{tokenize:a,context:null,indent:0,col:0}},token:function(t,e){if(t.sol()&&(e.context&&null==e.context.align&&(e.context.align=!1),e.indent=t.indentation()),t.eatSpace())return null;var n=e.tokenize(t,e);if("comment"!=n&&e.context&&null==e.context.align&&"pattern"!=e.context.type&&(e.context.align=!0),"("==o)l(e,")",t.column());else if("["==o)l(e,"]",t.column());else if("{"==o)l(e,"}",t.column());else if(/[\]\}\)]/.test(o)){for(;e.context&&"pattern"==e.context.type;)u(e);e.context&&o==e.context.type&&u(e)}else"."==o&&e.context&&"pattern"==e.context.type?u(e):/atom|string|variable/.test(n)&&e.context&&(/[\}\]]/.test(e.context.type)?l(e,"pattern",t.column()):"pattern"!=e.context.type||e.context.align||(e.context.align=!0,e.context.col=t.column()));return n},indent:function(t,e,n){var o=e&&e.charAt(0),r=t.context;if(/[\]\}]/.test(o))for(;r&&"pattern"==r.type;)r=r.prev;var c=r&&o==r.type;return r?"pattern"==r.type?r.col:r.align?r.col+(c?0:1):r.indent+(c?0:n.unit):0},languageData:{commentTokens:{line:"#"}}}}}]); +//# sourceMappingURL=6551.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/6551.index.js.map b/book/_build/html/_static/6551.index.js.map new file mode 100644 index 0000000..19ba5bf --- /dev/null +++ b/book/_build/html/_static/6551.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"6551.index.js","mappings":"+FAAA,IAAIA,EAEJ,SAASC,EAAWC,GAClB,OAAO,IAAIC,OAAO,OAASD,EAAME,KAAK,KAAO,KAAM,IACrD,C,6BACUH,EAAW,IAArB,IACII,EAAWJ,EAAW,CAAC,UAAW,QAAS,MAC3CK,EAAgB,cAEpB,SAASC,EAAUC,EAAQC,GACzB,IAmDoBC,EAnDhBC,EAAKH,EAAOI,OAEhB,GADAZ,EAAU,KACA,KAANW,GAAcH,EAAOK,MAAM,gBAAgB,GAI1C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AAUgB,EAAU,EAAIH,EAAGI,MANnC,CAOX,EAEAC,aAAc,CACZC,cAAe,CAACC,KAAM,M","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/turtle.js"],"sourcesContent":["var curPunc;\n\nfunction wordRegexp(words) {\n return new RegExp(\"^(?:\" + words.join(\"|\") + \")$\", \"i\");\n}\nvar ops = wordRegexp([]);\nvar keywords = wordRegexp([\"@prefix\", \"@base\", \"a\"]);\nvar operatorChars = /[*+\\-<>=&|]/;\n\nfunction tokenBase(stream, state) {\n var ch = stream.next();\n curPunc = null;\n if (ch == \"<\" && !stream.match(/^[\\s\\u00a0=]/, false)) {\n stream.match(/^[^\\s\\u00a0>]*>?/);\n return \"atom\";\n }\n else if (ch == \"\\\"\" || ch == \"'\") {\n state.tokenize = tokenLiteral(ch);\n return state.tokenize(stream, state);\n }\n else if (/[{}\\(\\),\\.;\\[\\]]/.test(ch)) {\n curPunc = ch;\n return null;\n }\n else if (ch == \"#\") {\n stream.skipToEnd();\n return \"comment\";\n }\n else if (operatorChars.test(ch)) {\n stream.eatWhile(operatorChars);\n return null;\n }\n else if (ch == \":\") {\n return \"operator\";\n } else {\n stream.eatWhile(/[_\\w\\d]/);\n if(stream.peek() == \":\") {\n return \"variableName.special\";\n } else {\n var word = stream.current();\n\n if(keywords.test(word)) {\n return \"meta\";\n }\n\n if(ch >= \"A\" && ch <= \"Z\") {\n return \"comment\";\n } else {\n return \"keyword\";\n }\n }\n var word = stream.current();\n if (ops.test(word))\n return null;\n else if (keywords.test(word))\n return \"meta\";\n else\n return \"variable\";\n }\n}\n\nfunction tokenLiteral(quote) {\n return function(stream, state) {\n var escaped = false, ch;\n while ((ch = stream.next()) != null) {\n if (ch == quote && !escaped) {\n state.tokenize = tokenBase;\n break;\n }\n escaped = !escaped && ch == \"\\\\\";\n }\n return \"string\";\n };\n}\n\nfunction pushContext(state, type, col) {\n state.context = {prev: state.context, indent: state.indent, col: col, type: type};\n}\nfunction popContext(state) {\n state.indent = state.context.indent;\n state.context = state.context.prev;\n}\n\nexport const turtle = {\n name: \"turtle\",\n startState: function() {\n return {tokenize: tokenBase,\n context: null,\n indent: 0,\n col: 0};\n },\n\n token: function(stream, state) {\n if (stream.sol()) {\n if (state.context && state.context.align == null) state.context.align = false;\n state.indent = stream.indentation();\n }\n if (stream.eatSpace()) return null;\n var style = state.tokenize(stream, state);\n\n if (style != \"comment\" && state.context && state.context.align == null && state.context.type != \"pattern\") {\n state.context.align = true;\n }\n\n if (curPunc == \"(\") pushContext(state, \")\", stream.column());\n else if (curPunc == \"[\") pushContext(state, \"]\", stream.column());\n else if (curPunc == \"{\") pushContext(state, \"}\", stream.column());\n else if (/[\\]\\}\\)]/.test(curPunc)) {\n while (state.context && state.context.type == \"pattern\") popContext(state);\n if (state.context && curPunc == state.context.type) popContext(state);\n }\n else if (curPunc == \".\" && state.context && state.context.type == \"pattern\") popContext(state);\n else if (/atom|string|variable/.test(style) && state.context) {\n if (/[\\}\\]]/.test(state.context.type))\n pushContext(state, \"pattern\", stream.column());\n else if (state.context.type == \"pattern\" && !state.context.align) {\n state.context.align = true;\n state.context.col = stream.column();\n }\n }\n\n return style;\n },\n\n indent: function(state, textAfter, cx) {\n var firstChar = textAfter && textAfter.charAt(0);\n var context = state.context;\n if (/[\\]\\}]/.test(firstChar))\n while (context && context.type == \"pattern\") context = context.prev;\n\n var closing = context && firstChar == context.type;\n if (!context)\n return 0;\n else if (context.type == \"pattern\")\n return context.col;\n else if (context.align)\n return context.col + (closing ? 0 : 1);\n else\n return context.indent + (closing ? 0 : cx.unit);\n },\n\n languageData: {\n commentTokens: {line: \"#\"}\n }\n};\n"],"names":["curPunc","wordRegexp","words","RegExp","join","keywords","operatorChars","tokenBase","stream","state","quote","ch","next","match","tokenize","escaped","test","skipToEnd","eatWhile","peek","word","current","pushContext","type","col","context","prev","indent","popContext","turtle","name","startState","token","sol","align","indentation","eatSpace","style","column","textAfter","cx","firstChar","charAt","closing","unit","languageData","commentTokens","line"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/6570.index.js b/book/_build/html/_static/6570.index.js new file mode 100644 index 0000000..744971f --- /dev/null +++ b/book/_build/html/_static/6570.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[6570],{36570:(e,t,n)=>{function r(e){for(var t={},n=0;nA});var i=r(["_","var","let","actor","class","enum","extension","import","protocol","struct","func","typealias","associatedtype","open","public","internal","fileprivate","private","deinit","init","new","override","self","subscript","super","convenience","dynamic","final","indirect","lazy","required","static","unowned","unowned(safe)","unowned(unsafe)","weak","as","is","break","case","continue","default","else","fallthrough","for","guard","if","in","repeat","switch","where","while","defer","return","inout","mutating","nonmutating","isolated","nonisolated","catch","do","rethrows","throw","throws","async","await","try","didSet","get","set","willSet","assignment","associativity","infix","left","none","operator","postfix","precedence","precedencegroup","prefix","right","Any","AnyObject","Type","dynamicType","Self","Protocol","__COLUMN__","__FILE__","__FUNCTION__","__LINE__"]),a=r(["var","let","actor","class","enum","extension","import","protocol","struct","func","typealias","associatedtype","for"]),o=r(["true","false","nil","self","super","_"]),u=r(["Array","Bool","Character","Dictionary","Double","Float","Int","Int8","Int16","Int32","Int64","Never","Optional","Set","String","UInt8","UInt16","UInt32","UInt64","Void"]),c="+-/*%=|&<>~^?!",s=":;,.(){}[]",f=/^\-?0b[01][01_]*/,l=/^\-?0o[0-7][0-7_]*/,p=/^\-?0x[\dA-Fa-f][\dA-Fa-f_]*(?:(?:\.[\dA-Fa-f][\dA-Fa-f_]*)?[Pp]\-?\d[\d_]*)?/,d=/^\-?\d[\d_]*(?:\.\d[\d_]*)?(?:[Ee]\-?\d[\d_]*)?/,h=/^\$\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\1/,m=/^\.(?:\$\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\1)/,v=/^\#[A-Za-z]+/,_=/^@(?:\$\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\1)/;function k(e,t,n){if(e.sol()&&(t.indented=e.indentation()),e.eatSpace())return null;var r,k=e.peek();if("/"==k){if(e.match("//"))return e.skipToEnd(),"comment";if(e.match("/*"))return t.tokenize.push(y),y(e,t)}if(e.match(v))return"builtin";if(e.match(_))return"attribute";if(e.match(f))return"number";if(e.match(l))return"number";if(e.match(p))return"number";if(e.match(d))return"number";if(e.match(m))return"property";if(c.indexOf(k)>-1)return e.next(),"operator";if(s.indexOf(k)>-1)return e.next(),e.match(".."),"punctuation";if(r=e.match(/("""|"|')/)){var w=x.bind(null,r[0]);return t.tokenize.push(w),w(e,t)}if(e.match(h)){var b=e.current();return u.hasOwnProperty(b)?"type":o.hasOwnProperty(b)?"atom":i.hasOwnProperty(b)?(a.hasOwnProperty(b)&&(t.prev="define"),"keyword"):"define"==n?"def":"variable"}return e.next(),null}function w(){var e=0;return function(t,n,r){var i=k(t,n,r);if("punctuation"==i)if("("==t.current())++e;else if(")"==t.current()){if(0==e)return t.backUp(1),n.tokenize.pop(),n.tokenize[n.tokenize.length-1](t,n);--e}return i}}function x(e,t,n){for(var r,i=1==e.length,a=!1;r=t.peek();)if(a){if(t.next(),"("==r)return n.tokenize.push(w()),"string";a=!1}else{if(t.match(e))return n.tokenize.pop(),"string";t.next(),a="\\"==r}return i&&n.tokenize.pop(),"string"}function y(e,t){for(var n;n=e.next();)if("/"===n&&e.eat("*"))t.tokenize.push(y);else if("*"===n&&e.eat("/")){t.tokenize.pop();break}return"comment"}function b(e,t,n){this.prev=e,this.align=t,this.indented=n}function g(e,t){var n=t.match(/^\s*($|\/[\/\*]|[)}\]])/,!1)?null:t.column()+1;e.context=new b(e.context,n,e.indented)}function z(e){e.context&&(e.indented=e.context.indented,e.context=e.context.prev)}const A={name:"swift",startState:function(){return{prev:null,context:null,indented:0,tokenize:[]}},token:function(e,t){var n=t.prev;t.prev=null;var r=(t.tokenize[t.tokenize.length-1]||k)(e,t,n);if(r&&"comment"!=r?t.prev||(t.prev=r):t.prev=n,"punctuation"==r){var i=/[\(\[\{]|([\]\)\}])/.exec(e.current());i&&(i[1]?z:g)(t,e)}return r},indent:function(e,t,n){var r=e.context;if(!r)return 0;var i=/^[\]\}\)]/.test(t);return null!=r.align?r.align-(i?1:0):r.indented+(i?0:n.unit)},languageData:{indentOnInput:/^\s*[\)\}\]]$/,commentTokens:{line:"//",block:{open:"/*",close:"*/"}},closeBrackets:{brackets:["(","[","{","'",'"',"`"]}}}}}]); +//# sourceMappingURL=6570.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/6570.index.js.map b/book/_build/html/_static/6570.index.js.map new file mode 100644 index 0000000..24d5425 --- /dev/null +++ b/book/_build/html/_static/6570.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"6570.index.js","mappings":"+FAAA,SAASA,EAAQC,GAEf,IADA,IAAIC,EAAM,CAAC,EACFC,EAAI,EAAGA,EAAIF,EAAMG,OAAQD,IAAKD,EAAID,EAAME,KAAM,EACvD,OAAOD,CACT,C,4BAEA,IAAIG,EAAWL,EAAQ,CAAC,IAAI,MAAM,MAAM,QAAQ,QAAQ,OAAO,YAAY,SAAS,WAAW,SAAS,OAAO,YAAY,iBACnG,OAAO,SAAS,WAAW,cAAc,UAAU,SAAS,OAAO,MAAM,WAAW,OAAO,YAAY,QACvG,cAAc,UAAU,QAAQ,WAAW,OAAO,WAAW,SAAS,UAAU,gBAAgB,kBAAkB,OAAO,KAAK,KAC9H,QAAQ,OAAO,WAAW,UAAU,OAAO,cAAc,MAAM,QAAQ,KAAK,KAAK,SAAS,SAAS,QAAQ,QAC3G,QAAQ,SAAS,QAAQ,WAAW,cAAc,WAAW,cAAc,QAAQ,KAAK,WAAW,QAAQ,SAAS,QAAQ,QAAQ,MAAM,SAAS,MAAM,MAAM,UAC/J,aAAa,gBAAgB,QAAQ,OAAO,OAAO,WAAW,UAAU,aAAa,kBAAkB,SAAS,QAChH,MAAM,YAAY,OAAO,cAAc,OAAO,WAAW,aAAa,WAAW,eAAe,aACpHM,EAAmBN,EAAQ,CA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AY6C,EAAU,EAAIF,EAAII,KAC1C,EAEAC,aAAc,CACZC,cAAe,gBACfC,cAAe,CAACC,KAAM,KAAMC,MAAO,CAACC,KAAM,KAAMC,MAAO,OACvDC,cAAe,CAACC,SAAU,CAAC,IAAK,IAAK,IAAK,IAAK,IAAK,O","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/swift.js"],"sourcesContent":["function wordSet(words) {\n var set = {}\n for (var i = 0; i < words.length; i++) set[words[i]] = true\n return set\n}\n\nvar keywords = wordSet([\"_\",\"var\",\"let\",\"actor\",\"class\",\"enum\",\"extension\",\"import\",\"protocol\",\"struct\",\"func\",\"typealias\",\"associatedtype\",\n \"open\",\"public\",\"internal\",\"fileprivate\",\"private\",\"deinit\",\"init\",\"new\",\"override\",\"self\",\"subscript\",\"super\",\n \"convenience\",\"dynamic\",\"final\",\"indirect\",\"lazy\",\"required\",\"static\",\"unowned\",\"unowned(safe)\",\"unowned(unsafe)\",\"weak\",\"as\",\"is\",\n \"break\",\"case\",\"continue\",\"default\",\"else\",\"fallthrough\",\"for\",\"guard\",\"if\",\"in\",\"repeat\",\"switch\",\"where\",\"while\",\n \"defer\",\"return\",\"inout\",\"mutating\",\"nonmutating\",\"isolated\",\"nonisolated\",\"catch\",\"do\",\"rethrows\",\"throw\",\"throws\",\"async\",\"await\",\"try\",\"didSet\",\"get\",\"set\",\"willSet\",\n \"assignment\",\"associativity\",\"infix\",\"left\",\"none\",\"operator\",\"postfix\",\"precedence\",\"precedencegroup\",\"prefix\",\"right\",\n \"Any\",\"AnyObject\",\"Type\",\"dynamicType\",\"Self\",\"Protocol\",\"__COLUMN__\",\"__FILE__\",\"__FUNCTION__\",\"__LINE__\"])\nvar definingKeywords = wordSet([\"var\",\"let\",\"actor\",\"class\",\"enum\",\"extension\",\"import\",\"protocol\",\"struct\",\"func\",\"typealias\",\"associatedtype\",\"for\"])\nvar atoms = wordSet([\"true\",\"false\",\"nil\",\"self\",\"super\",\"_\"])\nvar types = wordSet([\"Array\",\"Bool\",\"Character\",\"Dictionary\",\"Double\",\"Float\",\"Int\",\"Int8\",\"Int16\",\"Int32\",\"Int64\",\"Never\",\"Optional\",\"Set\",\"String\",\n \"UInt8\",\"UInt16\",\"UInt32\",\"UInt64\",\"Void\"])\nvar operators = \"+-/*%=|&<>~^?!\"\nvar punc = \":;,.(){}[]\"\nvar binary = /^\\-?0b[01][01_]*/\nvar octal = /^\\-?0o[0-7][0-7_]*/\nvar hexadecimal = /^\\-?0x[\\dA-Fa-f][\\dA-Fa-f_]*(?:(?:\\.[\\dA-Fa-f][\\dA-Fa-f_]*)?[Pp]\\-?\\d[\\d_]*)?/\nvar decimal = /^\\-?\\d[\\d_]*(?:\\.\\d[\\d_]*)?(?:[Ee]\\-?\\d[\\d_]*)?/\nvar identifier = /^\\$\\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\\1/\nvar property = /^\\.(?:\\$\\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\\1)/\nvar instruction = /^\\#[A-Za-z]+/\nvar attribute = /^@(?:\\$\\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\\1)/\n//var regexp = /^\\/(?!\\s)(?:\\/\\/)?(?:\\\\.|[^\\/])+\\//\n\nfunction tokenBase(stream, state, prev) {\n if (stream.sol()) state.indented = stream.indentation()\n if (stream.eatSpace()) return null\n\n var ch = stream.peek()\n if (ch == \"/\") {\n if (stream.match(\"//\")) {\n stream.skipToEnd()\n return \"comment\"\n }\n if (stream.match(\"/*\")) {\n state.tokenize.push(tokenComment)\n return tokenComment(stream, state)\n }\n }\n if (stream.match(instruction)) return \"builtin\"\n if (stream.match(attribute)) return \"attribute\"\n if (stream.match(binary)) return \"number\"\n if (stream.match(octal)) return \"number\"\n if (stream.match(hexadecimal)) return \"number\"\n if (stream.match(decimal)) return \"number\"\n if (stream.match(property)) return \"property\"\n if (operators.indexOf(ch) > -1) {\n stream.next()\n return \"operator\"\n }\n if (punc.indexOf(ch) > -1) {\n stream.next()\n stream.match(\"..\")\n return \"punctuation\"\n }\n var stringMatch\n if (stringMatch = stream.match(/(\"\"\"|\"|')/)) {\n var tokenize = tokenString.bind(null, stringMatch[0])\n state.tokenize.push(tokenize)\n return tokenize(stream, state)\n }\n\n if (stream.match(identifier)) {\n var ident = stream.current()\n if (types.hasOwnProperty(ident)) return \"type\"\n if (atoms.hasOwnProperty(ident)) return \"atom\"\n if (keywords.hasOwnProperty(ident)) {\n if (definingKeywords.hasOwnProperty(ident))\n state.prev = \"define\"\n return \"keyword\"\n }\n if (prev == \"define\") return \"def\"\n return \"variable\"\n }\n\n stream.next()\n return null\n}\n\nfunction tokenUntilClosingParen() {\n var depth = 0\n return function(stream, state, prev) {\n var inner = tokenBase(stream, state, prev)\n if (inner == \"punctuation\") {\n if (stream.current() == \"(\") ++depth\n else if (stream.current() == \")\") {\n if (depth == 0) {\n stream.backUp(1)\n state.tokenize.pop()\n return state.tokenize[state.tokenize.length - 1](stream, state)\n }\n else --depth\n }\n }\n return inner\n }\n}\n\nfunction tokenString(openQuote, stream, state) {\n var singleLine = openQuote.length == 1\n var ch, escaped = false\n while (ch = stream.peek()) {\n if (escaped) {\n stream.next()\n if (ch == \"(\") {\n state.tokenize.push(tokenUntilClosingParen())\n return \"string\"\n }\n escaped = false\n } else if (stream.match(openQuote)) {\n state.tokenize.pop()\n return \"string\"\n } else {\n stream.next()\n escaped = ch == \"\\\\\"\n }\n }\n if (singleLine) {\n state.tokenize.pop()\n }\n return \"string\"\n}\n\nfunction tokenComment(stream, state) {\n var ch\n while (ch = stream.next()) {\n if (ch === \"/\" && stream.eat(\"*\")) {\n state.tokenize.push(tokenComment)\n } else if (ch === \"*\" && stream.eat(\"/\")) {\n state.tokenize.pop()\n break\n }\n }\n return \"comment\"\n}\n\nfunction Context(prev, align, indented) {\n this.prev = prev\n this.align = align\n this.indented = indented\n}\n\nfunction pushContext(state, stream) {\n var align = stream.match(/^\\s*($|\\/[\\/\\*]|[)}\\]])/, false) ? null : stream.column() + 1\n state.context = new Context(state.context, align, state.indented)\n}\n\nfunction popContext(state) {\n if (state.context) {\n state.indented = state.context.indented\n state.context = state.context.prev\n }\n}\n\nexport const swift = {\n name: \"swift\",\n startState: function() {\n return {\n prev: null,\n context: null,\n indented: 0,\n tokenize: []\n }\n },\n\n token: function(stream, state) {\n var prev = state.prev\n state.prev = null\n var tokenize = state.tokenize[state.tokenize.length - 1] || tokenBase\n var style = tokenize(stream, state, prev)\n if (!style || style == \"comment\") state.prev = prev\n else if (!state.prev) state.prev = style\n\n if (style == \"punctuation\") {\n var bracket = /[\\(\\[\\{]|([\\]\\)\\}])/.exec(stream.current())\n if (bracket) (bracket[1] ? popContext : pushContext)(state, stream)\n }\n\n return style\n },\n\n indent: function(state, textAfter, iCx) {\n var cx = state.context\n if (!cx) return 0\n var closing = /^[\\]\\}\\)]/.test(textAfter)\n if (cx.align != null) return cx.align - (closing ? 1 : 0)\n return cx.indented + (closing ? 0 : iCx.unit)\n },\n\n languageData: {\n indentOnInput: /^\\s*[\\)\\}\\]]$/,\n commentTokens: {line: \"//\", block: {open: \"/*\", close: \"*/\"}},\n closeBrackets: {brackets: [\"(\", \"[\", \"{\", \"'\", '\"', \"`\"]}\n }\n}\n"],"names":["wordSet","words","set","i","length","keywords","definingKeywords","atoms","types","operators","punc","binary","octal","hexadecimal","decimal","identifier","property","instruction","attribute","tokenBase","stream","state","prev","sol","indented","indentation","eatSpace","stringMatch","ch","peek","match","skipToEnd","tokenize","push","tokenComment","indexOf","next","tokenString","bind","ident","current","hasOwnProperty","tokenUntilClosingParen","depth","inner","backUp","pop","openQuote","singleLine","escaped","eat","Context","align","this","pushContext","column","context","popContext","swift","name","startState","token","style","bracket","exec","indent","textAfter","iCx","cx","closing","test","unit","languageData","indentOnInput","commentTokens","line","block","open","close","closeBrackets","brackets"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/662.index.js b/book/_build/html/_static/662.index.js new file mode 100644 index 0000000..dca95d4 --- /dev/null +++ b/book/_build/html/_static/662.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[662],{30662:(e,t,r)=>{function a(e){var t=e.client||{},r=e.atoms||{false:!0,true:!0,null:!0},a=e.builtin||l(c),i=e.keywords||l(s),n=e.operatorChars||/^[*+\-%<>!=&|~^\/]/,o=e.support||{},u=e.hooks||{},d=e.dateSQL||{date:!0,time:!0,timestamp:!0},m=!1!==e.backslashStringEscapes,p=e.brackets||/^[\{}\(\)\[\]]/,g=e.punctuation||/^[;.,:]/;function h(e,s){var l=e.next();if(u[l]){var c=u[l](e,s);if(!1!==c)return c}if(o.hexNumber&&("0"==l&&e.match(/^[xX][0-9a-fA-F]+/)||("x"==l||"X"==l)&&e.match(/^'[0-9a-fA-F]*'/)))return"number";if(o.binaryNumber&&(("b"==l||"B"==l)&&e.match(/^'[01]+'/)||"0"==l&&e.match(/^b[01]*/)))return"number";if(l.charCodeAt(0)>47&&l.charCodeAt(0)<58)return e.match(/^[0-9]*(\.[0-9]+)?([eE][-+]?[0-9]+)?/),o.decimallessFloat&&e.match(/^\.(?!\.)/),"number";if("?"==l&&(e.eatSpace()||e.eol()||e.eat(";")))return"macroName";if("'"==l||'"'==l&&o.doubleQuote)return s.tokenize=b(l),s.tokenize(e,s);if((o.nCharCast&&("n"==l||"N"==l)||o.charsetCast&&"_"==l&&e.match(/[a-z][a-z0-9]*/i))&&("'"==e.peek()||'"'==e.peek()))return"keyword";if(o.escapeConstant&&("e"==l||"E"==l)&&("'"==e.peek()||'"'==e.peek()&&o.doubleQuote))return s.tokenize=function(e,t){return(t.tokenize=b(e.next(),!0))(e,t)},"keyword";if(o.commentSlashSlash&&"/"==l&&e.eat("/"))return e.skipToEnd(),"comment";if(o.commentHash&&"#"==l||"-"==l&&e.eat("-")&&(!o.commentSpaceRequired||e.eat(" ")))return e.skipToEnd(),"comment";if("/"==l&&e.eat("*"))return s.tokenize=f(1),s.tokenize(e,s);if("."!=l){if(n.test(l))return e.eatWhile(n),"operator";if(p.test(l))return"bracket";if(g.test(l))return e.eatWhile(g),"punctuation";if("{"==l&&(e.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/)||e.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/)))return"number";e.eatWhile(/^[_\w\d]/);var m=e.current().toLowerCase();return d.hasOwnProperty(m)&&(e.match(/^( )+'[^']*'/)||e.match(/^( )+"[^"]*"/))?"number":r.hasOwnProperty(m)?"atom":a.hasOwnProperty(m)?"type":i.hasOwnProperty(m)?"keyword":t.hasOwnProperty(m)?"builtin":null}return o.zerolessFloat&&e.match(/^(?:\d+(?:e[+-]?\d+)?)/i)?"number":e.match(/^\.+/)?null:o.ODBCdotTable&&e.match(/^[\w\d_$#]+/)?"type":void 0}function b(e,t){return function(r,a){for(var i,n=!1;null!=(i=r.next());){if(i==e&&!n){a.tokenize=h;break}n=(m||t)&&!n&&"\\"==i}return"string"}}function f(e){return function(t,r){var a=t.match(/^.*?(\/\*|\*\/)/);return a?"/*"==a[1]?r.tokenize=f(e+1):r.tokenize=e>1?f(e-1):h:t.skipToEnd(),"comment"}}function _(e,t,r){t.context={prev:t.context,indent:e.indentation(),col:e.column(),type:r}}return{name:"sql",startState:function(){return{tokenize:h,context:null}},token:function(e,t){if(e.sol()&&t.context&&null==t.context.align&&(t.context.align=!1),t.tokenize==h&&e.eatSpace())return null;var r=t.tokenize(e,t);if("comment"==r)return r;t.context&&null==t.context.align&&(t.context.align=!0);var a=e.current();return"("==a?_(e,t,")"):"["==a?_(e,t,"]"):t.context&&t.context.type==a&&function(e){e.indent=e.context.indent,e.context=e.context.prev}(t),r},indent:function(e,t,r){var a=e.context;if(!a)return null;var i=t.charAt(0)==a.type;return a.align?a.col+(i?0:1):a.indent+(i?0:r.unit)},languageData:{commentTokens:{line:o.commentSlashSlash?"//":o.commentHash?"#":"--",block:{open:"/*",close:"*/"}},closeBrackets:{brackets:["(","[","{","'",'"',"`"]}}}}function i(e){for(var t;null!=(t=e.next());)if("`"==t&&!e.eat("`"))return"string.special";return e.backUp(e.current().length-1),e.eatWhile(/\w/)?"string.special":null}function n(e){return e.eat("@")&&(e.match("session."),e.match("local."),e.match("global.")),e.eat("'")?(e.match(/^.*'/),"string.special"):e.eat('"')?(e.match(/^.*"/),"string.special"):e.eat("`")?(e.match(/^.*`/),"string.special"):e.match(/^[0-9a-zA-Z$\.\_]+/)?"string.special":null}function o(e){return e.eat("N")?"atom":e.match(/^[a-zA-Z.#!?]/)?"string.special":null}r.r(t),r.d(t,{cassandra:()=>h,esper:()=>w,gpSQL:()=>v,gql:()=>y,hive:()=>f,mariaDB:()=>p,msSQL:()=>d,mySQL:()=>m,pgSQL:()=>_,plSQL:()=>b,sparkSQL:()=>x,sql:()=>a,sqlite:()=>g,standardSQL:()=>u});var s="alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit ";function l(e){for(var t={},r=e.split(" "),a=0;a!=^\&|\/]/,brackets:/^[\{}\(\)]/,punctuation:/^[;.,:/]/,backslashStringEscapes:!1,dateSQL:l("date datetimeoffset datetime2 smalldatetime datetime time"),hooks:{"@":n}}),m=a({client:l("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),keywords:l(s+"accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group group_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),builtin:l("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),atoms:l("false true null unknown"),operatorChars:/^[*+\-%<>!=&|^]/,dateSQL:l("date time timestamp"),support:l("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),hooks:{"@":n,"`":i,"\\":o}}),p=a({client:l("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),keywords:l(s+"accessible action add after algorithm all always analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general generated get global grant grants group group_concat handler hard hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password persistent phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show shutdown signal slave slow smallint snapshot soft soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views virtual warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),builtin:l("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),atoms:l("false true null unknown"),operatorChars:/^[*+\-%<>!=&|^]/,dateSQL:l("date time timestamp"),support:l("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),hooks:{"@":n,"`":i,"\\":o}}),g=a({client:l("auth backup bail binary changes check clone databases dbinfo dump echo eqp exit explain fullschema headers help import imposter indexes iotrace limit lint load log mode nullvalue once open output print prompt quit read restore save scanstats schema separator session shell show stats system tables testcase timeout timer trace vfsinfo vfslist vfsname width"),keywords:l(s+"abort action add after all analyze attach autoincrement before begin cascade case cast check collate column commit conflict constraint cross current_date current_time current_timestamp database default deferrable deferred detach each else end escape except exclusive exists explain fail for foreign full glob if ignore immediate index indexed initially inner instead intersect isnull key left limit match natural no notnull null of offset outer plan pragma primary query raise recursive references regexp reindex release rename replace restrict right rollback row savepoint temp temporary then to transaction trigger unique using vacuum view virtual when with without"),builtin:l("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text clob bigint int int2 int8 integer float double char varchar date datetime year unsigned signed numeric real"),atoms:l("null current_date current_time current_timestamp"),operatorChars:/^[*+\-%<>!=&|/~]/,dateSQL:l("date time timestamp datetime"),support:l("decimallessFloat zerolessFloat"),identifierQuote:'"',hooks:{"@":n,":":n,"?":n,$:n,'"':function(e){for(var t;null!=(t=e.next());)if('"'==t&&!e.eat('"'))return"string.special";return e.backUp(e.current().length-1),e.eatWhile(/\w/)?"string.special":null},"`":i}}),h=a({client:{},keywords:l("add all allow alter and any apply as asc authorize batch begin by clustering columnfamily compact consistency count create custom delete desc distinct drop each_quorum exists filtering from grant if in index insert into key keyspace keyspaces level limit local_one local_quorum modify nan norecursive nosuperuser not of on one order password permission permissions primary quorum rename revoke schema select set storage superuser table three to token truncate ttl two type unlogged update use user users using values where with writetime"),builtin:l("ascii bigint blob boolean counter decimal double float frozen inet int list map static text timestamp timeuuid tuple uuid varchar varint"),atoms:l("false true infinity NaN"),operatorChars:/^[<>=]/,dateSQL:{},support:l("commentSlashSlash decimallessFloat"),hooks:{}}),b=a({client:l("appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap"),keywords:l("abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elseif elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning returns reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work"),builtin:l("abs acos add_months ascii asin atan atan2 average bfile bfilename bigserial bit blob ceil character chartorowid chr clob concat convert cos cosh count dec decode deref dual dump dup_val_on_index empty error exp false float floor found glb greatest hextoraw initcap instr instrb int integer isopen last_day least length lengthb ln lower lpad ltrim lub make_ref max min mlslabel mod months_between natural naturaln nchar nclob new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null number numeric nvarchar2 nvl others power rawtohex real reftohex round rowcount rowidtochar rowtype rpad rtrim serial sign signtype sin sinh smallint soundex sqlcode sqlerrm sqrt stddev string substr substrb sum sysdate tan tanh to_char text to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid unlogged upper user userenv varchar varchar2 variance varying vsize xml"),operatorChars:/^[*\/+\-%<>!=~]/,dateSQL:l("date time timestamp"),support:l("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber")}),f=a({keywords:l("select alter $elem$ $key$ $value$ add after all analyze and archive as asc before between binary both bucket buckets by cascade case cast change cluster clustered clusterstatus collection column columns comment compute concatenate continue create cross cursor data database databases dbproperties deferred delete delimited desc describe directory disable distinct distribute drop else enable end escaped exclusive exists explain export extended external fetch fields fileformat first format formatted from full function functions grant group having hold_ddltime idxproperties if import in index indexes inpath inputdriver inputformat insert intersect into is items join keys lateral left like limit lines load local location lock locks mapjoin materialized minus msck no_drop nocompress not of offline on option or order out outer outputdriver outputformat overwrite partition partitioned partitions percent plus preserve procedure purge range rcfile read readonly reads rebuild recordreader recordwriter recover reduce regexp rename repair replace restrict revoke right rlike row schema schemas semi sequencefile serde serdeproperties set shared show show_database sort sorted ssl statistics stored streamtable table tables tablesample tblproperties temporary terminated textfile then tmp to touch transform trigger unarchive undo union uniquejoin unlock update use using utc utc_tmestamp view when where while with admin authorization char compact compactions conf cube current current_date current_timestamp day decimal defined dependency directories elem_type exchange file following for grouping hour ignore inner interval jar less logical macro minute month more none noscan over owner partialscan preceding pretty principals protection reload rewrite role roles rollup rows second server sets skewed transactions truncate unbounded unset uri user values window year"),builtin:l("bool boolean long timestamp tinyint smallint bigint int float double date datetime unsigned string array struct map uniontype key_type utctimestamp value_type varchar"),atoms:l("false true null unknown"),operatorChars:/^[*+\-%<>!=]/,dateSQL:l("date timestamp"),support:l("ODBCdotTable doubleQuote binaryNumber hexNumber")}),_=a({client:l("source"),keywords:l(s+"a abort abs absent absolute access according action ada add admin after aggregate alias all allocate also alter always analyse analyze and any are array array_agg array_max_cardinality as asc asensitive assert assertion assignment asymmetric at atomic attach attribute attributes authorization avg backward base64 before begin begin_frame begin_partition bernoulli between bigint binary bit bit_length blob blocked bom boolean both breadth by c cache call called cardinality cascade cascaded case cast catalog catalog_name ceil ceiling chain char char_length character character_length character_set_catalog character_set_name character_set_schema characteristics characters check checkpoint class class_origin clob close cluster coalesce cobol collate collation collation_catalog collation_name collation_schema collect column column_name columns command_function command_function_code comment comments commit committed concurrently condition condition_number configuration conflict connect connection connection_name constant constraint constraint_catalog constraint_name constraint_schema constraints constructor contains content continue control conversion convert copy corr corresponding cost count covar_pop covar_samp create cross csv cube cume_dist current current_catalog current_date current_default_transform_group current_path current_role current_row current_schema current_time current_timestamp current_transform_group_for_type current_user cursor cursor_name cycle data database datalink datatype date datetime_interval_code datetime_interval_precision day db deallocate debug dec decimal declare default defaults deferrable deferred defined definer degree delete delimiter delimiters dense_rank depends depth deref derived desc describe descriptor detach detail deterministic diagnostics dictionary disable discard disconnect dispatch distinct dlnewcopy dlpreviouscopy dlurlcomplete dlurlcompleteonly dlurlcompletewrite dlurlpath dlurlpathonly dlurlpathwrite dlurlscheme dlurlserver dlvalue do document domain double drop dump dynamic dynamic_function dynamic_function_code each element else elseif elsif empty enable encoding encrypted end end_frame end_partition endexec enforced enum equals errcode error escape event every except exception exclude excluding exclusive exec execute exists exit exp explain expression extension external extract false family fetch file filter final first first_value flag float floor following for force foreach foreign fortran forward found frame_row free freeze from fs full function functions fusion g general generated get global go goto grant granted greatest group grouping groups handler having header hex hierarchy hint hold hour id identity if ignore ilike immediate immediately immutable implementation implicit import in include including increment indent index indexes indicator info inherit inherits initially inline inner inout input insensitive insert instance instantiable instead int integer integrity intersect intersection interval into invoker is isnull isolation join k key key_member key_type label lag language large last last_value lateral lead leading leakproof least left length level library like like_regex limit link listen ln load local localtime localtimestamp location locator lock locked log logged loop lower m map mapping match matched materialized max max_cardinality maxvalue member merge message message_length message_octet_length message_text method min minute minvalue mod mode modifies module month more move multiset mumps name names namespace national natural nchar nclob nesting new next nfc nfd nfkc nfkd nil no none normalize normalized not nothing notice notify notnull nowait nth_value ntile null nullable nullif nulls number numeric object occurrences_regex octet_length octets of off offset oids old on only open operator option options or order ordering ordinality others out outer output over overlaps overlay overriding owned owner p pad parallel parameter parameter_mode parameter_name parameter_ordinal_position parameter_specific_catalog parameter_specific_name parameter_specific_schema parser partial partition pascal passing passthrough password path percent percent_rank percentile_cont percentile_disc perform period permission pg_context pg_datatype_name pg_exception_context pg_exception_detail pg_exception_hint placing plans pli policy portion position position_regex power precedes preceding precision prepare prepared preserve primary print_strict_params prior privileges procedural procedure procedures program public publication query quote raise range rank read reads real reassign recheck recovery recursive ref references referencing refresh regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy regr_syy reindex relative release rename repeatable replace replica requiring reset respect restart restore restrict result result_oid return returned_cardinality returned_length returned_octet_length returned_sqlstate returning returns reverse revoke right role rollback rollup routine routine_catalog routine_name routine_schema routines row row_count row_number rows rowtype rule savepoint scale schema schema_name schemas scope scope_catalog scope_name scope_schema scroll search second section security select selective self sensitive sequence sequences serializable server server_name session session_user set setof sets share show similar simple size skip slice smallint snapshot some source space specific specific_name specifictype sql sqlcode sqlerror sqlexception sqlstate sqlwarning sqrt stable stacked standalone start state statement static statistics stddev_pop stddev_samp stdin stdout storage strict strip structure style subclass_origin submultiset subscription substring substring_regex succeeds sum symmetric sysid system system_time system_user t table table_name tables tablesample tablespace temp template temporary text then ties time timestamp timezone_hour timezone_minute to token top_level_count trailing transaction transaction_active transactions_committed transactions_rolled_back transform transforms translate translate_regex translation treat trigger trigger_catalog trigger_name trigger_schema trim trim_array true truncate trusted type types uescape unbounded uncommitted under unencrypted union unique unknown unlink unlisten unlogged unnamed unnest until untyped update upper uri usage use_column use_variable user user_defined_type_catalog user_defined_type_code user_defined_type_name user_defined_type_schema using vacuum valid validate validator value value_of values var_pop var_samp varbinary varchar variable_conflict variadic varying verbose version versioning view views volatile warning when whenever where while whitespace width_bucket window with within without work wrapper write xml xmlagg xmlattributes xmlbinary xmlcast xmlcomment xmlconcat xmldeclaration xmldocument xmlelement xmlexists xmlforest xmliterate xmlnamespaces xmlparse xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltext xmlvalidate year yes zone"),builtin:l("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml"),atoms:l("false true null unknown"),operatorChars:/^[*\/+\-%<>!=&|^\/#@?~]/,backslashStringEscapes:!1,dateSQL:l("date time timestamp"),support:l("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast escapeConstant")}),y=a({keywords:l("ancestor and asc by contains desc descendant distinct from group has in is limit offset on order select superset where"),atoms:l("false true"),builtin:l("blob datetime first key __key__ string integer double boolean null"),operatorChars:/^[*+\-%<>!=]/}),v=a({client:l("source"),keywords:l("abort absolute access action active add admin after aggregate all also alter always analyse analyze and any array as asc assertion assignment asymmetric at authorization backward before begin between bigint binary bit boolean both by cache called cascade cascaded case cast chain char character characteristics check checkpoint class close cluster coalesce codegen collate column comment commit committed concurrency concurrently configuration connection constraint constraints contains content continue conversion copy cost cpu_rate_limit create createdb createexttable createrole createuser cross csv cube current current_catalog current_date current_role current_schema current_time current_timestamp current_user cursor cycle data database day deallocate dec decimal declare decode default defaults deferrable deferred definer delete delimiter delimiters deny desc dictionary disable discard distinct distributed do document domain double drop dxl each else enable encoding encrypted end enum errors escape every except exchange exclude excluding exclusive execute exists explain extension external extract false family fetch fields filespace fill filter first float following for force foreign format forward freeze from full function global grant granted greatest group group_id grouping handler hash having header hold host hour identity if ignore ilike immediate immutable implicit in including inclusive increment index indexes inherit inherits initially inline inner inout input insensitive insert instead int integer intersect interval into invoker is isnull isolation join key language large last leading least left level like limit list listen load local localtime localtimestamp location lock log login mapping master match maxvalue median merge minute minvalue missing mode modifies modify month move name names national natural nchar new newline next no nocreatedb nocreateexttable nocreaterole nocreateuser noinherit nologin none noovercommit nosuperuser not nothing notify notnull nowait null nullif nulls numeric object of off offset oids old on only operator option options or order ordered others out outer over overcommit overlaps overlay owned owner parser partial partition partitions passing password percent percentile_cont percentile_disc placing plans position preceding precision prepare prepared preserve primary prior privileges procedural procedure protocol queue quote randomly range read readable reads real reassign recheck recursive ref references reindex reject relative release rename repeatable replace replica reset resource restart restrict returning returns revoke right role rollback rollup rootpartition row rows rule savepoint scatter schema scroll search second security segment select sequence serializable session session_user set setof sets share show similar simple smallint some split sql stable standalone start statement statistics stdin stdout storage strict strip subpartition subpartitions substring superuser symmetric sysid system table tablespace temp template temporary text then threshold ties time timestamp to trailing transaction treat trigger trim true truncate trusted type unbounded uncommitted unencrypted union unique unknown unlisten until update user using vacuum valid validation validator value values varchar variadic varying verbose version view volatile web when where whitespace window with within without work writable write xml xmlattributes xmlconcat xmlelement xmlexists xmlforest xmlparse xmlpi xmlroot xmlserialize year yes zone"),builtin:l("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml"),atoms:l("false true null unknown"),operatorChars:/^[*+\-%<>!=&|^\/#@?~]/,dateSQL:l("date time timestamp"),support:l("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast")}),x=a({keywords:l("add after all alter analyze and anti archive array as asc at between bucket buckets by cache cascade case cast change clear cluster clustered codegen collection column columns comment commit compact compactions compute concatenate cost create cross cube current current_date current_timestamp database databases data dbproperties defined delete delimited deny desc describe dfs directories distinct distribute drop else end escaped except exchange exists explain export extended external false fields fileformat first following for format formatted from full function functions global grant group grouping having if ignore import in index indexes inner inpath inputformat insert intersect interval into is items join keys last lateral lazy left like limit lines list load local location lock locks logical macro map minus msck natural no not null nulls of on optimize option options or order out outer outputformat over overwrite partition partitioned partitions percent preceding principals purge range recordreader recordwriter recover reduce refresh regexp rename repair replace reset restrict revoke right rlike role roles rollback rollup row rows schema schemas select semi separated serde serdeproperties set sets show skewed sort sorted start statistics stored stratify struct table tables tablesample tblproperties temp temporary terminated then to touch transaction transactions transform true truncate unarchive unbounded uncache union unlock unset use using values view when where window with"),builtin:l("tinyint smallint int bigint boolean float double string binary timestamp decimal array map struct uniontype delimited serde sequencefile textfile rcfile inputformat outputformat"),atoms:l("false true null"),operatorChars:/^[*\/+\-%<>!=~&|^]/,dateSQL:l("date time timestamp"),support:l("ODBCdotTable doubleQuote zerolessFloat")}),w=a({client:l("source"),keywords:l("alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit after all and as at asc avedev avg between by case cast coalesce count create current_timestamp day days delete define desc distinct else end escape events every exists false first from full group having hour hours in inner insert instanceof into irstream is istream join last lastweekday left limit like max match_recognize matches median measures metadatasql min minute minutes msec millisecond milliseconds not null offset on or order outer output partition pattern prev prior regexp retain-union retain-intersection right rstream sec second seconds select set some snapshot sql stddev sum then true unidirectional until update variable weekday when where window"),builtin:{},atoms:l("false true null"),operatorChars:/^[*+\-%<>!=&|^\/#@?~]/,dateSQL:l("time"),support:l("decimallessFloat zerolessFloat binaryNumber hexNumber")})}}]); +//# sourceMappingURL=662.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/662.index.js.map b/book/_build/html/_static/662.index.js.map new file mode 100644 index 0000000..1059c75 --- /dev/null +++ b/book/_build/html/_static/662.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"662.index.js","mappings":"8FAAO,SAASA,EAAIC,GAClB,IAAIC,EAAiBD,EAAaC,QAAU,CAAC,EACzCC,EAAiBF,EAAaE,OAAS,CAAC,OAAS,EAAM,MAAQ,EAAM,MAAQ,GAC7EC,EAAiBH,EAAaG,SAAWC,EAAIC,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,OAAQG,EAAI,UAEZE,SAAUF,EAAI,+0BACdD,QAAS,CAAC,EACVD,MAAOE,EAAI,mBACXI,cAAe,wBACfG,QAASP,EAAI,QACbK,QAASL,EAAI,0D","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/sql.js"],"sourcesContent":["export function sql(parserConfig) {\n var client = parserConfig.client || {},\n atoms = parserConfig.atoms || {\"false\": true, \"true\": true, \"null\": true},\n builtin = parserConfig.builtin || set(defaultBuiltin),\n keywords = parserConfig.keywords || set(sqlKeywords),\n operatorChars = parserConfig.operatorChars || /^[*+\\-%<>!=&|~^\\/]/,\n support = parserConfig.support || {},\n hooks = parserConfig.hooks || {},\n dateSQL = parserConfig.dateSQL || {\"date\" : true, \"time\" : true, \"timestamp\" : true},\n backslashStringEscapes = parserConfig.backslashStringEscapes !== false,\n brackets = parserConfig.brackets || /^[\\{}\\(\\)\\[\\]]/,\n punctuation = parserConfig.punctuation || /^[;.,:]/\n\n function tokenBase(stream, state) {\n var ch = stream.next();\n\n // call hooks from the mime type\n if (hooks[ch]) {\n var result = hooks[ch](stream, state);\n if (result !== false) return result;\n }\n\n if (support.hexNumber &&\n ((ch == \"0\" && stream.match(/^[xX][0-9a-fA-F]+/))\n || (ch == \"x\" || ch == \"X\") && stream.match(/^'[0-9a-fA-F]*'/))) {\n // hex\n // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html\n return \"number\";\n } else if (support.binaryNumber &&\n (((ch == \"b\" || ch == \"B\") && stream.match(/^'[01]+'/))\n || (ch == \"0\" && stream.match(/^b[01]*/)))) {\n // bitstring\n // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html\n return \"number\";\n } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) {\n // numbers\n // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html\n stream.match(/^[0-9]*(\\.[0-9]+)?([eE][-+]?[0-9]+)?/);\n support.decimallessFloat && stream.match(/^\\.(?!\\.)/);\n return \"number\";\n } else if (ch == \"?\" && (stream.eatSpace() || stream.eol() || stream.eat(\";\"))) {\n // placeholders\n return \"macroName\";\n } else if (ch == \"'\" || (ch == '\"' && support.doubleQuote)) {\n // strings\n // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html\n state.tokenize = tokenLiteral(ch);\n return state.tokenize(stream, state);\n } else if ((((support.nCharCast && (ch == \"n\" || ch == \"N\"))\n || (support.charsetCast && ch == \"_\" && stream.match(/[a-z][a-z0-9]*/i)))\n && (stream.peek() == \"'\" || stream.peek() == '\"'))) {\n // charset casting: _utf8'str', N'str', n'str'\n // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html\n return \"keyword\";\n } else if (support.escapeConstant && (ch == \"e\" || ch == \"E\")\n && (stream.peek() == \"'\" || (stream.peek() == '\"' && support.doubleQuote))) {\n // escape constant: E'str', e'str'\n // ref: https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS-ESCAPE\n state.tokenize = function(stream, state) {\n return (state.tokenize = tokenLiteral(stream.next(), true))(stream, state);\n }\n return \"keyword\";\n } else if (support.commentSlashSlash && ch == \"/\" && stream.eat(\"/\")) {\n // 1-line comment\n stream.skipToEnd();\n return \"comment\";\n } else if ((support.commentHash && ch == \"#\")\n || (ch == \"-\" && stream.eat(\"-\") && (!support.commentSpaceRequired || stream.eat(\" \")))) {\n // 1-line comments\n // ref: https://kb.askmonty.org/en/comment-syntax/\n stream.skipToEnd();\n return \"comment\";\n } else if (ch == \"/\" && stream.eat(\"*\")) {\n // multi-line comments\n // ref: https://kb.askmonty.org/en/comment-syntax/\n state.tokenize = tokenComment(1);\n return state.tokenize(stream, state);\n } else if (ch == \".\") {\n // .1 for 0.1\n if (support.zerolessFloat && stream.match(/^(?:\\d+(?:e[+-]?\\d+)?)/i))\n return \"number\";\n if (stream.match(/^\\.+/))\n return null\n // .table_name (ODBC)\n // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html\n if (support.ODBCdotTable && stream.match(/^[\\w\\d_$#]+/))\n return \"type\";\n } else if (operatorChars.test(ch)) {\n // operators\n stream.eatWhile(operatorChars);\n return \"operator\";\n } else if (brackets.test(ch)) {\n // brackets\n return \"bracket\";\n } else if (punctuation.test(ch)) {\n // punctuation\n stream.eatWhile(punctuation);\n return \"punctuation\";\n } else if (ch == '{' &&\n (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*\"[^\"]*\"( )*}/))) {\n // dates (weird ODBC syntax)\n // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html\n return \"number\";\n } else {\n stream.eatWhile(/^[_\\w\\d]/);\n var word = stream.current().toLowerCase();\n // dates (standard SQL syntax)\n // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html\n if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+\"[^\"]*\"/)))\n return \"number\";\n if (atoms.hasOwnProperty(word)) return \"atom\";\n if (builtin.hasOwnProperty(word)) return \"type\";\n if (keywords.hasOwnProperty(word)) return \"keyword\";\n if (client.hasOwnProperty(word)) return \"builtin\";\n return null;\n }\n }\n\n // 'string', with char specified in quote escaped by '\\'\n function tokenLiteral(quote, backslashEscapes) {\n return function(stream, state) {\n var escaped = false, ch;\n while ((ch = stream.next()) != null) {\n if (ch == quote && !escaped) {\n state.tokenize = tokenBase;\n break;\n }\n escaped = (backslashStringEscapes || backslashEscapes) && !escaped && ch == \"\\\\\";\n }\n return \"string\";\n };\n }\n function tokenComment(depth) {\n return function(stream, state) {\n var m = stream.match(/^.*?(\\/\\*|\\*\\/)/)\n if (!m) stream.skipToEnd()\n else if (m[1] == \"/*\") state.tokenize = tokenComment(depth + 1)\n else if (depth > 1) state.tokenize = tokenComment(depth - 1)\n else state.tokenize = tokenBase\n return \"comment\"\n }\n }\n\n function pushContext(stream, state, type) {\n state.context = {\n prev: state.context,\n indent: stream.indentation(),\n col: stream.column(),\n type: type\n };\n }\n\n function popContext(state) {\n state.indent = state.context.indent;\n state.context = state.context.prev;\n }\n\n return {\n name: \"sql\",\n\n startState: function() {\n return {tokenize: tokenBase, context: null};\n },\n\n token: function(stream, state) {\n if (stream.sol()) {\n if (state.context && state.context.align == null)\n state.context.align = false;\n }\n if (state.tokenize == tokenBase && stream.eatSpace()) return null;\n\n var style = state.tokenize(stream, state);\n if (style == \"comment\") return style;\n\n if (state.context && state.context.align == null)\n state.context.align = true;\n\n var tok = stream.current();\n if (tok == \"(\")\n pushContext(stream, state, \")\");\n else if (tok == \"[\")\n pushContext(stream, state, \"]\");\n else if (state.context && state.context.type == tok)\n popContext(state);\n return style;\n },\n\n indent: function(state, textAfter, iCx) {\n var cx = state.context;\n if (!cx) return null;\n var closing = textAfter.charAt(0) == cx.type;\n if (cx.align) return cx.col + (closing ? 0 : 1);\n else return cx.indent + (closing ? 0 : iCx.unit);\n },\n\n languageData: {\n commentTokens: {\n line: support.commentSlashSlash ? \"//\" : support.commentHash ? \"#\" : \"--\",\n block: {open: \"/*\", close: \"*/\"}\n },\n closeBrackets: {brackets: [\"(\", \"[\", \"{\", \"'\", '\"', \"`\"]}\n }\n };\n};\n\n// `identifier`\nfunction hookIdentifier(stream) {\n // MySQL/MariaDB identifiers\n // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html\n var ch;\n while ((ch = stream.next()) != null) {\n if (ch == \"`\" && !stream.eat(\"`\")) return \"string.special\";\n }\n stream.backUp(stream.current().length - 1);\n return stream.eatWhile(/\\w/) ? \"string.special\" : null;\n}\n\n// \"identifier\"\nfunction hookIdentifierDoublequote(stream) {\n // Standard SQL /SQLite identifiers\n // ref: http://web.archive.org/web/20160813185132/http://savage.net.au/SQL/sql-99.bnf.html#delimited%20identifier\n // ref: http://sqlite.org/lang_keywords.html\n var ch;\n while ((ch = stream.next()) != null) {\n if (ch == \"\\\"\" && !stream.eat(\"\\\"\")) return \"string.special\";\n }\n stream.backUp(stream.current().length - 1);\n return stream.eatWhile(/\\w/) ? \"string.special\" : null;\n}\n\n// variable token\nfunction hookVar(stream) {\n // variables\n // @@prefix.varName @varName\n // varName can be quoted with ` or ' or \"\n // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html\n if (stream.eat(\"@\")) {\n stream.match('session.');\n stream.match('local.');\n stream.match('global.');\n }\n\n if (stream.eat(\"'\")) {\n stream.match(/^.*'/);\n return \"string.special\";\n } else if (stream.eat('\"')) {\n stream.match(/^.*\"/);\n return \"string.special\";\n } else if (stream.eat(\"`\")) {\n stream.match(/^.*`/);\n return \"string.special\";\n } else if (stream.match(/^[0-9a-zA-Z$\\.\\_]+/)) {\n return \"string.special\";\n }\n return null;\n};\n\n// short client keyword token\nfunction hookClient(stream) {\n // \\N means NULL\n // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html\n if (stream.eat(\"N\")) {\n return \"atom\";\n }\n // \\g, etc\n // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html\n return stream.match(/^[a-zA-Z.#!?]/) ? \"string.special\" : null;\n}\n\n// these keywords are used by all SQL dialects (however, a mode can still overwrite it)\nvar sqlKeywords = \"alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit \";\n\n// turn a space-separated list into an array\nfunction set(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n}\n\nvar defaultBuiltin = \"bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision real date datetime year unsigned signed decimal numeric\"\n\n// A generic SQL Mode. It's not a standard, it just try to support what is generally supported\nexport const standardSQL = sql({\n keywords: set(sqlKeywords + \"begin\"),\n builtin: set(defaultBuiltin),\n atoms: set(\"false true null unknown\"),\n dateSQL: set(\"date time timestamp\"),\n support: set(\"ODBCdotTable doubleQuote binaryNumber hexNumber\")\n});\n\nexport const msSQL = sql({\n client: set(\"$partition binary_checksum checksum connectionproperty context_info current_request_id error_line error_message error_number error_procedure error_severity error_state formatmessage get_filestream_transaction_context getansinull host_id host_name isnull isnumeric min_active_rowversion newid newsequentialid rowcount_big xact_state object_id\"),\n keywords: set(sqlKeywords + \"begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare exec go if use index holdlock nolock nowait paglock readcommitted readcommittedlock readpast readuncommitted repeatableread rowlock serializable snapshot tablock tablockx updlock with\"),\n builtin: set(\"bigint numeric bit smallint decimal smallmoney int tinyint money float real char varchar text nchar nvarchar ntext binary varbinary image cursor timestamp hierarchyid uniqueidentifier sql_variant xml table \"),\n atoms: set(\"is not null like and or in left right between inner outer join all any some cross unpivot pivot exists\"),\n operatorChars: /^[*+\\-%<>!=^\\&|\\/]/,\n brackets: /^[\\{}\\(\\)]/,\n punctuation: /^[;.,:/]/,\n backslashStringEscapes: false,\n dateSQL: set(\"date datetimeoffset datetime2 smalldatetime datetime time\"),\n hooks: {\n \"@\": hookVar\n }\n});\n\nexport const mySQL = sql({\n client: set(\"charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee\"),\n keywords: set(sqlKeywords + \"accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group group_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat\"),\n builtin: set(\"bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric\"),\n atoms: set(\"false true null unknown\"),\n operatorChars: /^[*+\\-%<>!=&|^]/,\n dateSQL: set(\"date time timestamp\"),\n support: set(\"ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired\"),\n hooks: {\n \"@\": hookVar,\n \"`\": hookIdentifier,\n \"\\\\\": hookClient\n }\n});\n\nexport const mariaDB = sql({\n client: set(\"charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee\"),\n keywords: set(sqlKeywords + \"accessible action add after algorithm all always analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general generated get global grant grants group group_concat handler hard hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password persistent phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show shutdown signal slave slow smallint snapshot soft soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views virtual warnings when while with work write xa xor year_month zerofill begin do then else loop repeat\"),\n builtin: set(\"bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric\"),\n atoms: set(\"false true null unknown\"),\n operatorChars: /^[*+\\-%<>!=&|^]/,\n dateSQL: set(\"date time timestamp\"),\n support: set(\"ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired\"),\n hooks: {\n \"@\": hookVar,\n \"`\": hookIdentifier,\n \"\\\\\": hookClient\n }\n});\n\n// provided by the phpLiteAdmin project - phpliteadmin.org\nexport const sqlite = sql({\n // commands of the official SQLite client, ref: https://www.sqlite.org/cli.html#dotcmd\n client: set(\"auth backup bail binary changes check clone databases dbinfo dump echo eqp exit explain fullschema headers help import imposter indexes iotrace limit lint load log mode nullvalue once open output print prompt quit read restore save scanstats schema separator session shell show stats system tables testcase timeout timer trace vfsinfo vfslist vfsname width\"),\n // ref: http://sqlite.org/lang_keywords.html\n keywords: set(sqlKeywords + \"abort action add after all analyze attach autoincrement before begin cascade case cast check collate column commit conflict constraint cross current_date current_time current_timestamp database default deferrable deferred detach each else end escape except exclusive exists explain fail for foreign full glob if ignore immediate index indexed initially inner instead intersect isnull key left limit match natural no notnull null of offset outer plan pragma primary query raise recursive references regexp reindex release rename replace restrict right rollback row savepoint temp temporary then to transaction trigger unique using vacuum view virtual when with without\"),\n // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types.\n builtin: set(\"bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text clob bigint int int2 int8 integer float double char varchar date datetime year unsigned signed numeric real\"),\n // ref: http://sqlite.org/syntax/literal-value.html\n atoms: set(\"null current_date current_time current_timestamp\"),\n // ref: http://sqlite.org/lang_expr.html#binaryops\n operatorChars: /^[*+\\-%<>!=&|/~]/,\n // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types.\n dateSQL: set(\"date time timestamp datetime\"),\n support: set(\"decimallessFloat zerolessFloat\"),\n identifierQuote: \"\\\"\", //ref: http://sqlite.org/lang_keywords.html\n hooks: {\n // bind-parameters ref:http://sqlite.org/lang_expr.html#varparam\n \"@\": hookVar,\n \":\": hookVar,\n \"?\": hookVar,\n \"$\": hookVar,\n // The preferred way to escape Identifiers is using double quotes, ref: http://sqlite.org/lang_keywords.html\n \"\\\"\": hookIdentifierDoublequote,\n // there is also support for backticks, ref: http://sqlite.org/lang_keywords.html\n \"`\": hookIdentifier\n }\n});\n\n// the query language used by Apache Cassandra is called CQL, but this mime type\n// is called Cassandra to avoid confusion with Contextual Query Language\nexport const cassandra = sql({\n client: { },\n keywords: set(\"add all allow alter and any apply as asc authorize batch begin by clustering columnfamily compact consistency count create custom delete desc distinct drop each_quorum exists filtering from grant if in index insert into key keyspace keyspaces level limit local_one local_quorum modify nan norecursive nosuperuser not of on one order password permission permissions primary quorum rename revoke schema select set storage superuser table three to token truncate ttl two type unlogged update use user users using values where with writetime\"),\n builtin: set(\"ascii bigint blob boolean counter decimal double float frozen inet int list map static text timestamp timeuuid tuple uuid varchar varint\"),\n atoms: set(\"false true infinity NaN\"),\n operatorChars: /^[<>=]/,\n dateSQL: { },\n support: set(\"commentSlashSlash decimallessFloat\"),\n hooks: { }\n});\n\n// this is based on Peter Raganitsch's 'plsql' mode\nexport const plSQL = sql({\n client: set(\"appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap\"),\n keywords: set(\"abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elseif elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning returns reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work\"),\n builtin: set(\"abs acos add_months ascii asin atan atan2 average bfile bfilename bigserial bit blob ceil character chartorowid chr clob concat convert cos cosh count dec decode deref dual dump dup_val_on_index empty error exp false float floor found glb greatest hextoraw initcap instr instrb int integer isopen last_day least length lengthb ln lower lpad ltrim lub make_ref max min mlslabel mod months_between natural naturaln nchar nclob new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null number numeric nvarchar2 nvl others power rawtohex real reftohex round rowcount rowidtochar rowtype rpad rtrim serial sign signtype sin sinh smallint soundex sqlcode sqlerrm sqrt stddev string substr substrb sum sysdate tan tanh to_char text to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid unlogged upper user userenv varchar varchar2 variance varying vsize xml\"),\n operatorChars: /^[*\\/+\\-%<>!=~]/,\n dateSQL: set(\"date time timestamp\"),\n support: set(\"doubleQuote nCharCast zerolessFloat binaryNumber hexNumber\")\n});\n\n// Created to support specific hive keywords\nexport const hive = sql({\n keywords: set(\"select alter $elem$ $key$ $value$ add after all analyze and archive as asc before between binary both bucket buckets by cascade case cast change cluster clustered clusterstatus collection column columns comment compute concatenate continue create cross cursor data database databases dbproperties deferred delete delimited desc describe directory disable distinct distribute drop else enable end escaped exclusive exists explain export extended external fetch fields fileformat first format formatted from full function functions grant group having hold_ddltime idxproperties if import in index indexes inpath inputdriver inputformat insert intersect into is items join keys lateral left like limit lines load local location lock locks mapjoin materialized minus msck no_drop nocompress not of offline on option or order out outer outputdriver outputformat overwrite partition partitioned partitions percent plus preserve procedure purge range rcfile read readonly reads rebuild recordreader recordwriter recover reduce regexp rename repair replace restrict revoke right rlike row schema schemas semi sequencefile serde serdeproperties set shared show show_database sort sorted ssl statistics stored streamtable table tables tablesample tblproperties temporary terminated textfile then tmp to touch transform trigger unarchive undo union uniquejoin unlock update use using utc utc_tmestamp view when where while with admin authorization char compact compactions conf cube current current_date current_timestamp day decimal defined dependency directories elem_type exchange file following for grouping hour ignore inner interval jar less logical macro minute month more none noscan over owner partialscan preceding pretty principals protection reload rewrite role roles rollup rows second server sets skewed transactions truncate unbounded unset uri user values window year\"),\n builtin: set(\"bool boolean long timestamp tinyint smallint bigint int float double date datetime unsigned string array struct map uniontype key_type utctimestamp value_type varchar\"),\n atoms: set(\"false true null unknown\"),\n operatorChars: /^[*+\\-%<>!=]/,\n dateSQL: set(\"date timestamp\"),\n support: set(\"ODBCdotTable doubleQuote binaryNumber hexNumber\")\n});\n\nexport const pgSQL = sql({\n client: set(\"source\"),\n // For PostgreSQL - https://www.postgresql.org/docs/11/sql-keywords-appendix.html\n // For pl/pgsql lang - https://github.com/postgres/postgres/blob/REL_11_2/src/pl/plpgsql/src/pl_scanner.c\n keywords: set(sqlKeywords + \"a abort abs absent absolute access according action ada add admin after aggregate alias all allocate also alter always analyse analyze and any are array array_agg array_max_cardinality as asc asensitive assert assertion assignment asymmetric at atomic attach attribute attributes authorization avg backward base64 before begin begin_frame begin_partition bernoulli between bigint binary bit bit_length blob blocked bom boolean both breadth by c cache call called cardinality cascade cascaded case cast catalog catalog_name ceil ceiling chain char char_length character character_length character_set_catalog character_set_name character_set_schema characteristics characters check checkpoint class class_origin clob close cluster coalesce cobol collate collation collation_catalog collation_name collation_schema collect column column_name columns command_function command_function_code comment comments commit committed concurrently condition condition_number configuration conflict connect connection connection_name constant constraint constraint_catalog constraint_name constraint_schema constraints constructor contains content continue control conversion convert copy corr corresponding cost count covar_pop covar_samp create cross csv cube cume_dist current current_catalog current_date current_default_transform_group current_path current_role current_row current_schema current_time current_timestamp current_transform_group_for_type current_user cursor cursor_name cycle data database datalink datatype date datetime_interval_code datetime_interval_precision day db deallocate debug dec decimal declare default defaults deferrable deferred defined definer degree delete delimiter delimiters dense_rank depends depth deref derived desc describe descriptor detach detail deterministic diagnostics dictionary disable discard disconnect dispatch distinct dlnewcopy dlpreviouscopy dlurlcomplete dlurlcompleteonly dlurlcompletewrite dlurlpath dlurlpathonly dlurlpathwrite dlurlscheme dlurlserver dlvalue do document domain double drop dump dynamic dynamic_function dynamic_function_code each element else elseif elsif empty enable encoding encrypted end end_frame end_partition endexec enforced enum equals errcode error escape event every except exception exclude excluding exclusive exec execute exists exit exp explain expression extension external extract false family fetch file filter final first first_value flag float floor following for force foreach foreign fortran forward found frame_row free freeze from fs full function functions fusion g general generated get global go goto grant granted greatest group grouping groups handler having header hex hierarchy hint hold hour id identity if ignore ilike immediate immediately immutable implementation implicit import in include including increment indent index indexes indicator info inherit inherits initially inline inner inout input insensitive insert instance instantiable instead int integer integrity intersect intersection interval into invoker is isnull isolation join k key key_member key_type label lag language large last last_value lateral lead leading leakproof least left length level library like like_regex limit link listen ln load local localtime localtimestamp location locator lock locked log logged loop lower m map mapping match matched materialized max max_cardinality maxvalue member merge message message_length message_octet_length message_text method min minute minvalue mod mode modifies module month more move multiset mumps name names namespace national natural nchar nclob nesting new next nfc nfd nfkc nfkd nil no none normalize normalized not nothing notice notify notnull nowait nth_value ntile null nullable nullif nulls number numeric object occurrences_regex octet_length octets of off offset oids old on only open operator option options or order ordering ordinality others out outer output over overlaps overlay overriding owned owner p pad parallel parameter parameter_mode parameter_name parameter_ordinal_position parameter_specific_catalog parameter_specific_name parameter_specific_schema parser partial partition pascal passing passthrough password path percent percent_rank percentile_cont percentile_disc perform period permission pg_context pg_datatype_name pg_exception_context pg_exception_detail pg_exception_hint placing plans pli policy portion position position_regex power precedes preceding precision prepare prepared preserve primary print_strict_params prior privileges procedural procedure procedures program public publication query quote raise range rank read reads real reassign recheck recovery recursive ref references referencing refresh regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy regr_syy reindex relative release rename repeatable replace replica requiring reset respect restart restore restrict result result_oid return returned_cardinality returned_length returned_octet_length returned_sqlstate returning returns reverse revoke right role rollback rollup routine routine_catalog routine_name routine_schema routines row row_count row_number rows rowtype rule savepoint scale schema schema_name schemas scope scope_catalog scope_name scope_schema scroll search second section security select selective self sensitive sequence sequences serializable server server_name session session_user set setof sets share show similar simple size skip slice smallint snapshot some source space specific specific_name specifictype sql sqlcode sqlerror sqlexception sqlstate sqlwarning sqrt stable stacked standalone start state statement static statistics stddev_pop stddev_samp stdin stdout storage strict strip structure style subclass_origin submultiset subscription substring substring_regex succeeds sum symmetric sysid system system_time system_user t table table_name tables tablesample tablespace temp template temporary text then ties time timestamp timezone_hour timezone_minute to token top_level_count trailing transaction transaction_active transactions_committed transactions_rolled_back transform transforms translate translate_regex translation treat trigger trigger_catalog trigger_name trigger_schema trim trim_array true truncate trusted type types uescape unbounded uncommitted under unencrypted union unique unknown unlink unlisten unlogged unnamed unnest until untyped update upper uri usage use_column use_variable user user_defined_type_catalog user_defined_type_code user_defined_type_name user_defined_type_schema using vacuum valid validate validator value value_of values var_pop var_samp varbinary varchar variable_conflict variadic varying verbose version versioning view views volatile warning when whenever where while whitespace width_bucket window with within without work wrapper write xml xmlagg xmlattributes xmlbinary xmlcast xmlcomment xmlconcat xmldeclaration xmldocument xmlelement xmlexists xmlforest xmliterate xmlnamespaces xmlparse xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltext xmlvalidate year yes zone\"),\n // https://www.postgresql.org/docs/11/datatype.html\n builtin: set(\"bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml\"),\n atoms: set(\"false true null unknown\"),\n operatorChars: /^[*\\/+\\-%<>!=&|^\\/#@?~]/,\n backslashStringEscapes: false,\n dateSQL: set(\"date time timestamp\"),\n support: set(\"ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast escapeConstant\")\n});\n\n// Google's SQL-like query language, GQL\nexport const gql = sql({\n keywords: set(\"ancestor and asc by contains desc descendant distinct from group has in is limit offset on order select superset where\"),\n atoms: set(\"false true\"),\n builtin: set(\"blob datetime first key __key__ string integer double boolean null\"),\n operatorChars: /^[*+\\-%<>!=]/\n});\n\n// Greenplum\nexport const gpSQL = sql({\n client: set(\"source\"),\n //https://github.com/greenplum-db/gpdb/blob/master/src/include/parser/kwlist.h\n keywords: set(\"abort absolute access action active add admin after aggregate all also alter always analyse analyze and any array as asc assertion assignment asymmetric at authorization backward before begin between bigint binary bit boolean both by cache called cascade cascaded case cast chain char character characteristics check checkpoint class close cluster coalesce codegen collate column comment commit committed concurrency concurrently configuration connection constraint constraints contains content continue conversion copy cost cpu_rate_limit create createdb createexttable createrole createuser cross csv cube current current_catalog current_date current_role current_schema current_time current_timestamp current_user cursor cycle data database day deallocate dec decimal declare decode default defaults deferrable deferred definer delete delimiter delimiters deny desc dictionary disable discard distinct distributed do document domain double drop dxl each else enable encoding encrypted end enum errors escape every except exchange exclude excluding exclusive execute exists explain extension external extract false family fetch fields filespace fill filter first float following for force foreign format forward freeze from full function global grant granted greatest group group_id grouping handler hash having header hold host hour identity if ignore ilike immediate immutable implicit in including inclusive increment index indexes inherit inherits initially inline inner inout input insensitive insert instead int integer intersect interval into invoker is isnull isolation join key language large last leading least left level like limit list listen load local localtime localtimestamp location lock log login mapping master match maxvalue median merge minute minvalue missing mode modifies modify month move name names national natural nchar new newline next no nocreatedb nocreateexttable nocreaterole nocreateuser noinherit nologin none noovercommit nosuperuser not nothing notify notnull nowait null nullif nulls numeric object of off offset oids old on only operator option options or order ordered others out outer over overcommit overlaps overlay owned owner parser partial partition partitions passing password percent percentile_cont percentile_disc placing plans position preceding precision prepare prepared preserve primary prior privileges procedural procedure protocol queue quote randomly range read readable reads real reassign recheck recursive ref references reindex reject relative release rename repeatable replace replica reset resource restart restrict returning returns revoke right role rollback rollup rootpartition row rows rule savepoint scatter schema scroll search second security segment select sequence serializable session session_user set setof sets share show similar simple smallint some split sql stable standalone start statement statistics stdin stdout storage strict strip subpartition subpartitions substring superuser symmetric sysid system table tablespace temp template temporary text then threshold ties time timestamp to trailing transaction treat trigger trim true truncate trusted type unbounded uncommitted unencrypted union unique unknown unlisten until update user using vacuum valid validation validator value values varchar variadic varying verbose version view volatile web when where whitespace window with within without work writable write xml xmlattributes xmlconcat xmlelement xmlexists xmlforest xmlparse xmlpi xmlroot xmlserialize year yes zone\"),\n builtin: set(\"bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml\"),\n atoms: set(\"false true null unknown\"),\n operatorChars: /^[*+\\-%<>!=&|^\\/#@?~]/,\n dateSQL: set(\"date time timestamp\"),\n support: set(\"ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast\")\n});\n\n// Spark SQL\nexport const sparkSQL = sql({\n keywords: set(\"add after all alter analyze and anti archive array as asc at between bucket buckets by cache cascade case cast change clear cluster clustered codegen collection column columns comment commit compact compactions compute concatenate cost create cross cube current current_date current_timestamp database databases data dbproperties defined delete delimited deny desc describe dfs directories distinct distribute drop else end escaped except exchange exists explain export extended external false fields fileformat first following for format formatted from full function functions global grant group grouping having if ignore import in index indexes inner inpath inputformat insert intersect interval into is items join keys last lateral lazy left like limit lines list load local location lock locks logical macro map minus msck natural no not null nulls of on optimize option options or order out outer outputformat over overwrite partition partitioned partitions percent preceding principals purge range recordreader recordwriter recover reduce refresh regexp rename repair replace reset restrict revoke right rlike role roles rollback rollup row rows schema schemas select semi separated serde serdeproperties set sets show skewed sort sorted start statistics stored stratify struct table tables tablesample tblproperties temp temporary terminated then to touch transaction transactions transform true truncate unarchive unbounded uncache union unlock unset use using values view when where window with\"),\n builtin: set(\"tinyint smallint int bigint boolean float double string binary timestamp decimal array map struct uniontype delimited serde sequencefile textfile rcfile inputformat outputformat\"),\n atoms: set(\"false true null\"),\n operatorChars: /^[*\\/+\\-%<>!=~&|^]/,\n dateSQL: set(\"date time timestamp\"),\n support: set(\"ODBCdotTable doubleQuote zerolessFloat\")\n});\n\n// Esper\nexport const esper = sql({\n client: set(\"source\"),\n // http://www.espertech.com/esper/release-5.5.0/esper-reference/html/appendix_keywords.html\n keywords: set(\"alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit after all and as at asc avedev avg between by case cast coalesce count create current_timestamp day days delete define desc distinct else end escape events every exists false first from full group having hour hours in inner insert instanceof into irstream is istream join last lastweekday left limit like max match_recognize matches median measures metadatasql min minute minutes msec millisecond milliseconds not null offset on or order outer output partition pattern prev prior regexp retain-union retain-intersection right rstream sec second seconds select set some snapshot sql stddev sum then true unidirectional until update variable weekday when where window\"),\n builtin: {},\n atoms: set(\"false true null\"),\n operatorChars: /^[*+\\-%<>!=&|^\\/#@?~]/,\n dateSQL: set(\"time\"),\n support: set(\"decimallessFloat zerolessFloat binaryNumber hexNumber\")\n});\n\n/*\n How options are used by SQL Mode\n =================================================\n\n keywords:\n A list of keywords you want to be highlighted.\n builtin:\n A list of builtin types you want to be highlighted (if you want types to be of class \"builtin\" instead of \"keyword\").\n operatorChars:\n All characters that must be handled as operators.\n client:\n Commands parsed and executed by the client (not the server).\n support:\n A list of supported syntaxes which are not common, but are supported by more than 1 DBMS.\n * ODBCdotTable: .tableName\n * zerolessFloat: .1\n * doubleQuote\n * nCharCast: N'string'\n * charsetCast: _utf8'string'\n * commentHash: use # char for comments\n * commentSlashSlash: use // for comments\n * commentSpaceRequired: require a space after -- for comments\n atoms:\n Keywords that must be highlighted as atoms,. Some DBMS's support more atoms than others:\n UNKNOWN, INFINITY, UNDERFLOW, NaN...\n dateSQL:\n Used for date/time SQL standard syntax, because not all DBMS's support same temporal types.\n*/\n"],"names":["sql","parserConfig","client","atoms","builtin","set","defaultBuiltin","keywords","sqlKeywords","operatorChars","support","hooks","dateSQL","backslashStringEscapes","brackets","punctuation","tokenBase","stream","state","ch","next","result","hexNumber","match","binaryNumber","charCodeAt","decimallessFloat","eatSpace","eol","eat","doubleQuote","tokenize","tokenLiteral","nCharCast","charsetCast","peek","escapeConstant","commentSlashSlash","skipToEnd","commentHash","commentSpaceRequired","tokenComment","test","eatWhile","word","current","toLowerCase","hasOwnProperty","zerolessFloat","ODBCdotTable","quote","backslashEscapes","escaped","depth","m","pushContext","type","context","prev","indent","indentation","col","column","name","startState","token","sol","align","style","tok","popContext","textAfter","iCx","cx","closing","charAt","unit","languageData","commentTokens","line","block","open","close","closeBrackets","hookIdentifier","backUp","length","hookVar","hookClient","str","obj","words","split","i","standardSQL","msSQL","mySQL","mariaDB","sqlite","identifierQuote","cassandra","plSQL","hive","pgSQL","gql","gpSQL","sparkSQL","esper"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/6641.index.js b/book/_build/html/_static/6641.index.js new file mode 100644 index 0000000..d6010ce --- /dev/null +++ b/book/_build/html/_static/6641.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[6641],{56641:(e,c,O)=>{O.r(c),O.d(c,{wast:()=>s,wastLanguage:()=>$});var r=O(77120),n=O(86253),o=O(51392);const t={__proto__:null,anyref:34,dataref:34,eqref:34,externref:34,i31ref:34,funcref:34,i8:34,i16:34,i32:34,i64:34,f32:34,f64:34},Q=o.WQ.deserialize({version:14,states:"!^Q]QPOOOqQPO'#CbOOQO'#Cd'#CdOOQO'#Cl'#ClOOQO'#Ch'#ChQ]QPOOOOQO,58|,58|OxQPO,58|OOQO-E6f-E6fOOQO1G.h1G.h",stateData:"!P~O_OSPOSQOS~OTPOVROXROYROZROaQO~OSUO~P]OSXO~P]O",goto:"xaPPPPPPbPbPPPhPPPrXROPTVQTOQVPTWTVXSOPTV",nodeNames:"⚠ LineComment BlockComment Module ) ( App Identifier Type Keyword Number String",maxTerm:17,nodeProps:[["openedBy",4,"("],["closedBy",5,")"],["group",-6,6,7,8,9,10,11,"Expression"]],skippedNodes:[0,1,2],repeatNodeCount:1,tokenData:"/Q~R^XY}YZ}]^}pq}rs!Stu!qxy&Vyz'S{|'X}!O'X!Q!R'b!R![)_!]!^,{#T#o-^~!SO_~~!VTOr!Srs!fs#O!S#O#P!k#P~!S~!kOZ~~!nPO~!S~!tiqr$cst$ctu$cuv$cvw$cwx$cz{$c{|$c}!O$c!O!P$c!P!Q$c!Q![$c![!]$c!^!_$c!_!`$c!`!a$c!a!b$c!b!c$c!c!}$c#Q#R$c#R#S$c#S#T$c#T#o$c#p#q$c#r#s$c~$hiV~qr$cst$ctu$cuv$cvw$cwx$cz{$c{|$c}!O$c!O!P$c!P!Q$c!Q![$c![!]$c!^!_$c!_!`$c!`!a$c!a!b$c!b!c$c!c!}$c#Q#R$c#R#S$c#S#T$c#T#o$c#p#q$c#r#s$c~&[PT~!]!^&_~&bRO!]&_!]!^&k!^~&_~&nTOy&_yz&}z!]&_!]!^&k!^~&_~'SOQ~~'XOS~~'[Q!Q!R'b!R![)_~'gUY~!O!P'y!Q![)_!g!h(j#R#S)s#X#Y(j#l#m)y~(ORY~!Q![(X!g!h(j#X#Y(j~(^SY~!Q![(X!g!h(j#R#S)X#X#Y(j~(mR{|(v}!O(v!Q![(|~(yP!Q![(|~)RQY~!Q![(|#R#S(v~)[P!Q![(X~)dTY~!O!P'y!Q![)_!g!h(j#R#S)s#X#Y(j~)vP!Q![)_~)|R!Q![*V!c!i*V#T#Z*V~*[VY~!O!P*q!Q![*V!c!i*V!r!s+n#R#S)y#T#Z*V#d#e+n~*vTY~!Q![+V!c!i+V!r!s+n#T#Z+V#d#e+n~+[UY~!Q![+V!c!i+V!r!s+n#R#S,o#T#Z+V#d#e+n~+qT{|,Q}!O,Q!Q![,^!c!i,^#T#Z,^~,TR!Q![,^!c!i,^#T#Z,^~,cSY~!Q![,^!c!i,^#R#S,Q#T#Z,^~,rR!Q![+V!c!i+V#T#Z+V~-OP!]!^-R~-WQP~OY-RZ~-R~-ciX~qr-^st-^tu-^uv-^vw-^wx-^z{-^{|-^}!O-^!O!P-^!P!Q-^!Q![-^![!]-^!^!_-^!_!`-^!`!a-^!a!b-^!b!c-^!c!}-^#Q#R-^#R#S-^#S#T-^#T#o-^#p#q-^#r#s-^",tokenizers:[0],topRules:{Module:[0,3]},specialized:[{term:9,get:e=>t[e]||-1}],tokenPrec:0}),$=r.qp.define({name:"wast",parser:Q.configure({props:[r.uj.add({App:(0,r.vw)({closing:")",align:!1})}),r.x0.add({App:r.Dv,BlockComment:e=>({from:e.from+2,to:e.to-2})}),(0,n.Gv)({Keyword:n.pJ.keyword,Type:n.pJ.typeName,Number:n.pJ.number,String:n.pJ.string,Identifier:n.pJ.variableName,LineComment:n.pJ.lineComment,BlockComment:n.pJ.blockComment,"( )":n.pJ.paren})]}),languageData:{commentTokens:{line:";;",block:{open:"(;",close:";)"}},closeBrackets:{brackets:["(",'"']}}});function s(){return new r.ri($)}}}]); +//# sourceMappingURL=6641.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/6641.index.js.map b/book/_build/html/_static/6641.index.js.map new file mode 100644 index 0000000..a7ae9c6 --- /dev/null +++ b/book/_build/html/_static/6641.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"6641.index.js","mappings":"kLAKA,MAAMA,EAAe,CAACC,UAAU,KAAKC,OAAO,GAAIC,QAAQ,GAAIC,MAAM,GAAIC,UAAU,GAAIC,OAAO,GAAIC,QAAQ,GAAIC,GAAG,GAAIC,IAAI,GAAIC,IAAI,GAAIC,IAAI,GAAIC,IAAI,GAAIC,IAAI,IAChJC,EAAsB,iBAAqB,CAC/CC,QAAS,GACTC,OAAQ,2GACRC,UAAW,oDACXC,KAAM,4CACNC,UAAW,kFACXC,QAAS,GACTC,UAAW,CACT,CAAC,WAAY,EAAE,KACf,CAAC,WAAY,EAAE,KACf,CAAC,SAAU,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,GAAG,eAE7BC,aAAc,CAAC,EAAE,EAAE,GACnBC,gBAAiB,EACjBC,UAAW,wkCACXC,WAAY,CAAC,GACbC,SAAU,CAAC,OAAS,CAAC,EAAE,IACvBC,YAAa,CAAC,CAACC,KAAM,EAAGC,IAAKC,GAAS9B,EAAa8B,KAAW,IAC9DC,UAAW,IAGPC,EAA4B,YAAkB,CAChDC,KAAM,OACNnB,OAAqBA,EAAOoB,UAAU,CAClCC,MAAO,CACU,SAAmB,CAC5BC,KAAkB,QAAgB,CAAEC,QAAS,IAAKC,OAAO,MAEhD,SAAiB,CAC1BF,IAAK,KACLG,aAAaC,IAAe,CAAEC,KAAMD,EAAKC,KAAO,EAAGC,GAAIF,EAAKE,GAAK,OAExD,QAAU,CACnBC,QAAS,aACTC,KAAM,cACNC,OAAQ,YACRC,OAAQ,YACRC,WAAY,kBACZC,YAAa,iBACbT,aAAc,kBACd,MAAO,gBAInBU,aAAc,CACVC,cAAe,CAAEC,KAAM,KAAMC,MAAO,CAAEC,KAAM,KAAMC,MAAO,OACzDC,cAAe,CAAEC,SAAU,CAAC,IAAK,SAGzC,SAASC,IACL,OAAO,IAAI,KAAgBzB,EAC/B,C","sources":["webpack://thebe/../../node_modules/@codemirror/lang-wast/dist/index.js"],"sourcesContent":["import { LRLanguage, indentNodeProp, delimitedIndent, foldNodeProp, foldInside, LanguageSupport } from '@codemirror/language';\nimport { styleTags, tags } from '@lezer/highlight';\nimport { LRParser } from '@lezer/lr';\n\n// This file was generated by lezer-generator. You probably shouldn't edit it.\nconst spec_Keyword = {__proto__:null,anyref:34, dataref:34, eqref:34, externref:34, i31ref:34, funcref:34, i8:34, i16:34, i32:34, i64:34, f32:34, f64:34};\nconst parser = /*@__PURE__*/LRParser.deserialize({\n version: 14,\n states: \"!^Q]QPOOOqQPO'#CbOOQO'#Cd'#CdOOQO'#Cl'#ClOOQO'#Ch'#ChQ]QPOOOOQO,58|,58|OxQPO,58|OOQO-E6f-E6fOOQO1G.h1G.h\",\n stateData: \"!P~O_OSPOSQOS~OTPOVROXROYROZROaQO~OSUO~P]OSXO~P]O\",\n goto: \"xaPPPPPPbPbPPPhPPPrXROPTVQTOQVPTWTVXSOPTV\",\n nodeNames: \"⚠ LineComment BlockComment Module ) ( App Identifier Type Keyword Number String\",\n maxTerm: 17,\n nodeProps: [\n [\"openedBy\", 4,\"(\"],\n [\"closedBy\", 5,\")\"],\n [\"group\", -6,6,7,8,9,10,11,\"Expression\"]\n ],\n skippedNodes: [0,1,2],\n repeatNodeCount: 1,\n tokenData: \"/Q~R^XY}YZ}]^}pq}rs!Stu!qxy&Vyz'S{|'X}!O'X!Q!R'b!R![)_!]!^,{#T#o-^~!SO_~~!VTOr!Srs!fs#O!S#O#P!k#P~!S~!kOZ~~!nPO~!S~!tiqr$cst$ctu$cuv$cvw$cwx$cz{$c{|$c}!O$c!O!P$c!P!Q$c!Q![$c![!]$c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/*@__PURE__*/LRLanguage.define({\n name: \"wast\",\n parser: /*@__PURE__*/parser.configure({\n props: [\n /*@__PURE__*/indentNodeProp.add({\n App: /*@__PURE__*/delimitedIndent({ closing: \")\", align: false })\n }),\n /*@__PURE__*/foldNodeProp.add({\n App: foldInside,\n BlockComment(tree) { return { from: tree.from + 2, to: tree.to - 2 }; }\n }),\n /*@__PURE__*/styleTags({\n Keyword: tags.keyword,\n Type: tags.typeName,\n Number: tags.number,\n String: tags.string,\n Identifier: tags.variableName,\n LineComment: tags.lineComment,\n BlockComment: tags.blockComment,\n \"( )\": tags.paren\n })\n ]\n }),\n languageData: {\n commentTokens: { line: \";;\", block: { open: \"(;\", close: \";)\" } },\n closeBrackets: { brackets: [\"(\", '\"'] }\n }\n});\nfunction wast() {\n return new LanguageSupport(wastLanguage);\n}\n\nexport { wast, wastLanguage };\n"],"names":["spec_Keyword","__proto__","anyref","dataref","eqref","externref","i31ref","funcref","i8","i16","i32","i64","f32","f64","parser","version","states","stateData","goto","nodeNames","maxTerm","nodeProps","skippedNodes","repeatNodeCount","tokenData","tokenizers","topRules","specialized","term","get","value","tokenPrec","wastLanguage","name","configure","props","App","closing","align","BlockComment","tree","from","to","Keyword","Type","Number","String","Identifier","LineComment","languageData","commentTokens","line","block","open","close","closeBrackets","brackets","wast"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/6686.index.js b/book/_build/html/_static/6686.index.js new file mode 100644 index 0000000..32e3300 --- /dev/null +++ b/book/_build/html/_static/6686.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[6686],{76686:(e,t,n)=>{n.r(t),n.d(t,{q:()=>p});var r,o=new RegExp("^("+["abs","acos","aj","aj0","all","and","any","asc","asin","asof","atan","attr","avg","avgs","bin","by","ceiling","cols","cor","cos","count","cov","cross","csv","cut","delete","deltas","desc","dev","differ","distinct","div","do","each","ej","enlist","eval","except","exec","exit","exp","fby","fills","first","fkeys","flip","floor","from","get","getenv","group","gtime","hclose","hcount","hdel","hopen","hsym","iasc","idesc","if","ij","in","insert","inter","inv","key","keys","last","like","list","lj","load","log","lower","lsq","ltime","ltrim","mavg","max","maxs","mcount","md5","mdev","med","meta","min","mins","mmax","mmin","mmu","mod","msum","neg","next","not","null","or","over","parse","peach","pj","plist","prd","prds","prev","prior","rand","rank","ratios","raze","read0","read1","reciprocal","reverse","rload","rotate","rsave","rtrim","save","scan","select","set","setenv","show","signum","sin","sqrt","ss","ssr","string","sublist","sum","sums","sv","system","tables","tan","til","trim","txf","type","uj","ungroup","union","update","upper","upsert","value","var","view","views","vs","wavg","where","where","while","within","wj","wj1","wsum","xasc","xbar","xcol","xcols","xdesc","xexp","xgroup","xkey","xlog","xprev","xrank"].join("|")+")$"),i=/[|/&^!+:\\\-*%$=~#;@><,?_\'\"\[\(\]\)\s{}]/;function s(e,t){var n=e.sol(),c=e.next();if(r=null,n){if("/"==c)return(t.tokenize=a)(e,t);if("\\"==c)return e.eol()||/\s/.test(e.peek())?(e.skipToEnd(),/^\\\s*$/.test(e.current())?(t.tokenize=l)(e):t.tokenize=s,"comment"):(t.tokenize=s,"builtin")}if(/\s/.test(c))return"/"==e.peek()?(e.skipToEnd(),"comment"):"null";if('"'==c)return(t.tokenize=u)(e,t);if("`"==c)return e.eatWhile(/[A-Za-z\d_:\/.]/),"macroName";if("."==c&&/\d/.test(e.peek())||/\d/.test(c)){var d=null;return e.backUp(1),e.match(/^\d{4}\.\d{2}(m|\.\d{2}([DT](\d{2}(:\d{2}(:\d{2}(\.\d{1,9})?)?)?)?)?)/)||e.match(/^\d+D(\d{2}(:\d{2}(:\d{2}(\.\d{1,9})?)?)?)/)||e.match(/^\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?/)||e.match(/^\d+[ptuv]{1}/)?d="temporal":(e.match(/^0[NwW]{1}/)||e.match(/^0x[\da-fA-F]*/)||e.match(/^[01]+[b]{1}/)||e.match(/^\d+[chijn]{1}/)||e.match(/-?\d*(\.\d*)?(e[+\-]?\d+)?(e|f)?/))&&(d="number"),!d||(c=e.peek())&&!i.test(c)?(e.next(),"error"):d}return/[A-Za-z]|\./.test(c)?(e.eatWhile(/[A-Za-z._\d]/),o.test(e.current())?"keyword":"variable"):/[|/&^!+:\\\-*%$=~#;@><\.,?_\']/.test(c)||/[{}\(\[\]\)]/.test(c)?null:"error"}function a(e,t){return e.skipToEnd(),/\/\s*$/.test(e.current())?(t.tokenize=c)(e,t):t.tokenize=s,"comment"}function c(e,t){var n=e.sol()&&"\\"==e.peek();return e.skipToEnd(),n&&/^\\\s*$/.test(e.current())&&(t.tokenize=s),"comment"}function l(e){return e.skipToEnd(),"comment"}function u(e,t){for(var n,r=!1,o=!1;n=e.next();){if('"'==n&&!r){o=!0;break}r=!r&&"\\"==n}return o&&(t.tokenize=s),"string"}function d(e,t,n){e.context={prev:e.context,indent:e.indent,col:n,type:t}}function m(e){e.indent=e.context.indent,e.context=e.context.prev}const p={name:"q",startState:function(){return{tokenize:s,context:null,indent:0,col:0}},token:function(e,t){e.sol()&&(t.context&&null==t.context.align&&(t.context.align=!1),t.indent=e.indentation());var n=t.tokenize(e,t);if("comment"!=n&&t.context&&null==t.context.align&&"pattern"!=t.context.type&&(t.context.align=!0),"("==r)d(t,")",e.column());else if("["==r)d(t,"]",e.column());else if("{"==r)d(t,"}",e.column());else if(/[\]\}\)]/.test(r)){for(;t.context&&"pattern"==t.context.type;)m(t);t.context&&r==t.context.type&&m(t)}else"."==r&&t.context&&"pattern"==t.context.type?m(t):/atom|string|variable/.test(n)&&t.context&&(/[\}\]]/.test(t.context.type)?d(t,"pattern",e.column()):"pattern"!=t.context.type||t.context.align||(t.context.align=!0,t.context.col=e.column()));return n},indent:function(e,t,n){var r=t&&t.charAt(0),o=e.context;if(/[\]\}]/.test(r))for(;o&&"pattern"==o.type;)o=o.prev;var i=o&&r==o.type;return o?"pattern"==o.type?o.col:o.align?o.col+(i?0:1):o.indent+(i?0:n.unit):0}}}}]); +//# sourceMappingURL=6686.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/6686.index.js.map b/book/_build/html/_static/6686.index.js.map new file mode 100644 index 0000000..99821b3 --- /dev/null +++ b/book/_build/html/_static/6686.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"6686.index.js","mappings":"uHAAA,IAAIA,EACAC,EAEuB,IAAIC,OAAO,KAFjB,CAAC,MAAM,OAAO,KAAK,MAAM,MAAM,MAAM,MAAM,MAAM,OAAO,OAAO,OAAO,OAAO,MAAM,OAAO,MAAM,KAAK,UAAU,OAAO,MAAM,MAAM,QAAQ,MAAM,QAAQ,MAAM,MAAM,SAAS,SAAS,OAAO,MAAM,SAAS,WAAW,MAAM,KAAK,OAAO,KAAK,SAAS,OAAO,SAAS,OAAO,OAAO,MAAM,MAAM,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,OAAO,MAAM,SAAS,QAAQ,QAAQ,SAAS,SAAS,OAAO,QAAQ,OAAO,OAAO,QAAQ,KAAK,KAAK,KAAK,SAAS,QAAQ,MAAM,MAAM,OAAO,OAAO,OAAO,OAAO,KAAK,OAAO,MAAM,QAAQ,MAAM,QAAQ,QAAQ,OAAO,MAAM,OAAO,SAAS,MAAM,OAAO,MAAM,OAAO,MAAM,OAAO,OAAO,OAAO,MAAM,MAAM,OAAO,MAAM,OAAO,MAAM,OAAO,KAAK,OAAO,QAAQ,QAAQ,KAAK,QAAQ,MAAM,OAAO,OAAO,QAAQ,OAAO,OAAO,SAAS,OAAO,QAAQ,QAAQ,aAAa,UAAU,QAAQ,SAAS,QAAQ,QAAQ,OAAO,OAAO,SAAS,MAAM,SAAS,OAAO,SAAS,MAAM,OAAO,KAAK,MAAM,SAAS,UAAU,MAAM,OAAO,KAAK,SAAS,SAAS,MAAM,MAAM,OAAO,MAAM,OAAO,KAAK,UAAU,QAAQ,SAAS,QAAQ,SAAS,QAAQ,MAAM,OAAO,QAAQ,KAAK,OAAO,QAAQ,QAAQ,QAAQ,SAAS,KAAK,MAAM,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([\"abs\",\"acos\",\"aj\",\"aj0\",\"all\",\"and\",\"any\",\"asc\",\"asin\",\"asof\",\"atan\",\"attr\",\"avg\",\"avgs\",\"bin\",\"by\",\"ceiling\",\"cols\",\"cor\",\"cos\",\"count\",\"cov\",\"cross\",\"csv\",\"cut\",\"delete\",\"deltas\",\"desc\",\"dev\",\"differ\",\"distinct\",\"div\",\"do\",\"each\",\"ej\",\"enlist\",\"eval\",\"except\",\"exec\",\"exit\",\"exp\",\"fby\",\"fills\",\"first\",\"fkeys\",\"flip\",\"floor\",\"from\",\"get\",\"getenv\",\"group\",\"gtime\",\"hclose\",\"hcount\",\"hdel\",\"hopen\",\"hsym\",\"iasc\",\"idesc\",\"if\",\"ij\",\"in\",\"insert\",\"inter\",\"inv\",\"key\",\"keys\",\"last\",\"like\",\"list\",\"lj\",\"load\",\"log\",\"lower\",\"lsq\",\"ltime\",\"ltrim\",\"mavg\",\"max\",\"maxs\",\"mcount\",\"md5\",\"mdev\",\"med\",\"meta\",\"min\",\"mins\",\"mmax\",\"mmin\",\"mmu\",\"mod\",\"msum\",\"neg\",\"next\",\"not\",\"null\",\"or\",\"over\",\"parse\",\"peach\",\"pj\",\"plist\",\"prd\",\"prds\",\"prev\",\"prior\",\"rand\",\"rank\",\"ratios\",\"raze\",\"read0\",\"read1\",\"reciprocal\",\"reverse\",\"rload\",\"rotate\",\"rsave\",\"rtrim\",\"save\",\"scan\",\"select\",\"set\",\"setenv\",\"show\",\"signum\",\"sin\",\"sqrt\",\"ss\",\"ssr\",\"string\",\"sublist\",\"sum\",\"sums\",\"sv\",\"system\",\"tables\",\"tan\",\"til\",\"trim\",\"txf\",\"type\",\"uj\",\"ungroup\",\"union\",\"update\",\"upper\",\"upsert\",\"value\",\"var\",\"view\",\"views\",\"vs\",\"wavg\",\"where\",\"where\",\"while\",\"within\",\"wj\",\"wj1\",\"wsum\",\"xasc\",\"xbar\",\"xcol\",\"xcols\",\"xdesc\",\"xexp\",\"xgroup\",\"xkey\",\"xlog\",\"xprev\",\"xrank\"]),\n E=/[|/&^!+:\\\\\\-*%$=~#;@><,?_\\'\\\"\\[\\(\\]\\)\\s{}]/;\nfunction buildRE(w){return new RegExp(\"^(\"+w.join(\"|\")+\")$\");}\nfunction tokenBase(stream,state){\n var sol=stream.sol(),c=stream.next();\n curPunc=null;\n if(sol)\n if(c==\"/\")\n return(state.tokenize=tokenLineComment)(stream,state);\n else if(c==\"\\\\\"){\n if(stream.eol()||/\\s/.test(stream.peek()))\n return stream.skipToEnd(),/^\\\\\\s*$/.test(stream.current())?(state.tokenize=tokenCommentToEOF)(stream):state.tokenize=tokenBase,\"comment\";\n else\n return state.tokenize=tokenBase,\"builtin\";\n }\n if(/\\s/.test(c))\n return stream.peek()==\"/\"?(stream.skipToEnd(),\"comment\"):\"null\";\n if(c=='\"')\n return(state.tokenize=tokenString)(stream,state);\n if(c=='`')\n return stream.eatWhile(/[A-Za-z\\d_:\\/.]/),\"macroName\";\n if((\".\"==c&&/\\d/.test(stream.peek()))||/\\d/.test(c)){\n var t=null;\n stream.backUp(1);\n if(stream.match(/^\\d{4}\\.\\d{2}(m|\\.\\d{2}([DT](\\d{2}(:\\d{2}(:\\d{2}(\\.\\d{1,9})?)?)?)?)?)/)\n || stream.match(/^\\d+D(\\d{2}(:\\d{2}(:\\d{2}(\\.\\d{1,9})?)?)?)/)\n || stream.match(/^\\d{2}:\\d{2}(:\\d{2}(\\.\\d{1,9})?)?/)\n || stream.match(/^\\d+[ptuv]{1}/))\n t=\"temporal\";\n else if(stream.match(/^0[NwW]{1}/)\n || stream.match(/^0x[\\da-fA-F]*/)\n || stream.match(/^[01]+[b]{1}/)\n || stream.match(/^\\d+[chijn]{1}/)\n || stream.match(/-?\\d*(\\.\\d*)?(e[+\\-]?\\d+)?(e|f)?/))\n t=\"number\";\n return(t&&(!(c=stream.peek())||E.test(c)))?t:(stream.next(),\"error\");\n }\n if(/[A-Za-z]|\\./.test(c))\n return stream.eatWhile(/[A-Za-z._\\d]/),keywords.test(stream.current())?\"keyword\":\"variable\";\n if(/[|/&^!+:\\\\\\-*%$=~#;@><\\.,?_\\']/.test(c))\n return null;\n if(/[{}\\(\\[\\]\\)]/.test(c))\n return null;\n return\"error\";\n}\nfunction tokenLineComment(stream,state){\n return stream.skipToEnd(),/\\/\\s*$/.test(stream.current())?(state.tokenize=tokenBlockComment)(stream,state):(state.tokenize=tokenBase),\"comment\";\n}\nfunction tokenBlockComment(stream,state){\n var f=stream.sol()&&stream.peek()==\"\\\\\";\n stream.skipToEnd();\n if(f&&/^\\\\\\s*$/.test(stream.current()))\n state.tokenize=tokenBase;\n return\"comment\";\n}\nfunction tokenCommentToEOF(stream){return stream.skipToEnd(),\"comment\";}\nfunction tokenString(stream,state){\n var escaped=false,next,end=false;\n while((next=stream.next())){\n if(next==\"\\\"\"&&!escaped){end=true;break;}\n escaped=!escaped&&next==\"\\\\\";\n }\n if(end)state.tokenize=tokenBase;\n return\"string\";\n}\nfunction pushContext(state,type,col){state.context={prev:state.context,indent:state.indent,col:col,type:type};}\nfunction popContext(state){state.indent=state.context.indent;state.context=state.context.prev;}\nexport const q = {\n name: \"q\",\n startState:function(){\n return{tokenize:tokenBase,\n context:null,\n indent:0,\n col:0};\n },\n token:function(stream,state){\n if(stream.sol()){\n if(state.context&&state.context.align==null)\n state.context.align=false;\n state.indent=stream.indentation();\n }\n //if (stream.eatSpace()) return null;\n var style=state.tokenize(stream,state);\n if(style!=\"comment\"&&state.context&&state.context.align==null&&state.context.type!=\"pattern\"){\n state.context.align=true;\n }\n if(curPunc==\"(\")pushContext(state,\")\",stream.column());\n else if(curPunc==\"[\")pushContext(state,\"]\",stream.column());\n else if(curPunc==\"{\")pushContext(state,\"}\",stream.column());\n else if(/[\\]\\}\\)]/.test(curPunc)){\n while(state.context&&state.context.type==\"pattern\")popContext(state);\n if(state.context&&curPunc==state.context.type)popContext(state);\n }\n else if(curPunc==\".\"&&state.context&&state.context.type==\"pattern\")popContext(state);\n else if(/atom|string|variable/.test(style)&&state.context){\n if(/[\\}\\]]/.test(state.context.type))\n pushContext(state,\"pattern\",stream.column());\n else if(state.context.type==\"pattern\"&&!state.context.align){\n state.context.align=true;\n state.context.col=stream.column();\n }\n }\n return style;\n },\n indent:function(state,textAfter,cx){\n var firstChar=textAfter&&textAfter.charAt(0);\n var context=state.context;\n if(/[\\]\\}]/.test(firstChar))\n while (context&&context.type==\"pattern\")context=context.prev;\n var closing=context&&firstChar==context.type;\n if(!context)\n return 0;\n else if(context.type==\"pattern\")\n return context.col;\n else if(context.align)\n return context.col+(closing?0:1);\n else\n return context.indent+(closing?0:cx.unit);\n }\n};\n"],"names":["curPunc","keywords","RegExp","join","E","tokenBase","stream","state","sol","c","next","tokenize","tokenLineComment","eol","test","peek","skipToEnd","current","tokenCommentToEOF","tokenString","eatWhile","t","backUp","match","tokenBlockComment","f","escaped","end","pushContext","type","col","context","prev","indent","popContext","q","name","startState","token","align","indentation","style","column","textAfter","cx","firstChar","charAt","closing","unit"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/6737.index.js b/book/_build/html/_static/6737.index.js new file mode 100644 index 0000000..0d7d1cf --- /dev/null +++ b/book/_build/html/_static/6737.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[6737],{6737:(e,t,n)=>{n.r(t),n.d(t,{toml:()=>r});const r={name:"toml",startState:function(){return{inString:!1,stringType:"",lhs:!0,inArray:0}},token:function(e,t){if(t.inString||'"'!=e.peek()&&"'"!=e.peek()||(t.stringType=e.peek(),e.next(),t.inString=!0),e.sol()&&0===t.inArray&&(t.lhs=!0),t.inString){for(;t.inString&&!e.eol();)e.peek()===t.stringType?(e.next(),t.inString=!1):"\\"===e.peek()?(e.next(),e.next()):e.match(/^.[^\\\"\']*/);return t.lhs?"property":"string"}return t.inArray&&"]"===e.peek()?(e.next(),t.inArray--,"bracket"):t.lhs&&"["===e.peek()&&e.skipTo("]")?(e.next(),"]"===e.peek()&&e.next(),"atom"):"#"===e.peek()?(e.skipToEnd(),"comment"):e.eatSpace()?null:t.lhs&&e.eatWhile((function(e){return"="!=e&&" "!=e}))?"property":t.lhs&&"="===e.peek()?(e.next(),t.lhs=!1,null):!t.lhs&&e.match(/^\d\d\d\d[\d\-\:\.T]*Z/)?"atom":t.lhs||!e.match("true")&&!e.match("false")?t.lhs||"["!==e.peek()?!t.lhs&&e.match(/^\-?\d+(?:\.\d+)?/)?"number":(e.eatSpace()||e.next(),null):(t.inArray++,e.next(),"bracket"):"atom"},languageData:{commentTokens:{line:"#"}}}}}]); +//# sourceMappingURL=6737.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/6737.index.js.map b/book/_build/html/_static/6737.index.js.map new file mode 100644 index 0000000..4110e63 --- /dev/null +++ b/book/_build/html/_static/6737.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"6737.index.js","mappings":"yHAAO,MAAMA,EAAO,CAClBC,KAAM,OACNC,WAAY,WACV,MAAO,CACLC,UAAU,EACVC,WAAY,GACZC,KAAK,EACLC,QAAS,EAEb,EACAC,MAAO,SAAUC,EAAQC,GAWvB,GATKA,EAAMN,UAA+B,KAAjBK,EAAOE,QAAoC,KAAjBF,EAAOE,SACxDD,EAAML,WAAaI,EAAOE,OAC1BF,EAAOG,OACPF,EAAMN,UAAW,GAEfK,EAAOI,OAA2B,IAAlBH,EAAMH,UACxBG,EAAMJ,KAAM,GAGVI,EAAMN,SAAU,CAClB,KAAOM,EAAMN,WAAaK,EAAOK,OAC3BL,EAAOE,SAAWD,EAAML,YAC1BI,EAAOG,OACPF,EAAMN,UAAW,GACU,OAAlBK,EAAOE,QAChBF,EAAOG,OACPH,EAAOG,QAEPH,EAAOM,MAAM,gBAGjB,OAAOL,EAAMJ,IAAM,WAAa,QAClC,CAAO,OAAII,EAAMH,SAA6B,MAAlBE,EAAOE,QACjCF,EAAOG,OACPF,EAAMH,UACC,WACEG,EAAMJ,KAAyB,MAAlBG,EAAOE,QAAkBF,EAAOO,OAAO,MAC7DP,EAAOG,OAEe,MAAlBH,EAAOE,QAAgBF,EAAOG,OAC3B,QACoB,MAAlBH,EAAOE,QAChBF,EAAOQ,YACA,WACER,EAAOS,WACT,KACER,EAAMJ,KAAOG,EAAOU,UAAS,SAAUC,GAAK,MAAY,KAALA,GAAiB,KAALA,CAAU,IAC3E,WACEV,EAAMJ,KAAyB,MAAlBG,EAAOE,QAC7BF,EAAOG,OACPF,EAAMJ,KAAM,EACL,OACGI,EAAMJ,KAAOG,EAAOM,MAAM,0BAC7B,OACGL,EAAMJ,MAAQG,EAAOM,MAAM,UAAWN,EAAOM,MAAM,SAEnDL,EAAMJ,KAAyB,MAAlBG,EAAOE,QAIpBD,EAAMJ,KAAOG,EAAOM,MAAM,qBAC7B,UACGN,EAAOS,YACjBT,EAAOG,OAEF,OARLF,EAAMH,UACNE,EAAOG,OACA,WAJA,MAWX,EACAS,aAAc,CACZC,cAAe,CAAEC,KAAM,M","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/toml.js"],"sourcesContent":["export const toml = {\n name: \"toml\",\n startState: function () {\n return {\n inString: false,\n stringType: \"\",\n lhs: true,\n inArray: 0\n };\n },\n token: function (stream, state) {\n //check for state changes\n if (!state.inString && ((stream.peek() == '\"') || (stream.peek() == \"'\"))) {\n state.stringType = stream.peek();\n stream.next(); // Skip quote\n state.inString = true; // Update state\n }\n if (stream.sol() && state.inArray === 0) {\n state.lhs = true;\n }\n //return state\n if (state.inString) {\n while (state.inString && !stream.eol()) {\n if (stream.peek() === state.stringType) {\n stream.next(); // Skip quote\n state.inString = false; // Clear flag\n } else if (stream.peek() === '\\\\') {\n stream.next();\n stream.next();\n } else {\n stream.match(/^.[^\\\\\\\"\\']*/);\n }\n }\n return state.lhs ? \"property\" : \"string\"; // Token style\n } else if (state.inArray && stream.peek() === ']') {\n stream.next();\n state.inArray--;\n return 'bracket';\n } else if (state.lhs && stream.peek() === '[' && stream.skipTo(']')) {\n stream.next();//skip closing ]\n // array of objects has an extra open & close []\n if (stream.peek() === ']') stream.next();\n return \"atom\";\n } else if (stream.peek() === \"#\") {\n stream.skipToEnd();\n return \"comment\";\n } else if (stream.eatSpace()) {\n return null;\n } else if (state.lhs && stream.eatWhile(function (c) { return c != '=' && c != ' '; })) {\n return \"property\";\n } else if (state.lhs && stream.peek() === \"=\") {\n stream.next();\n state.lhs = false;\n return null;\n } else if (!state.lhs && stream.match(/^\\d\\d\\d\\d[\\d\\-\\:\\.T]*Z/)) {\n return 'atom'; //date\n } else if (!state.lhs && (stream.match('true') || stream.match('false'))) {\n return 'atom';\n } else if (!state.lhs && stream.peek() === '[') {\n state.inArray++;\n stream.next();\n return 'bracket';\n } else if (!state.lhs && stream.match(/^\\-?\\d+(?:\\.\\d+)?/)) {\n return 'number';\n } else if (!stream.eatSpace()) {\n stream.next();\n }\n return null;\n },\n languageData: {\n commentTokens: { line: '#' },\n },\n};\n"],"names":["toml","name","startState","inString","stringType","lhs","inArray","token","stream","state","peek","next","sol","eol","match","skipTo","skipToEnd","eatSpace","eatWhile","c","languageData","commentTokens","line"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/6842.index.js b/book/_build/html/_static/6842.index.js new file mode 100644 index 0000000..be636c1 --- /dev/null +++ b/book/_build/html/_static/6842.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[6842],{26842:(e,t,n)=>{function r(e){for(var t={},n=e.split(" "),r=0;rM});const i={name:"ttcn",keywords:r("activate address alive all alt altstep and and4b any break case component const continue control deactivate display do else encode enumerated except exception execute extends extension external for from function goto group if import in infinity inout interleave label language length log match message mixed mod modifies module modulepar mtc noblock not not4b nowait of on optional or or4b out override param pattern port procedure record recursive rem repeat return runs select self sender set signature system template testcase to type union value valueof var variant while with xor xor4b"),builtin:r("bit2hex bit2int bit2oct bit2str char2int char2oct encvalue decomp decvalue float2int float2str hex2bit hex2int hex2oct hex2str int2bit int2char int2float int2hex int2oct int2str int2unichar isbound ischosen ispresent isvalue lengthof log2str oct2bit oct2char oct2hex oct2int oct2str regexp replace rnd sizeof str2bit str2float str2hex str2int str2oct substr unichar2int unichar2char enum2int"),types:r("anytype bitstring boolean char charstring default float hexstring integer objid octetstring universal verdicttype timer"),timerOps:r("read running start stop timeout"),portOps:r("call catch check clear getcall getreply halt raise receive reply send trigger"),configOps:r("create connect disconnect done kill killed map unmap"),verdictOps:r("getverdict setverdict"),sutOps:r("action"),functionOps:r("apply derefers refers"),verdictConsts:r("error fail inconc none pass"),booleanConsts:r("true false"),otherConsts:r("null NULL omit"),visibilityModifiers:r("private public friend"),templateMatch:r("complement ifpresent subset superset permutation"),multiLineStrings:!0};var o=[];function a(e){if(e)for(var t in e)e.hasOwnProperty(t)&&o.push(t)}a(i.keywords),a(i.builtin),a(i.timerOps),a(i.portOps);var s,l=i.keywords||{},c=i.builtin||{},u=i.timerOps||{},p=i.portOps||{},m=i.configOps||{},f=i.verdictOps||{},d=i.sutOps||{},b=i.functionOps||{},h=i.verdictConsts||{},y=i.booleanConsts||{},v=i.otherConsts||{},g=i.types||{},x=i.visibilityModifiers||{},k=i.templateMatch||{},O=i.multiLineStrings,w=!1!==i.indentStatements,E=/[+\-*&@=<>!\/]/;function I(e,t){var n,r=e.next();if('"'==r||"'"==r)return t.tokenize=(n=r,function(e,t){for(var r,i=!1,o=!1;null!=(r=e.next());){if(r==n&&!i){var a=e.peek();a&&("b"!=(a=a.toLowerCase())&&"h"!=a&&"o"!=a||e.next()),o=!0;break}i=!i&&"\\"==r}return(o||!i&&!O)&&(t.tokenize=null),"string"}),t.tokenize(e,t);if(/[\[\]{}\(\),;\\:\?\.]/.test(r))return s=r,"punctuation";if("#"==r)return e.skipToEnd(),"atom";if("%"==r)return e.eatWhile(/\b/),"atom";if(/\d/.test(r))return e.eatWhile(/[\w\.]/),"number";if("/"==r){if(e.eat("*"))return t.tokenize=z,z(e,t);if(e.eat("/"))return e.skipToEnd(),"comment"}if(E.test(r))return"@"==r&&(e.match("try")||e.match("catch")||e.match("lazy"))?"keyword":(e.eatWhile(E),"operator");e.eatWhile(/[\w\$_\xa1-\uffff]/);var i=e.current();return l.propertyIsEnumerable(i)?"keyword":c.propertyIsEnumerable(i)?"builtin":u.propertyIsEnumerable(i)||m.propertyIsEnumerable(i)||f.propertyIsEnumerable(i)||p.propertyIsEnumerable(i)||d.propertyIsEnumerable(i)||b.propertyIsEnumerable(i)?"def":h.propertyIsEnumerable(i)||y.propertyIsEnumerable(i)||v.propertyIsEnumerable(i)?"string":g.propertyIsEnumerable(i)?"typeName.standard":x.propertyIsEnumerable(i)?"modifier":k.propertyIsEnumerable(i)?"atom":"variable"}function z(e,t){for(var n,r=!1;n=e.next();){if("/"==n&&r){t.tokenize=null;break}r="*"==n}return"comment"}function C(e,t,n,r,i){this.indented=e,this.column=t,this.type=n,this.align=r,this.prev=i}function L(e,t,n){var r=e.indented;return e.context&&"statement"==e.context.type&&(r=e.context.indented),e.context=new C(r,t,n,null,e.context)}function S(e){var t=e.context.type;return")"!=t&&"]"!=t&&"}"!=t||(e.indented=e.context.indented),e.context=e.context.prev}const M={name:"ttcn",startState:function(){return{tokenize:null,context:new C(0,0,"top",!1),indented:0,startOfLine:!0}},token:function(e,t){var n=t.context;if(e.sol()&&(null==n.align&&(n.align=!1),t.indented=e.indentation(),t.startOfLine=!0),e.eatSpace())return null;s=null;var r=(t.tokenize||I)(e,t);if("comment"==r)return r;if(null==n.align&&(n.align=!0),";"!=s&&":"!=s&&","!=s||"statement"!=n.type)if("{"==s)L(t,e.column(),"}");else if("["==s)L(t,e.column(),"]");else if("("==s)L(t,e.column(),")");else if("}"==s){for(;"statement"==n.type;)n=S(t);for("}"==n.type&&(n=S(t));"statement"==n.type;)n=S(t)}else s==n.type?S(t):w&&(("}"==n.type||"top"==n.type)&&";"!=s||"statement"==n.type&&"newstatement"==s)&&L(t,e.column(),"statement");else S(t);return t.startOfLine=!1,r},languageData:{indentOnInput:/^\s*[{}]$/,commentTokens:{line:"//",block:{open:"/*",close:"*/"}},autocomplete:o}}}}]); +//# sourceMappingURL=6842.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/6842.index.js.map b/book/_build/html/_static/6842.index.js.map new file mode 100644 index 0000000..e2b9e61 --- /dev/null +++ b/book/_build/html/_static/6842.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"6842.index.js","mappings":"+FAAA,SAASA,EAAMC,GAEb,IADA,IAAIC,EAAM,CAAC,EAAGF,EAAQC,EAAIE,MAAM,KACvBC,EAAI,EAAGA,EAAIJ,EAAMK,SAAUD,EAAGF,EAAIF,EAAMI,KAAM,EACvD,OAAOF,CACT,C,2BAEA,MAAMI,EAAe,CACnBC,KAAM,OACNC,SAAUR,EAAM,klBAWhBS,QAAST,EAAM,2YAQfU,MAAOV,EAAM,2HAEbW,SAAUX,EAAM,mCAChBY,QAASZ,EAAM,iFAEfa,UAAWb,EAAM,wDACjBc,WAAYd,EAAM,yBAClBe,OAAQf,EAAM,UACdgB,YAAahB,EAAM,yBAEnBiB,cAAejB,EAAM,+BACrBkB,cAAelB,EAAM,cACrBmB,YAAanB,EAAM,kBAEnBoB,oBAAqBpB,EAAM,yBAC3BqB,cAAerB,EAAM,oDACrBsB,kBAAkB,GAGpB,IAAIC,EAAW,GACf,SAASC,EAAItB,GACX,GAAIA,EAAK,IAAK,IAAIuB,KAAQvB,EAASA,EAAIwB,eAAeD,IACpDF,EAASI,KAAKF,EAClB,CACAD,EAAIlB,EAAaE,UACjBgB,EAAIlB,EAAaG,SACjBe,EAAIlB,EAAaK,UACjBa,EAAIlB,EAAaM,SAEjB,IAmBIgB,EAnBApB,EAAWF,EAAaE,UAAY,CAAC,EACrCC,EAAUH,EAAaG,SAAW,CAAC,EACnCE,EAAWL,EAAaK,UAAY,CAAC,EACrCC,EAAWN,EAAaM,SAAW,CAAC,EACpCC,EAAYP,EAAaO,WAAa,CAAC,EACvCC,EAAaR,EAAaQ,YAAc,CAAC,EACzCC,EAAST,EAAaS,QAAU,CAA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AAX5B,IACpCgC,EAAY3B,EAAOD,EAAOuB,SAAU,kBAdpCS,EAAW/B,GAkBb,OAFAA,EAAMmC,aAAc,EAEbM,CACT,EAEAC,aAAc,CACZC,cAAe,YACfC,cAAe,CAACC,KAAM,KAAMC,MAAO,CAACC,KAAM,KAAMC,MAAO,OACvDC,aAAc3D,G","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/ttcn.js"],"sourcesContent":["function words(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n}\n\nconst parserConfig = {\n name: \"ttcn\",\n keywords: words(\"activate address alive all alt altstep and and4b any\" +\n \" break case component const continue control deactivate\" +\n \" display do else encode enumerated except exception\" +\n \" execute extends extension external for from function\" +\n \" goto group if import in infinity inout interleave\" +\n \" label language length log match message mixed mod\" +\n \" modifies module modulepar mtc noblock not not4b nowait\" +\n \" of on optional or or4b out override param pattern port\" +\n \" procedure record recursive rem repeat return runs select\" +\n \" self sender set signature system template testcase to\" +\n \" type union value valueof var variant while with xor xor4b\"),\n builtin: words(\"bit2hex bit2int bit2oct bit2str char2int char2oct encvalue\" +\n \" decomp decvalue float2int float2str hex2bit hex2int\" +\n \" hex2oct hex2str int2bit int2char int2float int2hex\" +\n \" int2oct int2str int2unichar isbound ischosen ispresent\" +\n \" isvalue lengthof log2str oct2bit oct2char oct2hex oct2int\" +\n \" oct2str regexp replace rnd sizeof str2bit str2float\" +\n \" str2hex str2int str2oct substr unichar2int unichar2char\" +\n \" enum2int\"),\n types: words(\"anytype bitstring boolean char charstring default float\" +\n \" hexstring integer objid octetstring universal verdicttype timer\"),\n timerOps: words(\"read running start stop timeout\"),\n portOps: words(\"call catch check clear getcall getreply halt raise receive\" +\n \" reply send trigger\"),\n configOps: words(\"create connect disconnect done kill killed map unmap\"),\n verdictOps: words(\"getverdict setverdict\"),\n sutOps: words(\"action\"),\n functionOps: words(\"apply derefers refers\"),\n\n verdictConsts: words(\"error fail inconc none pass\"),\n booleanConsts: words(\"true false\"),\n otherConsts: words(\"null NULL omit\"),\n\n visibilityModifiers: words(\"private public friend\"),\n templateMatch: words(\"complement ifpresent subset superset permutation\"),\n multiLineStrings: true\n}\n\nvar wordList = []\nfunction add(obj) {\n if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop))\n wordList.push(prop);\n}\nadd(parserConfig.keywords);\nadd(parserConfig.builtin);\nadd(parserConfig.timerOps);\nadd(parserConfig.portOps);\n\nvar keywords = parserConfig.keywords || {},\n builtin = parserConfig.builtin || {},\n timerOps = parserConfig.timerOps || {},\n portOps = parserConfig.portOps || {},\n configOps = parserConfig.configOps || {},\n verdictOps = parserConfig.verdictOps || {},\n sutOps = parserConfig.sutOps || {},\n functionOps = parserConfig.functionOps || {},\n\n verdictConsts = parserConfig.verdictConsts || {},\n booleanConsts = parserConfig.booleanConsts || {},\n otherConsts = parserConfig.otherConsts || {},\n\n types = parserConfig.types || {},\n visibilityModifiers = parserConfig.visibilityModifiers || {},\n templateMatch = parserConfig.templateMatch || {},\n multiLineStrings = parserConfig.multiLineStrings,\n indentStatements = parserConfig.indentStatements !== false;\nvar isOperatorChar = /[+\\-*&@=<>!\\/]/;\nvar curPunc;\n\nfunction tokenBase(stream, state) {\n var ch = stream.next();\n\n if (ch == '\"' || ch == \"'\") {\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n }\n if (/[\\[\\]{}\\(\\),;\\\\:\\?\\.]/.test(ch)) {\n curPunc = ch;\n return \"punctuation\";\n }\n if (ch == \"#\"){\n stream.skipToEnd();\n return \"atom\";\n }\n if (ch == \"%\"){\n stream.eatWhile(/\\b/);\n return \"atom\";\n }\n if (/\\d/.test(ch)) {\n stream.eatWhile(/[\\w\\.]/);\n return \"number\";\n }\n if (ch == \"/\") {\n if (stream.eat(\"*\")) {\n state.tokenize = tokenComment;\n return tokenComment(stream, state);\n }\n if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return \"comment\";\n }\n }\n if (isOperatorChar.test(ch)) {\n if(ch == \"@\"){\n if(stream.match(\"try\") || stream.match(\"catch\")\n || stream.match(\"lazy\")){\n return \"keyword\";\n }\n }\n stream.eatWhile(isOperatorChar);\n return \"operator\";\n }\n stream.eatWhile(/[\\w\\$_\\xa1-\\uffff]/);\n var cur = stream.current();\n\n if (keywords.propertyIsEnumerable(cur)) return \"keyword\";\n if (builtin.propertyIsEnumerable(cur)) return \"builtin\";\n\n if (timerOps.propertyIsEnumerable(cur)) return \"def\";\n if (configOps.propertyIsEnumerable(cur)) return \"def\";\n if (verdictOps.propertyIsEnumerable(cur)) return \"def\";\n if (portOps.propertyIsEnumerable(cur)) return \"def\";\n if (sutOps.propertyIsEnumerable(cur)) return \"def\";\n if (functionOps.propertyIsEnumerable(cur)) return \"def\";\n\n if (verdictConsts.propertyIsEnumerable(cur)) return \"string\";\n if (booleanConsts.propertyIsEnumerable(cur)) return \"string\";\n if (otherConsts.propertyIsEnumerable(cur)) return \"string\";\n\n if (types.propertyIsEnumerable(cur)) return \"typeName.standard\";\n if (visibilityModifiers.propertyIsEnumerable(cur))\n return \"modifier\";\n if (templateMatch.propertyIsEnumerable(cur)) return \"atom\";\n\n return \"variable\";\n}\n\nfunction tokenString(quote) {\n return function(stream, state) {\n var escaped = false, next, end = false;\n while ((next = stream.next()) != null) {\n if (next == quote && !escaped){\n var afterQuote = stream.peek();\n //look if the character after the quote is like the B in '10100010'B\n if (afterQuote){\n afterQuote = afterQuote.toLowerCase();\n if(afterQuote == \"b\" || afterQuote == \"h\" || afterQuote == \"o\")\n stream.next();\n }\n end = true; break;\n }\n escaped = !escaped && next == \"\\\\\";\n }\n if (end || !(escaped || multiLineStrings))\n state.tokenize = null;\n return \"string\";\n };\n}\n\nfunction tokenComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if (ch == \"/\" && maybeEnd) {\n state.tokenize = null;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return \"comment\";\n}\n\nfunction Context(indented, column, type, align, prev) {\n this.indented = indented;\n this.column = column;\n this.type = type;\n this.align = align;\n this.prev = prev;\n}\n\nfunction pushContext(state, col, type) {\n var indent = state.indented;\n if (state.context && state.context.type == \"statement\")\n indent = state.context.indented;\n return state.context = new Context(indent, col, type, null, state.context);\n}\n\nfunction popContext(state) {\n var t = state.context.type;\n if (t == \")\" || t == \"]\" || t == \"}\")\n state.indented = state.context.indented;\n return state.context = state.context.prev;\n}\n\n//Interface\nexport const ttcn = {\n name: \"ttcn\",\n startState: function() {\n return {\n tokenize: null,\n context: new Context(0, 0, \"top\", false),\n indented: 0,\n startOfLine: true\n };\n },\n\n token: function(stream, state) {\n var ctx = state.context;\n if (stream.sol()) {\n if (ctx.align == null) ctx.align = false;\n state.indented = stream.indentation();\n state.startOfLine = true;\n }\n if (stream.eatSpace()) return null;\n curPunc = null;\n var style = (state.tokenize || tokenBase)(stream, state);\n if (style == \"comment\") return style;\n if (ctx.align == null) ctx.align = true;\n\n if ((curPunc == \";\" || curPunc == \":\" || curPunc == \",\")\n && ctx.type == \"statement\"){\n popContext(state);\n }\n else if (curPunc == \"{\") pushContext(state, stream.column(), \"}\");\n else if (curPunc == \"[\") pushContext(state, stream.column(), \"]\");\n else if (curPunc == \"(\") pushContext(state, stream.column(), \")\");\n else if (curPunc == \"}\") {\n while (ctx.type == \"statement\") ctx = popContext(state);\n if (ctx.type == \"}\") ctx = popContext(state);\n while (ctx.type == \"statement\") ctx = popContext(state);\n }\n else if (curPunc == ctx.type) popContext(state);\n else if (indentStatements &&\n (((ctx.type == \"}\" || ctx.type == \"top\") && curPunc != ';') ||\n (ctx.type == \"statement\" && curPunc == \"newstatement\")))\n pushContext(state, stream.column(), \"statement\");\n\n state.startOfLine = false;\n\n return style;\n },\n\n languageData: {\n indentOnInput: /^\\s*[{}]$/,\n commentTokens: {line: \"//\", block: {open: \"/*\", close: \"*/\"}},\n autocomplete: wordList\n }\n};\n"],"names":["words","str","obj","split","i","length","parserConfig","name","keywords","builtin","types","timerOps","portOps","configOps","verdictOps","sutOps","functionOps","verdictConsts","booleanConsts","otherConsts","visibilityModifiers","templateMatch","multiLineStrings","wordList","add","prop","hasOwnProperty","push","curPunc","indentStatements","isOperatorChar","tokenBase","stream","state","quote","ch","next","tokenize","escaped","end","afterQuote","peek","toLowerCase","test","skipToEnd","eatWhile","eat","tokenComment","match","cur","current","propertyIsEnumerable","maybeEnd","Context","indented","column","type","align","prev","this","pushContext","col","indent","context","popContext","t","ttcn","startState","startOfLine","token","ctx","sol","indentation","eatSpace","style","languageData","indentOnInput","commentTokens","line","block","open","close","autocomplete"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/6873.index.js b/book/_build/html/_static/6873.index.js new file mode 100644 index 0000000..fd09952 --- /dev/null +++ b/book/_build/html/_static/6873.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[6873],{96873:(t,e,n)=>{n.r(e),n.d(e,{textile:()=>p});var i={addition:"inserted",attributes:"propertyName",bold:"strong",cite:"keyword",code:"monospace",definitionList:"list",deletion:"deleted",div:"punctuation",em:"emphasis",footnote:"variable",footCite:"qualifier",header:"heading",html:"comment",image:"atom",italic:"emphasis",link:"link",linkDefinition:"link",list1:"list",list2:"list.special",list3:"list",notextile:"string.special",pre:"operator",p:"content",quote:"bracket",span:"quote",specialChar:"character",strong:"strong",sub:"content.special",sup:"content.special",table:"variableName.special",tableHeading:"operator"};function a(t,e,n){if("_"===n)return t.eat("_")?r(t,e,"italic",/__/,2):r(t,e,"em",/_/,1);if("*"===n)return t.eat("*")?r(t,e,"bold",/\*\*/,2):r(t,e,"strong",/\*/,1);if("["===n)return t.match(/\d+\]/)&&(e.footCite=!0),l(e);if("("===n&&t.match(/^(r|tm|c)\)/))return i.specialChar;if("<"===n&&t.match(/(\w+)[^>]+>[^<]+<\/\1>/))return i.html;if("?"===n&&t.eat("?"))return r(t,e,"cite",/\?\?/,2);if("="===n&&t.eat("="))return r(t,e,"notextile",/==/,2);if("-"===n&&!t.eat("-"))return r(t,e,"deletion",/-/,1);if("+"===n)return r(t,e,"addition",/\+/,1);if("~"===n)return r(t,e,"sub",/~/,1);if("^"===n)return r(t,e,"sup",/\^/,1);if("%"===n)return r(t,e,"span",/%/,1);if("@"===n)return r(t,e,"code",/@/,1);if("!"===n){var a=r(t,e,"image",/(?:\([^\)]+\))?!/,1);return t.match(/^:\S+/),a}return l(e)}function r(t,e,n,i,a){var r=t.pos>a?t.string.charAt(t.pos-a-1):null,o=t.peek();if(e[n]){if((!o||/\W/.test(o))&&r&&/\S/.test(r)){var u=l(e);return e[n]=!1,u}}else(!r||/\W/.test(r))&&o&&/\S/.test(o)&&t.match(new RegExp("^.*\\S"+i.source+"(?:\\W|$)"),!1)&&(e[n]=!0,e.mode=c.attributes);return l(e)}function l(t){var e=o(t);if(e)return e;var n=[];return t.layoutType&&n.push(i[t.layoutType]),n=n.concat(function(t){for(var e=[],n=1;n]+)?>(?:[^<]+<\/\1>)?/,link:/[^"]+":\S/,linkDefinition:/\[[^\s\]]+\]\S+/,list:/(?:#+|\*+)/,notextile:"notextile",para:"p",pre:"pre",table:"table",tableCellAttributes:/[\/\\]\d+/,tableHeading:/\|_\./,tableText:/[^"_\*\[\(\?\+~\^%@|-]+/,text:/[^!"_=\*\[\(<\?\+~\^%@-]+/},attributes:{align:/(?:<>|<|>|=)/,selector:/\([^\(][^\)]+\)/,lang:/\[[^\[\]]+\]/,pad:/(?:\(+|\)+){1,2}/,css:/\{[^\}]+\}/},createRe:function(t){switch(t){case"drawTable":return u.makeRe("^",u.single.drawTable,"$");case"html":return u.makeRe("^",u.single.html,"(?:",u.single.html,")*","$");case"linkDefinition":return u.makeRe("^",u.single.linkDefinition,"$");case"listLayout":return u.makeRe("^",u.single.list,s("allAttributes"),"*\\s+");case"tableCellAttributes":return u.makeRe("^",u.choiceRe(u.single.tableCellAttributes,s("allAttributes")),"+\\.");case"type":return u.makeRe("^",s("allTypes"));case"typeLayout":return u.makeRe("^",s("allTypes"),s("allAttributes"),"*\\.\\.?","(\\s+|$)");case"attributes":return u.makeRe("^",s("allAttributes"),"+");case"allTypes":return u.choiceRe(u.single.div,u.single.foot,u.single.header,u.single.bc,u.single.bq,u.single.notextile,u.single.pre,u.single.table,u.single.para);case"allAttributes":return u.choiceRe(u.attributes.selector,u.attributes.css,u.attributes.lang,u.attributes.align,u.attributes.pad);default:return u.makeRe("^",u.single[t])}},makeRe:function(){for(var t="",e=0;e]+>[^<]+<\\/\\1>/))\n return TOKEN_STYLES.html\n\n if (ch === \"?\" && stream.eat(\"?\"))\n return togglePhraseModifier(stream, state, \"cite\", /\\?\\?/, 2);\n\n if (ch === \"=\" && stream.eat(\"=\"))\n return togglePhraseModifier(stream, state, \"notextile\", /==/, 2);\n\n if (ch === \"-\" && !stream.eat(\"-\"))\n return togglePhraseModifier(stream, state, \"deletion\", /-/, 1);\n\n if (ch === \"+\")\n return togglePhraseModifier(stream, state, \"addition\", /\\+/, 1);\n\n if (ch === \"~\")\n return togglePhraseModifier(stream, state, \"sub\", /~/, 1);\n\n if (ch === \"^\")\n return togglePhraseModifier(stream, state, \"sup\", /\\^/, 1);\n\n if (ch === \"%\")\n return togglePhraseModifier(stream, state, \"span\", /%/, 1);\n\n if (ch === \"@\")\n return togglePhraseModifier(stream, state, \"code\", /@/, 1);\n\n if (ch === \"!\") {\n var type = togglePhraseModifier(stream, state, \"image\", /(?:\\([^\\)]+\\))?!/, 1);\n stream.match(/^:\\S+/); // optional Url portion\n return type;\n }\n return tokenStyles(state);\n}\n\nfunction togglePhraseModifier(stream, state, phraseModifier, closeRE, openSize) {\n var charBefore = stream.pos > openSize ? stream.string.charAt(stream.pos - openSize - 1) : null;\n var charAfter = stream.peek();\n if (state[phraseModifier]) {\n if ((!charAfter || /\\W/.test(charAfter)) && charBefore && /\\S/.test(charBefore)) {\n var type = tokenStyles(state);\n state[phraseModifier] = false;\n return type;\n }\n } else if ((!charBefore || /\\W/.test(charBefore)) && charAfter && /\\S/.test(charAfter) &&\n stream.match(new RegExp(\"^.*\\\\S\" + closeRE.source + \"(?:\\\\W|$)\"), false)) {\n state[phraseModifier] = true;\n state.mode = Modes.attributes;\n }\n return tokenStyles(state);\n};\n\nfunction tokenStyles(state) {\n var disabled = textileDisabled(state);\n if (disabled) return disabled;\n\n var styles = [];\n if (state.layoutType) styles.push(TOKEN_STYLES[state.layoutType]);\n\n styles = styles.concat(activeStyles(\n state, \"addition\", \"bold\", \"cite\", \"code\", \"deletion\", \"em\", \"footCite\",\n \"image\", \"italic\", \"link\", \"span\", \"strong\", \"sub\", \"sup\", \"table\", \"tableHeading\"));\n\n if (state.layoutType === \"header\")\n styles.push(TOKEN_STYLES.header + \"-\" + state.header);\n\n return styles.length ? styles.join(\" \") : null;\n}\n\nfunction textileDisabled(state) {\n var type = state.layoutType;\n\n switch(type) {\n case \"notextile\":\n case \"code\":\n case \"pre\":\n return TOKEN_STYLES[type];\n default:\n if (state.notextile)\n return TOKEN_STYLES.notextile + (type ? (\" \" + TOKEN_STYLES[type]) : \"\");\n return null;\n }\n}\n\nfunction activeStyles(state) {\n var styles = [];\n for (var i = 1; i < arguments.length; ++i) {\n if (state[arguments[i]])\n styles.push(TOKEN_STYLES[arguments[i]]);\n }\n return styles;\n}\n\nfunction blankLine(state) {\n var spanningLayout = state.spanningLayout, type = state.layoutType;\n\n for (var key in state) if (state.hasOwnProperty(key))\n delete state[key];\n\n state.mode = Modes.newLayout;\n if (spanningLayout) {\n state.layoutType = type;\n state.spanningLayout = true;\n }\n}\n\nvar REs = {\n cache: {},\n single: {\n bc: \"bc\",\n bq: \"bq\",\n definitionList: /- .*?:=+/,\n definitionListEnd: /.*=:\\s*$/,\n div: \"div\",\n drawTable: /\\|.*\\|/,\n foot: /fn\\d+/,\n header: /h[1-6]/,\n html: /\\s*<(?:\\/)?(\\w+)(?:[^>]+)?>(?:[^<]+<\\/\\1>)?/,\n link: /[^\"]+\":\\S/,\n linkDefinition: /\\[[^\\s\\]]+\\]\\S+/,\n list: /(?:#+|\\*+)/,\n notextile: \"notextile\",\n para: \"p\",\n pre: \"pre\",\n table: \"table\",\n tableCellAttributes: /[\\/\\\\]\\d+/,\n tableHeading: /\\|_\\./,\n tableText: /[^\"_\\*\\[\\(\\?\\+~\\^%@|-]+/,\n text: /[^!\"_=\\*\\[\\(<\\?\\+~\\^%@-]+/\n },\n attributes: {\n align: /(?:<>|<|>|=)/,\n selector: /\\([^\\(][^\\)]+\\)/,\n lang: /\\[[^\\[\\]]+\\]/,\n pad: /(?:\\(+|\\)+){1,2}/,\n css: /\\{[^\\}]+\\}/\n },\n createRe: function(name) {\n switch (name) {\n case \"drawTable\":\n return REs.makeRe(\"^\", REs.single.drawTable, \"$\");\n case \"html\":\n return REs.makeRe(\"^\", REs.single.html, \"(?:\", REs.single.html, \")*\", \"$\");\n case \"linkDefinition\":\n return REs.makeRe(\"^\", REs.single.linkDefinition, \"$\");\n case \"listLayout\":\n return REs.makeRe(\"^\", REs.single.list, RE(\"allAttributes\"), \"*\\\\s+\");\n case \"tableCellAttributes\":\n return REs.makeRe(\"^\", REs.choiceRe(REs.single.tableCellAttributes,\n RE(\"allAttributes\")), \"+\\\\.\");\n case \"type\":\n return REs.makeRe(\"^\", RE(\"allTypes\"));\n case \"typeLayout\":\n return REs.makeRe(\"^\", RE(\"allTypes\"), RE(\"allAttributes\"),\n \"*\\\\.\\\\.?\", \"(\\\\s+|$)\");\n case \"attributes\":\n return REs.makeRe(\"^\", RE(\"allAttributes\"), \"+\");\n\n case \"allTypes\":\n return REs.choiceRe(REs.single.div, REs.single.foot,\n REs.single.header, REs.single.bc, REs.single.bq,\n REs.single.notextile, REs.single.pre, REs.single.table,\n REs.single.para);\n\n case \"allAttributes\":\n return REs.choiceRe(REs.attributes.selector, REs.attributes.css,\n REs.attributes.lang, REs.attributes.align, REs.attributes.pad);\n\n default:\n return REs.makeRe(\"^\", REs.single[name]);\n }\n },\n makeRe: function() {\n var pattern = \"\";\n for (var i = 0; i < arguments.length; ++i) {\n var arg = arguments[i];\n pattern += (typeof arg === \"string\") ? arg : arg.source;\n }\n return new RegExp(pattern);\n },\n choiceRe: function() {\n var parts = [arguments[0]];\n for (var i = 1; i < arguments.length; ++i) {\n parts[i * 2 - 1] = \"|\";\n parts[i * 2] = arguments[i];\n }\n\n parts.unshift(\"(?:\");\n parts.push(\")\");\n return REs.makeRe.apply(null, parts);\n }\n};\n\nfunction RE(name) {\n return (REs.cache[name] || (REs.cache[name] = REs.createRe(name)));\n}\n\nvar Modes = {\n newLayout: function(stream, state) {\n if (stream.match(RE(\"typeLayout\"), false)) {\n state.spanningLayout = false;\n return (state.mode = Modes.blockType)(stream, state);\n }\n var newMode;\n if (!textileDisabled(state)) {\n if (stream.match(RE(\"listLayout\"), false))\n newMode = Modes.list;\n else if (stream.match(RE(\"drawTable\"), false))\n newMode = Modes.table;\n else if (stream.match(RE(\"linkDefinition\"), false))\n newMode = Modes.linkDefinition;\n else if (stream.match(RE(\"definitionList\")))\n newMode = Modes.definitionList;\n else if (stream.match(RE(\"html\"), false))\n newMode = Modes.html;\n }\n return (state.mode = (newMode || Modes.text))(stream, state);\n },\n\n blockType: function(stream, state) {\n var match, type;\n state.layoutType = null;\n\n if (match = stream.match(RE(\"type\")))\n type = match[0];\n else\n return (state.mode = Modes.text)(stream, state);\n\n if (match = type.match(RE(\"header\"))) {\n state.layoutType = \"header\";\n state.header = parseInt(match[0][1]);\n } else if (type.match(RE(\"bq\"))) {\n state.layoutType = \"quote\";\n } else if (type.match(RE(\"bc\"))) {\n state.layoutType = \"code\";\n } else if (type.match(RE(\"foot\"))) {\n state.layoutType = \"footnote\";\n } else if (type.match(RE(\"notextile\"))) {\n state.layoutType = \"notextile\";\n } else if (type.match(RE(\"pre\"))) {\n state.layoutType = \"pre\";\n } else if (type.match(RE(\"div\"))) {\n state.layoutType = \"div\";\n } else if (type.match(RE(\"table\"))) {\n state.layoutType = \"table\";\n }\n\n state.mode = Modes.attributes;\n return tokenStyles(state);\n },\n\n text: function(stream, state) {\n if (stream.match(RE(\"text\"))) return tokenStyles(state);\n\n var ch = stream.next();\n if (ch === '\"')\n return (state.mode = Modes.link)(stream, state);\n return handlePhraseModifier(stream, state, ch);\n },\n\n attributes: function(stream, state) {\n state.mode = Modes.layoutLength;\n\n if (stream.match(RE(\"attributes\")))\n return TOKEN_STYLES.attributes\n else\n return tokenStyles(state);\n },\n\n layoutLength: function(stream, state) {\n if (stream.eat(\".\") && stream.eat(\".\"))\n state.spanningLayout = true;\n\n state.mode = Modes.text;\n return tokenStyles(state);\n },\n\n list: function(stream, state) {\n var match = stream.match(RE(\"list\"));\n state.listDepth = match[0].length;\n var listMod = (state.listDepth - 1) % 3;\n if (!listMod)\n state.layoutType = \"list1\";\n else if (listMod === 1)\n state.layoutType = \"list2\";\n else\n state.layoutType = \"list3\";\n\n state.mode = Modes.attributes;\n return tokenStyles(state);\n },\n\n link: function(stream, state) {\n state.mode = Modes.text;\n if (stream.match(RE(\"link\"))) {\n stream.match(/\\S+/);\n return TOKEN_STYLES.link\n }\n return tokenStyles(state);\n },\n\n linkDefinition: function(stream) {\n stream.skipToEnd();\n return TOKEN_STYLES.linkDefinition\n },\n\n definitionList: function(stream, state) {\n stream.match(RE(\"definitionList\"));\n\n state.layoutType = \"definitionList\";\n\n if (stream.match(/\\s*$/))\n state.spanningLayout = true;\n else\n state.mode = Modes.attributes;\n\n return tokenStyles(state);\n },\n\n html: function(stream) {\n stream.skipToEnd();\n return TOKEN_STYLES.html\n },\n\n table: function(stream, state) {\n state.layoutType = \"table\";\n return (state.mode = Modes.tableCell)(stream, state);\n },\n\n tableCell: function(stream, state) {\n if (stream.match(RE(\"tableHeading\")))\n state.tableHeading = true;\n else\n stream.eat(\"|\");\n\n state.mode = Modes.tableCellAttributes;\n return tokenStyles(state);\n },\n\n tableCellAttributes: function(stream, state) {\n state.mode = Modes.tableText;\n\n if (stream.match(RE(\"tableCellAttributes\")))\n return TOKEN_STYLES.attributes\n else\n return tokenStyles(state);\n },\n\n tableText: function(stream, state) {\n if (stream.match(RE(\"tableText\")))\n return tokenStyles(state);\n\n if (stream.peek() === \"|\") { // end of cell\n state.mode = Modes.tableCell;\n return tokenStyles(state);\n }\n return handlePhraseModifier(stream, state, stream.next());\n }\n};\n\nexport const textile = {\n name: \"textile\",\n startState: function() {\n return { mode: Modes.newLayout };\n },\n token: function(stream, state) {\n if (stream.sol()) startNewLine(stream, state);\n return state.mode(stream, state);\n },\n blankLine: blankLine\n};\n"],"names":["TOKEN_STYLES","addition","attributes","bold","cite","code","definitionList","deletion","div","em","footnote","footCite","header","html","image","italic","link","linkDefinition","list1","list2","list3","notextile","pre","p","quote","span","specialChar","strong","sub","sup","table","tableHeading","handlePhraseModifier","stream","state","ch","eat","togglePhraseModifier","match","tokenStyles","type","phraseModifier","closeRE","openSize","charBefore","pos","string","charAt","charAfter","peek","test","RegExp","source","mode","Modes","disabled","textileDisabled","styles","layoutType","push","concat","i","arguments","length","activeStyles","join","REs","cache","single","bc","bq","definitionListEnd","drawTable","foot","list","para","tableCellAttributes","tableText","text","align","selector","lang","pad","css","createRe","name","makeRe","RE","choiceRe","pattern","arg","parts","unshift","apply","newLayout","spanningLayout","blockType","newMode","parseInt","next","layoutLength","listDepth","listMod","skipToEnd","tableCell","textile","startState","token","sol","startNewLine","blankLine","key","hasOwnProperty"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/6990.index.js b/book/_build/html/_static/6990.index.js new file mode 100644 index 0000000..f546703 --- /dev/null +++ b/book/_build/html/_static/6990.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[6990],{96990:(e,_,t)=>{function r(e){for(var _={},t=e.split(" "),r=0;ru});var s,i=r("break return rewrite set accept_mutex accept_mutex_delay access_log add_after_body add_before_body add_header addition_types aio alias allow ancient_browser ancient_browser_value auth_basic auth_basic_user_file auth_http auth_http_header auth_http_timeout autoindex autoindex_exact_size autoindex_localtime charset charset_types client_body_buffer_size client_body_in_file_only client_body_in_single_buffer client_body_temp_path client_body_timeout client_header_buffer_size client_header_timeout client_max_body_size connection_pool_size create_full_put_path daemon dav_access dav_methods debug_connection debug_points default_type degradation degrade deny devpoll_changes devpoll_events directio directio_alignment empty_gif env epoll_events error_log eventport_events expires fastcgi_bind fastcgi_buffer_size fastcgi_buffers fastcgi_busy_buffers_size fastcgi_cache fastcgi_cache_key fastcgi_cache_methods fastcgi_cache_min_uses fastcgi_cache_path fastcgi_cache_use_stale fastcgi_cache_valid fastcgi_catch_stderr fastcgi_connect_timeout fastcgi_hide_header fastcgi_ignore_client_abort fastcgi_ignore_headers fastcgi_index fastcgi_intercept_errors fastcgi_max_temp_file_size fastcgi_next_upstream fastcgi_param fastcgi_pass_header fastcgi_pass_request_body fastcgi_pass_request_headers fastcgi_read_timeout fastcgi_send_lowat fastcgi_send_timeout fastcgi_split_path_info fastcgi_store fastcgi_store_access fastcgi_temp_file_write_size fastcgi_temp_path fastcgi_upstream_fail_timeout fastcgi_upstream_max_fails flv geoip_city geoip_country google_perftools_profiles gzip gzip_buffers gzip_comp_level gzip_disable gzip_hash gzip_http_version gzip_min_length gzip_no_buffer gzip_proxied gzip_static gzip_types gzip_vary gzip_window if_modified_since ignore_invalid_headers image_filter image_filter_buffer image_filter_jpeg_quality image_filter_transparency imap_auth imap_capabilities imap_client_buffer index ip_hash keepalive_requests keepalive_timeout kqueue_changes kqueue_events large_client_header_buffers limit_conn limit_conn_log_level limit_rate limit_rate_after limit_req limit_req_log_level limit_req_zone limit_zone lingering_time lingering_timeout lock_file log_format log_not_found log_subrequest map_hash_bucket_size map_hash_max_size master_process memcached_bind memcached_buffer_size memcached_connect_timeout memcached_next_upstream memcached_read_timeout memcached_send_timeout memcached_upstream_fail_timeout memcached_upstream_max_fails merge_slashes min_delete_depth modern_browser modern_browser_value msie_padding msie_refresh multi_accept open_file_cache open_file_cache_errors open_file_cache_events open_file_cache_min_uses open_file_cache_valid open_log_file_cache output_buffers override_charset perl perl_modules perl_require perl_set pid pop3_auth pop3_capabilities port_in_redirect postpone_gzipping postpone_output protocol proxy proxy_bind proxy_buffer proxy_buffer_size proxy_buffering proxy_buffers proxy_busy_buffers_size proxy_cache proxy_cache_key proxy_cache_methods proxy_cache_min_uses proxy_cache_path proxy_cache_use_stale proxy_cache_valid proxy_connect_timeout proxy_headers_hash_bucket_size proxy_headers_hash_max_size proxy_hide_header proxy_ignore_client_abort proxy_ignore_headers proxy_intercept_errors proxy_max_temp_file_size proxy_method proxy_next_upstream proxy_pass_error_message proxy_pass_header proxy_pass_request_body proxy_pass_request_headers proxy_read_timeout proxy_redirect proxy_send_lowat proxy_send_timeout proxy_set_body proxy_set_header proxy_ssl_session_reuse proxy_store proxy_store_access proxy_temp_file_write_size proxy_temp_path proxy_timeout proxy_upstream_fail_timeout proxy_upstream_max_fails random_index read_ahead real_ip_header recursive_error_pages request_pool_size reset_timedout_connection resolver resolver_timeout rewrite_log rtsig_overflow_events rtsig_overflow_test rtsig_overflow_threshold rtsig_signo satisfy secure_link_secret send_lowat send_timeout sendfile sendfile_max_chunk server_name_in_redirect server_names_hash_bucket_size server_names_hash_max_size server_tokens set_real_ip_from smtp_auth smtp_capabilities smtp_client_buffer smtp_greeting_delay so_keepalive source_charset ssi ssi_ignore_recycled_buffers ssi_min_file_chunk ssi_silent_errors ssi_types ssi_value_length ssl ssl_certificate ssl_certificate_key ssl_ciphers ssl_client_certificate ssl_crl ssl_dhparam ssl_engine ssl_prefer_server_ciphers ssl_protocols ssl_session_cache ssl_session_timeout ssl_verify_client ssl_verify_depth starttls stub_status sub_filter sub_filter_once sub_filter_types tcp_nodelay tcp_nopush thread_stack_size timeout timer_resolution types_hash_bucket_size types_hash_max_size underscores_in_headers uninitialized_variable_warn use user userid userid_domain userid_expires userid_mark userid_name userid_p3p userid_path userid_service valid_referers variables_hash_bucket_size variables_hash_max_size worker_connections worker_cpu_affinity worker_priority worker_processes worker_rlimit_core worker_rlimit_nofile worker_rlimit_sigpending worker_threads working_directory xclient xml_entities xslt_stylesheet xslt_typesdrew@li229-23"),a=r("http mail events server types location upstream charset_map limit_except if geo map"),o=r("include root server server_name listen internal proxy_pass memcached_pass fastcgi_pass try_files");function n(e,_){return s=_,e}function c(e,_){e.eatWhile(/[\w\$_]/);var t=e.current();if(i.propertyIsEnumerable(t))return"keyword";if(a.propertyIsEnumerable(t))return"controlKeyword";if(o.propertyIsEnumerable(t))return"controlKeyword";var r,s=e.next();return"@"==s?(e.eatWhile(/[\w\\\-]/),n("meta",e.current())):"/"==s&&e.eat("*")?(_.tokenize=l,l(e,_)):"<"==s&&e.eat("!")?(_.tokenize=p,p(e,_)):"="!=s?"~"!=s&&"|"!=s||!e.eat("=")?'"'==s||"'"==s?(_.tokenize=(r=s,function(e,_){for(var t,s=!1;null!=(t=e.next())&&(t!=r||s);)s=!s&&"\\"==t;return s||(_.tokenize=c),n("string","string")}),_.tokenize(e,_)):"#"==s?(e.skipToEnd(),n("comment","comment")):"!"==s?(e.match(/^\s*\w*/),n("keyword","important")):/\d/.test(s)?(e.eatWhile(/[\w.%]/),n("number","unit")):/[,.+>*\/]/.test(s)?n(null,"select-op"):/[;{}:\[\]]/.test(s)?n(null,s):(e.eatWhile(/[\w\\\-]/),n("variable","variable")):n(null,"compare"):void n(null,"compare")}function l(e,_){for(var t,r=!1;null!=(t=e.next());){if(r&&"/"==t){_.tokenize=c;break}r="*"==t}return n("comment","comment")}function p(e,_){for(var t,r=0;null!=(t=e.next());){if(r>=2&&">"==t){_.tokenize=c;break}r="-"==t?r+1:0}return n("comment","comment")}const u={name:"nginx",startState:function(){return{tokenize:c,baseIndent:0,stack:[]}},token:function(e,_){if(e.eatSpace())return null;s=null;var t=_.tokenize(e,_),r=_.stack[_.stack.length-1];return"hash"==s&&"rule"==r?t="atom":"variable"==t&&("rule"==r?t="number":r&&"@media{"!=r||(t="tag")),"rule"==r&&/^[\{\};]$/.test(s)&&_.stack.pop(),"{"==s?"@media"==r?_.stack[_.stack.length-1]="@media{":_.stack.push("{"):"}"==s?_.stack.pop():"@media"==s?_.stack.push("@media"):"{"==r&&"comment"!=s&&_.stack.push("rule"),t},indent:function(e,_,t){var r=e.stack.length;return/^\}/.test(_)&&(r-="rule"==e.stack[e.stack.length-1]?2:1),e.baseIndent+r*t.unit},languageData:{indentOnInput:/^\s*\}$/}}}}]); +//# sourceMappingURL=6990.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/6990.index.js.map b/book/_build/html/_static/6990.index.js.map new file mode 100644 index 0000000..b4bf33a --- /dev/null +++ b/book/_build/html/_static/6990.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"6990.index.js","mappings":"+FAAA,SAASA,EAAMC,GAEb,IADA,IAAIC,EAAM,CAAC,EAAGF,EAAQC,EAAIE,MAAM,KACvBC,EAAI,EAAGA,EAAIJ,EAAMK,SAAUD,EAAGF,EAAIF,EAAMI,KAAM,EACvD,OAAOF,CACT,C,4BAEA,IAaII,EAbAC,EAAWP,EACa,wgKAIxBQ,EAAiBR,EACK,uFAGtBS,EAAqBT,EACK,oGAI9B,SAASU,EAAIC,EAAOC,GAAgB,OAAXN,EAAOM,EAAWD,CAAM,CAEjD,SAASE,EAAUC,EAAQC,GAGzBD,EAAOE,SAAS,WAEhB,IAAIC,EAAMH,EAAOI,UAGjB,GAAIX,EAASY,qBAAqBF,GAChC,MAAO,UAEJ,GAAIT,EAAeW,qBAAqBF,GAC3C,MAAO,iBAEJ,GAAIR,EAAmBU,qBAAqBF,GAC/C,MAAO,iBAIT,IAgEmBG,EAhEfC,EAAKP,EAAOQ,OAChB,MAAU,KAAND,GAAYP,EAAOE,SAAS,YAAoBN,EAAI,OAAQI,EAAOI,YACxD,KAANG,GAAaP,EAAOS,IAAI,MAC/BR,EAAMS,SAAWC,EACVA,EAAcX,EAAQC,IAEhB,KAANM,GAAaP,EAAOS,IAAI,MAC/BR,EAAMS,SAAWE,EACVA,EAAiBZ,EAAQC,IAEnB,KAANM,EACO,KAANA,GAAmB,KAANA,IAAcP,EAAO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AOyB,WAAY,OAAO,KAC9BjC,EAAO,KACP,IAAIK,EAAQI,EAAMS,SAASV,EAAQC,GAE/ByB,EAAUzB,EAAMsB,MAAMtB,EAAMsB,MAAMhC,OAAO,GAgB7C,MAfY,QAARC,GAA6B,QAAXkC,EAAmB7B,EAAQ,OAC/B,YAATA,IACQ,QAAX6B,EAAmB7B,EAAQ,SACrB6B,GAAsB,WAAXA,IAAsB7B,EAAQ,QAGtC,QAAX6B,GAAqB,YAAYV,KAAKxB,IACxCS,EAAMsB,MAAMI,MACF,KAARnC,EACa,UAAXkC,EAAqBzB,EAAMsB,MAAMtB,EAAMsB,MAAMhC,OAAO,GAAK,UACxDU,EAAMsB,MAAMK,KAAK,KAEP,KAARpC,EAAaS,EAAMsB,MAAMI,MACjB,UAARnC,EAAkBS,EAAMsB,MAAMK,KAAK,UACxB,KAAXF,GAA0B,WAARlC,GAAmBS,EAAMsB,MAAMK,KAAK,QACxD/B,CACT,EAEAgC,OAAQ,SAAS5B,EAAO6B,EAAWC,GACjC,IAAIC,EAAI/B,EAAMsB,MAAMhC,OAGpB,MAFI,MAAMyB,KAAKc,KACbE,GAA0C,QAArC/B,EAAMsB,MAAMtB,EAAMsB,MAAMhC,OAAO,GAAe,EAAI,GAClDU,EAAMqB,WAAaU,EAAID,EAAGE,IACnC,EAEAC,aAAc,CACZC,cAAe,W","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/nginx.js"],"sourcesContent":["function words(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n}\n\nvar keywords = words(\n /* ngxDirectiveControl */ \"break return rewrite set\" +\n /* ngxDirective */ \" accept_mutex accept_mutex_delay access_log add_after_body add_before_body add_header addition_types aio alias allow ancient_browser ancient_browser_value auth_basic auth_basic_user_file auth_http auth_http_header auth_http_timeout autoindex autoindex_exact_size autoindex_localtime charset charset_types client_body_buffer_size client_body_in_file_only client_body_in_single_buffer client_body_temp_path client_body_timeout client_header_buffer_size client_header_timeout client_max_body_size connection_pool_size create_full_put_path daemon dav_access dav_methods debug_connection debug_points default_type degradation degrade deny devpoll_changes devpoll_events directio directio_alignment empty_gif env epoll_events error_log eventport_events expires fastcgi_bind fastcgi_buffer_size fastcgi_buffers fastcgi_busy_buffers_size fastcgi_cache fastcgi_cache_key fastcgi_cache_methods fastcgi_cache_min_uses fastcgi_cache_path fastcgi_cache_use_stale fastcgi_cache_valid fastcgi_catch_stderr fastcgi_connect_timeout fastcgi_hide_header fastcgi_ignore_client_abort fastcgi_ignore_headers fastcgi_index fastcgi_intercept_errors fastcgi_max_temp_file_size fastcgi_next_upstream fastcgi_param fastcgi_pass_header fastcgi_pass_request_body fastcgi_pass_request_headers fastcgi_read_timeout fastcgi_send_lowat fastcgi_send_timeout fastcgi_split_path_info fastcgi_store fastcgi_store_access fastcgi_temp_file_write_size fastcgi_temp_path fastcgi_upstream_fail_timeout fastcgi_upstream_max_fails flv geoip_city geoip_country google_perftools_profiles gzip gzip_buffers gzip_comp_level gzip_disable gzip_hash gzip_http_version gzip_min_length gzip_no_buffer gzip_proxied gzip_static gzip_types gzip_vary gzip_window if_modified_since ignore_invalid_headers image_filter image_filter_buffer image_filter_jpeg_quality image_filter_transparency imap_auth imap_capabilities imap_client_buffer index ip_hash keepalive_requests keepalive_timeout kqueue_changes kqueue_events large_client_header_buffers limit_conn limit_conn_log_level limit_rate limit_rate_after limit_req limit_req_log_level limit_req_zone limit_zone lingering_time lingering_timeout lock_file log_format log_not_found log_subrequest map_hash_bucket_size map_hash_max_size master_process memcached_bind memcached_buffer_size memcached_connect_timeout memcached_next_upstream memcached_read_timeout memcached_send_timeout memcached_upstream_fail_timeout memcached_upstream_max_fails merge_slashes min_delete_depth modern_browser modern_browser_value msie_padding msie_refresh multi_accept open_file_cache open_file_cache_errors open_file_cache_events open_file_cache_min_uses open_file_cache_valid open_log_file_cache output_buffers override_charset perl perl_modules perl_require perl_set pid pop3_auth pop3_capabilities port_in_redirect postpone_gzipping postpone_output protocol proxy proxy_bind proxy_buffer proxy_buffer_size proxy_buffering proxy_buffers proxy_busy_buffers_size proxy_cache proxy_cache_key proxy_cache_methods proxy_cache_min_uses proxy_cache_path proxy_cache_use_stale proxy_cache_valid proxy_connect_timeout proxy_headers_hash_bucket_size proxy_headers_hash_max_size proxy_hide_header proxy_ignore_client_abort proxy_ignore_headers proxy_intercept_errors proxy_max_temp_file_size proxy_method proxy_next_upstream proxy_pass_error_message proxy_pass_header proxy_pass_request_body proxy_pass_request_headers proxy_read_timeout proxy_redirect proxy_send_lowat proxy_send_timeout proxy_set_body proxy_set_header proxy_ssl_session_reuse proxy_store proxy_store_access proxy_temp_file_write_size proxy_temp_path proxy_timeout proxy_upstream_fail_timeout proxy_upstream_max_fails random_index read_ahead real_ip_header recursive_error_pages request_pool_size reset_timedout_connection resolver resolver_timeout rewrite_log rtsig_overflow_events rtsig_overflow_test rtsig_overflow_threshold rtsig_signo satisfy secure_link_secret send_lowat send_timeout sendfile sendfile_max_chunk server_name_in_redirect server_names_hash_bucket_size server_names_hash_max_size server_tokens set_real_ip_from smtp_auth smtp_capabilities smtp_client_buffer smtp_greeting_delay so_keepalive source_charset ssi ssi_ignore_recycled_buffers ssi_min_file_chunk ssi_silent_errors ssi_types ssi_value_length ssl ssl_certificate ssl_certificate_key ssl_ciphers ssl_client_certificate ssl_crl ssl_dhparam ssl_engine ssl_prefer_server_ciphers ssl_protocols ssl_session_cache ssl_session_timeout ssl_verify_client ssl_verify_depth starttls stub_status sub_filter sub_filter_once sub_filter_types tcp_nodelay tcp_nopush thread_stack_size timeout timer_resolution types_hash_bucket_size types_hash_max_size underscores_in_headers uninitialized_variable_warn use user userid userid_domain userid_expires userid_mark userid_name userid_p3p userid_path userid_service valid_referers variables_hash_bucket_size variables_hash_max_size worker_connections worker_cpu_affinity worker_priority worker_processes worker_rlimit_core worker_rlimit_nofile worker_rlimit_sigpending worker_threads working_directory xclient xml_entities xslt_stylesheet xslt_typesdrew@li229-23\"\n);\n\nvar keywords_block = words(\n /* ngxDirectiveBlock */ \"http mail events server types location upstream charset_map limit_except if geo map\"\n);\n\nvar keywords_important = words(\n /* ngxDirectiveImportant */ \"include root server server_name listen internal proxy_pass memcached_pass fastcgi_pass try_files\"\n);\n\nvar type;\nfunction ret(style, tp) {type = tp; return style;}\n\nfunction tokenBase(stream, state) {\n\n\n stream.eatWhile(/[\\w\\$_]/);\n\n var cur = stream.current();\n\n\n if (keywords.propertyIsEnumerable(cur)) {\n return \"keyword\";\n }\n else if (keywords_block.propertyIsEnumerable(cur)) {\n return \"controlKeyword\";\n }\n else if (keywords_important.propertyIsEnumerable(cur)) {\n return \"controlKeyword\";\n }\n /**/\n\n var ch = stream.next();\n if (ch == \"@\") {stream.eatWhile(/[\\w\\\\\\-]/); return ret(\"meta\", stream.current());}\n else if (ch == \"/\" && stream.eat(\"*\")) {\n state.tokenize = tokenCComment;\n return tokenCComment(stream, state);\n }\n else if (ch == \"<\" && stream.eat(\"!\")) {\n state.tokenize = tokenSGMLComment;\n return tokenSGMLComment(stream, state);\n }\n else if (ch == \"=\") ret(null, \"compare\");\n else if ((ch == \"~\" || ch == \"|\") && stream.eat(\"=\")) return ret(null, \"compare\");\n else if (ch == \"\\\"\" || ch == \"'\") {\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n }\n else if (ch == \"#\") {\n stream.skipToEnd();\n return ret(\"comment\", \"comment\");\n }\n else if (ch == \"!\") {\n stream.match(/^\\s*\\w*/);\n return ret(\"keyword\", \"important\");\n }\n else if (/\\d/.test(ch)) {\n stream.eatWhile(/[\\w.%]/);\n return ret(\"number\", \"unit\");\n }\n else if (/[,.+>*\\/]/.test(ch)) {\n return ret(null, \"select-op\");\n }\n else if (/[;{}:\\[\\]]/.test(ch)) {\n return ret(null, ch);\n }\n else {\n stream.eatWhile(/[\\w\\\\\\-]/);\n return ret(\"variable\", \"variable\");\n }\n}\n\nfunction tokenCComment(stream, state) {\n var maybeEnd = false, ch;\n while ((ch = stream.next()) != null) {\n if (maybeEnd && ch == \"/\") {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return ret(\"comment\", \"comment\");\n}\n\nfunction tokenSGMLComment(stream, state) {\n var dashes = 0, ch;\n while ((ch = stream.next()) != null) {\n if (dashes >= 2 && ch == \">\") {\n state.tokenize = tokenBase;\n break;\n }\n dashes = (ch == \"-\") ? dashes + 1 : 0;\n }\n return ret(\"comment\", \"comment\");\n}\n\nfunction tokenString(quote) {\n return function(stream, state) {\n var escaped = false, ch;\n while ((ch = stream.next()) != null) {\n if (ch == quote && !escaped)\n break;\n escaped = !escaped && ch == \"\\\\\";\n }\n if (!escaped) state.tokenize = tokenBase;\n return ret(\"string\", \"string\");\n };\n}\n\nexport const nginx = {\n name: \"nginx\",\n startState: function() {\n return {tokenize: tokenBase,\n baseIndent: 0,\n stack: []};\n },\n\n token: function(stream, state) {\n if (stream.eatSpace()) return null;\n type = null;\n var style = state.tokenize(stream, state);\n\n var context = state.stack[state.stack.length-1];\n if (type == \"hash\" && context == \"rule\") style = \"atom\";\n else if (style == \"variable\") {\n if (context == \"rule\") style = \"number\";\n else if (!context || context == \"@media{\") style = \"tag\";\n }\n\n if (context == \"rule\" && /^[\\{\\};]$/.test(type))\n state.stack.pop();\n if (type == \"{\") {\n if (context == \"@media\") state.stack[state.stack.length-1] = \"@media{\";\n else state.stack.push(\"{\");\n }\n else if (type == \"}\") state.stack.pop();\n else if (type == \"@media\") state.stack.push(\"@media\");\n else if (context == \"{\" && type != \"comment\") state.stack.push(\"rule\");\n return style;\n },\n\n indent: function(state, textAfter, cx) {\n var n = state.stack.length;\n if (/^\\}/.test(textAfter))\n n -= state.stack[state.stack.length-1] == \"rule\" ? 2 : 1;\n return state.baseIndent + n * cx.unit;\n },\n\n languageData: {\n indentOnInput: /^\\s*\\}$/\n }\n};\n"],"names":["words","str","obj","split","i","length","type","keywords","keywords_block","keywords_important","ret","style","tp","tokenBase","stream","state","eatWhile","cur","current","propertyIsEnumerable","quote","ch","next","eat","tokenize","tokenCComment","tokenSGMLComment","escaped","skipToEnd","match","test","maybeEnd","dashes","nginx","name","startState","baseIndent","stack","token","eatSpace","context","pop","push","indent","textAfter","cx","n","unit","languageData","indentOnInput"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/7009.index.js b/book/_build/html/_static/7009.index.js new file mode 100644 index 0000000..c80e600 --- /dev/null +++ b/book/_build/html/_static/7009.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[7009],{57009:(e,t,r)=>{function n(e,t,r){return t(r),r(e,t)}r.r(t),r.d(t,{haskell:()=>F});var a=/[a-z_]/,i=/[A-Z]/,o=/\d/,l=/[0-9A-Fa-f]/,u=/[0-7]/,s=/[a-z_A-Z0-9'\xa1-\uffff]/,f=/[-!#$%&*+.\/<=>?@\\^|~:]/,c=/[(),;[\]`{}]/,d=/[ \t\v\f]/;function m(e,t){if(e.eatWhile(d))return null;var r=e.next();if(c.test(r)){if("{"==r&&e.eat("-")){var m="comment";return e.eat("#")&&(m="meta"),n(e,t,h(m,1))}return null}if("'"==r)return e.eat("\\"),e.next(),e.eat("'")?"string":"error";if('"'==r)return n(e,t,p);if(i.test(r))return e.eatWhile(s),e.eat(".")?"qualifier":"type";if(a.test(r))return e.eatWhile(s),"variable";if(o.test(r)){if("0"==r){if(e.eat(/[xX]/))return e.eatWhile(l),"integer";if(e.eat(/[oO]/))return e.eatWhile(u),"number"}return e.eatWhile(o),m="number",e.match(/^\.\d+/)&&(m="number"),e.eat(/[eE]/)&&(m="number",e.eat(/[-+]/),e.eatWhile(o)),m}return"."==r&&e.eat(".")?"keyword":f.test(r)?"-"==r&&e.eat(/-/)&&(e.eatWhile(/-/),!e.eat(f))?(e.skipToEnd(),"comment"):(e.eatWhile(f),"variable"):"error"}function h(e,t){return 0==t?m:function(r,n){for(var a=t;!r.eol();){var i=r.next();if("{"==i&&r.eat("-"))++a;else if("-"==i&&r.eat("}")&&0==--a)return n(m),e}return n(h(e,a)),e}}function p(e,t){for(;!e.eol();){var r=e.next();if('"'==r)return t(m),"string";if("\\"==r){if(e.eol()||e.eat(d))return t(g),"string";e.eat("&")||e.next()}}return t(m),"error"}function g(e,t){return e.eat("\\")?n(e,t,p):(e.next(),t(m),"error")}var w=function(){var e={};function t(t){return function(){for(var r=0;r","@","~","=>"),t("builtin")("!!","$!","$","&&","+","++","-",".","/","/=","<","<*","<=","<$>","<*>","=<<","==",">",">=",">>",">>=","^","^^","||","*","*>","**"),t("builtin")("Applicative","Bool","Bounded","Char","Double","EQ","Either","Enum","Eq","False","FilePath","Float","Floating","Fractional","Functor","GT","IO","IOError","Int","Integer","Integral","Just","LT","Left","Maybe","Monad","Nothing","Num","Ord","Ordering","Rational","Read","ReadS","Real","RealFloat","RealFrac","Right","Show","ShowS","String","True"),t("builtin")("abs","acos","acosh","all","and","any","appendFile","asTypeOf","asin","asinh","atan","atan2","atanh","break","catch","ceiling","compare","concat","concatMap","const","cos","cosh","curry","cycle","decodeFloat","div","divMod","drop","dropWhile","either","elem","encodeFloat","enumFrom","enumFromThen","enumFromThenTo","enumFromTo","error","even","exp","exponent","fail","filter","flip","floatDigits","floatRadix","floatRange","floor","fmap","foldl","foldl1","foldr","foldr1","fromEnum","fromInteger","fromIntegral","fromRational","fst","gcd","getChar","getContents","getLine","head","id","init","interact","ioError","isDenormalized","isIEEE","isInfinite","isNaN","isNegativeZero","iterate","last","lcm","length","lex","lines","log","logBase","lookup","map","mapM","mapM_","max","maxBound","maximum","maybe","min","minBound","minimum","mod","negate","not","notElem","null","odd","or","otherwise","pi","pred","print","product","properFraction","pure","putChar","putStr","putStrLn","quot","quotRem","read","readFile","readIO","readList","readLn","readParen","reads","readsPrec","realToFrac","recip","rem","repeat","replicate","return","reverse","round","scaleFloat","scanl","scanl1","scanr","scanr1","seq","sequence","sequence_","show","showChar","showList","showParen","showString","shows","showsPrec","significand","signum","sin","sinh","snd","span","splitAt","sqrt","subtract","succ","sum","tail","take","takeWhile","tan","tanh","toEnum","toInteger","toRational","truncate","uncurry","undefined","unlines","until","unwords","unzip","unzip3","userError","words","writeFile","zip","zip3","zipWith","zipWith3"),e}();const F={name:"haskell",startState:function(){return{f:m}},copyState:function(e){return{f:e.f}},token:function(e,t){var r=t.f(e,(function(e){t.f=e})),n=e.current();return w.hasOwnProperty(n)?w[n]:r},languageData:{commentTokens:{line:"--",block:{open:"{-",close:"-}"}}}}}}]); +//# sourceMappingURL=7009.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/7009.index.js.map b/book/_build/html/_static/7009.index.js.map new file mode 100644 index 0000000..9efd18b --- /dev/null +++ b/book/_build/html/_static/7009.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"7009.index.js","mappings":"+FAAA,SAASA,EAAYC,EAAQC,EAAUC,GAErC,OADAD,EAASC,GACFA,EAAEF,EAAQC,EACnB,C,8BAGA,IAAIE,EAAU,SACVC,EAAU,QACVC,EAAU,KACVC,EAAU,cACVC,EAAU,QACVC,EAAO,2BACPC,EAAW,2BACXC,EAAY,eACZC,EAAc,YAElB,SAASC,EAAOZ,EAAQC,GACtB,GAAID,EAAOa,SAASF,GAClB,OAAO,KAGT,IAAIG,EAAKd,EAAOe,OAChB,GAAIL,EAAUM,KAAKF,GAAK,CACtB,GAAU,KAANA,GAAad,EAAOiB,IAAI,KAAM,CAChC,IAAIC,EAAI,UAIR,OAHIlB,EAAOiB,IAAI,OACbC,EAAI,QAECnB,EAAYC,EAAQC,EAAUkB,EAASD,EAAG,GACnD,CACA,OAAO,IACT,CAEA,GAAU,KAANJ,EAOF,OANId,EAAOiB,IAAI,MACbjB,EAAOe,OAKLf,EAAOiB,IAAI,KACN,SAEF,QAGT,GAAU,KAANH,EACF,OAAOf,EAAYC,EAAQC,EAAUmB,GAGvC,GAAIhB,EAAQY,KAAKF,GAEf,OADAd,EAAOa,SAASL,GACZR,EAAOiB,IAAI,KACN,YAEF,OAGT,GAAId,EAA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aAAc,CACZC,cAAe,CAACC,KAAM,KAAMC,MAAO,CAACC,KAAM,KAAMC,MAAO,Q","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/haskell.js"],"sourcesContent":["function switchState(source, setState, f) {\n setState(f);\n return f(source, setState);\n}\n\n// These should all be Unicode extended, as per the Haskell 2010 report\nvar smallRE = /[a-z_]/;\nvar largeRE = /[A-Z]/;\nvar digitRE = /\\d/;\nvar hexitRE = /[0-9A-Fa-f]/;\nvar octitRE = /[0-7]/;\nvar idRE = /[a-z_A-Z0-9'\\xa1-\\uffff]/;\nvar symbolRE = /[-!#$%&*+.\\/<=>?@\\\\^|~:]/;\nvar specialRE = /[(),;[\\]`{}]/;\nvar whiteCharRE = /[ \\t\\v\\f]/; // newlines are handled in tokenizer\n\nfunction normal(source, setState) {\n if (source.eatWhile(whiteCharRE)) {\n return null;\n }\n\n var ch = source.next();\n if (specialRE.test(ch)) {\n if (ch == '{' && source.eat('-')) {\n var t = \"comment\";\n if (source.eat('#')) {\n t = \"meta\";\n }\n return switchState(source, setState, ncomment(t, 1));\n }\n return null;\n }\n\n if (ch == '\\'') {\n if (source.eat('\\\\')) {\n source.next(); // should handle other escapes here\n }\n else {\n source.next();\n }\n if (source.eat('\\'')) {\n return \"string\";\n }\n return \"error\";\n }\n\n if (ch == '\"') {\n return switchState(source, setState, stringLiteral);\n }\n\n if (largeRE.test(ch)) {\n source.eatWhile(idRE);\n if (source.eat('.')) {\n return \"qualifier\";\n }\n return \"type\";\n }\n\n if (smallRE.test(ch)) {\n source.eatWhile(idRE);\n return \"variable\";\n }\n\n if (digitRE.test(ch)) {\n if (ch == '0') {\n if (source.eat(/[xX]/)) {\n source.eatWhile(hexitRE); // should require at least 1\n return \"integer\";\n }\n if (source.eat(/[oO]/)) {\n source.eatWhile(octitRE); // should require at least 1\n return \"number\";\n }\n }\n source.eatWhile(digitRE);\n var t = \"number\";\n if (source.match(/^\\.\\d+/)) {\n t = \"number\";\n }\n if (source.eat(/[eE]/)) {\n t = \"number\";\n source.eat(/[-+]/);\n source.eatWhile(digitRE); // should require at least 1\n }\n return t;\n }\n\n if (ch == \".\" && source.eat(\".\"))\n return \"keyword\";\n\n if (symbolRE.test(ch)) {\n if (ch == '-' && source.eat(/-/)) {\n source.eatWhile(/-/);\n if (!source.eat(symbolRE)) {\n source.skipToEnd();\n return \"comment\";\n }\n }\n source.eatWhile(symbolRE);\n return \"variable\"\n }\n\n return \"error\";\n}\n\nfunction ncomment(type, nest) {\n if (nest == 0) {\n return normal;\n }\n return function(source, setState) {\n var currNest = nest;\n while (!source.eol()) {\n var ch = source.next();\n if (ch == '{' && source.eat('-')) {\n ++currNest;\n }\n else if (ch == '-' && source.eat('}')) {\n --currNest;\n if (currNest == 0) {\n setState(normal);\n return type;\n }\n }\n }\n setState(ncomment(type, currNest));\n return type;\n };\n}\n\nfunction stringLiteral(source, setState) {\n while (!source.eol()) {\n var ch = source.next();\n if (ch == '\"') {\n setState(normal);\n return \"string\";\n }\n if (ch == '\\\\') {\n if (source.eol() || source.eat(whiteCharRE)) {\n setState(stringGap);\n return \"string\";\n }\n if (source.eat('&')) {\n }\n else {\n source.next(); // should handle other escapes here\n }\n }\n }\n setState(normal);\n return \"error\";\n}\n\nfunction stringGap(source, setState) {\n if (source.eat('\\\\')) {\n return switchState(source, setState, stringLiteral);\n }\n source.next();\n setState(normal);\n return \"error\";\n}\n\n\nvar wellKnownWords = (function() {\n var wkw = {};\n function setType(t) {\n return function () {\n for (var i = 0; i < arguments.length; i++)\n wkw[arguments[i]] = t;\n };\n }\n\n setType(\"keyword\")(\n \"case\", \"class\", \"data\", \"default\", \"deriving\", \"do\", \"else\", \"foreign\",\n \"if\", \"import\", \"in\", \"infix\", \"infixl\", \"infixr\", \"instance\", \"let\",\n \"module\", \"newtype\", \"of\", \"then\", \"type\", \"where\", \"_\");\n\n setType(\"keyword\")(\n \"\\.\\.\", \":\", \"::\", \"=\", \"\\\\\", \"<-\", \"->\", \"@\", \"~\", \"=>\");\n\n setType(\"builtin\")(\n \"!!\", \"$!\", \"$\", \"&&\", \"+\", \"++\", \"-\", \".\", \"/\", \"/=\", \"<\", \"<*\", \"<=\",\n \"<$>\", \"<*>\", \"=<<\", \"==\", \">\", \">=\", \">>\", \">>=\", \"^\", \"^^\", \"||\", \"*\",\n \"*>\", \"**\");\n\n setType(\"builtin\")(\n \"Applicative\", \"Bool\", \"Bounded\", \"Char\", \"Double\", \"EQ\", \"Either\", \"Enum\",\n \"Eq\", \"False\", \"FilePath\", \"Float\", \"Floating\", \"Fractional\", \"Functor\",\n \"GT\", \"IO\", \"IOError\", \"Int\", \"Integer\", \"Integral\", \"Just\", \"LT\", \"Left\",\n \"Maybe\", \"Monad\", \"Nothing\", \"Num\", \"Ord\", \"Ordering\", \"Rational\", \"Read\",\n \"ReadS\", \"Real\", \"RealFloat\", \"RealFrac\", \"Right\", \"Show\", \"ShowS\",\n \"String\", \"True\");\n\n setType(\"builtin\")(\n \"abs\", \"acos\", \"acosh\", \"all\", \"and\", \"any\", \"appendFile\", \"asTypeOf\",\n \"asin\", \"asinh\", \"atan\", \"atan2\", \"atanh\", \"break\", \"catch\", \"ceiling\",\n \"compare\", \"concat\", \"concatMap\", \"const\", \"cos\", \"cosh\", \"curry\",\n \"cycle\", \"decodeFloat\", \"div\", \"divMod\", \"drop\", \"dropWhile\", \"either\",\n \"elem\", \"encodeFloat\", \"enumFrom\", \"enumFromThen\", \"enumFromThenTo\",\n \"enumFromTo\", \"error\", \"even\", \"exp\", \"exponent\", \"fail\", \"filter\",\n \"flip\", \"floatDigits\", \"floatRadix\", \"floatRange\", \"floor\", \"fmap\",\n \"foldl\", \"foldl1\", \"foldr\", \"foldr1\", \"fromEnum\", \"fromInteger\",\n \"fromIntegral\", \"fromRational\", \"fst\", \"gcd\", \"getChar\", \"getContents\",\n \"getLine\", \"head\", \"id\", \"init\", \"interact\", \"ioError\", \"isDenormalized\",\n \"isIEEE\", \"isInfinite\", \"isNaN\", \"isNegativeZero\", \"iterate\", \"last\",\n \"lcm\", \"length\", \"lex\", \"lines\", \"log\", \"logBase\", \"lookup\", \"map\",\n \"mapM\", \"mapM_\", \"max\", \"maxBound\", \"maximum\", \"maybe\", \"min\", \"minBound\",\n \"minimum\", \"mod\", \"negate\", \"not\", \"notElem\", \"null\", \"odd\", \"or\",\n \"otherwise\", \"pi\", \"pred\", \"print\", \"product\", \"properFraction\", \"pure\",\n \"putChar\", \"putStr\", \"putStrLn\", \"quot\", \"quotRem\", \"read\", \"readFile\",\n \"readIO\", \"readList\", \"readLn\", \"readParen\", \"reads\", \"readsPrec\",\n \"realToFrac\", \"recip\", \"rem\", \"repeat\", \"replicate\", \"return\", \"reverse\",\n \"round\", \"scaleFloat\", \"scanl\", \"scanl1\", \"scanr\", \"scanr1\", \"seq\",\n \"sequence\", \"sequence_\", \"show\", \"showChar\", \"showList\", \"showParen\",\n \"showString\", \"shows\", \"showsPrec\", \"significand\", \"signum\", \"sin\",\n \"sinh\", \"snd\", \"span\", \"splitAt\", \"sqrt\", \"subtract\", \"succ\", \"sum\",\n \"tail\", \"take\", \"takeWhile\", \"tan\", \"tanh\", \"toEnum\", \"toInteger\",\n \"toRational\", \"truncate\", \"uncurry\", \"undefined\", \"unlines\", \"until\",\n \"unwords\", \"unzip\", \"unzip3\", \"userError\", \"words\", \"writeFile\", \"zip\",\n \"zip3\", \"zipWith\", \"zipWith3\");\n\n return wkw;\n})();\n\nexport const haskell = {\n name: \"haskell\",\n startState: function () { return { f: normal }; },\n copyState: function (s) { return { f: s.f }; },\n\n token: function(stream, state) {\n var t = state.f(stream, function(s) { state.f = s; });\n var w = stream.current();\n return wellKnownWords.hasOwnProperty(w) ? wellKnownWords[w] : t;\n },\n\n languageData: {\n commentTokens: {line: \"--\", block: {open: \"{-\", close: \"-}\"}}\n }\n};\n"],"names":["switchState","source","setState","f","smallRE","largeRE","digitRE","hexitRE","octitRE","idRE","symbolRE","specialRE","whiteCharRE","normal","eatWhile","ch","next","test","eat","t","ncomment","stringLiteral","match","skipToEnd","type","nest","currNest","eol","stringGap","wellKnownWords","wkw","setType","i","arguments","length","haskell","name","startState","copyState","s","token","stream","state","w","current","hasOwnProperty","languageData","commentTokens","line","block","open","close"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/7047.index.js b/book/_build/html/_static/7047.index.js new file mode 100644 index 0000000..1d72e8b --- /dev/null +++ b/book/_build/html/_static/7047.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[7047],{97047:(e,t,n)=>{n.r(t),n.d(t,{commonmarkLanguage:()=>_e,deleteMarkupBackward:()=>tt,insertNewlineContinueMarkup:()=>Ye,markdown:()=>st,markdownKeymap:()=>nt,markdownLanguage:()=>Qe});var r,s=n(1727),i=n(65329),o=n(77120),a=n(64100),l=n(21649),h=n(86253);class f{static create(e,t,n,r,s){return new f(e,t,n,r+(r<<8)+e+(t<<4)|0,s,[],[])}constructor(e,t,n,r,s,i,o){this.type=e,this.value=t,this.from=n,this.hash=r,this.end=s,this.children=i,this.positions=o,this.hashProp=[[l.md.contextHash,r]]}addChild(e,t){e.prop(l.md.contextHash)!=this.hash&&(e=new l.mp(e.type,e.children,e.positions,e.length,this.hashProp)),this.children.push(e),this.positions.push(t)}toTree(e,t=this.end){let n=this.children.length-1;return n>=0&&(t=Math.max(t,this.positions[n]+this.children[n].length+this.from)),new l.mp(e.types[this.type],this.children,this.positions,t-this.from).balance({makeTree:(e,t,n)=>new l.mp(l.Jq.none,e,t,n,this.hashProp)})}}!function(e){e[e.Document=1]="Document",e[e.CodeBlock=2]="CodeBlock",e[e.FencedCode=3]="FencedCode",e[e.Blockquote=4]="Blockquote",e[e.HorizontalRule=5]="HorizontalRule",e[e.BulletList=6]="BulletList",e[e.OrderedList=7]="OrderedList",e[e.ListItem=8]="ListItem",e[e.ATXHeading1=9]="ATXHeading1",e[e.ATXHeading2=10]="ATXHeading2",e[e.ATXHeading3=11]="ATXHeading3",e[e.ATXHeading4=12]="ATXHeading4",e[e.ATXHeading5=13]="ATXHeading5",e[e.ATXHeading6=14]="ATXHeading6",e[e.SetextHeading1=15]="SetextHeading1",e[e.SetextHeading2=16]="SetextHeading2",e[e.HTMLBlock=17]="HTMLBlock",e[e.LinkReference=18]="LinkReference",e[e.Paragraph=19]="Paragraph",e[e.CommentBlock=20]="CommentBlock",e[e.ProcessingInstructionBlock=21]="ProcessingInstructionBlock",e[e.Escape=22]="Escape",e[e.Entity=23]="Entity",e[e.HardBreak=24]="HardBreak",e[e.Emphasis=25]="Emphasis",e[e.StrongEmphasis=26]="StrongEmphasis",e[e.Link=27]="Link",e[e.Image=28]="Image",e[e.InlineCode=29]="InlineCode",e[e.HTMLTag=30]="HTMLTag",e[e.Comment=31]="Comment",e[e.ProcessingInstruction=32]="ProcessingInstruction",e[e.URL=33]="URL",e[e.HeaderMark=34]="HeaderMark",e[e.QuoteMark=35]="QuoteMark",e[e.ListMark=36]="ListMark",e[e.LinkMark=37]="LinkMark",e[e.EmphasisMark=38]="EmphasisMark",e[e.CodeMark=39]="CodeMark",e[e.CodeText=40]="CodeText",e[e.CodeInfo=41]="CodeInfo",e[e.LinkTitle=42]="LinkTitle",e[e.LinkLabel=43]="LinkLabel"}(r||(r={}));class p{constructor(e,t){this.start=e,this.content=t,this.marks=[],this.parsers=[]}}class c{constructor(){this.text="",this.baseIndent=0,this.basePos=0,this.depth=0,this.markers=[],this.pos=0,this.indent=0,this.next=-1}forward(){this.basePos>this.pos&&this.forwardInner()}forwardInner(){let e=this.skipSpace(this.basePos);this.indent=this.countIndent(e,this.pos,this.indent),this.pos=e,this.next=e==this.text.length?-1:this.text.charCodeAt(e)}skipSpace(e){return g(this.text,e)}reset(e){for(this.text=e,this.baseIndent=this.basePos=this.pos=this.indent=0,this.forwardInner(),this.depth=1;this.markers.length;)this.markers.pop()}moveBase(e){this.basePos=e,this.baseIndent=this.countIndent(e,this.pos,this.indent)}moveBaseColumn(e){this.baseIndent=e,this.basePos=this.findColumn(e)}addMarker(e){this.markers.push(e)}countIndent(e,t=0,n=0){for(let r=t;r=t.stack[n.depth+1].value+n.baseIndent)return!0;if(n.indent>=n.baseIndent+4)return!1;let s=(e.type==r.OrderedList?w:C)(n,t,!1);return s>0&&(e.type!=r.BulletList||L(n,t,!1)<0)&&n.text.charCodeAt(n.pos+s-1)==e.value}const u={[r.Blockquote]:(e,t,n)=>62==n.next&&(n.markers.push(K(r.QuoteMark,t.lineStart+n.pos,t.lineStart+n.pos+1)),n.moveBase(n.pos+(m(n.text.charCodeAt(n.pos+1))?2:1)),e.end=t.lineStart+n.text.length,!0),[r.ListItem]:(e,t,n)=>!(n.indent-1||(n.moveBaseColumn(n.baseIndent+e.value),0)),[r.OrderedList]:d,[r.BulletList]:d,[r.Document]:()=>!0};function m(e){return 32==e||9==e||10==e||13==e}function g(e,t=0){for(;tn&&m(e.charCodeAt(t-1));)t--;return t}function x(e){if(96!=e.next&&126!=e.next)return-1;let t=e.pos+1;for(;t-1&&e.depth==t.stack.length||r<3?-1:1}function S(e,t){for(let n=e.stack.length-1;n>=0;n--)if(e.stack[n].type==t)return!0;return!1}function C(e,t,n){return 45!=e.next&&43!=e.next&&42!=e.next||e.pos!=e.text.length-1&&!m(e.text.charCodeAt(e.pos+1))||!(!n||S(t,r.BulletList)||e.skipSpace(e.pos+2)=48&&i<=57;){if(s++,s==e.text.length)return-1;i=e.text.charCodeAt(s)}return s==e.pos||s>e.pos+9||46!=i&&41!=i||se.pos+1||49!=e.next)?-1:s+1-e.pos}function y(e){if(35!=e.next)return-1;let t=e.pos+1;for(;t6?-1:n}function I(e){if(45!=e.next&&61!=e.next||e.indent>=e.baseIndent+4)return-1;let t=e.pos+1;for(;t/,B=/\?>/,E=[[/^<(?:script|pre|style)(?:\s|>|$)/i,/<\/(?:script|pre|style)>/i],[/^\s*/i.exec(s);if(o)return e.append(K(r.Comment,n,n+1+o[0].length));let a=/^\?[^]*?\?>/.exec(s);if(a)return e.append(K(r.ProcessingInstruction,n,n+1+a[0].length));let l=/^(?:![A-Z][^]*?>|!\[CDATA\[[^]*?\]\]>|\/\s*[a-zA-Z][\w-]*\s*>|\s*[a-zA-Z][\w-]*(\s+[a-zA-Z:_][\w-.:]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)*\s*(\/\s*)?>)/.exec(s);return l?e.append(K(r.HTMLTag,n,n+1+l[0].length)):-1},Emphasis(e,t,n){if(95!=t&&42!=t)return-1;let r=n+1;for(;e.char(r)==t;)r++;let s=e.slice(n-1,n),i=e.slice(r,r+1),o=se.test(s),a=se.test(i),l=/\s|^$/.test(s),h=/\s|^$/.test(i),f=!h&&(!a||l||o),p=!l&&(!o||h||a),c=f&&(42==t||!p||o),d=p&&(42==t||!f||a);return e.append(new ne(95==t?W:Y,n,r,(c?1:0)|(d?2:0)))},HardBreak(e,t,n){if(92==t&&10==e.char(n+1))return e.append(K(r.HardBreak,n,n+2));if(32==t){let t=n+1;for(;32==e.char(t);)t++;if(10==e.char(t)&&t>=n+2)return e.append(K(r.HardBreak,n,t+1))}return-1},Link:(e,t,n)=>91==t?e.append(new ne(ee,n,n+1,1)):-1,Image:(e,t,n)=>33==t&&91==e.char(n+1)?e.append(new ne(te,n,n+2,1)):-1,LinkEnd(e,t,n){if(93!=t)return-1;for(let t=e.parts.length-1;t>=0;t--){let s=e.parts[t];if(s instanceof ne&&(s.type==ee||s.type==te)){if(!s.side||e.skipSpace(s.to)==n&&!/[(\[]/.test(e.slice(n+1,n+2)))return e.parts[t]=null,-1;let i=e.takeContent(t),o=e.parts[t]=oe(e,i,s.type==ee?r.Link:r.Image,s.from,n+1);if(s.type==ee)for(let n=0;nt?K(r.URL,t+n,i+n):i==e.length&&null}}function le(e,t,n){let s=e.charCodeAt(t);if(39!=s&&34!=s&&40!=s)return!1;let i=40==s?41:s;for(let s=t+1,o=!1;s=this.end?-1:this.text.charCodeAt(e-this.offset)}get end(){return this.offset+this.text.length}slice(e,t){return this.text.slice(e-this.offset,t-this.offset)}append(e){return this.parts.push(e),e.to}addDelimiter(e,t,n,r,s){return this.append(new ne(e,t,n,(r?1:0)|(s?2:0)))}addElement(e){return this.append(e)}resolveMarkers(e){for(let t=e;t=e;o--){let e=this.parts[o];if(e instanceof ne&&1&e.side&&e.type==n.type&&!(s&&(1&n.side||2&e.side)&&(e.to-e.from+i)%3==0&&((e.to-e.from)%3||i%3))){r=e;break}}if(!r)continue;let a=n.type.resolve,l=[],h=r.from,f=n.to;if(s){let e=Math.min(2,r.to-r.from,i);h=r.to-e,f=n.from+e,a=1==e?"Emphasis":"StrongEmphasis"}r.type.mark&&l.push(this.elt(r.type.mark,h,r.to));for(let e=o+1;e=0;t--){let n=this.parts[t];if(n instanceof ne&&n.type==e)return t}return null}takeContent(e){let t=this.resolveMarkers(e);return this.parts.length=e,t}skipSpace(e){return g(this.text,e-this.offset)+this.offset}elt(e,t,n,r){return"string"==typeof e?K(this.parser.getNodeType(e),t,n,r):new V(e,t)}}function pe(e,t){if(!t.length)return e;if(!e.length)return t;let n=e.slice(),r=0;for(let e of t){for(;r(e?e-1:0))return!1;if(this.fragmentEnd<0){let e=this.fragment.to;for(;e>0&&"\n"!=this.input.read(e-1,e);)e--;this.fragmentEnd=e?e-1:0}let n=this.cursor;n||(n=this.cursor=this.fragment.tree.cursor(),n.firstChild());let r=e+this.fragment.offset;for(;n.to<=r;)if(!n.parent())return!1;for(;;){if(n.from>=r)return this.fragment.from<=t;if(!n.childAfter(r))return!1}}matches(e){let t=this.cursor.tree;return t&&t.prop(l.md.contextHash)==e}takeNodes(e){let t=this.cursor,n=this.fragment.offset,s=this.fragmentEnd-(this.fragment.openEnd?1:0),i=e.absoluteLineStart,o=i,a=e.block.children.length,h=o,f=a;for(;;){if(t.to-n>s){if(t.type.isAnonymous&&t.firstChild())continue;break}let i=ue(t.from-n,e.ranges);if(t.to-n<=e.ranges[e.rangeI].to)e.addNode(t.tree,i);else{let n=new l.mp(e.parser.nodeSet.types[r.Paragraph],[],[],0,e.block.hashProp);e.reusePlaceholders.set(n,t.tree),e.addNode(n,i)}if(t.type.is("Block")&&(ce.indexOf(t.type.id)<0?(o=t.to-n,a=e.block.children.length):(o=h,a=f,h=t.to-n,f=e.block.children.length)),!t.nextSibling())break}for(;e.block.children.length>a;)e.block.children.pop(),e.block.positions.pop();return o-i}}function ue(e,t){let n=e;for(let r=1;rP[e])),Object.keys(P).map((e=>R[e])),Object.keys(P),z,u,Object.keys(ie).map((e=>ie[e])),Object.keys(ie),[]);function ke(e,t,n){let r=[];for(let s=e.firstChild,i=t;;s=s.nextSibling){let e=s?s.from:n;if(e>i&&r.push({from:i,to:e}),!s)break;i=s.to}return r}const xe={resolve:"Strikethrough",mark:"StrikethroughMark"},be={defineNodes:[{name:"Strikethrough",style:{"Strikethrough/...":h.pJ.strikethrough}},{name:"StrikethroughMark",style:h.pJ.processingInstruction}],parseInline:[{name:"Strikethrough",parse(e,t,n){if(126!=t||126!=e.char(n+1)||126==e.char(n+2))return-1;let r=e.slice(n-1,n),s=e.slice(n+2,n+3),i=/\s|^$/.test(r),o=/\s|^$/.test(s),a=se.test(r),l=se.test(s);return e.addDelimiter(xe,n,n+2,!o&&(!l||i||a),!i&&(!a||o||l))},after:"Emphasis"}]};function Le(e,t,n=0,r,s=0){let i=0,o=!0,a=-1,l=-1,h=!1,f=()=>{r.push(e.elt("TableCell",s+a,s+l,e.parser.parseInline(t.slice(a,l),s+a)))};for(let p=n;p-1)&&i++,o=!1,r&&(a>-1&&f(),r.push(e.elt("TableDelimiter",p+s,p+s+1))),a=l=-1),h=!h&&92==n}return a>-1&&(i++,r&&f()),i}function Se(e,t){for(let n=t;nSe(t.content,0)?new we:null,endLeaf(e,t,n){if(n.parsers.some((e=>e instanceof we))||!Se(t.text,t.basePos))return!1;let r=e.scanLine(e.absoluteLineEnd+1).text;return Ce.test(r)&&Le(e,t.text,t.basePos)==Le(e,r,t.basePos)},before:"SetextHeading"}]};class Ie{nextLine(){return!1}finish(e,t){return e.addLeafElement(t,e.elt("Task",t.start,t.start+t.content.length,[e.elt("TaskMarker",t.start,t.start+3),...e.parser.parseInline(t.content.slice(3),t.start+3)])),!0}}const Ae={defineNodes:[{name:"Task",block:!0,style:h.pJ.list},{name:"TaskMarker",style:h.pJ.atom}],parseBlock:[{name:"TaskList",leaf:(e,t)=>/^\[[ xX]\][ \t]/.test(t.content)&&"ListItem"==e.parentType().name?new Ie:null,after:"SetextHeading"}]},Te=/(www\.)|(https?:\/\/)|([\w.+-]+@)|(mailto:|xmpp:)/gy,Be=/[\w-]+(\.\w+(\.\w+)?)(\/[^\s<]*)?/gy,Ee=/[\w.+-]+@[\w-]+\.[\w.-]+/gy,Me=/\/[a-zA-Z\d@.]+/gy;function ve(e,t,n,r){let s=0;for(let i=t;ive(e,t,r,"("))r--;else{if(";"!=s||!(n=/&(?:#\d+|#x[a-f\d]+|\w+);$/.exec(e.slice(t,r))))break;r=t+n.index}}return r}(e.text,r+s[0].length):s[3]?i=He(e.text,r):(i=He(e.text,r+s[0].length),i>-1&&"xmpp:"==s[0]&&(Me.lastIndex=i,s=Me.exec(e.text),s&&(i=s.index+s[0].length))),i<0?-1:(e.addElement(e.elt("URL",n,i+e.offset)),i+e.offset)):-1}}]}];function Ne(e,t,n){return(r,s,i)=>{if(s!=e||r.char(i+1)==e)return-1;let o=[r.elt(n,i,i+1)];for(let s=i+1;s!e.is("Block")||e.is("Document")||null!=$e(e)?void 0:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to}))),qe.add($e),o.uj.add({Document:()=>null}),o.pp.add({Document:Xe})]});function $e(e){let t=/^(?:ATX|Setext)Heading(\d)$/.exec(e.name);return t?+t[1]:void 0}function De(e,t){let n=e;for(;;){let e,r=n.nextSibling;if(!r||null!=(e=$e(r.type))&&e<=t)break;n=r}return n.to}const Fe=o.rs.of(((e,t,n)=>{for(let r=(0,o.qz)(e).resolveInner(n,-1);r&&!(r.fromn)return{from:n,to:t}}return null}));function Ue(e){return new o.SQ(Xe,e,[Fe],"markdown")}const _e=Ue(je),Qe=Ue(je.configure([Pe,Oe,Je,Re]));class Ze{constructor(e,t,n,r,s,i,o){this.node=e,this.from=t,this.to=n,this.spaceBefore=r,this.spaceAfter=s,this.type=i,this.item=o}blank(e,t=!0){let n=this.spaceBefore+("Blockquote"==this.node.name?">":"");if(null!=e){for(;n.length0;e--)n+=" ";return n+(t?this.spaceAfter:"")}marker(e,t){let n="OrderedList"==this.node.name?String(+Ve(this.item,e)[2]+t):"";return this.spaceBefore+n+this.type+this.spaceAfter}}function Ge(e,t){let n=[];for(let t=e;t&&"Document"!=t.name;t=t.parent)"ListItem"!=t.name&&"Blockquote"!=t.name&&"FencedCode"!=t.name||n.push(t);let r=[];for(let e=n.length-1;e>=0;e--){let s,i=n[e],o=t.lineAt(i.from),a=i.from-o.from;if("FencedCode"==i.name)r.push(new Ze(i,a,a,"","","",null));else if("Blockquote"==i.name&&(s=/^ *>( ?)/.exec(o.text.slice(a))))r.push(new Ze(i,a,a+s[0].length,"",s[1],">",null));else if("ListItem"==i.name&&"OrderedList"==i.parent.name&&(s=/^( *)\d+([.)])( *)/.exec(o.text.slice(a)))){let e=s[3],t=s[0].length;e.length>=4&&(e=e.slice(0,e.length-4),t-=4),r.push(new Ze(i.parent,a,a+t,s[1],e,s[2],i))}else if("ListItem"==i.name&&"BulletList"==i.parent.name&&(s=/^( *)([-+*])( {1,4}\[[ xX]\])?( +)/.exec(o.text.slice(a)))){let e=s[4],t=s[0].length;e.length>4&&(e=e.slice(0,e.length-4),t-=4);let n=s[2];s[3]&&(n+=s[3].replace(/[xX]/," ")),r.push(new Ze(i.parent,a,a+t,s[1],e,n,i))}}return r}function Ve(e,t){return/^(\s*)(\d+)(?=[.)])/.exec(t.sliceString(e.from,e.from+10))}function Ke(e,t,n,r=0){for(let s=-1,i=e;;){if("ListItem"==i.name){let e=Ve(i,t),o=+e[2];if(s>=0){if(o!=s+1)return;n.push({from:i.from+e[1].length,to:i.from+e[0].length,insert:String(s+2+r)})}s=o}let e=i.nextSibling;if(!e)break;i=e}}function We(e,t){let n=/^[ \t]*/.exec(e)[0].length;if(!n||"\t"!=t.facet(o.c))return e;let r="";for(let t=(0,s.IS)(e,4,n);t>0;)t>=4?(r+="\t",t-=4):(r+=" ",t--);return r+e.slice(n)}const Ye=({state:e,dispatch:t})=>{let n=(0,o.qz)(e),{doc:r}=e,i=null,a=e.changeByRange((t=>{if(!t.empty||!Qe.isActiveAt(e,t.from))return i={range:t};let o=t.from,a=r.lineAt(o),l=Ge(n.resolveInner(o,-1),r);for(;l.length&&l[l.length-1].from>o-a.from;)l.pop();if(!l.length)return i={range:t};let h=l[l.length-1];if(h.to-h.spaceAfter.length>o-a.from)return i={range:t};let f=o>=h.to-h.spaceAfter.length&&!/\S/.test(a.text.slice(h.to));if(h.item&&f){if(h.node.firstChild.to>=o||a.from>0&&!/[^\s>]/.test(r.lineAt(a.from-1).text)){let e,t=l.length>1?l[l.length-2]:null,n="";t&&t.item?(e=a.from+t.from,n=t.marker(r,1)):e=a.from+(t?t.to:0);let i=[{from:e,to:o,insert:n}];return"OrderedList"==h.node.name&&Ke(h.item,r,i,-2),t&&"OrderedList"==t.node.name&&Ke(t.item,r,i),{range:s.jT.cursor(e+n.length),changes:i}}{let t="";for(let e=0,n=l.length-2;e<=n;e++)t+=l[e].blank(e\s*$/.exec(n.text);if(s&&s.index==h.from){let r=e.changes([{from:n.from+s.index,to:n.to},{from:a.from+h.from,to:a.to}]);return{range:t.map(r),changes:r}}}let p=[];"OrderedList"==h.node.name&&Ke(h.item,r,p);let c=h.item&&h.item.from]*/.exec(a.text)[0].length>=h.to)for(let e=0,t=l.length-1;e<=t;e++)d+=e!=t||c?l[e].blank(ea.from&&/\s/.test(a.text.charAt(u-a.from-1));)u--;return d=We(d,e),p.push({from:u,to:o,insert:e.lineBreak+d}),{range:s.jT.cursor(u+d.length+1),changes:p}}));return!i&&(t(e.update(a,{scrollIntoView:!0,userEvent:"input"})),!0)};function et(e){return"QuoteMark"==e.name||"ListMark"==e.name}const tt=({state:e,dispatch:t})=>{let n=(0,o.qz)(e),r=null,i=e.changeByRange((t=>{let i=t.from,{doc:o}=e;if(t.empty&&Qe.isActiveAt(e,t.from)){let t=o.lineAt(i),r=Ge(function(e,t){let n=e.resolveInner(t,-1),r=t;et(n)&&(r=n.from,n=n.parent);for(let e;e=n.childBefore(r);)if(et(e))r=e.from;else{if("OrderedList"!=e.name&&"BulletList"!=e.name)break;n=e.lastChild,r=n.to}return n}(n,i),o);if(r.length){let n=r[r.length-1],o=n.to-n.spaceAfter.length+(n.spaceAfter?1:0);if(i-t.from>o&&!/\S/.test(t.text.slice(o,i-t.from)))return{range:s.jT.cursor(t.from+o),changes:{from:t.from+o,to:i}};if(i-t.from==o&&(!n.item||t.from<=n.item.from||!/\S/.test(t.text.slice(0,n.to)))){let r=t.from+n.from;if(n.item&&n.node.from{if(e&&m){let t=null;if(e=/\S*/.exec(e)[0],t="function"==typeof m?m(e):o.c6.matchLanguageName(m,e,!0),t instanceof o.c6)return t.support?t.support.language.parser:o.Be.getSkippingParser(t.load());if(t)return t.parser}return g?g.parser:null}):void 0;var m,g;c.push(function(e){let{codeParser:t,htmlParser:n}=e,s=(0,l.FE)(((e,s)=>{let i=e.type.id;if(!t||i!=r.CodeBlock&&i!=r.FencedCode){if(n&&(i==r.HTMLBlock||i==r.HTMLTag))return{parser:n,overlay:ke(e.node,e.from,e.to)}}else{let n="";if(i==r.FencedCode){let t=e.node.getChild(r.CodeInfo);t&&(n=s.read(t.from,t.to))}let o=t(n);if(o)return{parser:o,overlay:e=>e.type.id==r.CodeText}}return null}));return{wrap:s}}({codeParser:u,htmlParser:rt.language.parser})),a&&d.push(s.Wl.high(i.$f.of(nt)));let k=Ue(h.configure(c));return f&&d.push(k.data.of({autocomplete:it})),new o.ri(k,d)}function it(e){let{state:t,pos:n}=e,r=/<[:\-\.\w\u00b7-\uffff]*$/.exec(t.sliceDoc(n-25,n));if(!r)return null;let s=(0,o.qz)(t).resolveInner(n,-1);for(;s&&!s.type.isTop;){if("CodeBlock"==s.name||"FencedCode"==s.name||"ProcessingInstructionBlock"==s.name||"CommentBlock"==s.name||"Link"==s.name||"Image"==s.name)return null;s=s.parent}return{from:n-r[0].length,to:n,options:at(),validFor:/^<[:\-\.\w\u00b7-\uffff]*$/}}let ot=null;function at(){if(ot)return ot;let e=(0,ze.htmlCompletionSource)(new a.TK(s.yy.create({extensions:rt}),0,!0));return ot=e?e.options:[]}}}]); +//# sourceMappingURL=7047.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/7047.index.js.map b/book/_build/html/_static/7047.index.js.map new file mode 100644 index 0000000..9b1341b --- /dev/null +++ b/book/_build/html/_static/7047.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"7047.index.js","mappings":"0QAmCIA,E,iEAhCJ,MAAMC,EACFC,cAAcC,EAAMC,EAAOC,EAAMC,EAAYC,GAEzC,OAAO,IAAIN,EAAeE,EAAMC,EAAOC,EAD3BC,GAAcA,GAAc,GAAKH,GAAQC,GAAS,GAAM,EACjBG,EAAK,GAAI,GAChE,CACAC,YAAYL,EAEZC,EAAOC,EAAMI,EAAMF,EAAKG,EAAUC,GAC9BC,KAAKT,KAAOA,EACZS,KAAKR,MAAQA,EACbQ,KAAKP,KAAOA,EACZO,KAAKH,KAAOA,EACZG,KAAKL,IAAMA,EACXK,KAAKF,SAAWA,EAChBE,KAAKD,UAAYA,EACjBC,KAAKC,SAAW,CAAC,CAAC,iBAAsBJ,GAC5C,CACAK,SAASC,EAAOC,GACRD,EAAME,KAAK,mBAAyBL,KAAKH,OACzCM,EAAQ,IAAI,KAAKA,EAAMZ,KAAMY,EAAML,SAAUK,EAAMJ,UAAWI,EAAMG,OAAQN,KAAKC,WACrFD,KAAKF,SAASS,KAAKJ,GACnBH,KAAKD,UAAUQ,KAAKH,EACxB,CACAI,OAAOC,EAASd,EAAMK,KAAKL,KACvB,IAAIe,EAAOV,KAAKF,SAASQ,OAAS,EAGlC,OAFII,GAAQ,IACRf,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B4f,QAASC,KACTC,SAAU,6BAElB,CACA,IAAIC,GAAkB,KACtB,SAASF,KACL,GAAIE,GACA,OAAOA,GACX,IAAIrd,GAAS,KAAAsd,sBAAqB,IAAI,KAAkB,YAAmB,CAAEvB,WAAYT,KAAgB,GAAG,IAC5G,OAAO+B,GAAkBrd,EAASA,EAAOkd,QAAU,EACvD,C","sources":["webpack://thebe/../../node_modules/@lezer/markdown/dist/index.js","webpack://thebe/../../node_modules/@codemirror/lang-markdown/dist/index.js"],"sourcesContent":["import { NodeType, NodeProp, NodeSet, Tree, Parser, parseMixed } from '@lezer/common';\nimport { styleTags, tags, Tag } from '@lezer/highlight';\n\nclass CompositeBlock {\n static create(type, value, from, parentHash, end) {\n let hash = (parentHash + (parentHash << 8) + type + (value << 4)) | 0;\n return new CompositeBlock(type, value, from, hash, end, [], []);\n }\n constructor(type, \n // Used for indentation in list items, markup character in lists\n value, from, hash, end, children, positions) {\n this.type = type;\n this.value = value;\n this.from = from;\n this.hash = hash;\n this.end = end;\n this.children = children;\n this.positions = positions;\n this.hashProp = [[NodeProp.contextHash, hash]];\n }\n addChild(child, pos) {\n if (child.prop(NodeProp.contextHash) != this.hash)\n child = new Tree(child.type, child.children, child.positions, child.length, this.hashProp);\n this.children.push(child);\n this.positions.push(pos);\n }\n toTree(nodeSet, end = this.end) {\n let last = this.children.length - 1;\n if (last >= 0)\n end = Math.max(end, this.positions[last] + this.children[last].length + this.from);\n return new Tree(nodeSet.types[this.type], this.children, this.positions, end - this.from).balance({\n makeTree: (children, positions, length) => new Tree(NodeType.none, children, positions, length, this.hashProp)\n });\n }\n}\nvar Type;\n(function (Type) {\n Type[Type[\"Document\"] = 1] = \"Document\";\n Type[Type[\"CodeBlock\"] = 2] = \"CodeBlock\";\n Type[Type[\"FencedCode\"] = 3] = \"FencedCode\";\n Type[Type[\"Blockquote\"] = 4] = \"Blockquote\";\n Type[Type[\"HorizontalRule\"] = 5] = \"HorizontalRule\";\n Type[Type[\"BulletList\"] = 6] = \"BulletList\";\n Type[Type[\"OrderedList\"] = 7] = \"OrderedList\";\n Type[Type[\"ListItem\"] = 8] = \"ListItem\";\n Type[Type[\"ATXHeading1\"] = 9] = \"ATXHeading1\";\n Type[Type[\"ATXHeading2\"] = 10] = \"ATXHeading2\";\n Type[Type[\"ATXHeading3\"] = 11] = \"ATXHeading3\";\n Type[Type[\"ATXHeading4\"] = 12] = \"ATXHeading4\";\n Type[Type[\"ATXHeading5\"] = 13] = \"ATXHeading5\";\n Type[Type[\"ATXHeading6\"] = 14] = \"ATXHeading6\";\n Type[Type[\"SetextHeading1\"] = 15] = \"SetextHeading1\";\n Type[Type[\"SetextHeading2\"] = 16] = \"SetextHeading2\";\n Type[Type[\"HTMLBlock\"] = 17] = \"HTMLBlock\";\n Type[Type[\"LinkReference\"] = 18] = \"LinkReference\";\n Type[Type[\"Paragraph\"] = 19] = \"Paragraph\";\n Type[Type[\"CommentBlock\"] = 20] = \"CommentBlock\";\n Type[Type[\"ProcessingInstructionBlock\"] = 21] = \"ProcessingInstructionBlock\";\n // Inline\n Type[Type[\"Escape\"] = 22] = \"Escape\";\n Type[Type[\"Entity\"] = 23] = \"Entity\";\n Type[Type[\"HardBreak\"] = 24] = \"HardBreak\";\n Type[Type[\"Emphasis\"] = 25] = \"Emphasis\";\n Type[Type[\"StrongEmphasis\"] = 26] = \"StrongEmphasis\";\n Type[Type[\"Link\"] = 27] = \"Link\";\n Type[Type[\"Image\"] = 28] = \"Image\";\n Type[Type[\"InlineCode\"] = 29] = \"InlineCode\";\n Type[Type[\"HTMLTag\"] = 30] = \"HTMLTag\";\n Type[Type[\"Comment\"] = 31] = \"Comment\";\n Type[Type[\"ProcessingInstruction\"] = 32] = \"ProcessingInstruction\";\n Type[Type[\"URL\"] = 33] = \"URL\";\n // Smaller tokens\n Type[Type[\"HeaderMark\"] = 34] = \"HeaderMark\";\n Type[Type[\"QuoteMark\"] = 35] = \"QuoteMark\";\n Type[Type[\"ListMark\"] = 36] = \"ListMark\";\n Type[Type[\"LinkMark\"] = 37] = \"LinkMark\";\n Type[Type[\"EmphasisMark\"] = 38] = \"EmphasisMark\";\n Type[Type[\"CodeMark\"] = 39] = \"CodeMark\";\n Type[Type[\"CodeText\"] = 40] = \"CodeText\";\n Type[Type[\"CodeInfo\"] = 41] = \"CodeInfo\";\n Type[Type[\"LinkTitle\"] = 42] = \"LinkTitle\";\n Type[Type[\"LinkLabel\"] = 43] = \"LinkLabel\";\n})(Type || (Type = {}));\n/// Data structure used to accumulate a block's content during [leaf\n/// block parsing](#BlockParser.leaf).\nclass LeafBlock {\n /// @internal\n constructor(\n /// The start position of the block.\n start, \n /// The block's text content.\n content) {\n this.start = start;\n this.content = content;\n /// @internal\n this.marks = [];\n /// The block parsers active for this block.\n this.parsers = [];\n }\n}\n/// Data structure used during block-level per-line parsing.\nclass Line {\n constructor() {\n /// The line's full text.\n this.text = \"\";\n /// The base indent provided by the composite contexts (that have\n /// been handled so far).\n this.baseIndent = 0;\n /// The string position corresponding to the base indent.\n this.basePos = 0;\n /// The number of contexts handled @internal\n this.depth = 0;\n /// Any markers (i.e. block quote markers) parsed for the contexts. @internal\n this.markers = [];\n /// The position of the next non-whitespace character beyond any\n /// list, blockquote, or other composite block markers.\n this.pos = 0;\n /// The column of the next non-whitespace character.\n this.indent = 0;\n /// The character code of the character after `pos`.\n this.next = -1;\n }\n /// @internal\n forward() {\n if (this.basePos > this.pos)\n this.forwardInner();\n }\n /// @internal\n forwardInner() {\n let newPos = this.skipSpace(this.basePos);\n this.indent = this.countIndent(newPos, this.pos, this.indent);\n this.pos = newPos;\n this.next = newPos == this.text.length ? -1 : this.text.charCodeAt(newPos);\n }\n /// Skip whitespace after the given position, return the position of\n /// the next non-space character or the end of the line if there's\n /// only space after `from`.\n skipSpace(from) { return skipSpace(this.text, from); }\n /// @internal\n reset(text) {\n this.text = text;\n this.baseIndent = this.basePos = this.pos = this.indent = 0;\n this.forwardInner();\n this.depth = 1;\n while (this.markers.length)\n this.markers.pop();\n }\n /// Move the line's base position forward to the given position.\n /// This should only be called by composite [block\n /// parsers](#BlockParser.parse) or [markup skipping\n /// functions](#NodeSpec.composite).\n moveBase(to) {\n this.basePos = to;\n this.baseIndent = this.countIndent(to, this.pos, this.indent);\n }\n /// Move the line's base position forward to the given _column_.\n moveBaseColumn(indent) {\n this.baseIndent = indent;\n this.basePos = this.findColumn(indent);\n }\n /// Store a composite-block-level marker. Should be called from\n /// [markup skipping functions](#NodeSpec.composite) when they\n /// consume any non-whitespace characters.\n addMarker(elt) {\n this.markers.push(elt);\n }\n /// Find the column position at `to`, optionally starting at a given\n /// position and column.\n countIndent(to, from = 0, indent = 0) {\n for (let i = from; i < to; i++)\n indent += this.text.charCodeAt(i) == 9 ? 4 - indent % 4 : 1;\n return indent;\n }\n /// Find the position corresponding to the given column.\n findColumn(goal) {\n let i = 0;\n for (let indent = 0; i < this.text.length && indent < goal; i++)\n indent += this.text.charCodeAt(i) == 9 ? 4 - indent % 4 : 1;\n return i;\n }\n /// @internal\n scrub() {\n if (!this.baseIndent)\n return this.text;\n let result = \"\";\n for (let i = 0; i < this.basePos; i++)\n result += \" \";\n return result + this.text.slice(this.basePos);\n }\n}\nfunction skipForList(bl, cx, line) {\n if (line.pos == line.text.length ||\n (bl != cx.block && line.indent >= cx.stack[line.depth + 1].value + line.baseIndent))\n return true;\n if (line.indent >= line.baseIndent + 4)\n return false;\n let size = (bl.type == Type.OrderedList ? isOrderedList : isBulletList)(line, cx, false);\n return size > 0 &&\n (bl.type != Type.BulletList || isHorizontalRule(line, cx, false) < 0) &&\n line.text.charCodeAt(line.pos + size - 1) == bl.value;\n}\nconst DefaultSkipMarkup = {\n [Type.Blockquote](bl, cx, line) {\n if (line.next != 62 /* '>' */)\n return false;\n line.markers.push(elt(Type.QuoteMark, cx.lineStart + line.pos, cx.lineStart + line.pos + 1));\n line.moveBase(line.pos + (space(line.text.charCodeAt(line.pos + 1)) ? 2 : 1));\n bl.end = cx.lineStart + line.text.length;\n return true;\n },\n [Type.ListItem](bl, _cx, line) {\n if (line.indent < line.baseIndent + bl.value && line.next > -1)\n return false;\n line.moveBaseColumn(line.baseIndent + bl.value);\n return true;\n },\n [Type.OrderedList]: skipForList,\n [Type.BulletList]: skipForList,\n [Type.Document]() { return true; }\n};\nfunction space(ch) { return ch == 32 || ch == 9 || ch == 10 || ch == 13; }\nfunction skipSpace(line, i = 0) {\n while (i < line.length && space(line.charCodeAt(i)))\n i++;\n return i;\n}\nfunction skipSpaceBack(line, i, to) {\n while (i > to && space(line.charCodeAt(i - 1)))\n i--;\n return i;\n}\nfunction isFencedCode(line) {\n if (line.next != 96 && line.next != 126 /* '`~' */)\n return -1;\n let pos = line.pos + 1;\n while (pos < line.text.length && line.text.charCodeAt(pos) == line.next)\n pos++;\n if (pos < line.pos + 3)\n return -1;\n if (line.next == 96)\n for (let i = pos; i < line.text.length; i++)\n if (line.text.charCodeAt(i) == 96)\n return -1;\n return pos;\n}\nfunction isBlockquote(line) {\n return line.next != 62 /* '>' */ ? -1 : line.text.charCodeAt(line.pos + 1) == 32 ? 2 : 1;\n}\nfunction isHorizontalRule(line, cx, breaking) {\n if (line.next != 42 && line.next != 45 && line.next != 95 /* '_-*' */)\n return -1;\n let count = 1;\n for (let pos = line.pos + 1; pos < line.text.length; pos++) {\n let ch = line.text.charCodeAt(pos);\n if (ch == line.next)\n count++;\n else if (!space(ch))\n return -1;\n }\n // Setext headers take precedence\n if (breaking && line.next == 45 && isSetextUnderline(line) > -1 && line.depth == cx.stack.length)\n return -1;\n return count < 3 ? -1 : 1;\n}\nfunction inList(cx, type) {\n for (let i = cx.stack.length - 1; i >= 0; i--)\n if (cx.stack[i].type == type)\n return true;\n return false;\n}\nfunction isBulletList(line, cx, breaking) {\n return (line.next == 45 || line.next == 43 || line.next == 42 /* '-+*' */) &&\n (line.pos == line.text.length - 1 || space(line.text.charCodeAt(line.pos + 1))) &&\n (!breaking || inList(cx, Type.BulletList) || line.skipSpace(line.pos + 2) < line.text.length) ? 1 : -1;\n}\nfunction isOrderedList(line, cx, breaking) {\n let pos = line.pos, next = line.next;\n for (;;) {\n if (next >= 48 && next <= 57 /* '0-9' */)\n pos++;\n else\n break;\n if (pos == line.text.length)\n return -1;\n next = line.text.charCodeAt(pos);\n }\n if (pos == line.pos || pos > line.pos + 9 ||\n (next != 46 && next != 41 /* '.)' */) ||\n (pos < line.text.length - 1 && !space(line.text.charCodeAt(pos + 1))) ||\n breaking && !inList(cx, Type.OrderedList) &&\n (line.skipSpace(pos + 1) == line.text.length || pos > line.pos + 1 || line.next != 49 /* '1' */))\n return -1;\n return pos + 1 - line.pos;\n}\nfunction isAtxHeading(line) {\n if (line.next != 35 /* '#' */)\n return -1;\n let pos = line.pos + 1;\n while (pos < line.text.length && line.text.charCodeAt(pos) == 35)\n pos++;\n if (pos < line.text.length && line.text.charCodeAt(pos) != 32)\n return -1;\n let size = pos - line.pos;\n return size > 6 ? -1 : size;\n}\nfunction isSetextUnderline(line) {\n if (line.next != 45 && line.next != 61 /* '-=' */ || line.indent >= line.baseIndent + 4)\n return -1;\n let pos = line.pos + 1;\n while (pos < line.text.length && line.text.charCodeAt(pos) == line.next)\n pos++;\n let end = pos;\n while (pos < line.text.length && space(line.text.charCodeAt(pos)))\n pos++;\n return pos == line.text.length ? end : -1;\n}\nconst EmptyLine = /^[ \\t]*$/, CommentEnd = /-->/, ProcessingEnd = /\\?>/;\nconst HTMLBlockStyle = [\n [/^<(?:script|pre|style)(?:\\s|>|$)/i, /<\\/(?:script|pre|style)>/i],\n [/^\\s*/i.exec(after);\n if (comment)\n return cx.append(elt(Type.Comment, start, start + 1 + comment[0].length));\n let procInst = /^\\?[^]*?\\?>/.exec(after);\n if (procInst)\n return cx.append(elt(Type.ProcessingInstruction, start, start + 1 + procInst[0].length));\n let m = /^(?:![A-Z][^]*?>|!\\[CDATA\\[[^]*?\\]\\]>|\\/\\s*[a-zA-Z][\\w-]*\\s*>|\\s*[a-zA-Z][\\w-]*(\\s+[a-zA-Z:_][\\w-.:]*(?:\\s*=\\s*(?:[^\\s\"'=<>`]+|'[^']*'|\"[^\"]*\"))?)*\\s*(\\/\\s*)?>)/.exec(after);\n if (!m)\n return -1;\n return cx.append(elt(Type.HTMLTag, start, start + 1 + m[0].length));\n },\n Emphasis(cx, next, start) {\n if (next != 95 && next != 42)\n return -1;\n let pos = start + 1;\n while (cx.char(pos) == next)\n pos++;\n let before = cx.slice(start - 1, start), after = cx.slice(pos, pos + 1);\n let pBefore = Punctuation.test(before), pAfter = Punctuation.test(after);\n let sBefore = /\\s|^$/.test(before), sAfter = /\\s|^$/.test(after);\n let leftFlanking = !sAfter && (!pAfter || sBefore || pBefore);\n let rightFlanking = !sBefore && (!pBefore || sAfter || pAfter);\n let canOpen = leftFlanking && (next == 42 || !rightFlanking || pBefore);\n let canClose = rightFlanking && (next == 42 || !leftFlanking || pAfter);\n return cx.append(new InlineDelimiter(next == 95 ? EmphasisUnderscore : EmphasisAsterisk, start, pos, (canOpen ? 1 /* Mark.Open */ : 0) | (canClose ? 2 /* Mark.Close */ : 0)));\n },\n HardBreak(cx, next, start) {\n if (next == 92 /* '\\\\' */ && cx.char(start + 1) == 10 /* '\\n' */)\n return cx.append(elt(Type.HardBreak, start, start + 2));\n if (next == 32) {\n let pos = start + 1;\n while (cx.char(pos) == 32)\n pos++;\n if (cx.char(pos) == 10 && pos >= start + 2)\n return cx.append(elt(Type.HardBreak, start, pos + 1));\n }\n return -1;\n },\n Link(cx, next, start) {\n return next == 91 /* '[' */ ? cx.append(new InlineDelimiter(LinkStart, start, start + 1, 1 /* Mark.Open */)) : -1;\n },\n Image(cx, next, start) {\n return next == 33 /* '!' */ && cx.char(start + 1) == 91 /* '[' */\n ? cx.append(new InlineDelimiter(ImageStart, start, start + 2, 1 /* Mark.Open */)) : -1;\n },\n LinkEnd(cx, next, start) {\n if (next != 93 /* ']' */)\n return -1;\n // Scanning back to the next link/image start marker\n for (let i = cx.parts.length - 1; i >= 0; i--) {\n let part = cx.parts[i];\n if (part instanceof InlineDelimiter && (part.type == LinkStart || part.type == ImageStart)) {\n // If this one has been set invalid (because it would produce\n // a nested link) or there's no valid link here ignore both.\n if (!part.side || cx.skipSpace(part.to) == start && !/[(\\[]/.test(cx.slice(start + 1, start + 2))) {\n cx.parts[i] = null;\n return -1;\n }\n // Finish the content and replace the entire range in\n // this.parts with the link/image node.\n let content = cx.takeContent(i);\n let link = cx.parts[i] = finishLink(cx, content, part.type == LinkStart ? Type.Link : Type.Image, part.from, start + 1);\n // Set any open-link markers before this link to invalid.\n if (part.type == LinkStart)\n for (let j = 0; j < i; j++) {\n let p = cx.parts[j];\n if (p instanceof InlineDelimiter && p.type == LinkStart)\n p.side = 0;\n }\n return link.to;\n }\n }\n return -1;\n }\n};\nfunction finishLink(cx, content, type, start, startPos) {\n let { text } = cx, next = cx.char(startPos), endPos = startPos;\n content.unshift(elt(Type.LinkMark, start, start + (type == Type.Image ? 2 : 1)));\n content.push(elt(Type.LinkMark, startPos - 1, startPos));\n if (next == 40 /* '(' */) {\n let pos = cx.skipSpace(startPos + 1);\n let dest = parseURL(text, pos - cx.offset, cx.offset), title;\n if (dest) {\n pos = cx.skipSpace(dest.to);\n title = parseLinkTitle(text, pos - cx.offset, cx.offset);\n if (title)\n pos = cx.skipSpace(title.to);\n }\n if (cx.char(pos) == 41 /* ')' */) {\n content.push(elt(Type.LinkMark, startPos, startPos + 1));\n endPos = pos + 1;\n if (dest)\n content.push(dest);\n if (title)\n content.push(title);\n content.push(elt(Type.LinkMark, pos, endPos));\n }\n }\n else if (next == 91 /* '[' */) {\n let label = parseLinkLabel(text, startPos - cx.offset, cx.offset, false);\n if (label) {\n content.push(label);\n endPos = label.to;\n }\n }\n return elt(type, start, endPos, content);\n}\n// These return `null` when falling off the end of the input, `false`\n// when parsing fails otherwise (for use in the incremental link\n// reference parser).\nfunction parseURL(text, start, offset) {\n let next = text.charCodeAt(start);\n if (next == 60 /* '<' */) {\n for (let pos = start + 1; pos < text.length; pos++) {\n let ch = text.charCodeAt(pos);\n if (ch == 62 /* '>' */)\n return elt(Type.URL, start + offset, pos + 1 + offset);\n if (ch == 60 || ch == 10 /* '<\\n' */)\n return false;\n }\n return null;\n }\n else {\n let depth = 0, pos = start;\n for (let escaped = false; pos < text.length; pos++) {\n let ch = text.charCodeAt(pos);\n if (space(ch)) {\n break;\n }\n else if (escaped) {\n escaped = false;\n }\n else if (ch == 40 /* '(' */) {\n depth++;\n }\n else if (ch == 41 /* ')' */) {\n if (!depth)\n break;\n depth--;\n }\n else if (ch == 92 /* '\\\\' */) {\n escaped = true;\n }\n }\n return pos > start ? elt(Type.URL, start + offset, pos + offset) : pos == text.length ? null : false;\n }\n}\nfunction parseLinkTitle(text, start, offset) {\n let next = text.charCodeAt(start);\n if (next != 39 && next != 34 && next != 40 /* '\"\\'(' */)\n return false;\n let end = next == 40 ? 41 : next;\n for (let pos = start + 1, escaped = false; pos < text.length; pos++) {\n let ch = text.charCodeAt(pos);\n if (escaped)\n escaped = false;\n else if (ch == end)\n return elt(Type.LinkTitle, start + offset, pos + 1 + offset);\n else if (ch == 92 /* '\\\\' */)\n escaped = true;\n }\n return null;\n}\nfunction parseLinkLabel(text, start, offset, requireNonWS) {\n for (let escaped = false, pos = start + 1, end = Math.min(text.length, pos + 999); pos < end; pos++) {\n let ch = text.charCodeAt(pos);\n if (escaped)\n escaped = false;\n else if (ch == 93 /* ']' */)\n return requireNonWS ? false : elt(Type.LinkLabel, start + offset, pos + 1 + offset);\n else {\n if (requireNonWS && !space(ch))\n requireNonWS = false;\n if (ch == 91 /* '[' */)\n return false;\n else if (ch == 92 /* '\\\\' */)\n escaped = true;\n }\n }\n return null;\n}\n/// Inline parsing functions get access to this context, and use it to\n/// read the content and emit syntax nodes.\nclass InlineContext {\n /// @internal\n constructor(\n /// The parser that is being used.\n parser, \n /// The text of this inline section.\n text, \n /// The starting offset of the section in the document.\n offset) {\n this.parser = parser;\n this.text = text;\n this.offset = offset;\n /// @internal\n this.parts = [];\n }\n /// Get the character code at the given (document-relative)\n /// position.\n char(pos) { return pos >= this.end ? -1 : this.text.charCodeAt(pos - this.offset); }\n /// The position of the end of this inline section.\n get end() { return this.offset + this.text.length; }\n /// Get a substring of this inline section. Again uses\n /// document-relative positions.\n slice(from, to) { return this.text.slice(from - this.offset, to - this.offset); }\n /// @internal\n append(elt) {\n this.parts.push(elt);\n return elt.to;\n }\n /// Add a [delimiter](#DelimiterType) at this given position. `open`\n /// and `close` indicate whether this delimiter is opening, closing,\n /// or both. Returns the end of the delimiter, for convenient\n /// returning from [parse functions](#InlineParser.parse).\n addDelimiter(type, from, to, open, close) {\n return this.append(new InlineDelimiter(type, from, to, (open ? 1 /* Mark.Open */ : 0) | (close ? 2 /* Mark.Close */ : 0)));\n }\n /// Add an inline element. Returns the end of the element.\n addElement(elt) {\n return this.append(elt);\n }\n /// Resolve markers between this.parts.length and from, wrapping matched markers in the\n /// appropriate node and updating the content of this.parts. @internal\n resolveMarkers(from) {\n // Scan forward, looking for closing tokens\n for (let i = from; i < this.parts.length; i++) {\n let close = this.parts[i];\n if (!(close instanceof InlineDelimiter && close.type.resolve && (close.side & 2 /* Mark.Close */)))\n continue;\n let emp = close.type == EmphasisUnderscore || close.type == EmphasisAsterisk;\n let closeSize = close.to - close.from;\n let open, j = i - 1;\n // Continue scanning for a matching opening token\n for (; j >= from; j--) {\n let part = this.parts[j];\n if (part instanceof InlineDelimiter && (part.side & 1 /* Mark.Open */) && part.type == close.type &&\n // Ignore emphasis delimiters where the character count doesn't match\n !(emp && ((close.side & 1 /* Mark.Open */) || (part.side & 2 /* Mark.Close */)) &&\n (part.to - part.from + closeSize) % 3 == 0 && ((part.to - part.from) % 3 || closeSize % 3))) {\n open = part;\n break;\n }\n }\n if (!open)\n continue;\n let type = close.type.resolve, content = [];\n let start = open.from, end = close.to;\n // Emphasis marker effect depends on the character count. Size consumed is minimum of the two\n // markers.\n if (emp) {\n let size = Math.min(2, open.to - open.from, closeSize);\n start = open.to - size;\n end = close.from + size;\n type = size == 1 ? \"Emphasis\" : \"StrongEmphasis\";\n }\n // Move the covered region into content, optionally adding marker nodes\n if (open.type.mark)\n content.push(this.elt(open.type.mark, start, open.to));\n for (let k = j + 1; k < i; k++) {\n if (this.parts[k] instanceof Element)\n content.push(this.parts[k]);\n this.parts[k] = null;\n }\n if (close.type.mark)\n content.push(this.elt(close.type.mark, close.from, end));\n let element = this.elt(type, start, end, content);\n // If there are leftover emphasis marker characters, shrink the close/open markers. Otherwise, clear them.\n this.parts[j] = emp && open.from != start ? new InlineDelimiter(open.type, open.from, start, open.side) : null;\n let keep = this.parts[i] = emp && close.to != end ? new InlineDelimiter(close.type, end, close.to, close.side) : null;\n // Insert the new element in this.parts\n if (keep)\n this.parts.splice(i, 0, element);\n else\n this.parts[i] = element;\n }\n // Collect the elements remaining in this.parts into an array.\n let result = [];\n for (let i = from; i < this.parts.length; i++) {\n let part = this.parts[i];\n if (part instanceof Element)\n result.push(part);\n }\n return result;\n }\n /// Find an opening delimiter of the given type. Returns `null` if\n /// no delimiter is found, or an index that can be passed to\n /// [`takeContent`](#InlineContext.takeContent) otherwise.\n findOpeningDelimiter(type) {\n for (let i = this.parts.length - 1; i >= 0; i--) {\n let part = this.parts[i];\n if (part instanceof InlineDelimiter && part.type == type)\n return i;\n }\n return null;\n }\n /// Remove all inline elements and delimiters starting from the\n /// given index (which you should get from\n /// [`findOpeningDelimiter`](#InlineContext.findOpeningDelimiter),\n /// resolve delimiters inside of them, and return them as an array\n /// of elements.\n takeContent(startIndex) {\n let content = this.resolveMarkers(startIndex);\n this.parts.length = startIndex;\n return content;\n }\n /// Skip space after the given (document) position, returning either\n /// the position of the next non-space character or the end of the\n /// section.\n skipSpace(from) { return skipSpace(this.text, from - this.offset) + this.offset; }\n elt(type, from, to, children) {\n if (typeof type == \"string\")\n return elt(this.parser.getNodeType(type), from, to, children);\n return new TreeElement(type, from);\n }\n}\nfunction injectMarks(elements, marks) {\n if (!marks.length)\n return elements;\n if (!elements.length)\n return marks;\n let elts = elements.slice(), eI = 0;\n for (let mark of marks) {\n while (eI < elts.length && elts[eI].to < mark.to)\n eI++;\n if (eI < elts.length && elts[eI].from < mark.from) {\n let e = elts[eI];\n if (e instanceof Element)\n elts[eI] = new Element(e.type, e.from, e.to, injectMarks(e.children, [mark]));\n }\n else {\n elts.splice(eI++, 0, mark);\n }\n }\n return elts;\n}\n// These are blocks that can span blank lines, and should thus only be\n// reused if their next sibling is also being reused.\nconst NotLast = [Type.CodeBlock, Type.ListItem, Type.OrderedList, Type.BulletList];\nclass FragmentCursor {\n constructor(fragments, input) {\n this.fragments = fragments;\n this.input = input;\n // Index into fragment array\n this.i = 0;\n // Active fragment\n this.fragment = null;\n this.fragmentEnd = -1;\n // Cursor into the current fragment, if any. When `moveTo` returns\n // true, this points at the first block after `pos`.\n this.cursor = null;\n if (fragments.length)\n this.fragment = fragments[this.i++];\n }\n nextFragment() {\n this.fragment = this.i < this.fragments.length ? this.fragments[this.i++] : null;\n this.cursor = null;\n this.fragmentEnd = -1;\n }\n moveTo(pos, lineStart) {\n while (this.fragment && this.fragment.to <= pos)\n this.nextFragment();\n if (!this.fragment || this.fragment.from > (pos ? pos - 1 : 0))\n return false;\n if (this.fragmentEnd < 0) {\n let end = this.fragment.to;\n while (end > 0 && this.input.read(end - 1, end) != \"\\n\")\n end--;\n this.fragmentEnd = end ? end - 1 : 0;\n }\n let c = this.cursor;\n if (!c) {\n c = this.cursor = this.fragment.tree.cursor();\n c.firstChild();\n }\n let rPos = pos + this.fragment.offset;\n while (c.to <= rPos)\n if (!c.parent())\n return false;\n for (;;) {\n if (c.from >= rPos)\n return this.fragment.from <= lineStart;\n if (!c.childAfter(rPos))\n return false;\n }\n }\n matches(hash) {\n let tree = this.cursor.tree;\n return tree && tree.prop(NodeProp.contextHash) == hash;\n }\n takeNodes(cx) {\n let cur = this.cursor, off = this.fragment.offset, fragEnd = this.fragmentEnd - (this.fragment.openEnd ? 1 : 0);\n let start = cx.absoluteLineStart, end = start, blockI = cx.block.children.length;\n let prevEnd = end, prevI = blockI;\n for (;;) {\n if (cur.to - off > fragEnd) {\n if (cur.type.isAnonymous && cur.firstChild())\n continue;\n break;\n }\n let pos = toRelative(cur.from - off, cx.ranges);\n if (cur.to - off <= cx.ranges[cx.rangeI].to) { // Fits in current range\n cx.addNode(cur.tree, pos);\n }\n else {\n let dummy = new Tree(cx.parser.nodeSet.types[Type.Paragraph], [], [], 0, cx.block.hashProp);\n cx.reusePlaceholders.set(dummy, cur.tree);\n cx.addNode(dummy, pos);\n }\n // Taken content must always end in a block, because incremental\n // parsing happens on block boundaries. Never stop directly\n // after an indented code block, since those can continue after\n // any number of blank lines.\n if (cur.type.is(\"Block\")) {\n if (NotLast.indexOf(cur.type.id) < 0) {\n end = cur.to - off;\n blockI = cx.block.children.length;\n }\n else {\n end = prevEnd;\n blockI = prevI;\n prevEnd = cur.to - off;\n prevI = cx.block.children.length;\n }\n }\n if (!cur.nextSibling())\n break;\n }\n while (cx.block.children.length > blockI) {\n cx.block.children.pop();\n cx.block.positions.pop();\n }\n return end - start;\n }\n}\n// Convert an input-stream-relative position to a\n// Markdown-doc-relative position by subtracting the size of all input\n// gaps before `abs`.\nfunction toRelative(abs, ranges) {\n let pos = abs;\n for (let i = 1; i < ranges.length; i++) {\n let gapFrom = ranges[i - 1].to, gapTo = ranges[i].from;\n if (gapFrom < abs)\n pos -= gapTo - gapFrom;\n }\n return pos;\n}\nconst markdownHighlighting = styleTags({\n \"Blockquote/...\": tags.quote,\n HorizontalRule: tags.contentSeparator,\n \"ATXHeading1/... SetextHeading1/...\": tags.heading1,\n \"ATXHeading2/... SetextHeading2/...\": tags.heading2,\n \"ATXHeading3/...\": tags.heading3,\n \"ATXHeading4/...\": tags.heading4,\n \"ATXHeading5/...\": tags.heading5,\n \"ATXHeading6/...\": tags.heading6,\n \"Comment CommentBlock\": tags.comment,\n Escape: tags.escape,\n Entity: tags.character,\n \"Emphasis/...\": tags.emphasis,\n \"StrongEmphasis/...\": tags.strong,\n \"Link/... Image/...\": tags.link,\n \"OrderedList/... BulletList/...\": tags.list,\n \"BlockQuote/...\": tags.quote,\n \"InlineCode CodeText\": tags.monospace,\n URL: tags.url,\n \"HeaderMark HardBreak QuoteMark ListMark LinkMark EmphasisMark CodeMark\": tags.processingInstruction,\n \"CodeInfo LinkLabel\": tags.labelName,\n LinkTitle: tags.string,\n Paragraph: tags.content\n});\n/// The default CommonMark parser.\nconst parser = new MarkdownParser(new NodeSet(nodeTypes).extend(markdownHighlighting), Object.keys(DefaultBlockParsers).map(n => DefaultBlockParsers[n]), Object.keys(DefaultBlockParsers).map(n => DefaultLeafBlocks[n]), Object.keys(DefaultBlockParsers), DefaultEndLeaf, DefaultSkipMarkup, Object.keys(DefaultInline).map(n => DefaultInline[n]), Object.keys(DefaultInline), []);\n\nfunction leftOverSpace(node, from, to) {\n let ranges = [];\n for (let n = node.firstChild, pos = from;; n = n.nextSibling) {\n let nextPos = n ? n.from : to;\n if (nextPos > pos)\n ranges.push({ from: pos, to: nextPos });\n if (!n)\n break;\n pos = n.to;\n }\n return ranges;\n}\n/// Create a Markdown extension to enable nested parsing on code\n/// blocks and/or embedded HTML.\nfunction parseCode(config) {\n let { codeParser, htmlParser } = config;\n let wrap = parseMixed((node, input) => {\n let id = node.type.id;\n if (codeParser && (id == Type.CodeBlock || id == Type.FencedCode)) {\n let info = \"\";\n if (id == Type.FencedCode) {\n let infoNode = node.node.getChild(Type.CodeInfo);\n if (infoNode)\n info = input.read(infoNode.from, infoNode.to);\n }\n let parser = codeParser(info);\n if (parser)\n return { parser, overlay: node => node.type.id == Type.CodeText };\n }\n else if (htmlParser && (id == Type.HTMLBlock || id == Type.HTMLTag)) {\n return { parser: htmlParser, overlay: leftOverSpace(node.node, node.from, node.to) };\n }\n return null;\n });\n return { wrap };\n}\n\nconst StrikethroughDelim = { resolve: \"Strikethrough\", mark: \"StrikethroughMark\" };\n/// An extension that implements\n/// [GFM-style](https://github.github.com/gfm/#strikethrough-extension-)\n/// Strikethrough syntax using `~~` delimiters.\nconst Strikethrough = {\n defineNodes: [{\n name: \"Strikethrough\",\n style: { \"Strikethrough/...\": tags.strikethrough }\n }, {\n name: \"StrikethroughMark\",\n style: tags.processingInstruction\n }],\n parseInline: [{\n name: \"Strikethrough\",\n parse(cx, next, pos) {\n if (next != 126 /* '~' */ || cx.char(pos + 1) != 126 || cx.char(pos + 2) == 126)\n return -1;\n let before = cx.slice(pos - 1, pos), after = cx.slice(pos + 2, pos + 3);\n let sBefore = /\\s|^$/.test(before), sAfter = /\\s|^$/.test(after);\n let pBefore = Punctuation.test(before), pAfter = Punctuation.test(after);\n return cx.addDelimiter(StrikethroughDelim, pos, pos + 2, !sAfter && (!pAfter || sBefore || pBefore), !sBefore && (!pBefore || sAfter || pAfter));\n },\n after: \"Emphasis\"\n }]\n};\nfunction parseRow(cx, line, startI = 0, elts, offset = 0) {\n let count = 0, first = true, cellStart = -1, cellEnd = -1, esc = false;\n let parseCell = () => {\n elts.push(cx.elt(\"TableCell\", offset + cellStart, offset + cellEnd, cx.parser.parseInline(line.slice(cellStart, cellEnd), offset + cellStart)));\n };\n for (let i = startI; i < line.length; i++) {\n let next = line.charCodeAt(i);\n if (next == 124 /* '|' */ && !esc) {\n if (!first || cellStart > -1)\n count++;\n first = false;\n if (elts) {\n if (cellStart > -1)\n parseCell();\n elts.push(cx.elt(\"TableDelimiter\", i + offset, i + offset + 1));\n }\n cellStart = cellEnd = -1;\n }\n else if (esc || next != 32 && next != 9) {\n if (cellStart < 0)\n cellStart = i;\n cellEnd = i + 1;\n }\n esc = !esc && next == 92;\n }\n if (cellStart > -1) {\n count++;\n if (elts)\n parseCell();\n }\n return count;\n}\nfunction hasPipe(str, start) {\n for (let i = start; i < str.length; i++) {\n let next = str.charCodeAt(i);\n if (next == 124 /* '|' */)\n return true;\n if (next == 92 /* '\\\\' */)\n i++;\n }\n return false;\n}\nconst delimiterLine = /^\\|?(\\s*:?-+:?\\s*\\|)+(\\s*:?-+:?\\s*)?$/;\nclass TableParser {\n constructor() {\n // Null means we haven't seen the second line yet, false means this\n // isn't a table, and an array means this is a table and we've\n // parsed the given rows so far.\n this.rows = null;\n }\n nextLine(cx, line, leaf) {\n if (this.rows == null) { // Second line\n this.rows = false;\n let lineText;\n if ((line.next == 45 || line.next == 58 || line.next == 124 /* '-:|' */) &&\n delimiterLine.test(lineText = line.text.slice(line.pos))) {\n let firstRow = [], firstCount = parseRow(cx, leaf.content, 0, firstRow, leaf.start);\n if (firstCount == parseRow(cx, lineText, line.pos))\n this.rows = [cx.elt(\"TableHeader\", leaf.start, leaf.start + leaf.content.length, firstRow),\n cx.elt(\"TableDelimiter\", cx.lineStart + line.pos, cx.lineStart + line.text.length)];\n }\n }\n else if (this.rows) { // Line after the second\n let content = [];\n parseRow(cx, line.text, line.pos, content, cx.lineStart);\n this.rows.push(cx.elt(\"TableRow\", cx.lineStart + line.pos, cx.lineStart + line.text.length, content));\n }\n return false;\n }\n finish(cx, leaf) {\n if (!this.rows)\n return false;\n cx.addLeafElement(leaf, cx.elt(\"Table\", leaf.start, leaf.start + leaf.content.length, this.rows));\n return true;\n }\n}\n/// This extension provides\n/// [GFM-style](https://github.github.com/gfm/#tables-extension-)\n/// tables, using syntax like this:\n///\n/// ```\n/// | head 1 | head 2 |\n/// | --- | --- |\n/// | cell 1 | cell 2 |\n/// ```\nconst Table = {\n defineNodes: [\n { name: \"Table\", block: true },\n { name: \"TableHeader\", style: { \"TableHeader/...\": tags.heading } },\n \"TableRow\",\n { name: \"TableCell\", style: tags.content },\n { name: \"TableDelimiter\", style: tags.processingInstruction },\n ],\n parseBlock: [{\n name: \"Table\",\n leaf(_, leaf) { return hasPipe(leaf.content, 0) ? new TableParser : null; },\n endLeaf(cx, line, leaf) {\n if (leaf.parsers.some(p => p instanceof TableParser) || !hasPipe(line.text, line.basePos))\n return false;\n let next = cx.scanLine(cx.absoluteLineEnd + 1).text;\n return delimiterLine.test(next) && parseRow(cx, line.text, line.basePos) == parseRow(cx, next, line.basePos);\n },\n before: \"SetextHeading\"\n }]\n};\nclass TaskParser {\n nextLine() { return false; }\n finish(cx, leaf) {\n cx.addLeafElement(leaf, cx.elt(\"Task\", leaf.start, leaf.start + leaf.content.length, [\n cx.elt(\"TaskMarker\", leaf.start, leaf.start + 3),\n ...cx.parser.parseInline(leaf.content.slice(3), leaf.start + 3)\n ]));\n return true;\n }\n}\n/// Extension providing\n/// [GFM-style](https://github.github.com/gfm/#task-list-items-extension-)\n/// task list items, where list items can be prefixed with `[ ]` or\n/// `[x]` to add a checkbox.\nconst TaskList = {\n defineNodes: [\n { name: \"Task\", block: true, style: tags.list },\n { name: \"TaskMarker\", style: tags.atom }\n ],\n parseBlock: [{\n name: \"TaskList\",\n leaf(cx, leaf) {\n return /^\\[[ xX]\\][ \\t]/.test(leaf.content) && cx.parentType().name == \"ListItem\" ? new TaskParser : null;\n },\n after: \"SetextHeading\"\n }]\n};\nconst autolinkRE = /(www\\.)|(https?:\\/\\/)|([\\w.+-]+@)|(mailto:|xmpp:)/gy;\nconst urlRE = /[\\w-]+(\\.\\w+(\\.\\w+)?)(\\/[^\\s<]*)?/gy;\nconst emailRE = /[\\w.+-]+@[\\w-]+\\.[\\w.-]+/gy;\nconst xmppResourceRE = /\\/[a-zA-Z\\d@.]+/gy;\nfunction count(str, from, to, ch) {\n let result = 0;\n for (let i = from; i < to; i++)\n if (str[i] == ch)\n result++;\n return result;\n}\nfunction autolinkURLEnd(text, from) {\n urlRE.lastIndex = from;\n let m = urlRE.exec(text);\n if (!m)\n return -1;\n let end = from + m[0].length;\n for (;;) {\n let last = text[end - 1], m;\n if (/[?!.,:*_~]/.test(last) ||\n last == \")\" && count(text, from, end, \")\") > count(text, from, end, \"(\"))\n end--;\n else if (last == \";\" && (m = /&(?:#\\d+|#x[a-f\\d]+|\\w+);$/.exec(text.slice(from, end))))\n end = from + m.index;\n else\n break;\n }\n return end;\n}\nfunction autolinkEmailEnd(text, from) {\n emailRE.lastIndex = from;\n let m = emailRE.exec(text);\n if (!m)\n return -1;\n let last = m[0][m[0].length - 1];\n return last == \"_\" || last == \"-\" ? -1 : from + m[0].length - (last == \".\" ? 1 : 0);\n}\n/// Extension that implements autolinking for\n/// `www.`/`http://`/`https://`/`mailto:`/`xmpp:` URLs and email\n/// addresses.\nconst Autolink = {\n parseInline: [{\n name: \"Autolink\",\n parse(cx, next, absPos) {\n let pos = absPos - cx.offset;\n autolinkRE.lastIndex = pos;\n let m = autolinkRE.exec(cx.text), end = -1;\n if (!m)\n return -1;\n if (m[1] || m[2]) { // www., http://\n end = autolinkURLEnd(cx.text, pos + m[0].length);\n }\n else if (m[3]) { // email address\n end = autolinkEmailEnd(cx.text, pos);\n }\n else { // mailto:/xmpp:\n end = autolinkEmailEnd(cx.text, pos + m[0].length);\n if (end > -1 && m[0] == \"xmpp:\") {\n xmppResourceRE.lastIndex = end;\n m = xmppResourceRE.exec(cx.text);\n if (m)\n end = m.index + m[0].length;\n }\n }\n if (end < 0)\n return -1;\n cx.addElement(cx.elt(\"URL\", absPos, end + cx.offset));\n return end + cx.offset;\n }\n }]\n};\n/// Extension bundle containing [`Table`](#Table),\n/// [`TaskList`](#TaskList), [`Strikethrough`](#Strikethrough), and\n/// [`Autolink`](#Autolink).\nconst GFM = [Table, TaskList, Strikethrough, Autolink];\nfunction parseSubSuper(ch, node, mark) {\n return (cx, next, pos) => {\n if (next != ch || cx.char(pos + 1) == ch)\n return -1;\n let elts = [cx.elt(mark, pos, pos + 1)];\n for (let i = pos + 1; i < cx.end; i++) {\n let next = cx.char(i);\n if (next == ch)\n return cx.addElement(cx.elt(node, pos, i + 1, elts.concat(cx.elt(mark, i, i + 1))));\n if (next == 92 /* '\\\\' */)\n elts.push(cx.elt(\"Escape\", i, i++ + 2));\n if (space(next))\n break;\n }\n return -1;\n };\n}\n/// Extension providing\n/// [Pandoc-style](https://pandoc.org/MANUAL.html#superscripts-and-subscripts)\n/// superscript using `^` markers.\nconst Superscript = {\n defineNodes: [\n { name: \"Superscript\", style: tags.special(tags.content) },\n { name: \"SuperscriptMark\", style: tags.processingInstruction }\n ],\n parseInline: [{\n name: \"Superscript\",\n parse: parseSubSuper(94 /* '^' */, \"Superscript\", \"SuperscriptMark\")\n }]\n};\n/// Extension providing\n/// [Pandoc-style](https://pandoc.org/MANUAL.html#superscripts-and-subscripts)\n/// subscript using `~` markers.\nconst Subscript = {\n defineNodes: [\n { name: \"Subscript\", style: tags.special(tags.content) },\n { name: \"SubscriptMark\", style: tags.processingInstruction }\n ],\n parseInline: [{\n name: \"Subscript\",\n parse: parseSubSuper(126 /* '~' */, \"Subscript\", \"SubscriptMark\")\n }]\n};\n/// Extension that parses two colons with only letters, underscores,\n/// and numbers between them as `Emoji` nodes.\nconst Emoji = {\n defineNodes: [{ name: \"Emoji\", style: tags.character }],\n parseInline: [{\n name: \"Emoji\",\n parse(cx, next, pos) {\n let match;\n if (next != 58 /* ':' */ || !(match = /^[a-zA-Z_0-9]+:/.exec(cx.slice(pos + 1, cx.end))))\n return -1;\n return cx.addElement(cx.elt(\"Emoji\", pos, pos + 1 + match[0].length));\n }\n }]\n};\n\nexport { Autolink, BlockContext, Element, Emoji, GFM, InlineContext, LeafBlock, Line, MarkdownParser, Strikethrough, Subscript, Superscript, Table, TaskList, parseCode, parser };\n","import { EditorSelection, countColumn, Prec, EditorState } from '@codemirror/state';\nimport { keymap } from '@codemirror/view';\nimport { defineLanguageFacet, foldNodeProp, indentNodeProp, languageDataProp, foldService, syntaxTree, Language, LanguageDescription, ParseContext, indentUnit, LanguageSupport } from '@codemirror/language';\nimport { CompletionContext } from '@codemirror/autocomplete';\nimport { parser, GFM, Subscript, Superscript, Emoji, MarkdownParser, parseCode } from '@lezer/markdown';\nimport { html, htmlCompletionSource } from '@codemirror/lang-html';\nimport { NodeProp } from '@lezer/common';\n\nconst data = /*@__PURE__*/defineLanguageFacet({ commentTokens: { block: { open: \"\" } } });\nconst headingProp = /*@__PURE__*/new NodeProp();\nconst commonmark = /*@__PURE__*/parser.configure({\n props: [\n /*@__PURE__*/foldNodeProp.add(type => {\n return !type.is(\"Block\") || type.is(\"Document\") || isHeading(type) != null ? undefined\n : (tree, state) => ({ from: state.doc.lineAt(tree.from).to, to: tree.to });\n }),\n /*@__PURE__*/headingProp.add(isHeading),\n /*@__PURE__*/indentNodeProp.add({\n Document: () => null\n }),\n /*@__PURE__*/languageDataProp.add({\n Document: data\n })\n ]\n});\nfunction isHeading(type) {\n let match = /^(?:ATX|Setext)Heading(\\d)$/.exec(type.name);\n return match ? +match[1] : undefined;\n}\nfunction findSectionEnd(headerNode, level) {\n let last = headerNode;\n for (;;) {\n let next = last.nextSibling, heading;\n if (!next || (heading = isHeading(next.type)) != null && heading <= level)\n break;\n last = next;\n }\n return last.to;\n}\nconst headerIndent = /*@__PURE__*/foldService.of((state, start, end) => {\n for (let node = syntaxTree(state).resolveInner(end, -1); node; node = node.parent) {\n if (node.from < start)\n break;\n let heading = node.type.prop(headingProp);\n if (heading == null)\n continue;\n let upto = findSectionEnd(node, heading);\n if (upto > end)\n return { from: end, to: upto };\n }\n return null;\n});\nfunction mkLang(parser) {\n return new Language(data, parser, [headerIndent], \"markdown\");\n}\n/**\nLanguage support for strict CommonMark.\n*/\nconst commonmarkLanguage = /*@__PURE__*/mkLang(commonmark);\nconst extended = /*@__PURE__*/commonmark.configure([GFM, Subscript, Superscript, Emoji]);\n/**\nLanguage support for [GFM](https://github.github.com/gfm/) plus\nsubscript, superscript, and emoji syntax.\n*/\nconst markdownLanguage = /*@__PURE__*/mkLang(extended);\nfunction getCodeParser(languages, defaultLanguage) {\n return (info) => {\n if (info && languages) {\n let found = null;\n // Strip anything after whitespace\n info = /\\S*/.exec(info)[0];\n if (typeof languages == \"function\")\n found = languages(info);\n else\n found = LanguageDescription.matchLanguageName(languages, info, true);\n if (found instanceof LanguageDescription)\n return found.support ? found.support.language.parser : ParseContext.getSkippingParser(found.load());\n else if (found)\n return found.parser;\n }\n return defaultLanguage ? defaultLanguage.parser : null;\n };\n}\n\nclass Context {\n constructor(node, from, to, spaceBefore, spaceAfter, type, item) {\n this.node = node;\n this.from = from;\n this.to = to;\n this.spaceBefore = spaceBefore;\n this.spaceAfter = spaceAfter;\n this.type = type;\n this.item = item;\n }\n blank(maxWidth, trailing = true) {\n let result = this.spaceBefore + (this.node.name == \"Blockquote\" ? \">\" : \"\");\n if (maxWidth != null) {\n while (result.length < maxWidth)\n result += \" \";\n return result;\n }\n else {\n for (let i = this.to - this.from - result.length - this.spaceAfter.length; i > 0; i--)\n result += \" \";\n return result + (trailing ? this.spaceAfter : \"\");\n }\n }\n marker(doc, add) {\n let number = this.node.name == \"OrderedList\" ? String((+itemNumber(this.item, doc)[2] + add)) : \"\";\n return this.spaceBefore + number + this.type + this.spaceAfter;\n }\n}\nfunction getContext(node, doc) {\n let nodes = [];\n for (let cur = node; cur && cur.name != \"Document\"; cur = cur.parent) {\n if (cur.name == \"ListItem\" || cur.name == \"Blockquote\" || cur.name == \"FencedCode\")\n nodes.push(cur);\n }\n let context = [];\n for (let i = nodes.length - 1; i >= 0; i--) {\n let node = nodes[i], match;\n let line = doc.lineAt(node.from), startPos = node.from - line.from;\n if (node.name == \"FencedCode\") {\n context.push(new Context(node, startPos, startPos, \"\", \"\", \"\", null));\n }\n else if (node.name == \"Blockquote\" && (match = /^ *>( ?)/.exec(line.text.slice(startPos)))) {\n context.push(new Context(node, startPos, startPos + match[0].length, \"\", match[1], \">\", null));\n }\n else if (node.name == \"ListItem\" && node.parent.name == \"OrderedList\" &&\n (match = /^( *)\\d+([.)])( *)/.exec(line.text.slice(startPos)))) {\n let after = match[3], len = match[0].length;\n if (after.length >= 4) {\n after = after.slice(0, after.length - 4);\n len -= 4;\n }\n context.push(new Context(node.parent, startPos, startPos + len, match[1], after, match[2], node));\n }\n else if (node.name == \"ListItem\" && node.parent.name == \"BulletList\" &&\n (match = /^( *)([-+*])( {1,4}\\[[ xX]\\])?( +)/.exec(line.text.slice(startPos)))) {\n let after = match[4], len = match[0].length;\n if (after.length > 4) {\n after = after.slice(0, after.length - 4);\n len -= 4;\n }\n let type = match[2];\n if (match[3])\n type += match[3].replace(/[xX]/, ' ');\n context.push(new Context(node.parent, startPos, startPos + len, match[1], after, type, node));\n }\n }\n return context;\n}\nfunction itemNumber(item, doc) {\n return /^(\\s*)(\\d+)(?=[.)])/.exec(doc.sliceString(item.from, item.from + 10));\n}\nfunction renumberList(after, doc, changes, offset = 0) {\n for (let prev = -1, node = after;;) {\n if (node.name == \"ListItem\") {\n let m = itemNumber(node, doc);\n let number = +m[2];\n if (prev >= 0) {\n if (number != prev + 1)\n return;\n changes.push({ from: node.from + m[1].length, to: node.from + m[0].length, insert: String(prev + 2 + offset) });\n }\n prev = number;\n }\n let next = node.nextSibling;\n if (!next)\n break;\n node = next;\n }\n}\nfunction normalizeIndent(content, state) {\n let blank = /^[ \\t]*/.exec(content)[0].length;\n if (!blank || state.facet(indentUnit) != \"\\t\")\n return content;\n let col = countColumn(content, 4, blank);\n let space = \"\";\n for (let i = col; i > 0;) {\n if (i >= 4) {\n space += \"\\t\";\n i -= 4;\n }\n else {\n space += \" \";\n i--;\n }\n }\n return space + content.slice(blank);\n}\n/**\nThis command, when invoked in Markdown context with cursor\nselection(s), will create a new line with the markup for\nblockquotes and lists that were active on the old line. If the\ncursor was directly after the end of the markup for the old line,\ntrailing whitespace and list markers are removed from that line.\n\nThe command does nothing in non-Markdown context, so it should\nnot be used as the only binding for Enter (even in a Markdown\ndocument, HTML and code regions might use a different language).\n*/\nconst insertNewlineContinueMarkup = ({ state, dispatch }) => {\n let tree = syntaxTree(state), { doc } = state;\n let dont = null, changes = state.changeByRange(range => {\n if (!range.empty || !markdownLanguage.isActiveAt(state, range.from))\n return dont = { range };\n let pos = range.from, line = doc.lineAt(pos);\n let context = getContext(tree.resolveInner(pos, -1), doc);\n while (context.length && context[context.length - 1].from > pos - line.from)\n context.pop();\n if (!context.length)\n return dont = { range };\n let inner = context[context.length - 1];\n if (inner.to - inner.spaceAfter.length > pos - line.from)\n return dont = { range };\n let emptyLine = pos >= (inner.to - inner.spaceAfter.length) && !/\\S/.test(line.text.slice(inner.to));\n // Empty line in list\n if (inner.item && emptyLine) {\n // First list item or blank line before: delete a level of markup\n if (inner.node.firstChild.to >= pos ||\n line.from > 0 && !/[^\\s>]/.test(doc.lineAt(line.from - 1).text)) {\n let next = context.length > 1 ? context[context.length - 2] : null;\n let delTo, insert = \"\";\n if (next && next.item) { // Re-add marker for the list at the next level\n delTo = line.from + next.from;\n insert = next.marker(doc, 1);\n }\n else {\n delTo = line.from + (next ? next.to : 0);\n }\n let changes = [{ from: delTo, to: pos, insert }];\n if (inner.node.name == \"OrderedList\")\n renumberList(inner.item, doc, changes, -2);\n if (next && next.node.name == \"OrderedList\")\n renumberList(next.item, doc, changes);\n return { range: EditorSelection.cursor(delTo + insert.length), changes };\n }\n else { // Move this line down\n let insert = \"\";\n for (let i = 0, e = context.length - 2; i <= e; i++) {\n insert += context[i].blank(i < e ? countColumn(line.text, 4, context[i + 1].from) - insert.length : null, i < e);\n }\n insert = normalizeIndent(insert, state);\n return { range: EditorSelection.cursor(pos + insert.length + 1),\n changes: { from: line.from, insert: insert + state.lineBreak } };\n }\n }\n if (inner.node.name == \"Blockquote\" && emptyLine && line.from) {\n let prevLine = doc.lineAt(line.from - 1), quoted = />\\s*$/.exec(prevLine.text);\n // Two aligned empty quoted lines in a row\n if (quoted && quoted.index == inner.from) {\n let changes = state.changes([{ from: prevLine.from + quoted.index, to: prevLine.to },\n { from: line.from + inner.from, to: line.to }]);\n return { range: range.map(changes), changes };\n }\n }\n let changes = [];\n if (inner.node.name == \"OrderedList\")\n renumberList(inner.item, doc, changes);\n let continued = inner.item && inner.item.from < line.from;\n let insert = \"\";\n // If not dedented\n if (!continued || /^[\\s\\d.)\\-+*>]*/.exec(line.text)[0].length >= inner.to) {\n for (let i = 0, e = context.length - 1; i <= e; i++) {\n insert += i == e && !continued ? context[i].marker(doc, 1)\n : context[i].blank(i < e ? countColumn(line.text, 4, context[i + 1].from) - insert.length : null);\n }\n }\n let from = pos;\n while (from > line.from && /\\s/.test(line.text.charAt(from - line.from - 1)))\n from--;\n insert = normalizeIndent(insert, state);\n changes.push({ from, to: pos, insert: state.lineBreak + insert });\n return { range: EditorSelection.cursor(from + insert.length + 1), changes };\n });\n if (dont)\n return false;\n dispatch(state.update(changes, { scrollIntoView: true, userEvent: \"input\" }));\n return true;\n};\nfunction isMark(node) {\n return node.name == \"QuoteMark\" || node.name == \"ListMark\";\n}\nfunction contextNodeForDelete(tree, pos) {\n let node = tree.resolveInner(pos, -1), scan = pos;\n if (isMark(node)) {\n scan = node.from;\n node = node.parent;\n }\n for (let prev; prev = node.childBefore(scan);) {\n if (isMark(prev)) {\n scan = prev.from;\n }\n else if (prev.name == \"OrderedList\" || prev.name == \"BulletList\") {\n node = prev.lastChild;\n scan = node.to;\n }\n else {\n break;\n }\n }\n return node;\n}\n/**\nThis command will, when invoked in a Markdown context with the\ncursor directly after list or blockquote markup, delete one level\nof markup. When the markup is for a list, it will be replaced by\nspaces on the first invocation (a further invocation will delete\nthe spaces), to make it easy to continue a list.\n\nWhen not after Markdown block markup, this command will return\nfalse, so it is intended to be bound alongside other deletion\ncommands, with a higher precedence than the more generic commands.\n*/\nconst deleteMarkupBackward = ({ state, dispatch }) => {\n let tree = syntaxTree(state);\n let dont = null, changes = state.changeByRange(range => {\n let pos = range.from, { doc } = state;\n if (range.empty && markdownLanguage.isActiveAt(state, range.from)) {\n let line = doc.lineAt(pos);\n let context = getContext(contextNodeForDelete(tree, pos), doc);\n if (context.length) {\n let inner = context[context.length - 1];\n let spaceEnd = inner.to - inner.spaceAfter.length + (inner.spaceAfter ? 1 : 0);\n // Delete extra trailing space after markup\n if (pos - line.from > spaceEnd && !/\\S/.test(line.text.slice(spaceEnd, pos - line.from)))\n return { range: EditorSelection.cursor(line.from + spaceEnd),\n changes: { from: line.from + spaceEnd, to: pos } };\n if (pos - line.from == spaceEnd &&\n // Only apply this if we're on the line that has the\n // construct's syntax, or there's only indentation in the\n // target range\n (!inner.item || line.from <= inner.item.from || !/\\S/.test(line.text.slice(0, inner.to)))) {\n let start = line.from + inner.from;\n // Replace a list item marker with blank space\n if (inner.item && inner.node.from < inner.item.from && /\\S/.test(line.text.slice(inner.from, inner.to))) {\n let insert = inner.blank(countColumn(line.text, 4, inner.to) - countColumn(line.text, 4, inner.from));\n if (start == line.from)\n insert = normalizeIndent(insert, state);\n return { range: EditorSelection.cursor(start + insert.length),\n changes: { from: start, to: line.from + inner.to, insert } };\n }\n // Delete one level of indentation\n if (start < pos)\n return { range: EditorSelection.cursor(start), changes: { from: start, to: pos } };\n }\n }\n }\n return dont = { range };\n });\n if (dont)\n return false;\n dispatch(state.update(changes, { scrollIntoView: true, userEvent: \"delete\" }));\n return true;\n};\n\n/**\nA small keymap with Markdown-specific bindings. Binds Enter to\n[`insertNewlineContinueMarkup`](https://codemirror.net/6/docs/ref/#lang-markdown.insertNewlineContinueMarkup)\nand Backspace to\n[`deleteMarkupBackward`](https://codemirror.net/6/docs/ref/#lang-markdown.deleteMarkupBackward).\n*/\nconst markdownKeymap = [\n { key: \"Enter\", run: insertNewlineContinueMarkup },\n { key: \"Backspace\", run: deleteMarkupBackward }\n];\nconst htmlNoMatch = /*@__PURE__*/html({ matchClosingTags: false });\n/**\nMarkdown language support.\n*/\nfunction markdown(config = {}) {\n let { codeLanguages, defaultCodeLanguage, addKeymap = true, base: { parser } = commonmarkLanguage, completeHTMLTags = true } = config;\n if (!(parser instanceof MarkdownParser))\n throw new RangeError(\"Base parser provided to `markdown` should be a Markdown parser\");\n let extensions = config.extensions ? [config.extensions] : [];\n let support = [htmlNoMatch.support], defaultCode;\n if (defaultCodeLanguage instanceof LanguageSupport) {\n support.push(defaultCodeLanguage.support);\n defaultCode = defaultCodeLanguage.language;\n }\n else if (defaultCodeLanguage) {\n defaultCode = defaultCodeLanguage;\n }\n let codeParser = codeLanguages || defaultCode ? getCodeParser(codeLanguages, defaultCode) : undefined;\n extensions.push(parseCode({ codeParser, htmlParser: htmlNoMatch.language.parser }));\n if (addKeymap)\n support.push(Prec.high(keymap.of(markdownKeymap)));\n let lang = mkLang(parser.configure(extensions));\n if (completeHTMLTags)\n support.push(lang.data.of({ autocomplete: htmlTagCompletion }));\n return new LanguageSupport(lang, support);\n}\nfunction htmlTagCompletion(context) {\n let { state, pos } = context, m = /<[:\\-\\.\\w\\u00b7-\\uffff]*$/.exec(state.sliceDoc(pos - 25, pos));\n if (!m)\n return null;\n let tree = syntaxTree(state).resolveInner(pos, -1);\n while (tree && !tree.type.isTop) {\n if (tree.name == \"CodeBlock\" || tree.name == \"FencedCode\" || tree.name == \"ProcessingInstructionBlock\" ||\n tree.name == \"CommentBlock\" || tree.name == \"Link\" || tree.name == \"Image\")\n return null;\n tree = tree.parent;\n }\n return {\n from: pos - m[0].length, to: pos,\n options: htmlTagCompletions(),\n validFor: /^<[:\\-\\.\\w\\u00b7-\\uffff]*$/\n };\n}\nlet _tagCompletions = null;\nfunction htmlTagCompletions() {\n if (_tagCompletions)\n return _tagCompletions;\n let result = htmlCompletionSource(new CompletionContext(EditorState.create({ extensions: htmlNoMatch }), 0, true));\n return _tagCompletions = result ? result.options : [];\n}\n\nexport { commonmarkLanguage, deleteMarkupBackward, insertNewlineContinueMarkup, markdown, markdownKeymap, markdownLanguage };\n"],"names":["Type","CompositeBlock","static","type","value","from","parentHash","end","constructor","hash","children","positions","this","hashProp","addChild","child","pos","prop","length","push","toTree","nodeSet","last","Math","max","types","balance","makeTree","LeafBlock","start","content","marks","parsers","Line","text","baseIndent","basePos","depth","markers","indent","next","forward","forwardInner","newPos","skipSpace","countIndent","charCodeAt","reset","pop","moveBase","to","moveBaseColumn","findColumn","addMarker","elt","i","goal","scrub","result","slice","skipForList","bl","cx","line","block","stack","size","OrderedList","isOrderedList","isBulletList","BulletList","isHorizontalRule","DefaultSkipMarkup","Blockquote","QuoteMark","lineStart","space","ListItem","_cx","Document","ch","skipSpaceBack","isFencedCode","isBlockquote","breaking","count","isSetextUnderline","inList","isAtxHeading","EmptyLine","CommentEnd","ProcessingEnd","HTMLBlockStyle","isHTMLBlock","rest","e","test","getListIndent","indentAfter","indented","addCodeText","CodeText","DefaultBlockParsers","LinkReference","undefined","IndentedCode","base","pendingMarks","nextLine","m","codeStart","filter","concat","addNode","buffer","writeElements","finish","CodeBlock","FencedCode","fenceEnd","len","infoFrom","infoTo","CodeMark","CodeInfo","first","textStart","textEnd","prevLineEnd","startContext","HorizontalRule","newBase","ListMark","ATXHeading","off","endOfSpace","after","buf","write","HeaderMark","parser","parseInline","node","ATXHeading1","HTMLBlock","trailing","nodeType","CommentBlock","ProcessingInstructionBlock","SetextHeading","LinkReferenceParser","leaf","stage","elts","advance","complete","addLeafElement","nextStage","parseLinkLabel","LinkMark","skip","title","parseLinkTitle","titleEnd","lineEnd","parseURL","SetextHeadingParser","underline","underlineMark","SetextHeading1","SetextHeading2","DefaultLeafBlocks","_","DefaultEndLeaf","p","scanLineResult","BlockContext","input","fragments","ranges","atEnd","reusePlaceholders","Map","stoppedAt","rangeI","absoluteLineStart","absoluteLineEnd","create","FragmentCursor","readLine","parsedPos","finishContext","mark","reuseFragment","blockParsers","parse","leafBlockParsers","lines","stop","endLeafBlock","finishLeaf","stopAt","RangeError","moveTo","matches","taken","takeNodes","toRelative","moveRangeI","parentType","scanLine","r","lineChunkAt","textOffset","nextFrom","handler","skipContextMarkup","Error","chunk","lineChunks","eol","indexOf","startComposite","getNodeType","none","addElement","injectMarks","top","addGaps","tree","injectGaps","topNode","inline","Paragraph","TreeElement","Buffer","offset","dummies","rangeEnd","movePastNext","upto","inclusive","firstChild","nextSibling","reuse","get","propValues","MarkdownParser","blockNames","inlineParsers","inlineNames","wrappers","super","nodeTypes","Object","t","name","id","createParse","w","configure","spec","config","resolveConfig","nonEmpty","defineNodes","assign","styles","s","composite","style","some","group","props","Array","isArray","extend","remove","rm","parseBlock","found","before","findName","splice","endLeaf","wrap","InlineContext","outer","char","token","resolveMarkers","a","conf","conc","b","wrapA","wrapB","inner","names","Escape","nodes","writeTo","reused","topID","Element","startOff","EmphasisUnderscore","resolve","EmphasisAsterisk","LinkStart","ImageStart","InlineDelimiter","side","Escapable","Punctuation","RegExp","DefaultInline","escaped","append","Entity","exec","InlineCode","curSize","HTMLTag","url","URL","comment","Comment","procInst","ProcessingInstruction","Emphasis","pBefore","pAfter","sBefore","sAfter","leftFlanking","rightFlanking","canOpen","canClose","HardBreak","Link","Image","LinkEnd","parts","part","takeContent","link","finishLink","j","startPos","endPos","unshift","dest","label","LinkTitle","requireNonWS","min","LinkLabel","addDelimiter","open","close","emp","closeSize","k","element","findOpeningDelimiter","startIndex","elements","eI","NotLast","fragment","fragmentEnd","cursor","nextFragment","read","c","rPos","parent","childAfter","cur","fragEnd","openEnd","blockI","prevEnd","prevI","isAnonymous","dummy","set","is","abs","gapFrom","gapTo","markdownHighlighting","keys","map","n","leftOverSpace","nextPos","StrikethroughDelim","Strikethrough","parseRow","startI","cellStart","cellEnd","esc","parseCell","hasPipe","str","delimiterLine","TableParser","rows","lineText","firstRow","Table","TaskParser","TaskList","autolinkRE","urlRE","emailRE","xmppResourceRE","autolinkEmailEnd","lastIndex","GFM","absPos","index","autolinkURLEnd","parseSubSuper","Superscript","Subscript","Emoji","match","data","commentTokens","headingProp","commonmark","isHeading","state","doc","lineAt","add","findSectionEnd","headerNode","level","heading","headerIndent","resolveInner","mkLang","commonmarkLanguage","markdownLanguage","Context","spaceBefore","spaceAfter","item","blank","maxWidth","marker","number","String","itemNumber","getContext","context","replace","sliceString","renumberList","changes","prev","insert","normalizeIndent","facet","insertNewlineContinueMarkup","dispatch","dont","changeByRange","range","empty","isActiveAt","emptyLine","delTo","lineBreak","prevLine","quoted","continued","charAt","update","scrollIntoView","userEvent","isMark","deleteMarkupBackward","scan","childBefore","lastChild","contextNodeForDelete","spaceEnd","markdownKeymap","key","run","htmlNoMatch","html","matchClosingTags","markdown","codeLanguages","defaultCodeLanguage","addKeymap","completeHTMLTags","defaultCode","extensions","support","language","codeParser","languages","defaultLanguage","info","load","htmlParser","overlay","infoNode","getChild","parseCode","lang","of","autocomplete","htmlTagCompletion","sliceDoc","isTop","options","htmlTagCompletions","validFor","_tagCompletions","htmlCompletionSource"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/727.index.js b/book/_build/html/_static/727.index.js new file mode 100644 index 0000000..b2c0b36 --- /dev/null +++ b/book/_build/html/_static/727.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[727],{70727:(e,n,t)=>{t.r(n),t.d(n,{puppet:()=>c});var i={},a=/({)?([a-z][a-z0-9_]*)?((::[a-z][a-z0-9_]*)*::)?[a-zA-Z0-9_]+(})?/;function o(e,n){for(var t=n.split(" "),a=0;a.*/,!1),c=e.match(/(\s+)?[\w:_]+(\s+)?{/,!1),r=e.match(/(\s+)?[@]{1,2}[\w:_]+(\s+)?{/,!1),u=e.next();if("$"===u)return e.match(a)?n.continueString?"variableName.special":"variable":"error";if(n.continueString)return e.backUp(1),s(e,n);if(n.inDefinition){if(e.match(/(\s+)?[\w:_]+(\s+)?/))return"def";e.match(/\s+{/),n.inDefinition=!1}return n.inInclude?(e.match(/(\s+)?\S+(\s+)?/),n.inInclude=!1,"def"):e.match(/(\s+)?\w+\(/)?(e.backUp(1),"def"):o?(e.match(/(\s+)?\w+/),"tag"):t&&i.hasOwnProperty(t)?(e.backUp(1),e.match(/[\w]+/),e.match(/\s+\S+\s+{/,!1)&&(n.inDefinition=!0),"include"==t&&(n.inInclude=!0),i[t]):/(^|\s+)[A-Z][\w:_]+/.test(t)?(e.backUp(1),e.match(/(^|\s+)[A-Z][\w:_]+/),"def"):c?(e.match(/(\s+)?[\w:_]+/),"def"):r?(e.match(/(\s+)?[@]{1,2}/),"atom"):"#"==u?(e.skipToEnd(),"comment"):"'"==u||'"'==u?(n.pending=u,s(e,n)):"{"==u||"}"==u?"bracket":"/"==u?(e.match(/^[^\/]*\//),"string.special"):u.match(/[0-9]/)?(e.eatWhile(/[0-9]+/),"number"):"="==u?(">"==e.peek()&&e.next(),"operator"):(e.eatWhile(/[\w-]/),null)}(e,n)}}}}]); +//# sourceMappingURL=727.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/727.index.js.map b/book/_build/html/_static/727.index.js.map new file mode 100644 index 0000000..ed35716 --- /dev/null +++ b/book/_build/html/_static/727.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"727.index.js","mappings":"2HACA,IAAIA,EAAQ,CAAC,EAETC,EAAiB,mEAIrB,SAASC,EAAOC,EAAOC,GAErB,IADA,IAAIC,EAAQD,EAAOC,MAAM,KAChBC,EAAI,EAAGA,EAAID,EAAME,OAAQD,IAChCN,EAAMK,EAAMC,IAAMH,CAEtB,CAoBA,SAASK,EAAYC,EAAQC,GAE3B,IADA,IAAIC,EAASC,EAAMC,GAAY,GACvBJ,EAAOK,QAAUH,EAAUF,EAAOM,SAAWL,EAAMM,SAAS,CAClE,GAAgB,MAAZL,GAA2B,MAARC,GAAiC,KAAjBF,EAAMM,QAAgB,CAC3DH,GAAY,EACZ,KACF,CACAD,EAAOD,CACT,CASA,OARIE,GACFJ,EAAOQ,OAAO,GAEZN,GAAWD,EAAMM,QACnBN,EAAMQ,gBAAiB,EAEvBR,EAAMQ,gBAAiB,EAElB,QACT,CAnCAhB,EAAO,UAAW,kDAClBA,EAAO,UAAW,wCAClBA,EAAO,OAAQ,0DACfA,EAAO,UAAW,4rBAuKX,MAAMiB,EAAS,CACpBC,KAAM,SAENC,WAAY,WAMV,MALY,CACZX,cAAqB,EACrBA,WAAkB,EAClBA,gBAAuB,EACvBA,SAAgB,EAElB,EACAY,MAAO,SAAUb,EAAQC,GAEvB,OAAID,EAAOc,WAAmB,KAjJlC,SAAkBd,EAAQC,GAExB,IAAIc,EAAOf,EAAOgB,MAAM,SAAS,GAE7BC,EAAYjB,EAAOgB,MAAM,oBAAoB,GAG7CE,EAAWlB,EAAOgB,MAAM,wBAAwB,GAEhDG,EAAmBnB,EAAOgB,MAAM,gCAAgC,GAGhEI,EAAKpB,EAAOM,OAGhB,GAAW,MAAPc,EACF,OAAIpB,EAAOgB,MAAMxB,GAERS,EAAMQ,eAAiB,uBAAyB,WAGlD,QAGT,GAAIR,EAAMQ,eAGR,OADAT,EAAOQ,OAAO,GACPT,EAAYC,EAAQC,GAG7B,GAAIA,EAAMoB,aAAc,CAEtB,GAAIrB,EAAOgB,MAAM,uBACf,MAAO,MAGThB,EAAOgB,MAAM,QACbf,EAAMoB,cAAe,CACvB,CAEA,OAAIpB,EAAMqB,WAERtB,EAAOgB,MAAM,mBACbf,EAAMqB,WAAY,EACX,OAILtB,EAAOgB,MAAM,gBACfhB,EAAOQ,OAAO,GACP,OAGLS,GACFjB,EAAOgB,MAAM,aACN,OAGLD,GAAQxB,EAAMgC,eAAeR,IAE/Bf,EAAOQ,OAAO,GAEdR,EAAOgB,MAAM,SAGThB,EAAOgB,MAAM,cAAc,KAC7Bf,EAAMoB,cAAe,GAEX,WAARN,IACFd,EAAMqB,WAAY,GAGb/B,EAAMwB,IAGX,sBAAsBS,KAAKT,IAE7Bf,EAAOQ,OAAO,GAEdR,EAAOgB,MAAM,uBACN,OAGLE,GACFlB,EAAOgB,MAAM,iBACN,OAGLG,GACFnB,EAAOgB,MAAM,kBACN,QAGC,KAANI,GACFpB,EAAOyB,YACA,WAGC,KAANL,GAAmB,KAANA,GAEfnB,EAAMM,QAAUa,EAETrB,EAAYC,EAAQC,IAGnB,KAANmB,GAAmB,KAANA,EACR,UAIC,KAANA,GACFpB,EAAOgB,MAAM,aACN,kBAGLI,EAAGJ,MAAM,UACXhB,EAAO0B,SAAS,UACT,UAGC,KAANN,GACmB,KAAjBpB,EAAO2B,QACT3B,EAAOM,OAEF,aAGTN,EAAO0B,SAAS,SAET,KACT,CAiBWE,CAAS5B,EAAQC,EAC1B,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/puppet.js"],"sourcesContent":["// Stores the words from the define method\nvar words = {};\n// Taken, mostly, from the Puppet official variable standards regex\nvar variable_regex = /({)?([a-z][a-z0-9_]*)?((::[a-z][a-z0-9_]*)*::)?[a-zA-Z0-9_]+(})?/;\n\n// Takes a string of words separated by spaces and adds them as\n// keys with the value of the first argument 'style'\nfunction define(style, string) {\n var split = string.split(' ');\n for (var i = 0; i < split.length; i++) {\n words[split[i]] = style;\n }\n}\n\n// Takes commonly known puppet types/words and classifies them to a style\ndefine('keyword', 'class define site node include import inherits');\ndefine('keyword', 'case if else in and elsif default or');\ndefine('atom', 'false true running present absent file directory undef');\ndefine('builtin', 'action augeas burst chain computer cron destination dport exec ' +\n 'file filebucket group host icmp iniface interface jump k5login limit log_level ' +\n 'log_prefix macauthorization mailalias maillist mcx mount nagios_command ' +\n 'nagios_contact nagios_contactgroup nagios_host nagios_hostdependency ' +\n 'nagios_hostescalation nagios_hostextinfo nagios_hostgroup nagios_service ' +\n 'nagios_servicedependency nagios_serviceescalation nagios_serviceextinfo ' +\n 'nagios_servicegroup nagios_timeperiod name notify outiface package proto reject ' +\n 'resources router schedule scheduled_task selboolean selmodule service source ' +\n 'sport ssh_authorized_key sshkey stage state table tidy todest toports tosource ' +\n 'user vlan yumrepo zfs zone zpool');\n\n// After finding a start of a string ('|\") this function attempts to find the end;\n// If a variable is encountered along the way, we display it differently when it\n// is encapsulated in a double-quoted string.\nfunction tokenString(stream, state) {\n var current, prev, found_var = false;\n while (!stream.eol() && (current = stream.next()) != state.pending) {\n if (current === '$' && prev != '\\\\' && state.pending == '\"') {\n found_var = true;\n break;\n }\n prev = current;\n }\n if (found_var) {\n stream.backUp(1);\n }\n if (current == state.pending) {\n state.continueString = false;\n } else {\n state.continueString = true;\n }\n return \"string\";\n}\n\n// Main function\nfunction tokenize(stream, state) {\n // Matches one whole word\n var word = stream.match(/[\\w]+/, false);\n // Matches attributes (i.e. ensure => present ; 'ensure' would be matched)\n var attribute = stream.match(/(\\s+)?\\w+\\s+=>.*/, false);\n // Matches non-builtin resource declarations\n // (i.e. \"apache::vhost {\" or \"mycustomclasss {\" would be matched)\n var resource = stream.match(/(\\s+)?[\\w:_]+(\\s+)?{/, false);\n // Matches virtual and exported resources (i.e. @@user { ; and the like)\n var special_resource = stream.match(/(\\s+)?[@]{1,2}[\\w:_]+(\\s+)?{/, false);\n\n // Finally advance the stream\n var ch = stream.next();\n\n // Have we found a variable?\n if (ch === '$') {\n if (stream.match(variable_regex)) {\n // If so, and its in a string, assign it a different color\n return state.continueString ? 'variableName.special' : 'variable';\n }\n // Otherwise return an invalid variable\n return \"error\";\n }\n // Should we still be looking for the end of a string?\n if (state.continueString) {\n // If so, go through the loop again\n stream.backUp(1);\n return tokenString(stream, state);\n }\n // Are we in a definition (class, node, define)?\n if (state.inDefinition) {\n // If so, return def (i.e. for 'class myclass {' ; 'myclass' would be matched)\n if (stream.match(/(\\s+)?[\\w:_]+(\\s+)?/)) {\n return 'def';\n }\n // Match the rest it the next time around\n stream.match(/\\s+{/);\n state.inDefinition = false;\n }\n // Are we in an 'include' statement?\n if (state.inInclude) {\n // Match and return the included class\n stream.match(/(\\s+)?\\S+(\\s+)?/);\n state.inInclude = false;\n return 'def';\n }\n // Do we just have a function on our hands?\n // In 'ensure_resource(\"myclass\")', 'ensure_resource' is matched\n if (stream.match(/(\\s+)?\\w+\\(/)) {\n stream.backUp(1);\n return 'def';\n }\n // Have we matched the prior attribute regex?\n if (attribute) {\n stream.match(/(\\s+)?\\w+/);\n return 'tag';\n }\n // Do we have Puppet specific words?\n if (word && words.hasOwnProperty(word)) {\n // Negates the initial next()\n stream.backUp(1);\n // rs move the stream\n stream.match(/[\\w]+/);\n // We want to process these words differently\n // do to the importance they have in Puppet\n if (stream.match(/\\s+\\S+\\s+{/, false)) {\n state.inDefinition = true;\n }\n if (word == 'include') {\n state.inInclude = true;\n }\n // Returns their value as state in the prior define methods\n return words[word];\n }\n // Is there a match on a reference?\n if (/(^|\\s+)[A-Z][\\w:_]+/.test(word)) {\n // Negate the next()\n stream.backUp(1);\n // Match the full reference\n stream.match(/(^|\\s+)[A-Z][\\w:_]+/);\n return 'def';\n }\n // Have we matched the prior resource regex?\n if (resource) {\n stream.match(/(\\s+)?[\\w:_]+/);\n return 'def';\n }\n // Have we matched the prior special_resource regex?\n if (special_resource) {\n stream.match(/(\\s+)?[@]{1,2}/);\n return 'atom';\n }\n // Match all the comments. All of them.\n if (ch == \"#\") {\n stream.skipToEnd();\n return \"comment\";\n }\n // Have we found a string?\n if (ch == \"'\" || ch == '\"') {\n // Store the type (single or double)\n state.pending = ch;\n // Perform the looping function to find the end\n return tokenString(stream, state);\n }\n // Match all the brackets\n if (ch == '{' || ch == '}') {\n return 'bracket';\n }\n // Match characters that we are going to assume\n // are trying to be regex\n if (ch == '/') {\n stream.match(/^[^\\/]*\\//);\n return 'string.special';\n }\n // Match all the numbers\n if (ch.match(/[0-9]/)) {\n stream.eatWhile(/[0-9]+/);\n return 'number';\n }\n // Match the '=' and '=>' operators\n if (ch == '=') {\n if (stream.peek() == '>') {\n stream.next();\n }\n return \"operator\";\n }\n // Keep advancing through all the rest\n stream.eatWhile(/[\\w-]/);\n // Return a blank line for everything else\n return null;\n}\n// Start it all\nexport const puppet = {\n name: \"puppet\",\n\n startState: function () {\n var state = {};\n state.inDefinition = false;\n state.inInclude = false;\n state.continueString = false;\n state.pending = false;\n return state;\n },\n token: function (stream, state) {\n // Strip the spaces, but regex will account for them eitherway\n if (stream.eatSpace()) return null;\n // Go through the main process\n return tokenize(stream, state);\n }\n};\n"],"names":["words","variable_regex","define","style","string","split","i","length","tokenString","stream","state","current","prev","found_var","eol","next","pending","backUp","continueString","puppet","name","startState","token","eatSpace","word","match","attribute","resource","special_resource","ch","inDefinition","inInclude","hasOwnProperty","test","skipToEnd","eatWhile","peek","tokenize"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/7326.index.js b/book/_build/html/_static/7326.index.js new file mode 100644 index 0000000..92ae9c7 --- /dev/null +++ b/book/_build/html/_static/7326.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[7326],{67326:(e,t,n)=>{function r(e){for(var t={},n=e.split(" "),r=0;rz});var o=r("algorithm and annotation assert block break class connect connector constant constrainedby der discrete each else elseif elsewhen encapsulated end enumeration equation expandable extends external false final flow for function if import impure in initial inner input loop model not operator or outer output package parameter partial protected public pure record redeclare replaceable return stream then true type when while within"),i=r("abs acos actualStream asin atan atan2 cardinality ceil cos cosh delay div edge exp floor getInstanceName homotopy inStream integer log log10 mod pre reinit rem semiLinear sign sin sinh spatialDistribution sqrt tan tanh"),l=r("Real Boolean Integer String"),a=[].concat(Object.keys(o),Object.keys(i),Object.keys(l)),u=/[;=\(:\),{}.*<>+\-\/^\[\]]/,s=/(:=|<=|>=|==|<>|\.\+|\.\-|\.\*|\.\/|\.\^)/,c=/[0-9]/,k=/[_a-zA-Z]/;function p(e,t){return e.skipToEnd(),t.tokenize=null,"comment"}function f(e,t){for(var n,r=!1;n=e.next();){if(r&&"/"==n){t.tokenize=null;break}r="*"==n}return"comment"}function m(e,t){for(var n,r=!1;null!=(n=e.next());){if('"'==n&&!r){t.tokenize=null,t.sol=!1;break}r=!r&&"\\"==n}return"string"}function d(e,t){for(e.eatWhile(c);e.eat(c)||e.eat(k););var n=e.current();return!t.sol||"package"!=n&&"model"!=n&&"when"!=n&&"connector"!=n?t.sol&&"end"==n&&t.level>0&&t.level--:t.level++,t.tokenize=null,t.sol=!1,o.propertyIsEnumerable(n)?"keyword":i.propertyIsEnumerable(n)?"builtin":l.propertyIsEnumerable(n)?"atom":"variable"}function b(e,t){for(;e.eat(/[^']/););return t.tokenize=null,t.sol=!1,e.eat("'")?"variable":"error"}function h(e,t){return e.eatWhile(c),e.eat(".")&&e.eatWhile(c),(e.eat("e")||e.eat("E"))&&(e.eat("-")||e.eat("+"),e.eatWhile(c)),t.tokenize=null,t.sol=!1,"number"}const z={name:"modelica",startState:function(){return{tokenize:null,level:0,sol:!0}},token:function(e,t){if(null!=t.tokenize)return t.tokenize(e,t);if(e.sol()&&(t.sol=!0),e.eatSpace())return t.tokenize=null,null;var n=e.next();if("/"==n&&e.eat("/"))t.tokenize=p;else if("/"==n&&e.eat("*"))t.tokenize=f;else{if(s.test(n+e.peek()))return e.next(),t.tokenize=null,"operator";if(u.test(n))return t.tokenize=null,"operator";if(k.test(n))t.tokenize=d;else if("'"==n&&e.peek()&&"'"!=e.peek())t.tokenize=b;else if('"'==n)t.tokenize=m;else{if(!c.test(n))return t.tokenize=null,"error";t.tokenize=h}}return t.tokenize(e,t)},indent:function(e,t,n){if(null!=e.tokenize)return null;var r=e.level;return/(algorithm)/.test(t)&&r--,/(equation)/.test(t)&&r--,/(initial algorithm)/.test(t)&&r--,/(initial equation)/.test(t)&&r--,/(end)/.test(t)&&r--,r>0?n.unit*r:0},languageData:{commentTokens:{line:"//",block:{open:"/*",close:"*/"}},autocomplete:a}}}}]); +//# sourceMappingURL=7326.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/7326.index.js.map b/book/_build/html/_static/7326.index.js.map new file mode 100644 index 0000000..193b193 --- /dev/null +++ b/book/_build/html/_static/7326.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"7326.index.js","mappings":"+FAAA,SAASA,EAAMC,GAEb,IADA,IAAIC,EAAM,CAAC,EAAGF,EAAQC,EAAIE,MAAM,KACvBC,EAAE,EAAGA,EAAEJ,EAAMK,SAAUD,EAC9BF,EAAIF,EAAMI,KAAM,EAClB,OAAOF,CACT,C,+BAEA,IAAII,EAAWN,EAAM,ibACjBO,EAAUP,EAAM,8NAChBQ,EAAQR,EAAM,+BAEdS,EAAc,GAAGC,OAAOC,OAAOC,KAAKN,GAAWK,OAAOC,KAAKL,GAAUI,OAAOC,KAAKJ,IAEjFK,EAAuB,6BACvBC,EAAuB,4CACvBC,EAAU,QACVC,EAAa,YAEjB,SAASC,EAAiBC,EAAQC,GAGhC,OAFAD,EAAOE,YACPD,EAAME,SAAW,KACV,SACT,CAEA,SAASC,EAAkB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MAAO,CAACC,KAAM,KAAMC,MAAO,OACvDC,aAAc9C,G","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/modelica.js"],"sourcesContent":["function words(str) {\n var obj = {}, words = str.split(\" \");\n for (var i=0; i+\\-\\/^\\[\\]]/;\nvar isDoubleOperatorChar = /(:=|<=|>=|==|<>|\\.\\+|\\.\\-|\\.\\*|\\.\\/|\\.\\^)/;\nvar isDigit = /[0-9]/;\nvar isNonDigit = /[_a-zA-Z]/;\n\nfunction tokenLineComment(stream, state) {\n stream.skipToEnd();\n state.tokenize = null;\n return \"comment\";\n}\n\nfunction tokenBlockComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if (maybeEnd && ch == \"/\") {\n state.tokenize = null;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return \"comment\";\n}\n\nfunction tokenString(stream, state) {\n var escaped = false, ch;\n while ((ch = stream.next()) != null) {\n if (ch == '\"' && !escaped) {\n state.tokenize = null;\n state.sol = false;\n break;\n }\n escaped = !escaped && ch == \"\\\\\";\n }\n\n return \"string\";\n}\n\nfunction tokenIdent(stream, state) {\n stream.eatWhile(isDigit);\n while (stream.eat(isDigit) || stream.eat(isNonDigit)) { }\n\n\n var cur = stream.current();\n\n if(state.sol && (cur == \"package\" || cur == \"model\" || cur == \"when\" || cur == \"connector\")) state.level++;\n else if(state.sol && cur == \"end\" && state.level > 0) state.level--;\n\n state.tokenize = null;\n state.sol = false;\n\n if (keywords.propertyIsEnumerable(cur)) return \"keyword\";\n else if (builtin.propertyIsEnumerable(cur)) return \"builtin\";\n else if (atoms.propertyIsEnumerable(cur)) return \"atom\";\n else return \"variable\";\n}\n\nfunction tokenQIdent(stream, state) {\n while (stream.eat(/[^']/)) { }\n\n state.tokenize = null;\n state.sol = false;\n\n if(stream.eat(\"'\"))\n return \"variable\";\n else\n return \"error\";\n}\n\nfunction tokenUnsignedNumber(stream, state) {\n stream.eatWhile(isDigit);\n if (stream.eat('.')) {\n stream.eatWhile(isDigit);\n }\n if (stream.eat('e') || stream.eat('E')) {\n if (!stream.eat('-'))\n stream.eat('+');\n stream.eatWhile(isDigit);\n }\n\n state.tokenize = null;\n state.sol = false;\n return \"number\";\n}\n\n// Interface\nexport const modelica = {\n name: \"modelica\",\n startState: function() {\n return {\n tokenize: null,\n level: 0,\n sol: true\n };\n },\n\n token: function(stream, state) {\n if(state.tokenize != null) {\n return state.tokenize(stream, state);\n }\n\n if(stream.sol()) {\n state.sol = true;\n }\n\n // WHITESPACE\n if(stream.eatSpace()) {\n state.tokenize = null;\n return null;\n }\n\n var ch = stream.next();\n\n // LINECOMMENT\n if(ch == '/' && stream.eat('/')) {\n state.tokenize = tokenLineComment;\n }\n // BLOCKCOMMENT\n else if(ch == '/' && stream.eat('*')) {\n state.tokenize = tokenBlockComment;\n }\n // TWO SYMBOL TOKENS\n else if(isDoubleOperatorChar.test(ch+stream.peek())) {\n stream.next();\n state.tokenize = null;\n return \"operator\";\n }\n // SINGLE SYMBOL TOKENS\n else if(isSingleOperatorChar.test(ch)) {\n state.tokenize = null;\n return \"operator\";\n }\n // IDENT\n else if(isNonDigit.test(ch)) {\n state.tokenize = tokenIdent;\n }\n // Q-IDENT\n else if(ch == \"'\" && stream.peek() && stream.peek() != \"'\") {\n state.tokenize = tokenQIdent;\n }\n // STRING\n else if(ch == '\"') {\n state.tokenize = tokenString;\n }\n // UNSIGNED_NUMBER\n else if(isDigit.test(ch)) {\n state.tokenize = tokenUnsignedNumber;\n }\n // ERROR\n else {\n state.tokenize = null;\n return \"error\";\n }\n\n return state.tokenize(stream, state);\n },\n\n indent: function(state, textAfter, cx) {\n if (state.tokenize != null) return null;\n\n var level = state.level;\n if(/(algorithm)/.test(textAfter)) level--;\n if(/(equation)/.test(textAfter)) level--;\n if(/(initial algorithm)/.test(textAfter)) level--;\n if(/(initial equation)/.test(textAfter)) level--;\n if(/(end)/.test(textAfter)) level--;\n\n if(level > 0)\n return cx.unit*level;\n else\n return 0;\n },\n\n languageData: {\n commentTokens: {line: \"//\", block: {open: \"/*\", close: \"*/\"}},\n autocomplete: completions\n }\n};\n"],"names":["words","str","obj","split","i","length","keywords","builtin","atoms","completions","concat","Object","keys","isSingleOperatorChar","isDoubleOperatorChar","isDigit","isNonDigit","tokenLineComment","stream","state","skipToEnd","tokenize","tokenBlockComment","ch","maybeEnd","next","tokenString","escaped","sol","tokenIdent","eatWhile","eat","cur","current","level","propertyIsEnumerable","tokenQIdent","tokenUnsignedNumber","modelica","name","startState","token","eatSpace","test","peek","indent","textAfter","cx","unit","languageData","commentTokens","line","block","open","close","autocomplete"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/7343.index.js b/book/_build/html/_static/7343.index.js new file mode 100644 index 0000000..ff570ba --- /dev/null +++ b/book/_build/html/_static/7343.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[7343],{47343:(e,t,r)=>{function i(e){return new RegExp("^(("+e.join(")|(")+"))\\b","i")}r.r(t),r.d(t,{idl:()=>d});var a=["a_correlate","abs","acos","adapt_hist_equal","alog","alog2","alog10","amoeba","annotate","app_user_dir","app_user_dir_query","arg_present","array_equal","array_indices","arrow","ascii_template","asin","assoc","atan","axis","axis","bandpass_filter","bandreject_filter","barplot","bar_plot","beseli","beselj","beselk","besely","beta","biginteger","bilinear","bin_date","binary_template","bindgen","binomial","bit_ffs","bit_population","blas_axpy","blk_con","boolarr","boolean","boxplot","box_cursor","breakpoint","broyden","bubbleplot","butterworth","bytarr","byte","byteorder","bytscl","c_correlate","calendar","caldat","call_external","call_function","call_method","call_procedure","canny","catch","cd","cdf","ceil","chebyshev","check_math","chisqr_cvf","chisqr_pdf","choldc","cholsol","cindgen","cir_3pnt","clipboard","close","clust_wts","cluster","cluster_tree","cmyk_convert","code_coverage","color_convert","color_exchange","color_quan","color_range_map","colorbar","colorize_sample","colormap_applicable","colormap_gradient","colormap_rotation","colortable","comfit","command_line_args","common","compile_opt","complex","complexarr","complexround","compute_mesh_normals","cond","congrid","conj","constrained_min","contour","contour","convert_coord","convol","convol_fft","coord2to3","copy_lun","correlate","cos","cosh","cpu","cramer","createboxplotdata","create_cursor","create_struct","create_view","crossp","crvlength","ct_luminance","cti_test","cursor","curvefit","cv_coord","cvttobm","cw_animate","cw_animate_getp","cw_animate_load","cw_animate_run","cw_arcball","cw_bgroup","cw_clr_index","cw_colorsel","cw_defroi","cw_field","cw_filesel","cw_form","cw_fslider","cw_light_editor","cw_light_editor_get","cw_light_editor_set","cw_orient","cw_palette_editor","cw_palette_editor_get","cw_palette_editor_set","cw_pdmenu","cw_rgbslider","cw_tmpl","cw_zoom","db_exists","dblarr","dcindgen","dcomplex","dcomplexarr","define_key","define_msgblk","define_msgblk_from_file","defroi","defsysv","delvar","dendro_plot","dendrogram","deriv","derivsig","determ","device","dfpmin","diag_matrix","dialog_dbconnect","dialog_message","dialog_pickfile","dialog_printersetup","dialog_printjob","dialog_read_image","dialog_write_image","dictionary","digital_filter","dilate","dindgen","dissolve","dist","distance_measure","dlm_load","dlm_register","doc_library","double","draw_roi","edge_dog","efont","eigenql","eigenvec","ellipse","elmhes","emboss","empty","enable_sysrtn","eof","eos","erase","erf","erfc","erfcx","erode","errorplot","errplot","estimator_filter","execute","exit","exp","expand","expand_path","expint","extract","extract_slice","f_cvf","f_pdf","factorial","fft","file_basename","file_chmod","file_copy","file_delete","file_dirname","file_expand_path","file_gunzip","file_gzip","file_info","file_lines","file_link","file_mkdir","file_move","file_poll_input","file_readlink","file_same","file_search","file_tar","file_test","file_untar","file_unzip","file_which","file_zip","filepath","findgen","finite","fix","flick","float","floor","flow3","fltarr","flush","format_axis_values","forward_function","free_lun","fstat","fulstr","funct","function","fv_test","fx_root","fz_roots","gamma","gamma_ct","gauss_cvf","gauss_pdf","gauss_smooth","gauss2dfit","gaussfit","gaussian_function","gaussint","get_drive_list","get_dxf_objects","get_kbrd","get_login_info","get_lun","get_screen_size","getenv","getwindows","greg2jul","grib","grid_input","grid_tps","grid3","griddata","gs_iter","h_eq_ct","h_eq_int","hanning","hash","hdf","hdf5","heap_free","heap_gc","heap_nosave","heap_refcount","heap_save","help","hilbert","hist_2d","hist_equal","histogram","hls","hough","hqr","hsv","i18n_multibytetoutf8","i18n_multibytetowidechar","i18n_utf8tomultibyte","i18n_widechartomultibyte","ibeta","icontour","iconvertcoord","idelete","identity","idl_base64","idl_container","idl_validname","idlexbr_assistant","idlitsys_createtool","idlunit","iellipse","igamma","igetcurrent","igetdata","igetid","igetproperty","iimage","image","image_cont","image_statistics","image_threshold","imaginary","imap","indgen","int_2d","int_3d","int_tabulated","intarr","interpol","interpolate","interval_volume","invert","ioctl","iopen","ir_filter","iplot","ipolygon","ipolyline","iputdata","iregister","ireset","iresolve","irotate","isa","isave","iscale","isetcurrent","isetproperty","ishft","isocontour","isosurface","isurface","itext","itranslate","ivector","ivolume","izoom","journal","json_parse","json_serialize","jul2greg","julday","keyword_set","krig2d","kurtosis","kw_test","l64indgen","la_choldc","la_cholmprove","la_cholsol","la_determ","la_eigenproblem","la_eigenql","la_eigenvec","la_elmhes","la_gm_linear_model","la_hqr","la_invert","la_least_square_equality","la_least_squares","la_linear_equation","la_ludc","la_lumprove","la_lusol","la_svd","la_tridc","la_trimprove","la_triql","la_trired","la_trisol","label_date","label_region","ladfit","laguerre","lambda","lambdap","lambertw","laplacian","least_squares_filter","leefilt","legend","legendre","linbcg","lindgen","linfit","linkimage","list","ll_arc_distance","lmfit","lmgr","lngamma","lnp_test","loadct","locale_get","logical_and","logical_or","logical_true","lon64arr","lonarr","long","long64","lsode","lu_complex","ludc","lumprove","lusol","m_correlate","machar","make_array","make_dll","make_rt","map","mapcontinents","mapgrid","map_2points","map_continents","map_grid","map_image","map_patch","map_proj_forward","map_proj_image","map_proj_info","map_proj_init","map_proj_inverse","map_set","matrix_multiply","matrix_power","max","md_test","mean","meanabsdev","mean_filter","median","memory","mesh_clip","mesh_decimate","mesh_issolid","mesh_merge","mesh_numtriangles","mesh_obj","mesh_smooth","mesh_surfacearea","mesh_validate","mesh_volume","message","min","min_curve_surf","mk_html_help","modifyct","moment","morph_close","morph_distance","morph_gradient","morph_hitormiss","morph_open","morph_thin","morph_tophat","multi","n_elements","n_params","n_tags","ncdf","newton","noise_hurl","noise_pick","noise_scatter","noise_slur","norm","obj_class","obj_destroy","obj_hasmethod","obj_isa","obj_new","obj_valid","objarr","on_error","on_ioerror","online_help","openr","openu","openw","oplot","oploterr","orderedhash","p_correlate","parse_url","particle_trace","path_cache","path_sep","pcomp","plot","plot3d","plot","plot_3dbox","plot_field","ploterr","plots","polar_contour","polar_surface","polyfill","polyshade","pnt_line","point_lun","polarplot","poly","poly_2d","poly_area","poly_fit","polyfillv","polygon","polyline","polywarp","popd","powell","pref_commit","pref_get","pref_set","prewitt","primes","print","printf","printd","pro","product","profile","profiler","profiles","project_vol","ps_show_fonts","psafm","pseudo","ptr_free","ptr_new","ptr_valid","ptrarr","pushd","qgrid3","qhull","qromb","qromo","qsimp","query_*","query_ascii","query_bmp","query_csv","query_dicom","query_gif","query_image","query_jpeg","query_jpeg2000","query_mrsid","query_pict","query_png","query_ppm","query_srf","query_tiff","query_video","query_wav","r_correlate","r_test","radon","randomn","randomu","ranks","rdpix","read","readf","read_ascii","read_binary","read_bmp","read_csv","read_dicom","read_gif","read_image","read_interfile","read_jpeg","read_jpeg2000","read_mrsid","read_pict","read_png","read_ppm","read_spr","read_srf","read_sylk","read_tiff","read_video","read_wav","read_wave","read_x11_bitmap","read_xwd","reads","readu","real_part","rebin","recall_commands","recon3","reduce_colors","reform","region_grow","register_cursor","regress","replicate","replicate_inplace","resolve_all","resolve_routine","restore","retall","return","reverse","rk4","roberts","rot","rotate","round","routine_filepath","routine_info","rs_test","s_test","save","savgol","scale3","scale3d","scatterplot","scatterplot3d","scope_level","scope_traceback","scope_varfetch","scope_varname","search2d","search3d","sem_create","sem_delete","sem_lock","sem_release","set_plot","set_shading","setenv","sfit","shade_surf","shade_surf_irr","shade_volume","shift","shift_diff","shmdebug","shmmap","shmunmap","shmvar","show3","showfont","signum","simplex","sin","sindgen","sinh","size","skewness","skip_lun","slicer3","slide_image","smooth","sobel","socket","sort","spawn","sph_4pnt","sph_scat","spher_harm","spl_init","spl_interp","spline","spline_p","sprsab","sprsax","sprsin","sprstp","sqrt","standardize","stddev","stop","strarr","strcmp","strcompress","streamline","streamline","stregex","stretch","string","strjoin","strlen","strlowcase","strmatch","strmessage","strmid","strpos","strput","strsplit","strtrim","struct_assign","struct_hide","strupcase","surface","surface","surfr","svdc","svdfit","svsol","swap_endian","swap_endian_inplace","symbol","systime","t_cvf","t_pdf","t3d","tag_names","tan","tanh","tek_color","temporary","terminal_size","tetra_clip","tetra_surface","tetra_volume","text","thin","thread","threed","tic","time_test2","timegen","timer","timestamp","timestamptovalues","tm_test","toc","total","trace","transpose","tri_surf","triangulate","trigrid","triql","trired","trisol","truncate_lun","ts_coef","ts_diff","ts_fcast","ts_smooth","tv","tvcrs","tvlct","tvrd","tvscl","typename","uindgen","uint","uintarr","ul64indgen","ulindgen","ulon64arr","ulonarr","ulong","ulong64","uniq","unsharp_mask","usersym","value_locate","variance","vector","vector_field","vel","velovect","vert_t3d","voigt","volume","voronoi","voxel_proj","wait","warp_tri","watershed","wdelete","wf_draw","where","widget_base","widget_button","widget_combobox","widget_control","widget_displaycontextmenu","widget_draw","widget_droplist","widget_event","widget_info","widget_label","widget_list","widget_propertysheet","widget_slider","widget_tab","widget_table","widget_text","widget_tree","widget_tree_move","widget_window","wiener_filter","window","window","write_bmp","write_csv","write_gif","write_image","write_jpeg","write_jpeg2000","write_nrif","write_pict","write_png","write_ppm","write_spr","write_srf","write_sylk","write_tiff","write_video","write_wav","write_wave","writeu","wset","wshow","wtn","wv_applet","wv_cwt","wv_cw_wavelet","wv_denoise","wv_dwt","wv_fn_coiflet","wv_fn_daubechies","wv_fn_gaussian","wv_fn_haar","wv_fn_morlet","wv_fn_paul","wv_fn_symlet","wv_import_data","wv_import_wavelet","wv_plot3d_wps","wv_plot_multires","wv_pwt","wv_tool_denoise","xbm_edit","xdisplayfile","xdxf","xfont","xinteranimate","xloadct","xmanager","xmng_tmpl","xmtool","xobjview","xobjview_rotate","xobjview_write_image","xpalette","xpcolor","xplot3d","xregistered","xroi","xsq_test","xsurface","xvaredit","xvolume","xvolume_rotate","xvolume_write_image","xyouts","zlib_compress","zlib_uncompress","zoom","zoom_24"],_=i(a),o=["begin","end","endcase","endfor","endwhile","endif","endrep","endforeach","break","case","continue","for","foreach","goto","if","then","else","repeat","until","switch","while","do","pro","function"],l=i(o),s=new RegExp("^[_a-z¡-￿][_a-z0-9¡-￿]*","i"),n=/[+\-*&=<>\/@#~$]/,c=new RegExp("(and|or|eq|lt|le|gt|ge|ne|not)","i");const d={name:"idl",token:function(e){return function(e){if(e.eatSpace())return null;if(e.match(";"))return e.skipToEnd(),"comment";if(e.match(/^[0-9\.+-]/,!1)){if(e.match(/^[+-]?0x[0-9a-fA-F]+/))return"number";if(e.match(/^[+-]?\d*\.\d+([EeDd][+-]?\d+)?/))return"number";if(e.match(/^[+-]?\d+([EeDd][+-]?\d+)?/))return"number"}return e.match(/^"([^"]|(""))*"/)||e.match(/^'([^']|(''))*'/)?"string":e.match(l)?"keyword":e.match(_)?"builtin":e.match(s)?"variable":e.match(n)||e.match(c)?"operator":(e.next(),null)}(e)},languageData:{autocomplete:a.concat(o)}}}}]); +//# sourceMappingURL=7343.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/7343.index.js.map b/book/_build/html/_static/7343.index.js.map new file mode 100644 index 0000000..b0fddac --- /dev/null +++ b/book/_build/html/_static/7343.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"7343.index.js","mappings":"+FAAA,SAASA,EAAWC,GAClB,OAAO,IAAIC,OAAO,MAAQD,EAAME,KAAK,OAAS,QAAS,IACzD,C,0BAEA,IAAIC,EAAe,CACjB,cAAe,MAAO,OAAQ,mBAAoB,OAClD,QAAS,SAAU,SAAU,WAAY,eACzC,qBAAsB,c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O,SAASC,GACd,OAxCJ,SAAmBA,GAEjB,GAAIA,EAAOC,WAAY,OAAO,KAG9B,GAAID,EAAOE,MAAM,KAEf,OADAF,EAAOG,YACA,UAIT,GAAIH,EAAOE,MAAM,cAAc,GAAQ,CACrC,GAAIF,EAAOE,MAAM,wBACf,MAAO,SACT,GAAIF,EAAOE,MAAM,mCACf,MAAO,SACT,GAAIF,EAAOE,MAAM,8BACf,MAAO,QACX,CAGA,OAAIF,EAAOE,MAAM,oBACbF,EAAOE,MAAM,mBAD6B,SAI1CF,EAAOE,MAAMT,GAAoB,UACjCO,EAAOE,MAAMX,GAAoB,UACjCS,EAAOE,MAAMR,GAAuB,WAEpCM,EAAOE,MAAMP,IAAoBK,EAAOE,MAAMN,GACzC,YAGTI,EAAOI,OACA,KACT,CAKWC,CAAUL,EACnB,EACAM,aAAc,CACZC,aAAcjB,EAAakB,OAAOhB,I","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/idl.js"],"sourcesContent":["function wordRegexp(words) {\n return new RegExp('^((' + words.join(')|(') + '))\\\\b', 'i');\n};\n\nvar builtinArray = [\n 'a_correlate', 'abs', 'acos', 'adapt_hist_equal', 'alog',\n 'alog2', 'alog10', 'amoeba', 'annotate', 'app_user_dir',\n 'app_user_dir_query', 'arg_present', 'array_equal', 'array_indices',\n 'arrow', 'ascii_template', 'asin', 'assoc', 'atan',\n 'axis', 'axis', 'bandpass_filter', 'bandreject_filter', 'barplot',\n 'bar_plot', 'beseli', 'beselj', 'beselk', 'besely',\n 'beta', 'biginteger', 'bilinear', 'bin_date', 'binary_template',\n 'bindgen', 'binomial', 'bit_ffs', 'bit_population', 'blas_axpy',\n 'blk_con', 'boolarr', 'boolean', 'boxplot', 'box_cursor',\n 'breakpoint', 'broyden', 'bubbleplot', 'butterworth', 'bytarr',\n 'byte', 'byteorder', 'bytscl', 'c_correlate', 'calendar',\n 'caldat', 'call_external', 'call_function', 'call_method',\n 'call_procedure', 'canny', 'catch', 'cd', 'cdf', 'ceil',\n 'chebyshev', 'check_math', 'chisqr_cvf', 'chisqr_pdf', 'choldc',\n 'cholsol', 'cindgen', 'cir_3pnt', 'clipboard', 'close',\n 'clust_wts', 'cluster', 'cluster_tree', 'cmyk_convert', 'code_coverage',\n 'color_convert', 'color_exchange', 'color_quan', 'color_range_map',\n 'colorbar', 'colorize_sample', 'colormap_applicable',\n 'colormap_gradient', 'colormap_rotation', 'colortable',\n 'comfit', 'command_line_args', 'common', 'compile_opt', 'complex',\n 'complexarr', 'complexround', 'compute_mesh_normals', 'cond', 'congrid',\n 'conj', 'constrained_min', 'contour', 'contour', 'convert_coord',\n 'convol', 'convol_fft', 'coord2to3', 'copy_lun', 'correlate',\n 'cos', 'cosh', 'cpu', 'cramer', 'createboxplotdata',\n 'create_cursor', 'create_struct', 'create_view', 'crossp', 'crvlength',\n 'ct_luminance', 'cti_test', 'cursor', 'curvefit', 'cv_coord',\n 'cvttobm', 'cw_animate', 'cw_animate_getp', 'cw_animate_load',\n 'cw_animate_run', 'cw_arcball', 'cw_bgroup', 'cw_clr_index',\n 'cw_colorsel', 'cw_defroi', 'cw_field', 'cw_filesel', 'cw_form',\n 'cw_fslider', 'cw_light_editor', 'cw_light_editor_get',\n 'cw_light_editor_set', 'cw_orient', 'cw_palette_editor',\n 'cw_palette_editor_get', 'cw_palette_editor_set', 'cw_pdmenu',\n 'cw_rgbslider', 'cw_tmpl', 'cw_zoom', 'db_exists',\n 'dblarr', 'dcindgen', 'dcomplex', 'dcomplexarr', 'define_key',\n 'define_msgblk', 'define_msgblk_from_file', 'defroi', 'defsysv',\n 'delvar', 'dendro_plot', 'dendrogram', 'deriv', 'derivsig',\n 'determ', 'device', 'dfpmin', 'diag_matrix', 'dialog_dbconnect',\n 'dialog_message', 'dialog_pickfile', 'dialog_printersetup',\n 'dialog_printjob', 'dialog_read_image',\n 'dialog_write_image', 'dictionary', 'digital_filter', 'dilate', 'dindgen',\n 'dissolve', 'dist', 'distance_measure', 'dlm_load', 'dlm_register',\n 'doc_library', 'double', 'draw_roi', 'edge_dog', 'efont',\n 'eigenql', 'eigenvec', 'ellipse', 'elmhes', 'emboss',\n 'empty', 'enable_sysrtn', 'eof', 'eos', 'erase',\n 'erf', 'erfc', 'erfcx', 'erode', 'errorplot',\n 'errplot', 'estimator_filter', 'execute', 'exit', 'exp',\n 'expand', 'expand_path', 'expint', 'extract', 'extract_slice',\n 'f_cvf', 'f_pdf', 'factorial', 'fft', 'file_basename',\n 'file_chmod', 'file_copy', 'file_delete', 'file_dirname',\n 'file_expand_path', 'file_gunzip', 'file_gzip', 'file_info',\n 'file_lines', 'file_link', 'file_mkdir', 'file_move',\n 'file_poll_input', 'file_readlink', 'file_same',\n 'file_search', 'file_tar', 'file_test', 'file_untar', 'file_unzip',\n 'file_which', 'file_zip', 'filepath', 'findgen', 'finite',\n 'fix', 'flick', 'float', 'floor', 'flow3',\n 'fltarr', 'flush', 'format_axis_values', 'forward_function', 'free_lun',\n 'fstat', 'fulstr', 'funct', 'function', 'fv_test',\n 'fx_root', 'fz_roots', 'gamma', 'gamma_ct', 'gauss_cvf',\n 'gauss_pdf', 'gauss_smooth', 'gauss2dfit', 'gaussfit',\n 'gaussian_function', 'gaussint', 'get_drive_list', 'get_dxf_objects',\n 'get_kbrd', 'get_login_info',\n 'get_lun', 'get_screen_size', 'getenv', 'getwindows', 'greg2jul',\n 'grib', 'grid_input', 'grid_tps', 'grid3', 'griddata',\n 'gs_iter', 'h_eq_ct', 'h_eq_int', 'hanning', 'hash',\n 'hdf', 'hdf5', 'heap_free', 'heap_gc', 'heap_nosave',\n 'heap_refcount', 'heap_save', 'help', 'hilbert', 'hist_2d',\n 'hist_equal', 'histogram', 'hls', 'hough', 'hqr',\n 'hsv', 'i18n_multibytetoutf8',\n 'i18n_multibytetowidechar', 'i18n_utf8tomultibyte',\n 'i18n_widechartomultibyte',\n 'ibeta', 'icontour', 'iconvertcoord', 'idelete', 'identity',\n 'idl_base64', 'idl_container', 'idl_validname',\n 'idlexbr_assistant', 'idlitsys_createtool',\n 'idlunit', 'iellipse', 'igamma', 'igetcurrent', 'igetdata',\n 'igetid', 'igetproperty', 'iimage', 'image', 'image_cont',\n 'image_statistics', 'image_threshold', 'imaginary', 'imap', 'indgen',\n 'int_2d', 'int_3d', 'int_tabulated', 'intarr', 'interpol',\n 'interpolate', 'interval_volume', 'invert', 'ioctl', 'iopen',\n 'ir_filter', 'iplot', 'ipolygon', 'ipolyline', 'iputdata',\n 'iregister', 'ireset', 'iresolve', 'irotate', 'isa',\n 'isave', 'iscale', 'isetcurrent', 'isetproperty', 'ishft',\n 'isocontour', 'isosurface', 'isurface', 'itext', 'itranslate',\n 'ivector', 'ivolume', 'izoom', 'journal', 'json_parse',\n 'json_serialize', 'jul2greg', 'julday', 'keyword_set', 'krig2d',\n 'kurtosis', 'kw_test', 'l64indgen', 'la_choldc', 'la_cholmprove',\n 'la_cholsol', 'la_determ', 'la_eigenproblem', 'la_eigenql', 'la_eigenvec',\n 'la_elmhes', 'la_gm_linear_model', 'la_hqr', 'la_invert',\n 'la_least_square_equality', 'la_least_squares', 'la_linear_equation',\n 'la_ludc', 'la_lumprove', 'la_lusol',\n 'la_svd', 'la_tridc', 'la_trimprove', 'la_triql', 'la_trired',\n 'la_trisol', 'label_date', 'label_region', 'ladfit', 'laguerre',\n 'lambda', 'lambdap', 'lambertw', 'laplacian', 'least_squares_filter',\n 'leefilt', 'legend', 'legendre', 'linbcg', 'lindgen',\n 'linfit', 'linkimage', 'list', 'll_arc_distance', 'lmfit',\n 'lmgr', 'lngamma', 'lnp_test', 'loadct', 'locale_get',\n 'logical_and', 'logical_or', 'logical_true', 'lon64arr', 'lonarr',\n 'long', 'long64', 'lsode', 'lu_complex', 'ludc',\n 'lumprove', 'lusol', 'm_correlate', 'machar', 'make_array',\n 'make_dll', 'make_rt', 'map', 'mapcontinents', 'mapgrid',\n 'map_2points', 'map_continents', 'map_grid', 'map_image', 'map_patch',\n 'map_proj_forward', 'map_proj_image', 'map_proj_info',\n 'map_proj_init', 'map_proj_inverse',\n 'map_set', 'matrix_multiply', 'matrix_power', 'max', 'md_test',\n 'mean', 'meanabsdev', 'mean_filter', 'median', 'memory',\n 'mesh_clip', 'mesh_decimate', 'mesh_issolid',\n 'mesh_merge', 'mesh_numtriangles',\n 'mesh_obj', 'mesh_smooth', 'mesh_surfacearea',\n 'mesh_validate', 'mesh_volume',\n 'message', 'min', 'min_curve_surf', 'mk_html_help', 'modifyct',\n 'moment', 'morph_close', 'morph_distance',\n 'morph_gradient', 'morph_hitormiss',\n 'morph_open', 'morph_thin', 'morph_tophat', 'multi', 'n_elements',\n 'n_params', 'n_tags', 'ncdf', 'newton', 'noise_hurl',\n 'noise_pick', 'noise_scatter', 'noise_slur', 'norm', 'obj_class',\n 'obj_destroy', 'obj_hasmethod', 'obj_isa', 'obj_new', 'obj_valid',\n 'objarr', 'on_error', 'on_ioerror', 'online_help', 'openr',\n 'openu', 'openw', 'oplot', 'oploterr', 'orderedhash',\n 'p_correlate', 'parse_url', 'particle_trace', 'path_cache', 'path_sep',\n 'pcomp', 'plot', 'plot3d', 'plot', 'plot_3dbox',\n 'plot_field', 'ploterr', 'plots', 'polar_contour', 'polar_surface',\n 'polyfill', 'polyshade', 'pnt_line', 'point_lun', 'polarplot',\n 'poly', 'poly_2d', 'poly_area', 'poly_fit', 'polyfillv',\n 'polygon', 'polyline', 'polywarp', 'popd', 'powell',\n 'pref_commit', 'pref_get', 'pref_set', 'prewitt', 'primes',\n 'print', 'printf', 'printd', 'pro', 'product',\n 'profile', 'profiler', 'profiles', 'project_vol', 'ps_show_fonts',\n 'psafm', 'pseudo', 'ptr_free', 'ptr_new', 'ptr_valid',\n 'ptrarr', 'pushd', 'qgrid3', 'qhull', 'qromb',\n 'qromo', 'qsimp', 'query_*', 'query_ascii', 'query_bmp',\n 'query_csv', 'query_dicom', 'query_gif', 'query_image', 'query_jpeg',\n 'query_jpeg2000', 'query_mrsid', 'query_pict', 'query_png', 'query_ppm',\n 'query_srf', 'query_tiff', 'query_video', 'query_wav', 'r_correlate',\n 'r_test', 'radon', 'randomn', 'randomu', 'ranks',\n 'rdpix', 'read', 'readf', 'read_ascii', 'read_binary',\n 'read_bmp', 'read_csv', 'read_dicom', 'read_gif', 'read_image',\n 'read_interfile', 'read_jpeg', 'read_jpeg2000', 'read_mrsid', 'read_pict',\n 'read_png', 'read_ppm', 'read_spr', 'read_srf', 'read_sylk',\n 'read_tiff', 'read_video', 'read_wav', 'read_wave', 'read_x11_bitmap',\n 'read_xwd', 'reads', 'readu', 'real_part', 'rebin',\n 'recall_commands', 'recon3', 'reduce_colors', 'reform', 'region_grow',\n 'register_cursor', 'regress', 'replicate',\n 'replicate_inplace', 'resolve_all',\n 'resolve_routine', 'restore', 'retall', 'return', 'reverse',\n 'rk4', 'roberts', 'rot', 'rotate', 'round',\n 'routine_filepath', 'routine_info', 'rs_test', 's_test', 'save',\n 'savgol', 'scale3', 'scale3d', 'scatterplot', 'scatterplot3d',\n 'scope_level', 'scope_traceback', 'scope_varfetch',\n 'scope_varname', 'search2d',\n 'search3d', 'sem_create', 'sem_delete', 'sem_lock', 'sem_release',\n 'set_plot', 'set_shading', 'setenv', 'sfit', 'shade_surf',\n 'shade_surf_irr', 'shade_volume', 'shift', 'shift_diff', 'shmdebug',\n 'shmmap', 'shmunmap', 'shmvar', 'show3', 'showfont',\n 'signum', 'simplex', 'sin', 'sindgen', 'sinh',\n 'size', 'skewness', 'skip_lun', 'slicer3', 'slide_image',\n 'smooth', 'sobel', 'socket', 'sort', 'spawn',\n 'sph_4pnt', 'sph_scat', 'spher_harm', 'spl_init', 'spl_interp',\n 'spline', 'spline_p', 'sprsab', 'sprsax', 'sprsin',\n 'sprstp', 'sqrt', 'standardize', 'stddev', 'stop',\n 'strarr', 'strcmp', 'strcompress', 'streamline', 'streamline',\n 'stregex', 'stretch', 'string', 'strjoin', 'strlen',\n 'strlowcase', 'strmatch', 'strmessage', 'strmid', 'strpos',\n 'strput', 'strsplit', 'strtrim', 'struct_assign', 'struct_hide',\n 'strupcase', 'surface', 'surface', 'surfr', 'svdc',\n 'svdfit', 'svsol', 'swap_endian', 'swap_endian_inplace', 'symbol',\n 'systime', 't_cvf', 't_pdf', 't3d', 'tag_names',\n 'tan', 'tanh', 'tek_color', 'temporary', 'terminal_size',\n 'tetra_clip', 'tetra_surface', 'tetra_volume', 'text', 'thin',\n 'thread', 'threed', 'tic', 'time_test2', 'timegen',\n 'timer', 'timestamp', 'timestamptovalues', 'tm_test', 'toc',\n 'total', 'trace', 'transpose', 'tri_surf', 'triangulate',\n 'trigrid', 'triql', 'trired', 'trisol', 'truncate_lun',\n 'ts_coef', 'ts_diff', 'ts_fcast', 'ts_smooth', 'tv',\n 'tvcrs', 'tvlct', 'tvrd', 'tvscl', 'typename',\n 'uindgen', 'uint', 'uintarr', 'ul64indgen', 'ulindgen',\n 'ulon64arr', 'ulonarr', 'ulong', 'ulong64', 'uniq',\n 'unsharp_mask', 'usersym', 'value_locate', 'variance', 'vector',\n 'vector_field', 'vel', 'velovect', 'vert_t3d', 'voigt',\n 'volume', 'voronoi', 'voxel_proj', 'wait', 'warp_tri',\n 'watershed', 'wdelete', 'wf_draw', 'where', 'widget_base',\n 'widget_button', 'widget_combobox', 'widget_control',\n 'widget_displaycontextmenu', 'widget_draw',\n 'widget_droplist', 'widget_event', 'widget_info',\n 'widget_label', 'widget_list',\n 'widget_propertysheet', 'widget_slider', 'widget_tab',\n 'widget_table', 'widget_text',\n 'widget_tree', 'widget_tree_move', 'widget_window',\n 'wiener_filter', 'window',\n 'window', 'write_bmp', 'write_csv', 'write_gif', 'write_image',\n 'write_jpeg', 'write_jpeg2000', 'write_nrif', 'write_pict', 'write_png',\n 'write_ppm', 'write_spr', 'write_srf', 'write_sylk', 'write_tiff',\n 'write_video', 'write_wav', 'write_wave', 'writeu', 'wset',\n 'wshow', 'wtn', 'wv_applet', 'wv_cwt', 'wv_cw_wavelet',\n 'wv_denoise', 'wv_dwt', 'wv_fn_coiflet',\n 'wv_fn_daubechies', 'wv_fn_gaussian',\n 'wv_fn_haar', 'wv_fn_morlet', 'wv_fn_paul',\n 'wv_fn_symlet', 'wv_import_data',\n 'wv_import_wavelet', 'wv_plot3d_wps', 'wv_plot_multires',\n 'wv_pwt', 'wv_tool_denoise',\n 'xbm_edit', 'xdisplayfile', 'xdxf', 'xfont', 'xinteranimate',\n 'xloadct', 'xmanager', 'xmng_tmpl', 'xmtool', 'xobjview',\n 'xobjview_rotate', 'xobjview_write_image',\n 'xpalette', 'xpcolor', 'xplot3d',\n 'xregistered', 'xroi', 'xsq_test', 'xsurface', 'xvaredit',\n 'xvolume', 'xvolume_rotate', 'xvolume_write_image',\n 'xyouts', 'zlib_compress', 'zlib_uncompress', 'zoom', 'zoom_24'\n];\nvar builtins = wordRegexp(builtinArray);\n\nvar keywordArray = [\n 'begin', 'end', 'endcase', 'endfor',\n 'endwhile', 'endif', 'endrep', 'endforeach',\n 'break', 'case', 'continue', 'for',\n 'foreach', 'goto', 'if', 'then', 'else',\n 'repeat', 'until', 'switch', 'while',\n 'do', 'pro', 'function'\n];\nvar keywords = wordRegexp(keywordArray);\n\nvar identifiers = new RegExp('^[_a-z\\xa1-\\uffff][_a-z0-9\\xa1-\\uffff]*', 'i');\n\nvar singleOperators = /[+\\-*&=<>\\/@#~$]/;\nvar boolOperators = new RegExp('(and|or|eq|lt|le|gt|ge|ne|not)', 'i');\n\nfunction tokenBase(stream) {\n // whitespaces\n if (stream.eatSpace()) return null;\n\n // Handle one line Comments\n if (stream.match(';')) {\n stream.skipToEnd();\n return 'comment';\n }\n\n // Handle Number Literals\n if (stream.match(/^[0-9\\.+-]/, false)) {\n if (stream.match(/^[+-]?0x[0-9a-fA-F]+/))\n return 'number';\n if (stream.match(/^[+-]?\\d*\\.\\d+([EeDd][+-]?\\d+)?/))\n return 'number';\n if (stream.match(/^[+-]?\\d+([EeDd][+-]?\\d+)?/))\n return 'number';\n }\n\n // Handle Strings\n if (stream.match(/^\"([^\"]|(\"\"))*\"/)) { return 'string'; }\n if (stream.match(/^'([^']|(''))*'/)) { return 'string'; }\n\n // Handle words\n if (stream.match(keywords)) { return 'keyword'; }\n if (stream.match(builtins)) { return 'builtin'; }\n if (stream.match(identifiers)) { return 'variable'; }\n\n if (stream.match(singleOperators) || stream.match(boolOperators)) {\n return 'operator'; }\n\n // Handle non-detected items\n stream.next();\n return null;\n};\n\nexport const idl = {\n name: \"idl\",\n token: function(stream) {\n return tokenBase(stream);\n },\n languageData: {\n autocomplete: builtinArray.concat(keywordArray)\n }\n}\n"],"names":["wordRegexp","words","RegExp","join","builtinArray","builtins","keywordArray","keywords","identifiers","singleOperators","boolOperators","idl","name","token","stream","eatSpace","match","skipToEnd","next","tokenBase","languageData","autocomplete","concat"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/7358.index.js b/book/_build/html/_static/7358.index.js new file mode 100644 index 0000000..7f07d22 --- /dev/null +++ b/book/_build/html/_static/7358.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[7358],{27358:(E,t,e)=>{function R(E){var t=[];return E.split(" ").forEach((function(E){t.push({name:E})})),t}e.r(t),e.d(t,{forth:()=>T});var i=R("INVERT AND OR XOR 2* 2/ LSHIFT RSHIFT 0= = 0< < > U< MIN MAX 2DROP 2DUP 2OVER 2SWAP ?DUP DEPTH DROP DUP OVER ROT SWAP >R R> R@ + - 1+ 1- ABS NEGATE S>D * M* UM* FM/MOD SM/REM UM/MOD */ */MOD / /MOD MOD HERE , @ ! CELL+ CELLS C, C@ C! CHARS 2@ 2! ALIGN ALIGNED +! ALLOT CHAR [CHAR] [ ] BL FIND EXECUTE IMMEDIATE COUNT LITERAL STATE ; DOES> >BODY EVALUATE SOURCE >IN <# # #S #> HOLD SIGN BASE >NUMBER HEX DECIMAL FILL MOVE . CR EMIT SPACE SPACES TYPE U. .R U.R ACCEPT TRUE FALSE <> U> 0<> 0> NIP TUCK ROLL PICK 2>R 2R@ 2R> WITHIN UNUSED MARKER I J TO COMPILE, [COMPILE] SAVE-INPUT RESTORE-INPUT PAD ERASE 2LITERAL DNEGATE D- D+ D0< D0= D2* D2/ D< D= DMAX DMIN D>S DABS M+ M*/ D. D.R 2ROT DU< CATCH THROW FREE RESIZE ALLOCATE CS-PICK CS-ROLL GET-CURRENT SET-CURRENT FORTH-WORDLIST GET-ORDER SET-ORDER PREVIOUS SEARCH-WORDLIST WORDLIST FIND ALSO ONLY FORTH DEFINITIONS ORDER -TRAILING /STRING SEARCH COMPARE CMOVE CMOVE> BLANK SLITERAL"),O=R("IF ELSE THEN BEGIN WHILE REPEAT UNTIL RECURSE [IF] [ELSE] [THEN] ?DO DO LOOP +LOOP UNLOOP LEAVE EXIT AGAIN CASE OF ENDOF ENDCASE");function r(E,t){var e;for(e=E.length-1;e>=0;e--)if(E[e].name===t.toUpperCase())return E[e]}const T={name:"forth",startState:function(){return{state:"",base:10,coreWordList:i,immediateWordList:O,wordList:[]}},token:function(E,t){var e;if(E.eatSpace())return null;if(""===t.state){if(E.match(/^(\]|:NONAME)(\s|$)/i))return t.state=" compilation","builtin";if(e=E.match(/^(\:)\s+(\S+)(\s|$)+/))return t.wordList.push({name:e[2].toUpperCase()}),t.state=" compilation","def";if(e=E.match(/^(VARIABLE|2VARIABLE|CONSTANT|2CONSTANT|CREATE|POSTPONE|VALUE|WORD)\s+(\S+)(\s|$)+/i))return t.wordList.push({name:e[2].toUpperCase()}),"def";if(e=E.match(/^(\'|\[\'\])\s+(\S+)(\s|$)+/))return"builtin"}else{if(E.match(/^(\;|\[)(\s)/))return t.state="",E.backUp(1),"builtin";if(E.match(/^(\;|\[)($)/))return t.state="","builtin";if(E.match(/^(POSTPONE)\s+\S+(\s|$)+/))return"builtin"}return(e=E.match(/^(\S+)(\s+|$)/))?void 0!==r(t.wordList,e[1])?"variable":"\\"===e[1]?(E.skipToEnd(),"comment"):void 0!==r(t.coreWordList,e[1])?"builtin":void 0!==r(t.immediateWordList,e[1])?"keyword":"("===e[1]?(E.eatWhile((function(E){return")"!==E})),E.eat(")"),"comment"):".("===e[1]?(E.eatWhile((function(E){return")"!==E})),E.eat(")"),"string"):'S"'===e[1]||'."'===e[1]||'C"'===e[1]?(E.eatWhile((function(E){return'"'!==E})),E.eat('"'),"string"):e[1]-68719476735?"number":"atom":void 0}}}}]); +//# sourceMappingURL=7358.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/7358.index.js.map b/book/_build/html/_static/7358.index.js.map new file mode 100644 index 0000000..969ca20 --- /dev/null +++ b/book/_build/html/_static/7358.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"7358.index.js","mappings":"+FAAA,SAASA,EAAWC,GAClB,IAAIC,EAAM,GAIV,OAHAD,EAAME,MAAM,KAAKC,SAAQ,SAASC,GAChCH,EAAII,KAAK,CAACC,KAAMF,GAClB,IACOH,CACT,C,4BAEA,IAAIM,EAAeR,EACjB,u6BAuCES,EAAoBT,EAAW,oIAEnC,SAASU,EAAgBC,EAAUC,GACjC,IAAIC,EACJ,IAAKA,EAAIF,EAASG,OAAS,EAAGD,GAAK,EAAGA,IACpC,GAAIF,EAASE,GAAGN,OAASK,EAAKG,cAC5B,OAAOJ,EAASE,EAItB,CACO,MAAMG,EAAQ,CACnBT,KAAM,QACNU,WAAY,WACV,MAAO,CACLC,MAAO,GACPC,KAAM,GACNX,aAAcA,EACdC,kBAAmBA,EACnBE,SAAU,GAEd,EACAS,MAAO,SAAUC,EAAQC,GACvB,IAAIC,EACJ,GAAIF,EAAOG,WACT,OAAO,KAET,GAAkB,KAAdF,EAAIJ,MAAc,CACpB,GAAIG,EAAOI,MAAM,wBAEf,OADAH,EAAIJ,MAAQ,eACL,UAGT,GADAK,EAAMF,EAAOI,MAAM,wBAIjB,OAFAH,EAAIX,SAASL,KAAK,CAACC,KAAMgB,EAAI,GAAGR,gBAChCO,EAAIJ,MAAQ,eACL,MAGT,GADAK,EAAMF,EAAOI,MAAM,uFAGjB,OADAH,EAAIX,SAASL,KAAK,CAACC,KAAMgB,EAAI,GAAGR,gBACzB,MAGT,GADAQ,EAAMF,EAAOI,MAAM,+BAEjB,MAAO,SAEX,KAAO,CAEL,GAAIJ,EAAOI,MAAM,gBAGf,OAFAH,EAAIJ,MAAQ,GACZG,EAAOK,OAAO,GACP,UAET,GAAIL,EAAOI,MAAM,eAEf,OADAH,EAAIJ,MAAQ,GACL,UAET,GAAIG,EAAOI,MAAM,4BACf,MAAO,SAEX,CAIA,OADAF,EAAMF,EAAOI,MAAM,uBAE4BE,IAAzCjB,EAAeY,EAAIX,SAAUY,EAAI,IAC5B,WAIM,OAAXA,EAAI,IACNF,EAAOO,YACA,gBAIwCD,IAA7CjB,EAAeY,EAAId,aAAce,EAAI,IAChC,eAE6CI,IAAlDjB,EAAeY,EAAIb,kBAAmBc,EAAI,IACrC,UAGM,MAAXA,EAAI,IACNF,EAAOQ,UAAS,SAAUC,GAAK,MAAa,MAANA,CAAW,IACjDT,EAAOU,IAAI,KACJ,WAIM,OAAXR,EAAI,IACNF,EAAOQ,UAAS,SAAUC,GAAK,MAAa,MAANA,CAAW,IACjDT,EAAOU,IAAI,KACJ,UAEM,OAAXR,EAAI,IAA0B,OAAXA,EAAI,IAA0B,OAAXA,EAAI,IAC5CF,EAAOQ,UAAS,SAAUC,GAAK,MAAa,MAANA,CAAW,IACjDT,EAAOU,IAAI,KACJ,UAILR,EAAI,GAAK,YACJ,SAMF,YA7CT,CA+CF,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/forth.js"],"sourcesContent":["function toWordList(words) {\n var ret = [];\n words.split(' ').forEach(function(e){\n ret.push({name: e});\n });\n return ret;\n}\n\nvar coreWordList = toWordList(\n 'INVERT AND OR XOR\\\n 2* 2/ LSHIFT RSHIFT\\\n 0= = 0< < > U< MIN MAX\\\n 2DROP 2DUP 2OVER 2SWAP ?DUP DEPTH DROP DUP OVER ROT SWAP\\\n >R R> R@\\\n + - 1+ 1- ABS NEGATE\\\n S>D * M* UM*\\\n FM/MOD SM/REM UM/MOD */ */MOD / /MOD MOD\\\n HERE , @ ! CELL+ CELLS C, C@ C! CHARS 2@ 2!\\\n ALIGN ALIGNED +! ALLOT\\\n CHAR [CHAR] [ ] BL\\\n FIND EXECUTE IMMEDIATE COUNT LITERAL STATE\\\n ; DOES> >BODY\\\n EVALUATE\\\n SOURCE >IN\\\n <# # #S #> HOLD SIGN BASE >NUMBER HEX DECIMAL\\\n FILL MOVE\\\n . CR EMIT SPACE SPACES TYPE U. .R U.R\\\n ACCEPT\\\n TRUE FALSE\\\n <> U> 0<> 0>\\\n NIP TUCK ROLL PICK\\\n 2>R 2R@ 2R>\\\n WITHIN UNUSED MARKER\\\n I J\\\n TO\\\n COMPILE, [COMPILE]\\\n SAVE-INPUT RESTORE-INPUT\\\n PAD ERASE\\\n 2LITERAL DNEGATE\\\n D- D+ D0< D0= D2* D2/ D< D= DMAX DMIN D>S DABS\\\n M+ M*/ D. D.R 2ROT DU<\\\n CATCH THROW\\\n FREE RESIZE ALLOCATE\\\n CS-PICK CS-ROLL\\\n GET-CURRENT SET-CURRENT FORTH-WORDLIST GET-ORDER SET-ORDER\\\n PREVIOUS SEARCH-WORDLIST WORDLIST FIND ALSO ONLY FORTH DEFINITIONS ORDER\\\n -TRAILING /STRING SEARCH COMPARE CMOVE CMOVE> BLANK SLITERAL');\n\nvar immediateWordList = toWordList('IF ELSE THEN BEGIN WHILE REPEAT UNTIL RECURSE [IF] [ELSE] [THEN] ?DO DO LOOP +LOOP UNLOOP LEAVE EXIT AGAIN CASE OF ENDOF ENDCASE');\n\nfunction searchWordList (wordList, word) {\n var i;\n for (i = wordList.length - 1; i >= 0; i--) {\n if (wordList[i].name === word.toUpperCase()) {\n return wordList[i];\n }\n }\n return undefined;\n}\nexport const forth = {\n name: \"forth\",\n startState: function() {\n return {\n state: '',\n base: 10,\n coreWordList: coreWordList,\n immediateWordList: immediateWordList,\n wordList: []\n };\n },\n token: function (stream, stt) {\n var mat;\n if (stream.eatSpace()) {\n return null;\n }\n if (stt.state === '') { // interpretation\n if (stream.match(/^(\\]|:NONAME)(\\s|$)/i)) {\n stt.state = ' compilation';\n return 'builtin';\n }\n mat = stream.match(/^(\\:)\\s+(\\S+)(\\s|$)+/);\n if (mat) {\n stt.wordList.push({name: mat[2].toUpperCase()});\n stt.state = ' compilation';\n return 'def';\n }\n mat = stream.match(/^(VARIABLE|2VARIABLE|CONSTANT|2CONSTANT|CREATE|POSTPONE|VALUE|WORD)\\s+(\\S+)(\\s|$)+/i);\n if (mat) {\n stt.wordList.push({name: mat[2].toUpperCase()});\n return 'def';\n }\n mat = stream.match(/^(\\'|\\[\\'\\])\\s+(\\S+)(\\s|$)+/);\n if (mat) {\n return 'builtin'\n }\n } else { // compilation\n // ; [\n if (stream.match(/^(\\;|\\[)(\\s)/)) {\n stt.state = '';\n stream.backUp(1);\n return 'builtin';\n }\n if (stream.match(/^(\\;|\\[)($)/)) {\n stt.state = '';\n return 'builtin';\n }\n if (stream.match(/^(POSTPONE)\\s+\\S+(\\s|$)+/)) {\n return 'builtin';\n }\n }\n\n // dynamic wordlist\n mat = stream.match(/^(\\S+)(\\s+|$)/);\n if (mat) {\n if (searchWordList(stt.wordList, mat[1]) !== undefined) {\n return 'variable';\n }\n\n // comments\n if (mat[1] === '\\\\') {\n stream.skipToEnd();\n return 'comment';\n }\n\n // core words\n if (searchWordList(stt.coreWordList, mat[1]) !== undefined) {\n return 'builtin';\n }\n if (searchWordList(stt.immediateWordList, mat[1]) !== undefined) {\n return 'keyword';\n }\n\n if (mat[1] === '(') {\n stream.eatWhile(function (s) { return s !== ')'; });\n stream.eat(')');\n return 'comment';\n }\n\n // // strings\n if (mat[1] === '.(') {\n stream.eatWhile(function (s) { return s !== ')'; });\n stream.eat(')');\n return 'string';\n }\n if (mat[1] === 'S\"' || mat[1] === '.\"' || mat[1] === 'C\"') {\n stream.eatWhile(function (s) { return s !== '\"'; });\n stream.eat('\"');\n return 'string';\n }\n\n // numbers\n if (mat[1] - 0xfffffffff) {\n return 'number';\n }\n // if (mat[1].match(/^[-+]?[0-9]+\\.[0-9]*/)) {\n // return 'number';\n // }\n\n return 'atom';\n }\n }\n};\n"],"names":["toWordList","words","ret","split","forEach","e","push","name","coreWordList","immediateWordList","searchWordList","wordList","word","i","length","toUpperCase","forth","startState","state","base","token","stream","stt","mat","eatSpace","match","backUp","undefined","skipToEnd","eatWhile","s","eat"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/7373.index.js b/book/_build/html/_static/7373.index.js new file mode 100644 index 0000000..3fc9f45 --- /dev/null +++ b/book/_build/html/_static/7373.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[7373],{47373:(e,t,n)=>{n.r(t),n.d(t,{solr:()=>a});var r=/[^\s\|\!\+\-\*\?\~\^\&\:\(\)\[\]\{\}\"\\]/,o=/[\|\!\+\-\*\?\~\^\&]/,u=/^(OR|AND|NOT|TO)$/i;function i(e,t){var n,a,k=e.next();return'"'==k?t.tokenize=(a=k,function(e,t){for(var n,r=!1;null!=(n=e.next())&&(n!=a||r);)r=!r&&"\\"==n;return r||(t.tokenize=i),"string"}):o.test(k)?t.tokenize=(n=k,function(e,t){return"|"==n?e.eat(/\|/):"&"==n&&e.eat(/\&/),t.tokenize=i,"operator"}):r.test(k)&&(t.tokenize=function(e){return function(t,n){for(var o=e;(e=t.peek())&&null!=e.match(r);)o+=t.next();return n.tokenize=i,u.test(o)?"operator":function(e){return parseFloat(e).toString()===e}(o)?"number":":"==t.peek()?"propertyName":"string"}}(k)),t.tokenize!=i?t.tokenize(e,t):null}const a={name:"solr",startState:function(){return{tokenize:i}},token:function(e,t){return e.eatSpace()?null:t.tokenize(e,t)}}}}]); +//# sourceMappingURL=7373.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/7373.index.js.map b/book/_build/html/_static/7373.index.js.map new file mode 100644 index 0000000..d0ae4de --- /dev/null +++ b/book/_build/html/_static/7373.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"7373.index.js","mappings":"0HAAA,IAAIA,EAAe,4CACfC,EAAiB,uBACjBC,EAAmB,qBAkDvB,SAASC,EAAUC,EAAQC,GACzB,IAhCqBC,EAbFC,EA6CfC,EAAKJ,EAAOK,OAQhB,MAPU,KAAND,EACFH,EAAMK,UA/CWH,EA+CYC,EA9CxB,SAASJ,EAAQC,GAEtB,IADA,IAAqBI,EAAjBE,GAAU,EACmB,OAAzBF,EAAOL,EAAOK,UAChBA,GAAQF,GAAUI,IACtBA,GAAWA,GAAmB,MAARF,EAIxB,OADKE,IAASN,EAAMK,SAAWP,GACxB,QACT,GAsCSF,EAAeW,KAAKJ,GAC3BH,EAAMK,UApCaJ,EAoCYE,EAnC1B,SAASJ,EAAQC,GAOtB,MANgB,KAAZC,EACFF,EAAOS,IAAI,MACQ,KAAZP,GACPF,EAAOS,IAAI,MAEbR,EAAMK,SAAWP,EACV,UACT,GA4BSH,EAAaY,KAAKJ,KACzBH,EAAMK,SA1BV,SAAmBF,GACjB,OAAO,SAASJ,EAAQC,GAEtB,IADA,IAAIS,EAAON,GACHA,EAAKJ,EAAOW,SAAqC,MAA1BP,EAAGQ,MAAMhB,IACtCc,GAAQV,EAAOK,OAIjB,OADAJ,EAAMK,SAAWP,EACbD,EAAiBU,KAAKE,GACjB,WAtCb,SAAkBA,GAChB,OAAOG,WAAWH,GAAMI,aAAeJ,CACzC,CAqCaK,CAASL,GACT,SACiB,KAAjBV,EAAOW,OACP,eAEA,QACX,CACF,CASqBK,CAAUZ,IAErBH,EAAMK,UAAYP,EAAaE,EAAMK,SAASN,EAAQC,GAAS,IACzE,CAEO,MAAMgB,EAAO,CAClBC,KAAM,OAENC,WAAY,WACV,MAAO,CACLb,SAAUP,EAEd,EAEAqB,MAAO,SAASpB,EAAQC,GACtB,OAAID,EAAOqB,WAAmB,KACvBpB,EAAMK,SAASN,EAAQC,EAChC,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/solr.js"],"sourcesContent":["var isStringChar = /[^\\s\\|\\!\\+\\-\\*\\?\\~\\^\\&\\:\\(\\)\\[\\]\\{\\}\\\"\\\\]/;\nvar isOperatorChar = /[\\|\\!\\+\\-\\*\\?\\~\\^\\&]/;\nvar isOperatorString = /^(OR|AND|NOT|TO)$/i;\n\nfunction isNumber(word) {\n return parseFloat(word).toString() === word;\n}\n\nfunction tokenString(quote) {\n return function(stream, state) {\n var escaped = false, next;\n while ((next = stream.next()) != null) {\n if (next == quote && !escaped) break;\n escaped = !escaped && next == \"\\\\\";\n }\n\n if (!escaped) state.tokenize = tokenBase;\n return \"string\";\n };\n}\n\nfunction tokenOperator(operator) {\n return function(stream, state) {\n if (operator == \"|\")\n stream.eat(/\\|/);\n else if (operator == \"&\")\n stream.eat(/\\&/);\n\n state.tokenize = tokenBase;\n return \"operator\";\n };\n}\n\nfunction tokenWord(ch) {\n return function(stream, state) {\n var word = ch;\n while ((ch = stream.peek()) && ch.match(isStringChar) != null) {\n word += stream.next();\n }\n\n state.tokenize = tokenBase;\n if (isOperatorString.test(word))\n return \"operator\";\n else if (isNumber(word))\n return \"number\";\n else if (stream.peek() == \":\")\n return \"propertyName\";\n else\n return \"string\";\n };\n}\n\nfunction tokenBase(stream, state) {\n var ch = stream.next();\n if (ch == '\"')\n state.tokenize = tokenString(ch);\n else if (isOperatorChar.test(ch))\n state.tokenize = tokenOperator(ch);\n else if (isStringChar.test(ch))\n state.tokenize = tokenWord(ch);\n\n return (state.tokenize != tokenBase) ? state.tokenize(stream, state) : null;\n}\n\nexport const solr = {\n name: \"solr\",\n\n startState: function() {\n return {\n tokenize: tokenBase\n };\n },\n\n token: function(stream, state) {\n if (stream.eatSpace()) return null;\n return state.tokenize(stream, state);\n }\n};\n"],"names":["isStringChar","isOperatorChar","isOperatorString","tokenBase","stream","state","operator","quote","ch","next","tokenize","escaped","test","eat","word","peek","match","parseFloat","toString","isNumber","tokenWord","solr","name","startState","token","eatSpace"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/7396.index.js b/book/_build/html/_static/7396.index.js new file mode 100644 index 0000000..7d53b70 --- /dev/null +++ b/book/_build/html/_static/7396.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[7396],{67396:(e,t,a)=>{a.r(t),a.d(t,{Cassandra:()=>ve,MSSQL:()=>be,MariaSQL:()=>he,MySQL:()=>ge,PLSQL:()=>ye,PostgreSQL:()=>ue,SQLDialect:()=>re,SQLite:()=>_e,StandardSQL:()=>de,keywordCompletion:()=>oe,keywordCompletionSource:()=>ie,schemaCompletion:()=>le,schemaCompletionSource:()=>se,sql:()=>ce});var n=a(77120),r=a(86253),i=a(51392),o=a(64100);const s=36,l=1,c=2,d=3,u=4,m=5,p=6,f=7,g=8,h=9,b=10,_=11,v=12,y=13,k=14,x=15,O=16,w=17,Q=18,C=19,S=20,q=21,P=22,T=23,U=24;function z(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57}function X(e,t,a){for(let n=!1;;){if(e.next<0)return;if(e.next==t&&!n)return void e.advance();n=a&&!n&&92==e.next,e.advance()}}function B(e,t){for(;95==e.next||z(e.next);)null!=t&&(t+=String.fromCharCode(e.next)),e.advance();return t}function J(e,t){for(;48==e.next||49==e.next;)e.advance();t&&e.next==t&&e.advance()}function j(e,t){for(;;){if(46==e.next){if(t)break;t=!0}else if(e.next<48||e.next>57)break;e.advance()}if(69==e.next||101==e.next)for(e.advance(),43!=e.next&&45!=e.next||e.advance();e.next>=48&&e.next<=57;)e.advance()}function R(e){for(;!(e.next<0||10==e.next);)e.advance()}function Z(e,t){for(let a=0;a!=&|~^/",specialVar:"?",identifierQuotes:'"',words:V(I,D)};function E(e){return new i.Jq((t=>{var a;let{next:n}=t;if(t.advance(),Z(n,L)){for(;Z(t.next,L);)t.advance();t.acceptToken(s)}else if(36==n&&36==t.next&&e.doubleDollarQuotedStrings)!function(e){for(;;){if(e.next<0||e.peek(1)<0)return;if(36==e.next&&36==e.peek(1))return void e.advance(2);e.advance()}}(t),t.acceptToken(d);else if(39==n||34==n&&e.doubleQuotedStrings)X(t,n,e.backslashEscapes),t.acceptToken(d);else if(35==n&&e.hashComments||47==n&&47==t.next&&e.slashComments)R(t),t.acceptToken(l);else if(45!=n||45!=t.next||e.spaceAfterDashes&&32!=t.peek(1))if(47==n&&42==t.next){t.advance();for(let e=1;;){let a=t.next;if(t.next<0)break;if(t.advance(),42==a&&47==t.next){if(e--,t.advance(),!e)break}else 47==a&&42==t.next&&(e++,t.advance())}t.acceptToken(c)}else if(101!=n&&69!=n||39!=t.next)if(110!=n&&78!=n||39!=t.next||!e.charSetCasts)if(95==n&&e.charSetCasts)for(let a=0;;a++){if(39==t.next&&a>1){t.advance(),X(t,39,e.backslashEscapes),t.acceptToken(d);break}if(!z(t.next))break;t.advance()}else if(e.plsqlQuotingMechanism&&(113==n||81==n)&&39==t.next&&t.peek(1)>0&&!Z(t.peek(1),L)){let e=t.peek(1);t.advance(2),function(e,t){let a="[{<(".indexOf(String.fromCharCode(t)),n=a<0?t:"]}>)".charCodeAt(a);for(;;){if(e.next<0)return;if(e.next==n&&39==e.peek(1))return void e.advance(2);e.advance()}}(t,e),t.acceptToken(d)}else if(40==n)t.acceptToken(f);else if(41==n)t.acceptToken(g);else if(123==n)t.acceptToken(h);else if(125==n)t.acceptToken(b);else if(91==n)t.acceptToken(_);else if(93==n)t.acceptToken(v);else if(59==n)t.acceptToken(y);else if(e.unquotedBitLiterals&&48==n&&98==t.next)t.advance(),J(t),t.acceptToken(P);else if(98!=n&&66!=n||39!=t.next&&34!=t.next){if(48==n&&(120==t.next||88==t.next)||(120==n||88==n)&&39==t.next){let e=39==t.next;for(t.advance();(r=t.next)>=48&&r<=57||r>=97&&r<=102||r>=65&&r<=70;)t.advance();e&&39==t.next&&t.advance(),t.acceptToken(u)}else if(46==n&&t.next>=48&&t.next<=57)j(t,!0),t.acceptToken(u);else if(46==n)t.acceptToken(k);else if(n>=48&&n<=57)j(t,!1),t.acceptToken(u);else if(Z(n,e.operatorChars)){for(;Z(t.next,e.operatorChars);)t.advance();t.acceptToken(x)}else if(Z(n,e.specialVar))t.next==n&&t.advance(),function(e){if(39==e.next||34==e.next||96==e.next){let t=e.next;e.advance(),X(e,t,!1)}else B(e)}(t),t.acceptToken(w);else if(Z(n,e.identifierQuotes))X(t,n,!1),t.acceptToken(C);else if(58==n||44==n)t.acceptToken(O);else if(z(n)){let r=B(t,String.fromCharCode(n));t.acceptToken(46==t.next?Q:null!==(a=e.words[r.toLowerCase()])&&void 0!==a?a:Q)}}else{const a=t.next;t.advance(),e.treatBitsAsBytes?(X(t,a,e.backslashEscapes),t.acceptToken(T)):(J(t,a),t.acceptToken(P))}else t.advance(),X(t,39,e.backslashEscapes),t.acceptToken(d);else t.advance(),X(t,39,!0);else R(t),t.acceptToken(l);var r}))}const W=E($),N=i.WQ.deserialize({version:14,states:"%vQ]QQOOO#wQRO'#DSO$OQQO'#CwO%eQQO'#CxO%lQQO'#CyO%sQQO'#CzOOQQ'#DS'#DSOOQQ'#C}'#C}O'UQRO'#C{OOQQ'#Cv'#CvOOQQ'#C|'#C|Q]QQOOQOQQOOO'`QQO'#DOO(xQRO,59cO)PQQO,59cO)UQQO'#DSOOQQ,59d,59dO)cQQO,59dOOQQ,59e,59eO)jQQO,59eOOQQ,59f,59fO)qQQO,59fOOQQ-E6{-E6{OOQQ,59b,59bOOQQ-E6z-E6zOOQQ,59j,59jOOQQ-E6|-E6|O+VQRO1G.}O+^QQO,59cOOQQ1G/O1G/OOOQQ1G/P1G/POOQQ1G/Q1G/QP+kQQO'#C}O+rQQO1G.}O)PQQO,59cO,PQQO'#Cw",stateData:",[~OtOSPOSQOS~ORUOSUOTUOUUOVROXSOZTO]XO^QO_UO`UOaPObPOcPOdUOeUOfUOgUOhUO~O^]ORvXSvXTvXUvXVvXXvXZvX]vX_vX`vXavXbvXcvXdvXevXfvXgvXhvX~OsvX~P!jOa_Ob_Oc_O~ORUOSUOTUOUUOVROXSOZTO^tO_UO`UOa`Ob`Oc`OdUOeUOfUOgUOhUO~OWaO~P$ZOYcO~P$ZO[eO~P$ZORUOSUOTUOUUOVROXSOZTO^QO_UO`UOaPObPOcPOdUOeUOfUOgUOhUO~O]hOsoX~P%zOajObjOcjO~O^]ORkaSkaTkaUkaVkaXkaZka]ka_ka`kaakabkackadkaekafkagkahka~Oska~P'kO^]O~OWvXYvX[vX~P!jOWnO~P$ZOYoO~P$ZO[pO~P$ZO^]ORkiSkiTkiUkiVkiXkiZki]ki_ki`kiakibkickidkiekifkigkihki~Oski~P)xOWkaYka[ka~P'kO]hO~P$ZOWkiYki[ki~P)xOasObsOcsO~O",goto:"#hwPPPPPPPPPPPPPPPPPPPPPPPPPPx||||!Y!^!d!xPPP#[TYOZeUORSTWZbdfqT[OZQZORiZSWOZQbRQdSQfTZgWbdfqQ^PWk^lmrQl_Qm`RrseVORSTWZbdfq",nodeNames:"⚠ LineComment BlockComment String Number Bool Null ( ) { } [ ] ; . Operator Punctuation SpecialVar Identifier QuotedIdentifier Keyword Type Bits Bytes Builtin Script Statement CompositeIdentifier Parens Braces Brackets Statement",maxTerm:38,skippedNodes:[0,1,2],repeatNodeCount:3,tokenData:"RORO",tokenizers:[0,W],topRules:{Script:[0,25]},tokenPrec:0});function G(e){let t=e.cursor().moveTo(e.from,-1);for(;/Comment/.test(t.name);)t.moveTo(t.from,-1);return t.node}function A(e,t){let a=e.sliceString(t.from,t.to),n=/^([`'"])(.*)\1$/.exec(a);return n?n[2]:a}function M(e){return e&&("Identifier"==e.name||"QuotedIdentifier"==e.name)}function Y(e,t){if("CompositeIdentifier"==t.name){let a=[];for(let n=t.firstChild;n;n=n.nextSibling)M(n)&&a.push(A(e,n));return a}return[A(e,t)]}function K(e,t){for(let a=[];;){if(!t||"."!=t.name)return a;let n=G(t);if(!M(n))return a;a.unshift(A(e,n)),t=G(n)}}const F=new Set("where group having order union intersect except all distinct limit offset fetch for".split(" ")),H=/^\w*$/,ee=/^[`'"]?\w*[`'"]?$/;class te{constructor(){this.list=[],this.children=void 0}child(e,t){let a=this.children||(this.children=Object.create(null));return a[e]||(e&&this.list.push(ae(e,"type",t)),a[e]=new te)}addCompletions(e){for(let t of e){let e=this.list.findIndex((e=>e.label==t.label));e>-1?this.list[e]=t:this.list.push(t)}}}function ae(e,t,a){return/[^\w\xb5-\uffff]/.test(e)?{label:e,type:t,apply:a+e+a}:{label:e,type:t}}let ne=N.configure({props:[n.uj.add({Statement:(0,n.tC)()}),n.x0.add({Statement:e=>({from:e.firstChild.to,to:e.to}),BlockComment:e=>({from:e.from+2,to:e.to-2})}),(0,r.Gv)({Keyword:r.pJ.keyword,Type:r.pJ.typeName,Builtin:r.pJ.standard(r.pJ.name),Bits:r.pJ.number,Bytes:r.pJ.string,Bool:r.pJ.bool,Null:r.pJ.null,Number:r.pJ.number,String:r.pJ.string,Identifier:r.pJ.name,QuotedIdentifier:r.pJ.special(r.pJ.string),SpecialVar:r.pJ.special(r.pJ.name),LineComment:r.pJ.lineComment,BlockComment:r.pJ.blockComment,Operator:r.pJ.operator,"Semi Punctuation":r.pJ.punctuation,"( )":r.pJ.paren,"{ }":r.pJ.brace,"[ ]":r.pJ.squareBracket})]});class re{constructor(e,t,a){this.dialect=e,this.language=t,this.spec=a}get extension(){return this.language.extension}static define(e){let t=function(e,t,a,n){let r={};for(let t in $)r[t]=(e.hasOwnProperty(t)?e:$)[t];return t&&(r.words=V(t,a||"",n)),r}(e,e.keywords,e.types,e.builtin),a=n.qp.define({name:"sql",parser:ne.configure({tokenizers:[{from:W,to:E(t)}]}),languageData:{commentTokens:{line:"--",block:{open:"/*",close:"*/"}},closeBrackets:{brackets:["(","[","{","'",'"',"`"]}}});return new re(t,a,e)}}function ie(e,t=!1){return function(e,t){let a=Object.keys(e).map((a=>({label:t?a.toUpperCase():a,type:e[a]==q?"type":e[a]==S?"keyword":"variable",boost:-1})));return(0,o.eC)(["QuotedIdentifier","SpecialVar","String","LineComment","BlockComment","."],(0,o.Mb)(a))}(e.dialect.words,t)}function oe(e,t=!1){return e.language.data.of({autocomplete:ie(e,t)})}function se(e){return e.schema?function(e,t,a,r,i,o){var s;let l=new te,c=(null===(s=null==o?void 0:o.spec.identifierQuotes)||void 0===s?void 0:s[0])||'"',d=l.child(i||"",c);for(let t in e){let a=t.replace(/\\?\./g,(e=>"."==e?"\0":e)).split("\0"),n=1==a.length?d:l;for(let e of a)n=n.child(e.replace(/\\\./g,"."),c);for(let a of e[t])a&&n.list.push("string"==typeof a?ae(a,"property",c):a)}return t&&d.addCompletions(t),a&&l.addCompletions(a),l.addCompletions(d.list),r&&l.addCompletions(d.child(r,c).list),e=>{let{parents:t,from:a,quoted:i,empty:o,aliases:s}=function(e,t){let a=(0,n.qz)(e).resolveInner(t,-1),r=function(e,t){let a;for(let e=t;!a;e=e.parent){if(!e)return null;"Statement"==e.name&&(a=e)}let n=null;for(let t=a.firstChild,r=!1,i=null;t;t=t.nextSibling){let a="Keyword"==t.name?e.sliceString(t.from,t.to).toLowerCase():null,o=null;if(r)if("as"==a&&i&&M(t.nextSibling))o=A(e,t.nextSibling);else{if(a&&F.has(a))break;i&&M(t)&&(o=A(e,t))}else r="from"==a;o&&(n||(n=Object.create(null)),n[o]=Y(e,i)),i=/Identifier$/.test(t.name)?t:null}return n}(e.doc,a);return"Identifier"==a.name||"QuotedIdentifier"==a.name||"Keyword"==a.name?{from:a.from,quoted:"QuotedIdentifier"==a.name?e.doc.sliceString(a.from,a.from+1):null,parents:K(e.doc,G(a)),aliases:r}:"."==a.name?{from:t,quoted:null,parents:K(e.doc,a),aliases:r}:{from:t,quoted:null,parents:[],empty:!0,aliases:r}}(e.state,e.pos);if(o&&!e.explicit)return null;s&&1==t.length&&(t=s[t[0]]||t);let u=l;for(let e of t){for(;!u.children||!u.children[e];)if(u==l)u=d;else{if(u!=d||!r)return null;u=u.child(r,c)}u=u.child(e,c)}let m=i&&e.state.sliceDoc(e.pos,e.pos+1)==i,p=u.list;return u==l&&s&&(p=p.concat(Object.keys(s).map((e=>({label:e,type:"constant"}))))),{from:a,to:m?e.pos+1:void 0,options:(f=i,g=p,f?g.map((e=>Object.assign(Object.assign({},e),{label:f+e.label+f,apply:void 0}))):g),validFor:i?ee:H};var f,g}}(e.schema,e.tables,e.schemas,e.defaultTable,e.defaultSchema,e.dialect||de):()=>null}function le(e){return e.schema?(e.dialect||de).language.data.of({autocomplete:se(e)}):[]}function ce(e={}){let t=e.dialect||de;return new n.ri(t.language,[le(e),oe(t,!!e.upperCaseKeywords)])}const de=re.define({}),ue=re.define({charSetCasts:!0,doubleDollarQuotedStrings:!0,operatorChars:"+-*/<>=~!@#%^&|`?",specialVar:"",keywords:I+"a abort abs absent access according ada admin aggregate alias also always analyse analyze array_agg array_max_cardinality asensitive assert assignment asymmetric atomic attach attribute attributes avg backward base64 begin_frame begin_partition bernoulli bit_length blocked bom c cache called cardinality catalog_name ceil ceiling chain char_length character_length character_set_catalog character_set_name character_set_schema characteristics characters checkpoint class class_origin cluster coalesce cobol collation_catalog collation_name collation_schema collect column_name columns command_function command_function_code comment comments committed concurrently condition_number configuration conflict connection_name constant constraint_catalog constraint_name constraint_schema contains content control conversion convert copy corr cost covar_pop covar_samp csv cume_dist current_catalog current_row current_schema cursor_name database datalink datatype datetime_interval_code datetime_interval_precision db debug defaults defined definer degree delimiter delimiters dense_rank depends derived detach detail dictionary disable discard dispatch dlnewcopy dlpreviouscopy dlurlcomplete dlurlcompleteonly dlurlcompletewrite dlurlpath dlurlpathonly dlurlpathwrite dlurlscheme dlurlserver dlvalue document dump dynamic_function dynamic_function_code element elsif empty enable encoding encrypted end_frame end_partition endexec enforced enum errcode error event every exclude excluding exclusive exp explain expression extension extract family file filter final first_value flag floor following force foreach fortran forward frame_row freeze fs functions fusion g generated granted greatest groups handler header hex hierarchy hint id ignore ilike immediately immutable implementation implicit import include including increment indent index indexes info inherit inherits inline insensitive instance instantiable instead integrity intersection invoker isnull k key_member key_type label lag last_value lead leakproof least length library like_regex link listen ln load location lock locked log logged lower m mapping matched materialized max max_cardinality maxvalue member merge message message_length message_octet_length message_text min minvalue mod mode more move multiset mumps name namespace nfc nfd nfkc nfkd nil normalize normalized nothing notice notify notnull nowait nth_value ntile nullable nullif nulls number occurrences_regex octet_length octets off offset oids operator options ordering others over overlay overriding owned owner p parallel parameter_mode parameter_name parameter_ordinal_position parameter_specific_catalog parameter_specific_name parameter_specific_schema parser partition pascal passing passthrough password percent percent_rank percentile_cont percentile_disc perform period permission pg_context pg_datatype_name pg_exception_context pg_exception_detail pg_exception_hint placing plans pli policy portion position position_regex power precedes preceding prepared print_strict_params procedural procedures program publication query quote raise range rank reassign recheck recovery refresh regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy regr_syy reindex rename repeatable replace replica requiring reset respect restart restore result_oid returned_cardinality returned_length returned_octet_length returned_sqlstate returning reverse routine_catalog routine_name routine_schema routines row_count row_number rowtype rule scale schema_name schemas scope scope_catalog scope_name scope_schema security selective self sensitive sequence sequences serializable server server_name setof share show simple skip slice snapshot source specific_name sqlcode sqlerror sqrt stable stacked standalone statement statistics stddev_pop stddev_samp stdin stdout storage strict strip structure style subclass_origin submultiset subscription substring substring_regex succeeds sum symmetric sysid system system_time t table_name tables tablesample tablespace temp template ties token top_level_count transaction_active transactions_committed transactions_rolled_back transform transforms translate translate_regex trigger_catalog trigger_name trigger_schema trim trim_array truncate trusted type types uescape unbounded uncommitted unencrypted unlink unlisten unlogged unnamed untyped upper uri use_column use_variable user_defined_type_catalog user_defined_type_code user_defined_type_name user_defined_type_schema vacuum valid validate validator value_of var_pop var_samp varbinary variable_conflict variadic verbose version versioning views volatile warning whitespace width_bucket window within wrapper xmlagg xmlattributes xmlbinary xmlcast xmlcomment xmlconcat xmldeclaration xmldocument xmlelement xmlexists xmlforest xmliterate xmlnamespaces xmlparse xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltext xmlvalidate yes",types:D+"bigint int8 bigserial serial8 varbit bool box bytea cidr circle precision float8 inet int4 json jsonb line lseg macaddr macaddr8 money numeric pg_lsn point polygon float4 int2 smallserial serial2 serial serial4 text timetz timestamptz tsquery tsvector txid_snapshot uuid xml"}),me="accessible algorithm analyze asensitive authors auto_increment autocommit avg avg_row_length binlog btree cache catalog_name chain change changed checkpoint checksum class_origin client_statistics coalesce code collations columns comment committed completion concurrent consistent contains contributors convert database databases day_hour day_microsecond day_minute day_second delay_key_write delayed delimiter des_key_file dev_pop dev_samp deviance directory disable discard distinctrow div dual dumpfile enable enclosed ends engine engines enum errors escaped even event events every explain extended fast field fields flush force found_rows fulltext grants handler hash high_priority hosts hour_microsecond hour_minute hour_second ignore ignore_server_ids import index index_statistics infile innodb insensitive insert_method install invoker iterate keys kill linear lines list load lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modify mutex mysql_errno no_write_to_binlog offline offset one online optimize optionally outfile pack_keys parser partition partitions password phase plugin plugins prev processlist profile profiles purge query quick range read_write rebuild recover regexp relaylog remove rename reorganize repair repeatable replace require resume rlike row_format rtree schedule schema_name schemas second_microsecond security sensitive separator serializable server share show slave slow snapshot soname spatial sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result ssl starting starts std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace terminated triggers truncate uncommitted uninstall unlock upgrade use use_frm user_resources user_statistics utc_date utc_time utc_timestamp variables views warnings xa xor year_month zerofill",pe=D+"bool blob long longblob longtext medium mediumblob mediumint mediumtext tinyblob tinyint tinytext text bigint int1 int2 int3 int4 int8 float4 float8 varbinary varcharacter precision datetime unsigned signed",fe="charset clear edit ego help nopager notee nowarning pager print prompt quit rehash source status system tee",ge=re.define({operatorChars:"*+-%<>!=&|^",charSetCasts:!0,doubleQuotedStrings:!0,unquotedBitLiterals:!0,hashComments:!0,spaceAfterDashes:!0,specialVar:"@?",identifierQuotes:"`",keywords:I+"group_concat "+me,types:pe,builtin:fe}),he=re.define({operatorChars:"*+-%<>!=&|^",charSetCasts:!0,doubleQuotedStrings:!0,unquotedBitLiterals:!0,hashComments:!0,spaceAfterDashes:!0,specialVar:"@?",identifierQuotes:"`",keywords:I+"always generated groupby_concat hard persistent shutdown soft virtual "+me,types:pe,builtin:fe}),be=re.define({keywords:I+"trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare exec go if use index holdlock nolock nowait paglock pivot readcommitted readcommittedlock readpast readuncommitted repeatableread rowlock serializable snapshot tablock tablockx unpivot updlock with",types:D+"bigint smallint smallmoney tinyint money real text nvarchar ntext varbinary image hierarchyid uniqueidentifier sql_variant xml",builtin:"binary_checksum checksum connectionproperty context_info current_request_id error_line error_message error_number error_procedure error_severity error_state formatmessage get_filestream_transaction_context getansinull host_id host_name isnull isnumeric min_active_rowversion newid newsequentialid rowcount_big xact_state object_id",operatorChars:"*+-%<>!=^&|/",specialVar:"@"}),_e=re.define({keywords:I+"abort analyze attach autoincrement conflict database detach exclusive fail glob ignore index indexed instead isnull notnull offset plan pragma query raise regexp reindex rename replace temp vacuum virtual",types:D+"bool blob long longblob longtext medium mediumblob mediumint mediumtext tinyblob tinyint tinytext text bigint int2 int8 unsigned signed real",builtin:"auth backup bail changes clone databases dbinfo dump echo eqp explain fullschema headers help import imposter indexes iotrace lint load log mode nullvalue once print prompt quit restore save scanstats separator shell show stats system tables testcase timeout timer trace vfsinfo vfslist vfsname width",operatorChars:"*+-%<>!=&|/~",identifierQuotes:'`"',specialVar:"@:?$"}),ve=re.define({keywords:"add all allow alter and any apply as asc authorize batch begin by clustering columnfamily compact consistency count create custom delete desc distinct drop each_quorum exists filtering from grant if in index insert into key keyspace keyspaces level limit local_one local_quorum modify nan norecursive nosuperuser not of on one order password permission permissions primary quorum rename revoke schema select set storage superuser table three to token truncate ttl two type unlogged update use user users using values where with writetime infinity NaN",types:D+"ascii bigint blob counter frozen inet list map static text timeuuid tuple uuid varint",slashComments:!0}),ye=re.define({keywords:I+"abort accept access add all alter and any arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body by case cast char_base check close cluster clusters colauth column comment commit compress connected constant constraint crash create current currval cursor data_base database dba deallocate debugoff debugon declare default definition delay delete desc digits dispose distinct do drop else elseif elsif enable end entry exception exception_init exchange exclusive exists external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base of off offline on online only option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw rebuild record ref references refresh rename replace resource restrict return returning returns reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work",builtin:"appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define echo editfile embedded feedback flagger flush heading headsep instance linesize lno loboffset logsource longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar repfooter repheader serveroutput shiftinout show showmode spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout timing trimout trimspool ttitle underline verify version wrap",types:D+"ascii bfile bfilename bigserial bit blob dec long number nvarchar nvarchar2 serial smallint string text uid varchar2 xml",operatorChars:"*/+-%<>!=~",doubleQuotedStrings:!0,charSetCasts:!0,plsqlQuotingMechanism:!0})}}]); +//# sourceMappingURL=7396.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/7396.index.js.map b/book/_build/html/_static/7396.index.js.map new file mode 100644 index 0000000..4376b3e --- /dev/null +++ b/book/_build/html/_static/7396.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"7396.index.js","mappings":"qaAMA,MAAMA,EAAa,G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nGzL,MAAO0L,GACPzL,QAAS0L,KAMPG,GAAqBtF,GAAW+E,OAAO,CACzCxL,SAAUS,EAAc,8SACxBR,MAAOO,EAAW,iIAClBN,QAAS,6UACTkB,cAAe,eACfC,WAAY,MAKV2K,GAAsBvF,GAAW+E,OAAO,CAC1CxL,SAAUS,EAAc,+MACxBR,MAAOO,EAAW,+IAClBN,QAAS,+SACTkB,cAAe,eACfE,iBAAkB,KAClBD,WAAY,SAKV4K,GAAyBxF,GAAW+E,OAAO,CAC7CxL,SAAU,yiBACVC,MAAOO,EAAW,wFAClBK,eAAe,IAKbqL,GAAqBzF,GAAW+E,OAAO,CACzCxL,SAAUS,EAAc,wnDACxBP,QAAS,6mBACTD,MAAOO,EAAW,2HAClBY,cAAe,aACfN,qBAAqB,EACrBI,cAAc,EACdC,uBAAuB,G","sources":["webpack://thebe/../../node_modules/@codemirror/lang-sql/dist/index.js"],"sourcesContent":["import { syntaxTree, indentNodeProp, continuedIndent, foldNodeProp, LRLanguage, LanguageSupport } from '@codemirror/language';\nimport { styleTags, tags } from '@lezer/highlight';\nimport { ExternalTokenizer, LRParser } from '@lezer/lr';\nimport { ifNotIn, completeFromList } from '@codemirror/autocomplete';\n\n// This file was generated by lezer-generator. You probably shouldn't edit it.\nconst whitespace = 36,\n LineComment = 1,\n BlockComment = 2,\n String$1 = 3,\n Number = 4,\n Bool = 5,\n Null = 6,\n ParenL = 7,\n ParenR = 8,\n BraceL = 9,\n BraceR = 10,\n BracketL = 11,\n BracketR = 12,\n Semi = 13,\n Dot = 14,\n Operator = 15,\n Punctuation = 16,\n SpecialVar = 17,\n Identifier = 18,\n QuotedIdentifier = 19,\n Keyword = 20,\n Type = 21,\n Bits = 22,\n Bytes = 23,\n Builtin = 24;\n\nfunction isAlpha(ch) {\n return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || ch >= 48 /* _0 */ && ch <= 57 /* _9 */;\n}\nfunction isHexDigit(ch) {\n return ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch >= 97 /* a */ && ch <= 102 /* f */ || ch >= 65 /* A */ && ch <= 70 /* F */;\n}\nfunction readLiteral(input, endQuote, backslashEscapes) {\n for (let escaped = false;;) {\n if (input.next < 0)\n return;\n if (input.next == endQuote && !escaped) {\n input.advance();\n return;\n }\n escaped = backslashEscapes && !escaped && input.next == 92 /* Backslash */;\n input.advance();\n }\n}\nfunction readDoubleDollarLiteral(input) {\n for (;;) {\n if (input.next < 0 || input.peek(1) < 0)\n return;\n if (input.next == 36 /* Dollar */ && input.peek(1) == 36 /* Dollar */) {\n input.advance(2);\n return;\n }\n input.advance();\n }\n}\nfunction readPLSQLQuotedLiteral(input, openDelim) {\n let matchingDelim = \"[{<(\".indexOf(String.fromCharCode(openDelim));\n let closeDelim = matchingDelim < 0 ? openDelim : \"]}>)\".charCodeAt(matchingDelim);\n for (;;) {\n if (input.next < 0)\n return;\n if (input.next == closeDelim && input.peek(1) == 39 /* SingleQuote */) {\n input.advance(2);\n return;\n }\n input.advance();\n }\n}\nfunction readWord(input, result) {\n for (;;) {\n if (input.next != 95 /* Underscore */ && !isAlpha(input.next))\n break;\n if (result != null)\n result += String.fromCharCode(input.next);\n input.advance();\n }\n return result;\n}\nfunction readWordOrQuoted(input) {\n if (input.next == 39 /* SingleQuote */ || input.next == 34 /* DoubleQuote */ || input.next == 96 /* Backtick */) {\n let quote = input.next;\n input.advance();\n readLiteral(input, quote, false);\n }\n else {\n readWord(input);\n }\n}\nfunction readBits(input, endQuote) {\n while (input.next == 48 /* _0 */ || input.next == 49 /* _1 */)\n input.advance();\n if (endQuote && input.next == endQuote)\n input.advance();\n}\nfunction readNumber(input, sawDot) {\n for (;;) {\n if (input.next == 46 /* Dot */) {\n if (sawDot)\n break;\n sawDot = true;\n }\n else if (input.next < 48 /* _0 */ || input.next > 57 /* _9 */) {\n break;\n }\n input.advance();\n }\n if (input.next == 69 /* E */ || input.next == 101 /* e */) {\n input.advance();\n if (input.next == 43 /* Plus */ || input.next == 45 /* Dash */)\n input.advance();\n while (input.next >= 48 /* _0 */ && input.next <= 57 /* _9 */)\n input.advance();\n }\n}\nfunction eol(input) {\n while (!(input.next < 0 || input.next == 10 /* Newline */))\n input.advance();\n}\nfunction inString(ch, str) {\n for (let i = 0; i < str.length; i++)\n if (str.charCodeAt(i) == ch)\n return true;\n return false;\n}\nconst Space = \" \\t\\r\\n\";\nfunction keywords(keywords, types, builtin) {\n let result = Object.create(null);\n result[\"true\"] = result[\"false\"] = Bool;\n result[\"null\"] = result[\"unknown\"] = Null;\n for (let kw of keywords.split(\" \"))\n if (kw)\n result[kw] = Keyword;\n for (let tp of types.split(\" \"))\n if (tp)\n result[tp] = Type;\n for (let kw of (builtin || \"\").split(\" \"))\n if (kw)\n result[kw] = Builtin;\n return result;\n}\nconst SQLTypes = \"array binary bit boolean char character clob date decimal double float int integer interval large national nchar nclob numeric object precision real smallint time timestamp varchar varying \";\nconst SQLKeywords = \"absolute action add after all allocate alter and any are as asc assertion at authorization before begin between both breadth by call cascade cascaded case cast catalog check close collate collation column commit condition connect connection constraint constraints constructor continue corresponding count create cross cube current current_date current_default_transform_group current_transform_group_for_type current_path current_role current_time current_timestamp current_user cursor cycle data day deallocate declare default deferrable deferred delete depth deref desc describe descriptor deterministic diagnostics disconnect distinct do domain drop dynamic each else elseif end end-exec equals escape except exception exec execute exists exit external fetch first for foreign found from free full function general get global go goto grant group grouping handle having hold hour identity if immediate in indicator initially inner inout input insert intersect into is isolation join key language last lateral leading leave left level like limit local localtime localtimestamp locator loop map match method minute modifies module month names natural nesting new next no none not of old on only open option or order ordinality out outer output overlaps pad parameter partial path prepare preserve primary prior privileges procedure public read reads recursive redo ref references referencing relative release repeat resignal restrict result return returns revoke right role rollback rollup routine row rows savepoint schema scroll search second section select session session_user set sets signal similar size some space specific specifictype sql sqlexception sqlstate sqlwarning start state static system_user table temporary then timezone_hour timezone_minute to trailing transaction translation treat trigger under undo union unique unnest until update usage user using value values view when whenever where while with without work write year zone \";\nconst defaults = {\n backslashEscapes: false,\n hashComments: false,\n spaceAfterDashes: false,\n slashComments: false,\n doubleQuotedStrings: false,\n doubleDollarQuotedStrings: false,\n unquotedBitLiterals: false,\n treatBitsAsBytes: false,\n charSetCasts: false,\n plsqlQuotingMechanism: false,\n operatorChars: \"*+\\-%<>!=&|~^/\",\n specialVar: \"?\",\n identifierQuotes: '\"',\n words: /*@__PURE__*/keywords(SQLKeywords, SQLTypes)\n};\nfunction dialect(spec, kws, types, builtin) {\n let dialect = {};\n for (let prop in defaults)\n dialect[prop] = (spec.hasOwnProperty(prop) ? spec : defaults)[prop];\n if (kws)\n dialect.words = keywords(kws, types || \"\", builtin);\n return dialect;\n}\nfunction tokensFor(d) {\n return new ExternalTokenizer(input => {\n var _a;\n let { next } = input;\n input.advance();\n if (inString(next, Space)) {\n while (inString(input.next, Space))\n input.advance();\n input.acceptToken(whitespace);\n }\n else if (next == 36 /* Dollar */ && input.next == 36 /* Dollar */ && d.doubleDollarQuotedStrings) {\n readDoubleDollarLiteral(input);\n input.acceptToken(String$1);\n }\n else if (next == 39 /* SingleQuote */ || next == 34 /* DoubleQuote */ && d.doubleQuotedStrings) {\n readLiteral(input, next, d.backslashEscapes);\n input.acceptToken(String$1);\n }\n else if (next == 35 /* Hash */ && d.hashComments ||\n next == 47 /* Slash */ && input.next == 47 /* Slash */ && d.slashComments) {\n eol(input);\n input.acceptToken(LineComment);\n }\n else if (next == 45 /* Dash */ && input.next == 45 /* Dash */ &&\n (!d.spaceAfterDashes || input.peek(1) == 32 /* Space */)) {\n eol(input);\n input.acceptToken(LineComment);\n }\n else if (next == 47 /* Slash */ && input.next == 42 /* Star */) {\n input.advance();\n for (let depth = 1;;) {\n let cur = input.next;\n if (input.next < 0)\n break;\n input.advance();\n if (cur == 42 /* Star */ && input.next == 47 /* Slash */) {\n depth--;\n input.advance();\n if (!depth)\n break;\n }\n else if (cur == 47 /* Slash */ && input.next == 42 /* Star */) {\n depth++;\n input.advance();\n }\n }\n input.acceptToken(BlockComment);\n }\n else if ((next == 101 /* e */ || next == 69 /* E */) && input.next == 39 /* SingleQuote */) {\n input.advance();\n readLiteral(input, 39 /* SingleQuote */, true);\n }\n else if ((next == 110 /* n */ || next == 78 /* N */) && input.next == 39 /* SingleQuote */ &&\n d.charSetCasts) {\n input.advance();\n readLiteral(input, 39 /* SingleQuote */, d.backslashEscapes);\n input.acceptToken(String$1);\n }\n else if (next == 95 /* Underscore */ && d.charSetCasts) {\n for (let i = 0;; i++) {\n if (input.next == 39 /* SingleQuote */ && i > 1) {\n input.advance();\n readLiteral(input, 39 /* SingleQuote */, d.backslashEscapes);\n input.acceptToken(String$1);\n break;\n }\n if (!isAlpha(input.next))\n break;\n input.advance();\n }\n }\n else if (d.plsqlQuotingMechanism &&\n (next == 113 /* q */ || next == 81 /* Q */) && input.next == 39 /* SingleQuote */ &&\n input.peek(1) > 0 && !inString(input.peek(1), Space)) {\n let openDelim = input.peek(1);\n input.advance(2);\n readPLSQLQuotedLiteral(input, openDelim);\n input.acceptToken(String$1);\n }\n else if (next == 40 /* ParenL */) {\n input.acceptToken(ParenL);\n }\n else if (next == 41 /* ParenR */) {\n input.acceptToken(ParenR);\n }\n else if (next == 123 /* BraceL */) {\n input.acceptToken(BraceL);\n }\n else if (next == 125 /* BraceR */) {\n input.acceptToken(BraceR);\n }\n else if (next == 91 /* BracketL */) {\n input.acceptToken(BracketL);\n }\n else if (next == 93 /* BracketR */) {\n input.acceptToken(BracketR);\n }\n else if (next == 59 /* Semi */) {\n input.acceptToken(Semi);\n }\n else if (d.unquotedBitLiterals && next == 48 /* _0 */ && input.next == 98 /* b */) {\n input.advance();\n readBits(input);\n input.acceptToken(Bits);\n }\n else if ((next == 98 /* b */ || next == 66 /* B */) && (input.next == 39 /* SingleQuote */ || input.next == 34 /* DoubleQuote */)) {\n const quoteStyle = input.next;\n input.advance();\n if (d.treatBitsAsBytes) {\n readLiteral(input, quoteStyle, d.backslashEscapes);\n input.acceptToken(Bytes);\n }\n else {\n readBits(input, quoteStyle);\n input.acceptToken(Bits);\n }\n }\n else if (next == 48 /* _0 */ && (input.next == 120 /* x */ || input.next == 88 /* X */) ||\n (next == 120 /* x */ || next == 88 /* X */) && input.next == 39 /* SingleQuote */) {\n let quoted = input.next == 39 /* SingleQuote */;\n input.advance();\n while (isHexDigit(input.next))\n input.advance();\n if (quoted && input.next == 39 /* SingleQuote */)\n input.advance();\n input.acceptToken(Number);\n }\n else if (next == 46 /* Dot */ && input.next >= 48 /* _0 */ && input.next <= 57 /* _9 */) {\n readNumber(input, true);\n input.acceptToken(Number);\n }\n else if (next == 46 /* Dot */) {\n input.acceptToken(Dot);\n }\n else if (next >= 48 /* _0 */ && next <= 57 /* _9 */) {\n readNumber(input, false);\n input.acceptToken(Number);\n }\n else if (inString(next, d.operatorChars)) {\n while (inString(input.next, d.operatorChars))\n input.advance();\n input.acceptToken(Operator);\n }\n else if (inString(next, d.specialVar)) {\n if (input.next == next)\n input.advance();\n readWordOrQuoted(input);\n input.acceptToken(SpecialVar);\n }\n else if (inString(next, d.identifierQuotes)) {\n readLiteral(input, next, false);\n input.acceptToken(QuotedIdentifier);\n }\n else if (next == 58 /* Colon */ || next == 44 /* Comma */) {\n input.acceptToken(Punctuation);\n }\n else if (isAlpha(next)) {\n let word = readWord(input, String.fromCharCode(next));\n input.acceptToken(input.next == 46 /* Dot */ ? Identifier : (_a = d.words[word.toLowerCase()]) !== null && _a !== void 0 ? _a : Identifier);\n }\n });\n}\nconst tokens = /*@__PURE__*/tokensFor(defaults);\n\n// This file was generated by lezer-generator. You probably shouldn't edit it.\nconst parser$1 = /*@__PURE__*/LRParser.deserialize({\n version: 14,\n states: \"%vQ]QQOOO#wQRO'#DSO$OQQO'#CwO%eQQO'#CxO%lQQO'#CyO%sQQO'#CzOOQQ'#DS'#DSOOQQ'#C}'#C}O'UQRO'#C{OOQQ'#Cv'#CvOOQQ'#C|'#C|Q]QQOOQOQQOOO'`QQO'#DOO(xQRO,59cO)PQQO,59cO)UQQO'#DSOOQQ,59d,59dO)cQQO,59dOOQQ,59e,59eO)jQQO,59eOOQQ,59f,59fO)qQQO,59fOOQQ-E6{-E6{OOQQ,59b,59bOOQQ-E6z-E6zOOQQ,59j,59jOOQQ-E6|-E6|O+VQRO1G.}O+^QQO,59cOOQQ1G/O1G/OOOQQ1G/P1G/POOQQ1G/Q1G/QP+kQQO'#C}O+rQQO1G.}O)PQQO,59cO,PQQO'#Cw\",\n stateData: \",[~OtOSPOSQOS~ORUOSUOTUOUUOVROXSOZTO]XO^QO_UO`UOaPObPOcPOdUOeUOfUOgUOhUO~O^]ORvXSvXTvXUvXVvXXvXZvX]vX_vX`vXavXbvXcvXdvXevXfvXgvXhvX~OsvX~P!jOa_Ob_Oc_O~ORUOSUOTUOUUOVROXSOZTO^tO_UO`UOa`Ob`Oc`OdUOeUOfUOgUOhUO~OWaO~P$ZOYcO~P$ZO[eO~P$ZORUOSUOTUOUUOVROXSOZTO^QO_UO`UOaPObPOcPOdUOeUOfUOgUOhUO~O]hOsoX~P%zOajObjOcjO~O^]ORkaSkaTkaUkaVkaXkaZka]ka_ka`kaakabkackadkaekafkagkahka~Oska~P'kO^]O~OWvXYvX[vX~P!jOWnO~P$ZOYoO~P$ZO[pO~P$ZO^]ORkiSkiTkiUkiVkiXkiZki]ki_ki`kiakibkickidkiekifkigkihki~Oski~P)xOWkaYka[ka~P'kO]hO~P$ZOWkiYki[ki~P)xOasObsOcsO~O\",\n goto: \"#hwPPPPPPPPPPPPPPPPPPPPPPPPPPx||||!Y!^!d!xPPP#[TYOZeUORSTWZbdfqT[OZQZORiZSWOZQbRQdSQfTZgWbdfqQ^PWk^lmrQl_Qm`RrseVORSTWZbdfq\",\n nodeNames: \"⚠ LineComment BlockComment String Number Bool Null ( ) { } [ ] ; . Operator Punctuation SpecialVar Identifier QuotedIdentifier Keyword Type Bits Bytes Builtin Script Statement CompositeIdentifier Parens Braces Brackets Statement\",\n maxTerm: 38,\n skippedNodes: [0,1,2],\n repeatNodeCount: 3,\n tokenData: \"RORO\",\n tokenizers: [0, tokens],\n topRules: {\"Script\":[0,25]},\n tokenPrec: 0\n});\n\nfunction tokenBefore(tree) {\n let cursor = tree.cursor().moveTo(tree.from, -1);\n while (/Comment/.test(cursor.name))\n cursor.moveTo(cursor.from, -1);\n return cursor.node;\n}\nfunction idName(doc, node) {\n let text = doc.sliceString(node.from, node.to);\n let quoted = /^([`'\"])(.*)\\1$/.exec(text);\n return quoted ? quoted[2] : text;\n}\nfunction plainID(node) {\n return node && (node.name == \"Identifier\" || node.name == \"QuotedIdentifier\");\n}\nfunction pathFor(doc, id) {\n if (id.name == \"CompositeIdentifier\") {\n let path = [];\n for (let ch = id.firstChild; ch; ch = ch.nextSibling)\n if (plainID(ch))\n path.push(idName(doc, ch));\n return path;\n }\n return [idName(doc, id)];\n}\nfunction parentsFor(doc, node) {\n for (let path = [];;) {\n if (!node || node.name != \".\")\n return path;\n let name = tokenBefore(node);\n if (!plainID(name))\n return path;\n path.unshift(idName(doc, name));\n node = tokenBefore(name);\n }\n}\nfunction sourceContext(state, startPos) {\n let pos = syntaxTree(state).resolveInner(startPos, -1);\n let aliases = getAliases(state.doc, pos);\n if (pos.name == \"Identifier\" || pos.name == \"QuotedIdentifier\" || pos.name == \"Keyword\") {\n return { from: pos.from,\n quoted: pos.name == \"QuotedIdentifier\" ? state.doc.sliceString(pos.from, pos.from + 1) : null,\n parents: parentsFor(state.doc, tokenBefore(pos)),\n aliases };\n }\n if (pos.name == \".\") {\n return { from: startPos, quoted: null, parents: parentsFor(state.doc, pos), aliases };\n }\n else {\n return { from: startPos, quoted: null, parents: [], empty: true, aliases };\n }\n}\nconst EndFrom = /*@__PURE__*/new Set(/*@__PURE__*/\"where group having order union intersect except all distinct limit offset fetch for\".split(\" \"));\nfunction getAliases(doc, at) {\n let statement;\n for (let parent = at; !statement; parent = parent.parent) {\n if (!parent)\n return null;\n if (parent.name == \"Statement\")\n statement = parent;\n }\n let aliases = null;\n for (let scan = statement.firstChild, sawFrom = false, prevID = null; scan; scan = scan.nextSibling) {\n let kw = scan.name == \"Keyword\" ? doc.sliceString(scan.from, scan.to).toLowerCase() : null;\n let alias = null;\n if (!sawFrom) {\n sawFrom = kw == \"from\";\n }\n else if (kw == \"as\" && prevID && plainID(scan.nextSibling)) {\n alias = idName(doc, scan.nextSibling);\n }\n else if (kw && EndFrom.has(kw)) {\n break;\n }\n else if (prevID && plainID(scan)) {\n alias = idName(doc, scan);\n }\n if (alias) {\n if (!aliases)\n aliases = Object.create(null);\n aliases[alias] = pathFor(doc, prevID);\n }\n prevID = /Identifier$/.test(scan.name) ? scan : null;\n }\n return aliases;\n}\nfunction maybeQuoteCompletions(quote, completions) {\n if (!quote)\n return completions;\n return completions.map(c => (Object.assign(Object.assign({}, c), { label: quote + c.label + quote, apply: undefined })));\n}\nconst Span = /^\\w*$/, QuotedSpan = /^[`'\"]?\\w*[`'\"]?$/;\nclass CompletionLevel {\n constructor() {\n this.list = [];\n this.children = undefined;\n }\n child(name, idQuote) {\n let children = this.children || (this.children = Object.create(null));\n let found = children[name];\n if (found)\n return found;\n if (name)\n this.list.push(nameCompletion(name, \"type\", idQuote));\n return (children[name] = new CompletionLevel);\n }\n addCompletions(list) {\n for (let option of list) {\n let found = this.list.findIndex(o => o.label == option.label);\n if (found > -1)\n this.list[found] = option;\n else\n this.list.push(option);\n }\n }\n}\nfunction nameCompletion(label, type, idQuote) {\n if (!/[^\\w\\xb5-\\uffff]/.test(label))\n return { label, type };\n return { label, type, apply: idQuote + label + idQuote };\n}\nfunction completeFromSchema(schema, tables, schemas, defaultTableName, defaultSchemaName, dialect) {\n var _a;\n let top = new CompletionLevel;\n let idQuote = ((_a = dialect === null || dialect === void 0 ? void 0 : dialect.spec.identifierQuotes) === null || _a === void 0 ? void 0 : _a[0]) || '\"';\n let defaultSchema = top.child(defaultSchemaName || \"\", idQuote);\n for (let table in schema) {\n let parts = table.replace(/\\\\?\\./g, p => p == \".\" ? \"\\0\" : p).split(\"\\0\");\n let base = parts.length == 1 ? defaultSchema : top;\n for (let part of parts)\n base = base.child(part.replace(/\\\\\\./g, \".\"), idQuote);\n for (let option of schema[table])\n if (option)\n base.list.push(typeof option == \"string\" ? nameCompletion(option, \"property\", idQuote) : option);\n }\n if (tables)\n defaultSchema.addCompletions(tables);\n if (schemas)\n top.addCompletions(schemas);\n top.addCompletions(defaultSchema.list);\n if (defaultTableName)\n top.addCompletions(defaultSchema.child(defaultTableName, idQuote).list);\n return (context) => {\n let { parents, from, quoted, empty, aliases } = sourceContext(context.state, context.pos);\n if (empty && !context.explicit)\n return null;\n if (aliases && parents.length == 1)\n parents = aliases[parents[0]] || parents;\n let level = top;\n for (let name of parents) {\n while (!level.children || !level.children[name]) {\n if (level == top)\n level = defaultSchema;\n else if (level == defaultSchema && defaultTableName)\n level = level.child(defaultTableName, idQuote);\n else\n return null;\n }\n level = level.child(name, idQuote);\n }\n let quoteAfter = quoted && context.state.sliceDoc(context.pos, context.pos + 1) == quoted;\n let options = level.list;\n if (level == top && aliases)\n options = options.concat(Object.keys(aliases).map(name => ({ label: name, type: \"constant\" })));\n return {\n from,\n to: quoteAfter ? context.pos + 1 : undefined,\n options: maybeQuoteCompletions(quoted, options),\n validFor: quoted ? QuotedSpan : Span\n };\n };\n}\nfunction completeKeywords(keywords, upperCase) {\n let completions = Object.keys(keywords).map(keyword => ({\n label: upperCase ? keyword.toUpperCase() : keyword,\n type: keywords[keyword] == Type ? \"type\" : keywords[keyword] == Keyword ? \"keyword\" : \"variable\",\n boost: -1\n }));\n return ifNotIn([\"QuotedIdentifier\", \"SpecialVar\", \"String\", \"LineComment\", \"BlockComment\", \".\"], completeFromList(completions));\n}\n\nlet parser = /*@__PURE__*/parser$1.configure({\n props: [\n /*@__PURE__*/indentNodeProp.add({\n Statement: /*@__PURE__*/continuedIndent()\n }),\n /*@__PURE__*/foldNodeProp.add({\n Statement(tree) { return { from: tree.firstChild.to, to: tree.to }; },\n BlockComment(tree) { return { from: tree.from + 2, to: tree.to - 2 }; }\n }),\n /*@__PURE__*/styleTags({\n Keyword: tags.keyword,\n Type: tags.typeName,\n Builtin: /*@__PURE__*/tags.standard(tags.name),\n Bits: tags.number,\n Bytes: tags.string,\n Bool: tags.bool,\n Null: tags.null,\n Number: tags.number,\n String: tags.string,\n Identifier: tags.name,\n QuotedIdentifier: /*@__PURE__*/tags.special(tags.string),\n SpecialVar: /*@__PURE__*/tags.special(tags.name),\n LineComment: tags.lineComment,\n BlockComment: tags.blockComment,\n Operator: tags.operator,\n \"Semi Punctuation\": tags.punctuation,\n \"( )\": tags.paren,\n \"{ }\": tags.brace,\n \"[ ]\": tags.squareBracket\n })\n ]\n});\n/**\nRepresents an SQL dialect.\n*/\nclass SQLDialect {\n constructor(\n /**\n @internal\n */\n dialect, \n /**\n The language for this dialect.\n */\n language, \n /**\n The spec used to define this dialect.\n */\n spec) {\n this.dialect = dialect;\n this.language = language;\n this.spec = spec;\n }\n /**\n Returns the language for this dialect as an extension.\n */\n get extension() { return this.language.extension; }\n /**\n Define a new dialect.\n */\n static define(spec) {\n let d = dialect(spec, spec.keywords, spec.types, spec.builtin);\n let language = LRLanguage.define({\n name: \"sql\",\n parser: parser.configure({\n tokenizers: [{ from: tokens, to: tokensFor(d) }]\n }),\n languageData: {\n commentTokens: { line: \"--\", block: { open: \"/*\", close: \"*/\" } },\n closeBrackets: { brackets: [\"(\", \"[\", \"{\", \"'\", '\"', \"`\"] }\n }\n });\n return new SQLDialect(d, language, spec);\n }\n}\n/**\nReturns a completion source that provides keyword completion for\nthe given SQL dialect.\n*/\nfunction keywordCompletionSource(dialect, upperCase = false) {\n return completeKeywords(dialect.dialect.words, upperCase);\n}\n/**\nFIXME remove on 1.0 @internal\n*/\nfunction keywordCompletion(dialect, upperCase = false) {\n return dialect.language.data.of({\n autocomplete: keywordCompletionSource(dialect, upperCase)\n });\n}\n/**\nReturns a completion sources that provides schema-based completion\nfor the given configuration.\n*/\nfunction schemaCompletionSource(config) {\n return config.schema ? completeFromSchema(config.schema, config.tables, config.schemas, config.defaultTable, config.defaultSchema, config.dialect || StandardSQL)\n : () => null;\n}\n/**\nFIXME remove on 1.0 @internal\n*/\nfunction schemaCompletion(config) {\n return config.schema ? (config.dialect || StandardSQL).language.data.of({\n autocomplete: schemaCompletionSource(config)\n }) : [];\n}\n/**\nSQL language support for the given SQL dialect, with keyword\ncompletion, and, if provided, schema-based completion as extra\nextensions.\n*/\nfunction sql(config = {}) {\n let lang = config.dialect || StandardSQL;\n return new LanguageSupport(lang.language, [schemaCompletion(config), keywordCompletion(lang, !!config.upperCaseKeywords)]);\n}\n/**\nThe standard SQL dialect.\n*/\nconst StandardSQL = /*@__PURE__*/SQLDialect.define({});\n/**\nDialect for [PostgreSQL](https://www.postgresql.org).\n*/\nconst PostgreSQL = /*@__PURE__*/SQLDialect.define({\n charSetCasts: true,\n doubleDollarQuotedStrings: true,\n operatorChars: \"+-*/<>=~!@#%^&|`?\",\n specialVar: \"\",\n keywords: SQLKeywords + \"a abort abs absent access according ada admin aggregate alias also always analyse analyze array_agg array_max_cardinality asensitive assert assignment asymmetric atomic attach attribute attributes avg backward base64 begin_frame begin_partition bernoulli bit_length blocked bom c cache called cardinality catalog_name ceil ceiling chain char_length character_length character_set_catalog character_set_name character_set_schema characteristics characters checkpoint class class_origin cluster coalesce cobol collation_catalog collation_name collation_schema collect column_name columns command_function command_function_code comment comments committed concurrently condition_number configuration conflict connection_name constant constraint_catalog constraint_name constraint_schema contains content control conversion convert copy corr cost covar_pop covar_samp csv cume_dist current_catalog current_row current_schema cursor_name database datalink datatype datetime_interval_code datetime_interval_precision db debug defaults defined definer degree delimiter delimiters dense_rank depends derived detach detail dictionary disable discard dispatch dlnewcopy dlpreviouscopy dlurlcomplete dlurlcompleteonly dlurlcompletewrite dlurlpath dlurlpathonly dlurlpathwrite dlurlscheme dlurlserver dlvalue document dump dynamic_function dynamic_function_code element elsif empty enable encoding encrypted end_frame end_partition endexec enforced enum errcode error event every exclude excluding exclusive exp explain expression extension extract family file filter final first_value flag floor following force foreach fortran forward frame_row freeze fs functions fusion g generated granted greatest groups handler header hex hierarchy hint id ignore ilike immediately immutable implementation implicit import include including increment indent index indexes info inherit inherits inline insensitive instance instantiable instead integrity intersection invoker isnull k key_member key_type label lag last_value lead leakproof least length library like_regex link listen ln load location lock locked log logged lower m mapping matched materialized max max_cardinality maxvalue member merge message message_length message_octet_length message_text min minvalue mod mode more move multiset mumps name namespace nfc nfd nfkc nfkd nil normalize normalized nothing notice notify notnull nowait nth_value ntile nullable nullif nulls number occurrences_regex octet_length octets off offset oids operator options ordering others over overlay overriding owned owner p parallel parameter_mode parameter_name parameter_ordinal_position parameter_specific_catalog parameter_specific_name parameter_specific_schema parser partition pascal passing passthrough password percent percent_rank percentile_cont percentile_disc perform period permission pg_context pg_datatype_name pg_exception_context pg_exception_detail pg_exception_hint placing plans pli policy portion position position_regex power precedes preceding prepared print_strict_params procedural procedures program publication query quote raise range rank reassign recheck recovery refresh regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy regr_syy reindex rename repeatable replace replica requiring reset respect restart restore result_oid returned_cardinality returned_length returned_octet_length returned_sqlstate returning reverse routine_catalog routine_name routine_schema routines row_count row_number rowtype rule scale schema_name schemas scope scope_catalog scope_name scope_schema security selective self sensitive sequence sequences serializable server server_name setof share show simple skip slice snapshot source specific_name sqlcode sqlerror sqrt stable stacked standalone statement statistics stddev_pop stddev_samp stdin stdout storage strict strip structure style subclass_origin submultiset subscription substring substring_regex succeeds sum symmetric sysid system system_time t table_name tables tablesample tablespace temp template ties token top_level_count transaction_active transactions_committed transactions_rolled_back transform transforms translate translate_regex trigger_catalog trigger_name trigger_schema trim trim_array truncate trusted type types uescape unbounded uncommitted unencrypted unlink unlisten unlogged unnamed untyped upper uri use_column use_variable user_defined_type_catalog user_defined_type_code user_defined_type_name user_defined_type_schema vacuum valid validate validator value_of var_pop var_samp varbinary variable_conflict variadic verbose version versioning views volatile warning whitespace width_bucket window within wrapper xmlagg xmlattributes xmlbinary xmlcast xmlcomment xmlconcat xmldeclaration xmldocument xmlelement xmlexists xmlforest xmliterate xmlnamespaces xmlparse xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltext xmlvalidate yes\",\n types: SQLTypes + \"bigint int8 bigserial serial8 varbit bool box bytea cidr circle precision float8 inet int4 json jsonb line lseg macaddr macaddr8 money numeric pg_lsn point polygon float4 int2 smallserial serial2 serial serial4 text timetz timestamptz tsquery tsvector txid_snapshot uuid xml\"\n});\nconst MySQLKeywords = \"accessible algorithm analyze asensitive authors auto_increment autocommit avg avg_row_length binlog btree cache catalog_name chain change changed checkpoint checksum class_origin client_statistics coalesce code collations columns comment committed completion concurrent consistent contains contributors convert database databases day_hour day_microsecond day_minute day_second delay_key_write delayed delimiter des_key_file dev_pop dev_samp deviance directory disable discard distinctrow div dual dumpfile enable enclosed ends engine engines enum errors escaped even event events every explain extended fast field fields flush force found_rows fulltext grants handler hash high_priority hosts hour_microsecond hour_minute hour_second ignore ignore_server_ids import index index_statistics infile innodb insensitive insert_method install invoker iterate keys kill linear lines list load lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modify mutex mysql_errno no_write_to_binlog offline offset one online optimize optionally outfile pack_keys parser partition partitions password phase plugin plugins prev processlist profile profiles purge query quick range read_write rebuild recover regexp relaylog remove rename reorganize repair repeatable replace require resume rlike row_format rtree schedule schema_name schemas second_microsecond security sensitive separator serializable server share show slave slow snapshot soname spatial sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result ssl starting starts std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace terminated triggers truncate uncommitted uninstall unlock upgrade use use_frm user_resources user_statistics utc_date utc_time utc_timestamp variables views warnings xa xor year_month zerofill\";\nconst MySQLTypes = SQLTypes + \"bool blob long longblob longtext medium mediumblob mediumint mediumtext tinyblob tinyint tinytext text bigint int1 int2 int3 int4 int8 float4 float8 varbinary varcharacter precision datetime unsigned signed\";\nconst MySQLBuiltin = \"charset clear edit ego help nopager notee nowarning pager print prompt quit rehash source status system tee\";\n/**\n[MySQL](https://dev.mysql.com/) dialect.\n*/\nconst MySQL = /*@__PURE__*/SQLDialect.define({\n operatorChars: \"*+-%<>!=&|^\",\n charSetCasts: true,\n doubleQuotedStrings: true,\n unquotedBitLiterals: true,\n hashComments: true,\n spaceAfterDashes: true,\n specialVar: \"@?\",\n identifierQuotes: \"`\",\n keywords: SQLKeywords + \"group_concat \" + MySQLKeywords,\n types: MySQLTypes,\n builtin: MySQLBuiltin\n});\n/**\nVariant of [`MySQL`](https://codemirror.net/6/docs/ref/#lang-sql.MySQL) for\n[MariaDB](https://mariadb.org/).\n*/\nconst MariaSQL = /*@__PURE__*/SQLDialect.define({\n operatorChars: \"*+-%<>!=&|^\",\n charSetCasts: true,\n doubleQuotedStrings: true,\n unquotedBitLiterals: true,\n hashComments: true,\n spaceAfterDashes: true,\n specialVar: \"@?\",\n identifierQuotes: \"`\",\n keywords: SQLKeywords + \"always generated groupby_concat hard persistent shutdown soft virtual \" + MySQLKeywords,\n types: MySQLTypes,\n builtin: MySQLBuiltin\n});\n/**\nSQL dialect for Microsoft [SQL\nServer](https://www.microsoft.com/en-us/sql-server).\n*/\nconst MSSQL = /*@__PURE__*/SQLDialect.define({\n keywords: SQLKeywords + \"trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare exec go if use index holdlock nolock nowait paglock pivot readcommitted readcommittedlock readpast readuncommitted repeatableread rowlock serializable snapshot tablock tablockx unpivot updlock with\",\n types: SQLTypes + \"bigint smallint smallmoney tinyint money real text nvarchar ntext varbinary image hierarchyid uniqueidentifier sql_variant xml\",\n builtin: \"binary_checksum checksum connectionproperty context_info current_request_id error_line error_message error_number error_procedure error_severity error_state formatmessage get_filestream_transaction_context getansinull host_id host_name isnull isnumeric min_active_rowversion newid newsequentialid rowcount_big xact_state object_id\",\n operatorChars: \"*+-%<>!=^&|/\",\n specialVar: \"@\"\n});\n/**\n[SQLite](https://sqlite.org/) dialect.\n*/\nconst SQLite = /*@__PURE__*/SQLDialect.define({\n keywords: SQLKeywords + \"abort analyze attach autoincrement conflict database detach exclusive fail glob ignore index indexed instead isnull notnull offset plan pragma query raise regexp reindex rename replace temp vacuum virtual\",\n types: SQLTypes + \"bool blob long longblob longtext medium mediumblob mediumint mediumtext tinyblob tinyint tinytext text bigint int2 int8 unsigned signed real\",\n builtin: \"auth backup bail changes clone databases dbinfo dump echo eqp explain fullschema headers help import imposter indexes iotrace lint load log mode nullvalue once print prompt quit restore save scanstats separator shell show stats system tables testcase timeout timer trace vfsinfo vfslist vfsname width\",\n operatorChars: \"*+-%<>!=&|/~\",\n identifierQuotes: \"`\\\"\",\n specialVar: \"@:?$\"\n});\n/**\nDialect for [Cassandra](https://cassandra.apache.org/)'s SQL-ish query language.\n*/\nconst Cassandra = /*@__PURE__*/SQLDialect.define({\n keywords: \"add all allow alter and any apply as asc authorize batch begin by clustering columnfamily compact consistency count create custom delete desc distinct drop each_quorum exists filtering from grant if in index insert into key keyspace keyspaces level limit local_one local_quorum modify nan norecursive nosuperuser not of on one order password permission permissions primary quorum rename revoke schema select set storage superuser table three to token truncate ttl two type unlogged update use user users using values where with writetime infinity NaN\",\n types: SQLTypes + \"ascii bigint blob counter frozen inet list map static text timeuuid tuple uuid varint\",\n slashComments: true\n});\n/**\n[PL/SQL](https://en.wikipedia.org/wiki/PL/SQL) dialect.\n*/\nconst PLSQL = /*@__PURE__*/SQLDialect.define({\n keywords: SQLKeywords + \"abort accept access add all alter and any arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body by case cast char_base check close cluster clusters colauth column comment commit compress connected constant constraint crash create current currval cursor data_base database dba deallocate debugoff debugon declare default definition delay delete desc digits dispose distinct do drop else elseif elsif enable end entry exception exception_init exchange exclusive exists external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base of off offline on online only option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw rebuild record ref references refresh rename replace resource restrict return returning returns reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work\",\n builtin: \"appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define echo editfile embedded feedback flagger flush heading headsep instance linesize lno loboffset logsource longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar repfooter repheader serveroutput shiftinout show showmode spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout timing trimout trimspool ttitle underline verify version wrap\",\n types: SQLTypes + \"ascii bfile bfilename bigserial bit blob dec long number nvarchar nvarchar2 serial smallint string text uid varchar2 xml\",\n operatorChars: \"*/+-%<>!=~\",\n doubleQuotedStrings: true,\n charSetCasts: true,\n plsqlQuotingMechanism: true\n});\n\nexport { Cassandra, MSSQL, MariaSQL, MySQL, PLSQL, PostgreSQL, SQLDialect, SQLite, StandardSQL, keywordCompletion, keywordCompletionSource, schemaCompletion, schemaCompletionSource, sql };\n"],"names":["whitespace","LineComment","BlockComment","String$1","Number","Bool","Null","ParenL","ParenR","BraceL","BraceR","BracketL","BracketR","Semi","Dot","Operator","Punctuation","SpecialVar","Identifier","QuotedIdentifier","Keyword","Type","Bits","Bytes","Builtin","isAlpha","ch","readLiteral","input","endQuote","backslashEscapes","escaped","next","advance","readWord","result","String","fromCharCode","readBits","readNumber","sawDot","eol","inString","str","i","length","charCodeAt","Space","keywords","types","builtin","Object","create","kw","split","tp","SQLTypes","SQLKeywords","defaults","hashComments","spaceAfterDashes","slashComments","doubleQuotedStrings","doubleDollarQuotedStrings","unquotedBitLiterals","treatBitsAsBytes","charSetCasts","plsqlQuotingMechanism","operatorChars","specialVar","identifierQuotes","words","tokensFor","d","_a","acceptToken","peek","readDoubleDollarLiteral","depth","cur","openDelim","matchingDelim","indexOf","closeDelim","readPLSQLQuotedLiteral","quoted","quote","readWordOrQuoted","word","toLowerCase","quoteStyle","tokens","parser$1","version","states","stateData","goto","nodeNames","maxTerm","skippedNodes","repeatNodeCount","tokenData","tokenizers","topRules","tokenPrec","tokenBefore","tree","cursor","moveTo","from","test","name","node","idName","doc","text","sliceString","to","exec","plainID","pathFor","id","path","firstChild","nextSibling","push","parentsFor","unshift","EndFrom","Set","Span","QuotedSpan","CompletionLevel","constructor","this","list","children","undefined","child","idQuote","nameCompletion","addCompletions","option","found","findIndex","o","label","type","apply","parser","configure","props","Statement","SQLDialect","dialect","language","spec","extension","static","kws","prop","hasOwnProperty","languageData","commentTokens","line","block","open","close","closeBrackets","brackets","keywordCompletionSource","upperCase","completions","keys","map","keyword","toUpperCase","boost","completeKeywords","keywordCompletion","data","of","autocomplete","schemaCompletionSource","config","schema","tables","schemas","defaultTableName","defaultSchemaName","top","defaultSchema","table","parts","replace","p","base","part","context","parents","empty","aliases","state","startPos","pos","resolveInner","at","statement","parent","scan","sawFrom","prevID","alias","has","getAliases","sourceContext","explicit","level","quoteAfter","sliceDoc","options","concat","c","assign","validFor","completeFromSchema","defaultTable","StandardSQL","schemaCompletion","sql","lang","upperCaseKeywords","define","PostgreSQL","MySQLKeywords","MySQLTypes","MySQLBuiltin","MySQL","MariaSQL","MSSQL","SQLite","Cassandra","PLSQL"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/7420.index.js b/book/_build/html/_static/7420.index.js new file mode 100644 index 0000000..49d52ed --- /dev/null +++ b/book/_build/html/_static/7420.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[7420],{77420:(e,t,n)=>{function $(e){return new RegExp("^(("+e.join(")|(")+"))\\b","i")}n.r(t),n.d(t,{mumps:()=>l});var a=new RegExp("^[\\+\\-\\*/&#!_?\\\\<>=\\'\\[\\]]"),o=new RegExp("^(('=)|(<=)|(>=)|('>)|('<)|([[)|(]])|(^$))"),r=new RegExp("^[\\.,:]"),c=new RegExp("[()]"),m=new RegExp("^[%A-Za-z][A-Za-z0-9]*"),s=$(["\\$ascii","\\$char","\\$data","\\$ecode","\\$estack","\\$etrap","\\$extract","\\$find","\\$fnumber","\\$get","\\$horolog","\\$io","\\$increment","\\$job","\\$justify","\\$length","\\$name","\\$next","\\$order","\\$piece","\\$qlength","\\$qsubscript","\\$query","\\$quit","\\$random","\\$reverse","\\$select","\\$stack","\\$test","\\$text","\\$translate","\\$view","\\$x","\\$y","\\$a","\\$c","\\$d","\\$e","\\$ec","\\$es","\\$et","\\$f","\\$fn","\\$g","\\$h","\\$i","\\$j","\\$l","\\$n","\\$na","\\$o","\\$p","\\$q","\\$ql","\\$qs","\\$r","\\$re","\\$s","\\$st","\\$t","\\$tr","\\$v","\\$z"]),i=$(["break","close","do","else","for","goto","halt","hang","if","job","kill","lock","merge","new","open","quit","read","set","tcommit","trollback","tstart","use","view","write","xecute","b","c","d","e","f","g","h","i","j","k","l","m","n","o","q","r","s","tc","tro","ts","u","v","w","x"]);const l={name:"mumps",startState:function(){return{label:!1,commandMode:0}},token:function(e,t){var n=function(e,t){e.sol()&&(t.label=!0,t.commandMode=0);var n=e.peek();return" "==n||"\t"==n?(t.label=!1,0==t.commandMode?t.commandMode=1:(t.commandMode<0||2==t.commandMode)&&(t.commandMode=0)):"."!=n&&t.commandMode>0&&(t.commandMode=":"==n?-1:2),"("!==n&&"\t"!==n||(t.label=!1),";"===n?(e.skipToEnd(),"comment"):e.match(/^[-+]?\d+(\.\d+)?([eE][-+]?\d+)?/)?"number":'"'==n?e.skipTo('"')?(e.next(),"string"):(e.skipToEnd(),"error"):e.match(o)||e.match(a)?"operator":e.match(r)?null:c.test(n)?(e.next(),"bracket"):t.commandMode>0&&e.match(i)?"controlKeyword":e.match(s)?"builtin":e.match(m)?"variable":"$"===n||"^"===n?(e.next(),"builtin"):"@"===n?(e.next(),"string.special"):/[\w%]/.test(n)?(e.eatWhile(/[\w%]/),"variable"):(e.next(),"error")}(e,t);return t.label?"tag":n}}}}]); +//# sourceMappingURL=7420.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/7420.index.js.map b/book/_build/html/_static/7420.index.js.map new file mode 100644 index 0000000..21a8d4b --- /dev/null +++ b/book/_build/html/_static/7420.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"7420.index.js","mappings":"+FAAA,SAASA,EAAWC,GAClB,OAAO,IAAIC,OAAO,MAAQD,EAAME,KAAK,OAAS,QAAS,IACzD,C,4BAEA,IAAIC,EAAkB,IAAIF,OAAO,sCAC7BG,EAAkB,IAAIH,OAAO,8CAC7BI,EAAmB,IAAIJ,OAAO,YAC9BK,EAAW,IAAIL,OAAO,QACtBM,EAAc,IAAIN,OAAO,0BAIzBO,EAAiBT,EADK,CAAC,WAAY,UAAW,UAAW,WAAY,YAAa,WAAY,aAAc,UAAW,aAAc,SAAU,aAAc,QAAS,eAAgB,SAAU,aAAc,YAAa,UAAW,UAAW,WAAY,WAAY,aAAc,gBAAiB,WAAY,UAAW,YAAa,aAAc,YAAa,WAAY,UAAW,UAAW,eAAgB,UAAW,OAAQ,OAAQ,OAAQ,OAAQ,OAAQ,OAAQ,QAAS,QAAS,QAAS,OAAQ,QAAS,OAAQ,OAAQ,OAAQ,OAAQ,OAAQ,OAAQ,QAAS,OAAQ,OAAQ,OAAQ,QAAS,QAAS,OAAQ,QAAS,OAAQ,QAAS,OAAQ,QAAS,OAAQ,SAE9pBU,EAAUV,EAJQ,CAAC,QAAQ,QAAQ,KAAK,OAAO,MAAM,OAAQ,OAAQ,OAAQ,KAAM,MAAM,OAAO,OAAO,QAAQ,MAAM,OAAQ,OAAQ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AAQC,GAC9B,OAAIA,EAAMJ,MAAc,MACjBK,CACT,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/mumps.js"],"sourcesContent":["function wordRegexp(words) {\n return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\", \"i\");\n}\n\nvar singleOperators = new RegExp(\"^[\\\\+\\\\-\\\\*/&#!_?\\\\\\\\<>=\\\\'\\\\[\\\\]]\");\nvar doubleOperators = new RegExp(\"^(('=)|(<=)|(>=)|('>)|('<)|([[)|(]])|(^$))\");\nvar singleDelimiters = new RegExp(\"^[\\\\.,:]\");\nvar brackets = new RegExp(\"[()]\");\nvar identifiers = new RegExp(\"^[%A-Za-z][A-Za-z0-9]*\");\nvar commandKeywords = [\"break\",\"close\",\"do\",\"else\",\"for\",\"goto\", \"halt\", \"hang\", \"if\", \"job\",\"kill\",\"lock\",\"merge\",\"new\",\"open\", \"quit\", \"read\", \"set\", \"tcommit\", \"trollback\", \"tstart\", \"use\", \"view\", \"write\", \"xecute\", \"b\",\"c\",\"d\",\"e\",\"f\",\"g\", \"h\", \"i\", \"j\",\"k\",\"l\",\"m\",\"n\",\"o\", \"q\", \"r\", \"s\", \"tc\", \"tro\", \"ts\", \"u\", \"v\", \"w\", \"x\"];\n// The following list includes intrinsic functions _and_ special variables\nvar intrinsicFuncsWords = [\"\\\\$ascii\", \"\\\\$char\", \"\\\\$data\", \"\\\\$ecode\", \"\\\\$estack\", \"\\\\$etrap\", \"\\\\$extract\", \"\\\\$find\", \"\\\\$fnumber\", \"\\\\$get\", \"\\\\$horolog\", \"\\\\$io\", \"\\\\$increment\", \"\\\\$job\", \"\\\\$justify\", \"\\\\$length\", \"\\\\$name\", \"\\\\$next\", \"\\\\$order\", \"\\\\$piece\", \"\\\\$qlength\", \"\\\\$qsubscript\", \"\\\\$query\", \"\\\\$quit\", \"\\\\$random\", \"\\\\$reverse\", \"\\\\$select\", \"\\\\$stack\", \"\\\\$test\", \"\\\\$text\", \"\\\\$translate\", \"\\\\$view\", \"\\\\$x\", \"\\\\$y\", \"\\\\$a\", \"\\\\$c\", \"\\\\$d\", \"\\\\$e\", \"\\\\$ec\", \"\\\\$es\", \"\\\\$et\", \"\\\\$f\", \"\\\\$fn\", \"\\\\$g\", \"\\\\$h\", \"\\\\$i\", \"\\\\$j\", \"\\\\$l\", \"\\\\$n\", \"\\\\$na\", \"\\\\$o\", \"\\\\$p\", \"\\\\$q\", \"\\\\$ql\", \"\\\\$qs\", \"\\\\$r\", \"\\\\$re\", \"\\\\$s\", \"\\\\$st\", \"\\\\$t\", \"\\\\$tr\", \"\\\\$v\", \"\\\\$z\"];\nvar intrinsicFuncs = wordRegexp(intrinsicFuncsWords);\nvar command = wordRegexp(commandKeywords);\n\nfunction tokenBase(stream, state) {\n if (stream.sol()) {\n state.label = true;\n state.commandMode = 0;\n }\n\n // The character has meaning in MUMPS. Ignoring consecutive\n // spaces would interfere with interpreting whether the next non-space\n // character belongs to the command or argument context.\n\n // Examine each character and update a mode variable whose interpretation is:\n // >0 => command 0 => argument <0 => command post-conditional\n var ch = stream.peek();\n\n if (ch == \" \" || ch == \"\\t\") { // Pre-process \n state.label = false;\n if (state.commandMode == 0)\n state.commandMode = 1;\n else if ((state.commandMode < 0) || (state.commandMode == 2))\n state.commandMode = 0;\n } else if ((ch != \".\") && (state.commandMode > 0)) {\n if (ch == \":\")\n state.commandMode = -1; // SIS - Command post-conditional\n else\n state.commandMode = 2;\n }\n\n // Do not color parameter list as line tag\n if ((ch === \"(\") || (ch === \"\\u0009\"))\n state.label = false;\n\n // MUMPS comment starts with \";\"\n if (ch === \";\") {\n stream.skipToEnd();\n return \"comment\";\n }\n\n // Number Literals // SIS/RLM - MUMPS permits canonic number followed by concatenate operator\n if (stream.match(/^[-+]?\\d+(\\.\\d+)?([eE][-+]?\\d+)?/))\n return \"number\";\n\n // Handle Strings\n if (ch == '\"') {\n if (stream.skipTo('\"')) {\n stream.next();\n return \"string\";\n } else {\n stream.skipToEnd();\n return \"error\";\n }\n }\n\n // Handle operators and Delimiters\n if (stream.match(doubleOperators) || stream.match(singleOperators))\n return \"operator\";\n\n // Prevents leading \".\" in DO block from falling through to error\n if (stream.match(singleDelimiters))\n return null;\n\n if (brackets.test(ch)) {\n stream.next();\n return \"bracket\";\n }\n\n if (state.commandMode > 0 && stream.match(command))\n return \"controlKeyword\";\n\n if (stream.match(intrinsicFuncs))\n return \"builtin\";\n\n if (stream.match(identifiers))\n return \"variable\";\n\n // Detect dollar-sign when not a documented intrinsic function\n // \"^\" may introduce a GVN or SSVN - Color same as function\n if (ch === \"$\" || ch === \"^\") {\n stream.next();\n return \"builtin\";\n }\n\n // MUMPS Indirection\n if (ch === \"@\") {\n stream.next();\n return \"string.special\";\n }\n\n if (/[\\w%]/.test(ch)) {\n stream.eatWhile(/[\\w%]/);\n return \"variable\";\n }\n\n // Handle non-detected items\n stream.next();\n return \"error\";\n}\n\nexport const mumps = {\n name: \"mumps\",\n startState: function() {\n return {\n label: false,\n commandMode: 0\n };\n },\n\n token: function(stream, state) {\n var style = tokenBase(stream, state);\n if (state.label) return \"tag\";\n return style;\n }\n};\n"],"names":["wordRegexp","words","RegExp","join","singleOperators","doubleOperators","singleDelimiters","brackets","identifiers","intrinsicFuncs","command","mumps","name","startState","label","commandMode","token","stream","state","style","sol","ch","peek","skipToEnd","match","skipTo","next","test","eatWhile","tokenBase"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/7471.index.js b/book/_build/html/_static/7471.index.js new file mode 100644 index 0000000..4997d65 --- /dev/null +++ b/book/_build/html/_static/7471.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[7471],{57471:(e,n,t)=>{function r(e){for(var n={},t=e.split(" "),r=0;rs});var i=r("if elsif else stop require"),u=r("true false not");function o(e,n){var t,r=e.next();if("/"==r&&e.eat("*"))return n.tokenize=a,a(e,n);if("#"===r)return e.skipToEnd(),"comment";if('"'==r)return n.tokenize=(t=r,function(e,n){for(var r,i=!1;null!=(r=e.next())&&(r!=t||i);)i=!i&&"\\"==r;return i||(n.tokenize=o),"string"}),n.tokenize(e,n);if("("==r)return n._indent.push("("),n._indent.push("{"),null;if("{"===r)return n._indent.push("{"),null;if(")"==r&&(n._indent.pop(),n._indent.pop()),"}"===r)return n._indent.pop(),null;if(","==r)return null;if(";"==r)return null;if(/[{}\(\),;]/.test(r))return null;if(/\d/.test(r))return e.eatWhile(/[\d]/),e.eat(/[KkMmGg]/),"number";if(":"==r)return e.eatWhile(/[a-zA-Z_]/),e.eatWhile(/[a-zA-Z0-9_]/),"operator";e.eatWhile(/\w/);var s=e.current();return"text"==s&&e.eat(":")?(n.tokenize=l,"string"):i.propertyIsEnumerable(s)?"keyword":u.propertyIsEnumerable(s)?"atom":null}function l(e,n){return n._multiLineString=!0,e.sol()?("."==e.next()&&e.eol()&&(n._multiLineString=!1,n.tokenize=o),"string"):(e.eatSpace(),"#"==e.peek()?(e.skipToEnd(),"comment"):(e.skipToEnd(),"string"))}function a(e,n){for(var t,r=!1;null!=(t=e.next());){if(r&&"/"==t){n.tokenize=o;break}r="*"==t}return"comment"}const s={name:"sieve",startState:function(e){return{tokenize:o,baseIndent:e||0,_indent:[]}},token:function(e,n){return e.eatSpace()?null:(n.tokenize||o)(e,n)},indent:function(e,n,t){var r=e._indent.length;return n&&"}"==n[0]&&r--,r<0&&(r=0),r*t.unit},languageData:{indentOnInput:/^\s*\}$/}}}}]); +//# sourceMappingURL=7471.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/7471.index.js.map b/book/_build/html/_static/7471.index.js.map new file mode 100644 index 0000000..ac37d36 --- /dev/null +++ b/book/_build/html/_static/7471.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"7471.index.js","mappings":"+FAAA,SAASA,EAAMC,GAEb,IADA,IAAIC,EAAM,CAAC,EAAGF,EAAQC,EAAIE,MAAM,KACvBC,EAAI,EAAGA,EAAIJ,EAAMK,SAAUD,EAAGF,EAAIF,EAA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CAEA,SAASE,EAAqBjB,EAAQC,GAIpC,OAFAA,EAAMkB,kBAAmB,EAEpBnB,EAAOoB,OAYU,KAAjBpB,EAAOI,QAAoBJ,EAAOqB,QAErCpB,EAAMkB,kBAAmB,EACzBlB,EAAMK,SAAWP,GAGZ,WAjBLC,EAAOsB,WAEc,KAAjBtB,EAAOuB,QACTvB,EAAOQ,YACA,YAGTR,EAAOQ,YACA,UAUX,CAEA,SAASD,EAAcP,EAAQC,GAE7B,IADA,IAAsBE,EAAlBqB,GAAW,EACgB,OAAvBrB,EAAKH,EAAOI,SAAiB,CACnC,GAAIoB,GAAkB,KAANrB,EAAW,CACzBF,EAAMK,SAAWP,EACjB,KACF,CACAyB,EAAkB,KAANrB,CACd,CACA,MAAO,SACT,CAeO,MAAMsB,EAAQ,CACnBC,KAAM,QACNC,WAAY,SAASC,GACnB,MAAO,CAACtB,SAAUP,EACV8B,WAAYD,GAAQ,EACpBlB,QAAS,GACnB,EAEAoB,MAAO,SAAS9B,EAAQC,GACtB,OAAID,EAAOsB,WACF,MAEDrB,EAAMK,UAAYP,GAAWC,EAAQC,EAC/C,EAEA8B,OAAQ,SAAS9B,EAAO+B,EAAYC,GAClC,IAAIrC,EAASK,EAAMS,QAAQd,OAO3B,OANIoC,GAAgC,KAAjBA,EAAW,IAC5BpC,IAEEA,EAAQ,IACVA,EAAS,GAEJA,EAASqC,EAAGC,IACrB,EAEAC,aAAc,CACZC,cAAe,W","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/sieve.js"],"sourcesContent":["function words(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n}\n\nvar keywords = words(\"if elsif else stop require\");\nvar atoms = words(\"true false not\");\n\nfunction tokenBase(stream, state) {\n\n var ch = stream.next();\n if (ch == \"/\" && stream.eat(\"*\")) {\n state.tokenize = tokenCComment;\n return tokenCComment(stream, state);\n }\n\n if (ch === '#') {\n stream.skipToEnd();\n return \"comment\";\n }\n\n if (ch == \"\\\"\") {\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n }\n\n if (ch == \"(\") {\n state._indent.push(\"(\");\n // add virtual angel wings so that editor behaves...\n // ...more sane incase of broken brackets\n state._indent.push(\"{\");\n return null;\n }\n\n if (ch === \"{\") {\n state._indent.push(\"{\");\n return null;\n }\n\n if (ch == \")\") {\n state._indent.pop();\n state._indent.pop();\n }\n\n if (ch === \"}\") {\n state._indent.pop();\n return null;\n }\n\n if (ch == \",\")\n return null;\n\n if (ch == \";\")\n return null;\n\n\n if (/[{}\\(\\),;]/.test(ch))\n return null;\n\n // 1*DIGIT \"K\" / \"M\" / \"G\"\n if (/\\d/.test(ch)) {\n stream.eatWhile(/[\\d]/);\n stream.eat(/[KkMmGg]/);\n return \"number\";\n }\n\n // \":\" (ALPHA / \"_\") *(ALPHA / DIGIT / \"_\")\n if (ch == \":\") {\n stream.eatWhile(/[a-zA-Z_]/);\n stream.eatWhile(/[a-zA-Z0-9_]/);\n\n return \"operator\";\n }\n\n stream.eatWhile(/\\w/);\n var cur = stream.current();\n\n // \"text:\" *(SP / HTAB) (hash-comment / CRLF)\n // *(multiline-literal / multiline-dotstart)\n // \".\" CRLF\n if ((cur == \"text\") && stream.eat(\":\"))\n {\n state.tokenize = tokenMultiLineString;\n return \"string\";\n }\n\n if (keywords.propertyIsEnumerable(cur))\n return \"keyword\";\n\n if (atoms.propertyIsEnumerable(cur))\n return \"atom\";\n\n return null;\n}\n\nfunction tokenMultiLineString(stream, state)\n{\n state._multiLineString = true;\n // the first line is special it may contain a comment\n if (!stream.sol()) {\n stream.eatSpace();\n\n if (stream.peek() == \"#\") {\n stream.skipToEnd();\n return \"comment\";\n }\n\n stream.skipToEnd();\n return \"string\";\n }\n\n if ((stream.next() == \".\") && (stream.eol()))\n {\n state._multiLineString = false;\n state.tokenize = tokenBase;\n }\n\n return \"string\";\n}\n\nfunction tokenCComment(stream, state) {\n var maybeEnd = false, ch;\n while ((ch = stream.next()) != null) {\n if (maybeEnd && ch == \"/\") {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return \"comment\";\n}\n\nfunction tokenString(quote) {\n return function(stream, state) {\n var escaped = false, ch;\n while ((ch = stream.next()) != null) {\n if (ch == quote && !escaped)\n break;\n escaped = !escaped && ch == \"\\\\\";\n }\n if (!escaped) state.tokenize = tokenBase;\n return \"string\";\n };\n}\n\nexport const sieve = {\n name: \"sieve\",\n startState: function(base) {\n return {tokenize: tokenBase,\n baseIndent: base || 0,\n _indent: []};\n },\n\n token: function(stream, state) {\n if (stream.eatSpace())\n return null;\n\n return (state.tokenize || tokenBase)(stream, state);\n },\n\n indent: function(state, _textAfter, cx) {\n var length = state._indent.length;\n if (_textAfter && (_textAfter[0] == \"}\"))\n length--;\n\n if (length <0)\n length = 0;\n\n return length * cx.unit;\n },\n\n languageData: {\n indentOnInput: /^\\s*\\}$/\n }\n};\n"],"names":["words","str","obj","split","i","length","keywords","atoms","tokenBase","stream","state","quote","ch","next","eat","tokenize","tokenCComment","skipToEnd","escaped","_indent","push","pop","test","eatWhile","cur","current","tokenMultiLineString","propertyIsEnumerable","_multiLineString","sol","eol","eatSpace","peek","maybeEnd","sieve","name","startState","base","baseIndent","token","indent","_textAfter","cx","unit","languageData","indentOnInput"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/7543.index.js b/book/_build/html/_static/7543.index.js new file mode 100644 index 0000000..8bf2368 --- /dev/null +++ b/book/_build/html/_static/7543.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[7543],{77543:(e,t,n)=>{function r(e,t,n){return t(n),n(e,t)}n.r(t),n.d(t,{elm:()=>b});var i=/[a-z]/,o=/[A-Z]/,a=/[a-zA-Z0-9_]/,u=/[0-9]/,f=/[0-9A-Fa-f]/,s=/[-&*+.\\/<>=?^|:]/,l=/[(),[\]{}]/,c=/[ \v\f]/;function p(){return function(e,t){if(e.eatWhile(c))return null;var n=e.next();if(l.test(n))return"{"===n&&e.eat("-")?r(e,t,h(1)):"["===n&&e.match("glsl|")?r(e,t,g):"builtin";if("'"===n)return r(e,t,x);if('"'===n)return e.eat('"')?e.eat('"')?r(e,t,k):"string":r(e,t,m);if(o.test(n))return e.eatWhile(a),"type";if(i.test(n)){var p=1===e.pos;return e.eatWhile(a),p?"def":"variable"}if(u.test(n)){if("0"===n){if(e.eat(/[xX]/))return e.eatWhile(f),"number"}else e.eatWhile(u);return e.eat(".")&&e.eatWhile(u),e.eat(/[eE]/)&&(e.eat(/[-+]/),e.eatWhile(u)),"number"}return s.test(n)?"-"===n&&e.eat("-")?(e.skipToEnd(),"comment"):(e.eatWhile(s),"keyword"):"_"===n?"keyword":"error"}}function h(e){return 0==e?p():function(t,n){for(;!t.eol();){var r=t.next();if("{"==r&&t.eat("-"))++e;else if("-"==r&&t.eat("}")&&0==--e)return n(p()),"comment"}return n(h(e)),"comment"}}function k(e,t){for(;!e.eol();)if('"'===e.next()&&e.eat('"')&&e.eat('"'))return t(p()),"string";return"string"}function m(e,t){for(;e.skipTo('\\"');)e.next(),e.next();return e.skipTo('"')?(e.next(),t(p()),"string"):(e.skipToEnd(),t(p()),"error")}function x(e,t){for(;e.skipTo("\\'");)e.next(),e.next();return e.skipTo("'")?(e.next(),t(p()),"string"):(e.skipToEnd(),t(p()),"error")}function g(e,t){for(;!e.eol();)if("|"===e.next()&&e.eat("]"))return t(p()),"string";return"string"}var d={case:1,of:1,as:1,if:1,then:1,else:1,let:1,in:1,type:1,alias:1,module:1,where:1,import:1,exposing:1,port:1};const b={name:"elm",startState:function(){return{f:p()}},copyState:function(e){return{f:e.f}},token:function(e,t){var n=t.f(e,(function(e){t.f=e})),r=e.current();return d.hasOwnProperty(r)?"keyword":n},languageData:{commentTokens:{line:"--"}}}}}]); +//# sourceMappingURL=7543.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/7543.index.js.map b/book/_build/html/_static/7543.index.js.map new file mode 100644 index 0000000..94d0b99 --- /dev/null +++ b/book/_build/html/_static/7543.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"7543.index.js","mappings":"+FAAA,SAASA,EAAYC,EAAQC,EAAUC,GAGrC,OADAD,EAASC,GACFA,EAAEF,EAAQC,EACnB,C,0BAEA,IAAIE,EAAU,QACVC,EAAU,QACVC,EAAU,eAEVC,EAAU,QACVC,EAAQ,cACRC,EAAW,oBACXC,EAAY,aACZC,EAAW,UAEf,SAASC,IAEP,OAAO,SAASX,EAAQC,GAEtB,GAAID,EAAOY,SAASF,GAElB,OAAO,KAGT,IAAIG,EAAOb,EAAOc,OAElB,GAAIL,EAAUM,KAAKF,GAEjB,MAAiB,MAATA,GAAgBb,EAAOgB,IAAI,KAC/BjB,EAAYC,EAAQC,EAAUgB,EAAkB,IACtC,MAATJ,GAAgBb,EAAOkB,MAAM,SAC9BnB,EAAYC,EAAQC,EAAUkB,GAC9B,UAGN,GAAa,MAATN,EAEF,OAAOd,EAAYC,EAAQC,EAAUmB,GAGvC,GAAa,MAATP,EAEF,OAAOb,EAAOgB,IAAI,KACdhB,EAAOgB,IAAI,KACXjB,EAAYC,EAAQC,EAAUoB,GAC9B,SACFtB,EAAYC,EAAQC,EAAUqB,GAGlC,GAAIlB,EAAQW,KAAKF,GAGf,OADAb,EAAOY,SAASP,GACT,OAGT,GAAIF,EAAQY,KAAKF,GACjB,CACE,IAAIU,EAAuB,IAAfvB,EAAOwB,IAEnB,OADAxB,EAAOY,SAASP,GACTkB,EAAQ,MAAQ,UACzB,CAEA,GAAIjB,EAAQS,KAAKF,GACjB,CACE,GAAa,MAATA,GAEF,GAAIb,EAAOgB,IAAI,QAGb,OADAhB,EAAOY,SAASL,GACT,cAKTP,EAAOY,SAASN,GAWlB,OATIN,EAAOgB,IAAI,MAEbhB,EAAOY,SAASN,GAEdN,EAAOgB,IAAI,UAEbhB,EAAOgB,IAAI,QACXhB,EAAOY,SAASN,IAEX,QACT,CAEA,OAAIE,EAASO,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,EACPC,OAAQ,EACRC,MAAO,EACPC,OAAQ,EACRC,SAAU,EACVC,KAAM,GAGD,MAAMC,EAAM,CACjBC,KAAM,MACNC,WAAY,WAAe,MAAO,CAAE7C,EAAGS,IAAY,EACnDqC,UAAY,SAAUC,GAAK,MAAO,CAAE/C,EAAG+C,EAAE/C,EAAK,EAE9CgD,MAAO,SAASC,EAAQC,GACtB,IAAId,EAAOc,EAAMlD,EAAEiD,GAAQ,SAASF,GAAKG,EAAMlD,EAAI+C,CAAG,IAClDI,EAAOF,EAAOG,UAClB,OAAQzB,EAAe0B,eAAeF,GAAS,UAAYf,CAC7D,EAEAkB,aAAc,CACZC,cAAe,CAACC,KAAM,O","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/elm.js"],"sourcesContent":["function switchState(source, setState, f)\n{\n setState(f);\n return f(source, setState);\n}\n\nvar lowerRE = /[a-z]/;\nvar upperRE = /[A-Z]/;\nvar innerRE = /[a-zA-Z0-9_]/;\n\nvar digitRE = /[0-9]/;\nvar hexRE = /[0-9A-Fa-f]/;\nvar symbolRE = /[-&*+.\\\\/<>=?^|:]/;\nvar specialRE = /[(),[\\]{}]/;\nvar spacesRE = /[ \\v\\f]/; // newlines are handled in tokenizer\n\nfunction normal()\n{\n return function(source, setState)\n {\n if (source.eatWhile(spacesRE))\n {\n return null;\n }\n\n var char = source.next();\n\n if (specialRE.test(char))\n {\n return (char === '{' && source.eat('-'))\n ? switchState(source, setState, chompMultiComment(1))\n : (char === '[' && source.match('glsl|'))\n ? switchState(source, setState, chompGlsl)\n : 'builtin';\n }\n\n if (char === '\\'')\n {\n return switchState(source, setState, chompChar);\n }\n\n if (char === '\"')\n {\n return source.eat('\"')\n ? source.eat('\"')\n ? switchState(source, setState, chompMultiString)\n : 'string'\n : switchState(source, setState, chompSingleString);\n }\n\n if (upperRE.test(char))\n {\n source.eatWhile(innerRE);\n return 'type';\n }\n\n if (lowerRE.test(char))\n {\n var isDef = source.pos === 1;\n source.eatWhile(innerRE);\n return isDef ? \"def\" : \"variable\";\n }\n\n if (digitRE.test(char))\n {\n if (char === '0')\n {\n if (source.eat(/[xX]/))\n {\n source.eatWhile(hexRE); // should require at least 1\n return \"number\";\n }\n }\n else\n {\n source.eatWhile(digitRE);\n }\n if (source.eat('.'))\n {\n source.eatWhile(digitRE); // should require at least 1\n }\n if (source.eat(/[eE]/))\n {\n source.eat(/[-+]/);\n source.eatWhile(digitRE); // should require at least 1\n }\n return \"number\";\n }\n\n if (symbolRE.test(char))\n {\n if (char === '-' && source.eat('-'))\n {\n source.skipToEnd();\n return \"comment\";\n }\n source.eatWhile(symbolRE);\n return \"keyword\";\n }\n\n if (char === '_')\n {\n return \"keyword\";\n }\n\n return \"error\";\n }\n}\n\nfunction chompMultiComment(nest)\n{\n if (nest == 0)\n {\n return normal();\n }\n return function(source, setState)\n {\n while (!source.eol())\n {\n var char = source.next();\n if (char == '{' && source.eat('-'))\n {\n ++nest;\n }\n else if (char == '-' && source.eat('}'))\n {\n --nest;\n if (nest === 0)\n {\n setState(normal());\n return 'comment';\n }\n }\n }\n setState(chompMultiComment(nest));\n return 'comment';\n }\n}\n\nfunction chompMultiString(source, setState)\n{\n while (!source.eol())\n {\n var char = source.next();\n if (char === '\"' && source.eat('\"') && source.eat('\"'))\n {\n setState(normal());\n return 'string';\n }\n }\n return 'string';\n}\n\nfunction chompSingleString(source, setState)\n{\n while (source.skipTo('\\\\\"')) { source.next(); source.next(); }\n if (source.skipTo('\"'))\n {\n source.next();\n setState(normal());\n return 'string';\n }\n source.skipToEnd();\n setState(normal());\n return 'error';\n}\n\nfunction chompChar(source, setState)\n{\n while (source.skipTo(\"\\\\'\")) { source.next(); source.next(); }\n if (source.skipTo(\"'\"))\n {\n source.next();\n setState(normal());\n return 'string';\n }\n source.skipToEnd();\n setState(normal());\n return 'error';\n}\n\nfunction chompGlsl(source, setState)\n{\n while (!source.eol())\n {\n var char = source.next();\n if (char === '|' && source.eat(']'))\n {\n setState(normal());\n return 'string';\n }\n }\n return 'string';\n}\n\nvar wellKnownWords = {\n case: 1,\n of: 1,\n as: 1,\n if: 1,\n then: 1,\n else: 1,\n let: 1,\n in: 1,\n type: 1,\n alias: 1,\n module: 1,\n where: 1,\n import: 1,\n exposing: 1,\n port: 1\n};\n\nexport const elm = {\n name: \"elm\",\n startState: function () { return { f: normal() }; },\n copyState: function (s) { return { f: s.f }; },\n\n token: function(stream, state) {\n var type = state.f(stream, function(s) { state.f = s; });\n var word = stream.current();\n return (wellKnownWords.hasOwnProperty(word)) ? 'keyword' : type;\n },\n\n languageData: {\n commentTokens: {line: \"--\"}\n }\n};\n"],"names":["switchState","source","setState","f","lowerRE","upperRE","innerRE","digitRE","hexRE","symbolRE","specialRE","spacesRE","normal","eatWhile","char","next","test","eat","chompMultiComment","match","chompGlsl","chompChar","chompMultiString","chompSingleString","isDef","pos","skipToEnd","nest","eol","skipTo","wellKnownWords","case","of","as","if","then","else","let","in","type","alias","module","where","import","exposing","port","elm","name","startState","copyState","s","token","stream","state","word","current","hasOwnProperty","languageData","commentTokens","line"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/7561.index.js b/book/_build/html/_static/7561.index.js new file mode 100644 index 0000000..4abb593 --- /dev/null +++ b/book/_build/html/_static/7561.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[7561],{87561:(e,t,a)=>{a.r(t),a.d(t,{asterisk:()=>o});var n=["exten","same","include","ignorepat","switch"],i=["#include","#exec"],r=["addqueuemember","adsiprog","aelsub","agentlogin","agentmonitoroutgoing","agi","alarmreceiver","amd","answer","authenticate","background","backgrounddetect","bridge","busy","callcompletioncancel","callcompletionrequest","celgenuserevent","changemonitor","chanisavail","channelredirect","chanspy","clearhash","confbridge","congestion","continuewhile","controlplayback","dahdiacceptr2call","dahdibarge","dahdiras","dahdiscan","dahdisendcallreroutingfacility","dahdisendkeypadfacility","datetime","dbdel","dbdeltree","deadagi","dial","dictate","directory","disa","dumpchan","eagi","echo","endwhile","exec","execif","execiftime","exitwhile","extenspy","externalivr","festival","flash","followme","forkcdr","getcpeid","gosub","gosubif","goto","gotoif","gotoiftime","hangup","iax2provision","ices","importvar","incomplete","ivrdemo","jabberjoin","jabberleave","jabbersend","jabbersendgroup","jabberstatus","jack","log","macro","macroexclusive","macroexit","macroif","mailboxexists","meetme","meetmeadmin","meetmechanneladmin","meetmecount","milliwatt","minivmaccmess","minivmdelete","minivmgreet","minivmmwi","minivmnotify","minivmrecord","mixmonitor","monitor","morsecode","mp3player","mset","musiconhold","nbscat","nocdr","noop","odbc","odbc","odbcfinish","originate","ospauth","ospfinish","osplookup","ospnext","page","park","parkandannounce","parkedcall","pausemonitor","pausequeuemember","pickup","pickupchan","playback","playtones","privacymanager","proceeding","progress","queue","queuelog","raiseexception","read","readexten","readfile","receivefax","receivefax","receivefax","record","removequeuemember","resetcdr","retrydial","return","ringing","sayalpha","saycountedadj","saycountednoun","saycountpl","saydigits","saynumber","sayphonetic","sayunixtime","senddtmf","sendfax","sendfax","sendfax","sendimage","sendtext","sendurl","set","setamaflags","setcallerpres","setmusiconhold","sipaddheader","sipdtmfmode","sipremoveheader","skel","slastation","slatrunk","sms","softhangup","speechactivategrammar","speechbackground","speechcreate","speechdeactivategrammar","speechdestroy","speechloadgrammar","speechprocessingsound","speechstart","speechunloadgrammar","stackpop","startmusiconhold","stopmixmonitor","stopmonitor","stopmusiconhold","stopplaytones","system","testclient","testserver","transfer","tryexec","trysystem","unpausemonitor","unpausequeuemember","userevent","verbose","vmauthenticate","vmsayname","voicemail","voicemailmain","wait","waitexten","waitfornoise","waitforring","waitforsilence","waitmusiconhold","waituntil","while","zapateller"];const o={name:"asterisk",startState:function(){return{blockComment:!1,extenStart:!1,extenSame:!1,extenInclude:!1,extenExten:!1,extenPriority:!1,extenApplication:!1}},token:function(e,t){var a="";return e.eatSpace()?null:t.extenStart?(e.eatWhile(/[^\s]/),a=e.current(),/^=>?$/.test(a)?(t.extenExten=!0,t.extenStart=!1,"strong"):(t.extenStart=!1,e.skipToEnd(),"error")):t.extenExten?(t.extenExten=!1,t.extenPriority=!0,e.eatWhile(/[^,]/),t.extenInclude&&(e.skipToEnd(),t.extenPriority=!1,t.extenInclude=!1),t.extenSame&&(t.extenPriority=!1,t.extenSame=!1,t.extenApplication=!0),"tag"):t.extenPriority?(t.extenPriority=!1,t.extenApplication=!0,e.next(),t.extenSame?null:(e.eatWhile(/[^,]/),"number")):t.extenApplication?(e.eatWhile(/,/),","===(a=e.current())?null:(e.eatWhile(/\w/),a=e.current().toLowerCase(),t.extenApplication=!1,-1!==r.indexOf(a)?"def":null)):function(e,t){var a="",r=e.next();if(t.blockComment)return"-"==r&&e.match("-;",!0)?t.blockComment=!1:e.skipTo("--;")?(e.next(),e.next(),e.next(),t.blockComment=!1):e.skipToEnd(),"comment";if(";"==r)return e.match("--",!0)&&!e.match("-",!1)?(t.blockComment=!0,"comment"):(e.skipToEnd(),"comment");if("["==r)return e.skipTo("]"),e.eat("]"),"header";if('"'==r)return e.skipTo('"'),"string";if("'"==r)return e.skipTo("'"),"string.special";if("#"==r&&(e.eatWhile(/\w/),a=e.current(),-1!==i.indexOf(a)))return e.skipToEnd(),"strong";if("$"==r&&"{"==e.peek())return e.skipTo("}"),e.eat("}"),"variableName.special";if(e.eatWhile(/\w/),a=e.current(),-1!==n.indexOf(a)){switch(t.extenStart=!0,a){case"same":t.extenSame=!0;break;case"include":case"switch":case"ignorepat":t.extenInclude=!0}return"atom"}}(e,t)},languageData:{commentTokens:{line:";",block:{open:";--",close:"--;"}}}}}}]); +//# sourceMappingURL=7561.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/7561.index.js.map b/book/_build/html/_static/7561.index.js.map new file mode 100644 index 0000000..697f568 --- /dev/null +++ b/book/_build/html/_static/7561.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"7561.index.js","mappings":"8HAAA,IAAIA,EAAW,CAAC,QAAS,OAAQ,UAAU,YAAY,UACnDC,EAA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Q,OACPR,EAAOQ,OACPP,EAAMT,cAAe,GAErBQ,EAAOO,YAEF,UAET,GAAS,KAANI,EACD,OAAIX,EAAOY,MAAM,MAAM,KAChBZ,EAAOY,MAAM,KAAK,IACrBX,EAAMT,cAAe,EACd,YAGXQ,EAAOO,YACA,WAGT,GAAS,KAANI,EAGD,OAFAX,EAAOa,OAAO,KACdb,EAAOc,IAAI,KACJ,SAGT,GAAS,KAANH,EAED,OADAX,EAAOa,OAAO,KACP,SAET,GAAS,KAANF,EAED,OADAX,EAAOa,OAAO,KACP,iBAGT,GAAS,KAANF,IACDX,EAAOI,SAAS,MAChBF,EAAMF,EAAOK,WACc,IAAxBlB,EAAMuB,QAAQR,IAEf,OADAF,EAAOO,YACA,SAIX,GAAS,KAANI,GAES,KADAX,EAAOe,OAIf,OAFAf,EAAOa,OAAO,KACdb,EAAOc,IAAI,KACJ,uBAMX,GAFAd,EAAOI,SAAS,MAChBF,EAAMF,EAAOK,WACc,IAAxBnB,EAAMwB,QAAQR,GAAa,CAE5B,OADAD,EAAMR,YAAa,EACZS,GACP,IAAK,OAAQD,EAAMP,WAAY,EAAM,MACrC,IAAK,UACL,IAAK,SACL,IAAK,YACHO,EAAMN,cAAe,EAGvB,MAAO,MACT,CACF,CAkEaqB,CAAWhB,EAAOC,EAI7B,EAEAgB,aAAc,CACZC,cAAe,CAACC,KAAM,IAAKC,MAAO,CAACC,KAAM,MAAOC,MAAO,S","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/asterisk.js"],"sourcesContent":["var atoms = [\"exten\", \"same\", \"include\",\"ignorepat\",\"switch\"],\n dpcmd = [\"#include\",\"#exec\"],\n apps = [\n \"addqueuemember\",\"adsiprog\",\"aelsub\",\"agentlogin\",\"agentmonitoroutgoing\",\"agi\",\n \"alarmreceiver\",\"amd\",\"answer\",\"authenticate\",\"background\",\"backgrounddetect\",\n \"bridge\",\"busy\",\"callcompletioncancel\",\"callcompletionrequest\",\"celgenuserevent\",\n \"changemonitor\",\"chanisavail\",\"channelredirect\",\"chanspy\",\"clearhash\",\"confbridge\",\n \"congestion\",\"continuewhile\",\"controlplayback\",\"dahdiacceptr2call\",\"dahdibarge\",\n \"dahdiras\",\"dahdiscan\",\"dahdisendcallreroutingfacility\",\"dahdisendkeypadfacility\",\n \"datetime\",\"dbdel\",\"dbdeltree\",\"deadagi\",\"dial\",\"dictate\",\"directory\",\"disa\",\n \"dumpchan\",\"eagi\",\"echo\",\"endwhile\",\"exec\",\"execif\",\"execiftime\",\"exitwhile\",\"extenspy\",\n \"externalivr\",\"festival\",\"flash\",\"followme\",\"forkcdr\",\"getcpeid\",\"gosub\",\"gosubif\",\n \"goto\",\"gotoif\",\"gotoiftime\",\"hangup\",\"iax2provision\",\"ices\",\"importvar\",\"incomplete\",\n \"ivrdemo\",\"jabberjoin\",\"jabberleave\",\"jabbersend\",\"jabbersendgroup\",\"jabberstatus\",\n \"jack\",\"log\",\"macro\",\"macroexclusive\",\"macroexit\",\"macroif\",\"mailboxexists\",\"meetme\",\n \"meetmeadmin\",\"meetmechanneladmin\",\"meetmecount\",\"milliwatt\",\"minivmaccmess\",\"minivmdelete\",\n \"minivmgreet\",\"minivmmwi\",\"minivmnotify\",\"minivmrecord\",\"mixmonitor\",\"monitor\",\"morsecode\",\n \"mp3player\",\"mset\",\"musiconhold\",\"nbscat\",\"nocdr\",\"noop\",\"odbc\",\"odbc\",\"odbcfinish\",\n \"originate\",\"ospauth\",\"ospfinish\",\"osplookup\",\"ospnext\",\"page\",\"park\",\"parkandannounce\",\n \"parkedcall\",\"pausemonitor\",\"pausequeuemember\",\"pickup\",\"pickupchan\",\"playback\",\"playtones\",\n \"privacymanager\",\"proceeding\",\"progress\",\"queue\",\"queuelog\",\"raiseexception\",\"read\",\"readexten\",\n \"readfile\",\"receivefax\",\"receivefax\",\"receivefax\",\"record\",\"removequeuemember\",\n \"resetcdr\",\"retrydial\",\"return\",\"ringing\",\"sayalpha\",\"saycountedadj\",\"saycountednoun\",\n \"saycountpl\",\"saydigits\",\"saynumber\",\"sayphonetic\",\"sayunixtime\",\"senddtmf\",\"sendfax\",\n \"sendfax\",\"sendfax\",\"sendimage\",\"sendtext\",\"sendurl\",\"set\",\"setamaflags\",\n \"setcallerpres\",\"setmusiconhold\",\"sipaddheader\",\"sipdtmfmode\",\"sipremoveheader\",\"skel\",\n \"slastation\",\"slatrunk\",\"sms\",\"softhangup\",\"speechactivategrammar\",\"speechbackground\",\n \"speechcreate\",\"speechdeactivategrammar\",\"speechdestroy\",\"speechloadgrammar\",\"speechprocessingsound\",\n \"speechstart\",\"speechunloadgrammar\",\"stackpop\",\"startmusiconhold\",\"stopmixmonitor\",\"stopmonitor\",\n \"stopmusiconhold\",\"stopplaytones\",\"system\",\"testclient\",\"testserver\",\"transfer\",\"tryexec\",\n \"trysystem\",\"unpausemonitor\",\"unpausequeuemember\",\"userevent\",\"verbose\",\"vmauthenticate\",\n \"vmsayname\",\"voicemail\",\"voicemailmain\",\"wait\",\"waitexten\",\"waitfornoise\",\"waitforring\",\n \"waitforsilence\",\"waitmusiconhold\",\"waituntil\",\"while\",\"zapateller\"\n ];\n\nfunction basicToken(stream,state){\n var cur = '';\n var ch = stream.next();\n // comment\n if (state.blockComment) {\n if (ch == \"-\" && stream.match(\"-;\", true)) {\n state.blockComment = false;\n } else if (stream.skipTo(\"--;\")) {\n stream.next();\n stream.next();\n stream.next();\n state.blockComment = false;\n } else {\n stream.skipToEnd();\n }\n return \"comment\";\n }\n if(ch == \";\") {\n if (stream.match(\"--\", true)) {\n if (!stream.match(\"-\", false)) { // Except ;--- is not a block comment\n state.blockComment = true;\n return \"comment\";\n }\n }\n stream.skipToEnd();\n return \"comment\";\n }\n // context\n if(ch == '[') {\n stream.skipTo(']');\n stream.eat(']');\n return \"header\";\n }\n // string\n if(ch == '\"') {\n stream.skipTo('\"');\n return \"string\";\n }\n if(ch == \"'\") {\n stream.skipTo(\"'\");\n return \"string.special\";\n }\n // dialplan commands\n if(ch == '#') {\n stream.eatWhile(/\\w/);\n cur = stream.current();\n if(dpcmd.indexOf(cur) !== -1) {\n stream.skipToEnd();\n return \"strong\";\n }\n }\n // application args\n if(ch == '$'){\n var ch1 = stream.peek();\n if(ch1 == '{'){\n stream.skipTo('}');\n stream.eat('}');\n return \"variableName.special\";\n }\n }\n // extension\n stream.eatWhile(/\\w/);\n cur = stream.current();\n if(atoms.indexOf(cur) !== -1) {\n state.extenStart = true;\n switch(cur) {\n case 'same': state.extenSame = true; break;\n case 'include':\n case 'switch':\n case 'ignorepat':\n state.extenInclude = true;break;\n default:break;\n }\n return \"atom\";\n }\n}\n\nexport const asterisk = {\n name: \"asterisk\",\n startState: function() {\n return {\n blockComment: false,\n extenStart: false,\n extenSame: false,\n extenInclude: false,\n extenExten: false,\n extenPriority: false,\n extenApplication: false\n };\n },\n token: function(stream, state) {\n\n var cur = '';\n if(stream.eatSpace()) return null;\n // extension started\n if(state.extenStart){\n stream.eatWhile(/[^\\s]/);\n cur = stream.current();\n if(/^=>?$/.test(cur)){\n state.extenExten = true;\n state.extenStart = false;\n return \"strong\";\n } else {\n state.extenStart = false;\n stream.skipToEnd();\n return \"error\";\n }\n } else if(state.extenExten) {\n // set exten and priority\n state.extenExten = false;\n state.extenPriority = true;\n stream.eatWhile(/[^,]/);\n if(state.extenInclude) {\n stream.skipToEnd();\n state.extenPriority = false;\n state.extenInclude = false;\n }\n if(state.extenSame) {\n state.extenPriority = false;\n state.extenSame = false;\n state.extenApplication = true;\n }\n return \"tag\";\n } else if(state.extenPriority) {\n state.extenPriority = false;\n state.extenApplication = true;\n stream.next(); // get comma\n if(state.extenSame) return null;\n stream.eatWhile(/[^,]/);\n return \"number\";\n } else if(state.extenApplication) {\n stream.eatWhile(/,/);\n cur = stream.current();\n if(cur === ',') return null;\n stream.eatWhile(/\\w/);\n cur = stream.current().toLowerCase();\n state.extenApplication = false;\n if(apps.indexOf(cur) !== -1){\n return \"def\";\n }\n } else{\n return basicToken(stream,state);\n }\n\n return null;\n },\n\n languageData: {\n commentTokens: {line: \";\", block: {open: \";--\", close: \"--;\"}}\n }\n};\n"],"names":["atoms","dpcmd","apps","asterisk","name","startState","blockComment","extenStart","extenSame","extenInclude","extenExten","extenPriority","extenApplication","token","stream","state","cur","eatSpace","eatWhile","current","test","skipToEnd","next","toLowerCase","indexOf","ch","match","skipTo","eat","peek","basicToken","languageData","commentTokens","line","block","open","close"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/7732.index.js b/book/_build/html/_static/7732.index.js new file mode 100644 index 0000000..d3b2a6d --- /dev/null +++ b/book/_build/html/_static/7732.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[7732],{7732:(e,a,t)=>{t.r(a),t.d(a,{mathematica:()=>i});var n="[a-zA-Z\\$][a-zA-Z0-9\\$]*",c="(?:\\.\\d+|\\d+\\.\\d*|\\d+)",m="(?:`(?:`?"+c+")?)",o=new RegExp("(?:(?:\\d+)(?:\\^\\^(?:\\.\\w+|\\w+\\.\\w*|\\w+)"+m+"?(?:\\*\\^[+-]?\\d+)?))"),r=new RegExp("(?:"+c+m+"?(?:\\*\\^[+-]?\\d+)?)"),z=new RegExp("(?:`?)(?:"+n+")(?:`(?:"+n+"))*(?:`?)");function A(e,a){var t;return'"'===(t=e.next())?(a.tokenize=Z,a.tokenize(e,a)):"("===t&&e.eat("*")?(a.commentLevel++,a.tokenize=$,a.tokenize(e,a)):(e.backUp(1),e.match(o,!0,!1)||e.match(r,!0,!1)?"number":e.match(/(?:In|Out)\[[0-9]*\]/,!0,!1)?"atom":e.match(/([a-zA-Z\$][a-zA-Z0-9\$]*(?:`[a-zA-Z0-9\$]+)*::usage)/,!0,!1)?"meta":e.match(/([a-zA-Z\$][a-zA-Z0-9\$]*(?:`[a-zA-Z0-9\$]+)*::[a-zA-Z\$][a-zA-Z0-9\$]*):?/,!0,!1)?"string.special":e.match(/([a-zA-Z\$][a-zA-Z0-9\$]*\s*:)(?:(?:[a-zA-Z\$][a-zA-Z0-9\$]*)|(?:[^:=>~@\^\&\*\)\[\]'\?,\|])).*/,!0,!1)||e.match(/[a-zA-Z\$][a-zA-Z0-9\$]*_+[a-zA-Z\$][a-zA-Z0-9\$]*/,!0,!1)||e.match(/[a-zA-Z\$][a-zA-Z0-9\$]*_+/,!0,!1)||e.match(/_+[a-zA-Z\$][a-zA-Z0-9\$]*/,!0,!1)?"variableName.special":e.match(/\\\[[a-zA-Z\$][a-zA-Z0-9\$]*\]/,!0,!1)?"character":e.match(/(?:\[|\]|{|}|\(|\))/,!0,!1)?"bracket":e.match(/(?:#[a-zA-Z\$][a-zA-Z0-9\$]*|#+[0-9]?)/,!0,!1)?"variableName.constant":e.match(z,!0,!1)?"keyword":e.match(/(?:\\|\+|\-|\*|\/|,|;|\.|:|@|~|=|>|<|&|\||_|`|'|\^|\?|!|%)/,!0,!1)?"operator":(e.next(),"error"))}function Z(e,a){for(var t,n=!1,c=!1;null!=(t=e.next());){if('"'===t&&!c){n=!0;break}c=!c&&"\\"===t}return n&&!c&&(a.tokenize=A),"string"}function $(e,a){for(var t,n;a.commentLevel>0&&null!=(n=e.next());)"("===t&&"*"===n&&a.commentLevel++,"*"===t&&")"===n&&a.commentLevel--,t=n;return a.commentLevel<=0&&(a.tokenize=A),"comment"}const i={name:"mathematica",startState:function(){return{tokenize:A,commentLevel:0}},token:function(e,a){return e.eatSpace()?null:a.tokenize(e,a)},languageData:{commentTokens:{block:{open:"(*",close:"*)"}}}}}}]); +//# sourceMappingURL=7732.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/7732.index.js.map b/book/_build/html/_static/7732.index.js.map new file mode 100644 index 0000000..8b331a4 --- /dev/null +++ b/book/_build/html/_static/7732.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"7732.index.js","mappings":"gIACA,IAAIA,EAAa,6BAEbC,EAAa,+BAEbC,EAAa,YAAYD,EAAO,MAGhCE,EAAoB,IAAIC,OAAO,mDAAmCF,EAAW,2BAC7E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AMM,aAAe,GAA+B,OAAzBJ,EAAOH,EAAOG,SAChC,MAATU,GAAyB,MAATV,GAAcF,EAAMM,eAC3B,MAATM,GAAyB,MAATV,GAAcF,EAAMM,eACxCM,EAAOV,EAKT,OAHIF,EAAMM,cAAgB,IACxBN,EAAMG,SAAWL,GAEZ,SACT,CAEO,MAAMe,EAAc,CACzBC,KAAM,cACNC,WAAY,WAAY,MAAO,CAACZ,SAAUL,EAAWQ,aAAc,EAAG,EACtEU,MAAO,SAASjB,EAAQC,GACtB,OAAID,EAAOkB,WAAmB,KACvBjB,EAAMG,SAASJ,EAAQC,EAChC,EACAkB,aAAc,CACZC,cAAe,CAACC,MAAO,CAACC,KAAM,KAAMC,MAAO,Q","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/mathematica.js"],"sourcesContent":["// used pattern building blocks\nvar Identifier = '[a-zA-Z\\\\$][a-zA-Z0-9\\\\$]*';\nvar pBase = \"(?:\\\\d+)\";\nvar pFloat = \"(?:\\\\.\\\\d+|\\\\d+\\\\.\\\\d*|\\\\d+)\";\nvar pFloatBase = \"(?:\\\\.\\\\w+|\\\\w+\\\\.\\\\w*|\\\\w+)\";\nvar pPrecision = \"(?:`(?:`?\"+pFloat+\")?)\";\n\n// regular expressions\nvar reBaseForm = new RegExp('(?:'+pBase+'(?:\\\\^\\\\^'+pFloatBase+pPrecision+'?(?:\\\\*\\\\^[+-]?\\\\d+)?))');\nvar reFloatForm = new RegExp('(?:' + pFloat + pPrecision + '?(?:\\\\*\\\\^[+-]?\\\\d+)?)');\nvar reIdInContext = new RegExp('(?:`?)(?:' + Identifier + ')(?:`(?:' + Identifier + '))*(?:`?)');\n\nfunction tokenBase(stream, state) {\n var ch;\n\n // get next character\n ch = stream.next();\n\n // string\n if (ch === '\"') {\n state.tokenize = tokenString;\n return state.tokenize(stream, state);\n }\n\n // comment\n if (ch === '(') {\n if (stream.eat('*')) {\n state.commentLevel++;\n state.tokenize = tokenComment;\n return state.tokenize(stream, state);\n }\n }\n\n // go back one character\n stream.backUp(1);\n\n // look for numbers\n // Numbers in a baseform\n if (stream.match(reBaseForm, true, false)) {\n return 'number';\n }\n\n // Mathematica numbers. Floats (1.2, .2, 1.) can have optionally a precision (`float) or an accuracy definition\n // (``float). Note: while 1.2` is possible 1.2`` is not. At the end an exponent (float*^+12) can follow.\n if (stream.match(reFloatForm, true, false)) {\n return 'number';\n }\n\n /* In[23] and Out[34] */\n if (stream.match(/(?:In|Out)\\[[0-9]*\\]/, true, false)) {\n return 'atom';\n }\n\n // usage\n if (stream.match(/([a-zA-Z\\$][a-zA-Z0-9\\$]*(?:`[a-zA-Z0-9\\$]+)*::usage)/, true, false)) {\n return 'meta';\n }\n\n // message\n if (stream.match(/([a-zA-Z\\$][a-zA-Z0-9\\$]*(?:`[a-zA-Z0-9\\$]+)*::[a-zA-Z\\$][a-zA-Z0-9\\$]*):?/, true, false)) {\n return 'string.special';\n }\n\n // this makes a look-ahead match for something like variable:{_Integer}\n // the match is then forwarded to the mma-patterns tokenizer.\n if (stream.match(/([a-zA-Z\\$][a-zA-Z0-9\\$]*\\s*:)(?:(?:[a-zA-Z\\$][a-zA-Z0-9\\$]*)|(?:[^:=>~@\\^\\&\\*\\)\\[\\]'\\?,\\|])).*/, true, false)) {\n return 'variableName.special';\n }\n\n // catch variables which are used together with Blank (_), BlankSequence (__) or BlankNullSequence (___)\n // Cannot start with a number, but can have numbers at any other position. Examples\n // blub__Integer, a1_, b34_Integer32\n if (stream.match(/[a-zA-Z\\$][a-zA-Z0-9\\$]*_+[a-zA-Z\\$][a-zA-Z0-9\\$]*/, true, false)) {\n return 'variableName.special';\n }\n if (stream.match(/[a-zA-Z\\$][a-zA-Z0-9\\$]*_+/, true, false)) {\n return 'variableName.special';\n }\n if (stream.match(/_+[a-zA-Z\\$][a-zA-Z0-9\\$]*/, true, false)) {\n return 'variableName.special';\n }\n\n // Named characters in Mathematica, like \\[Gamma].\n if (stream.match(/\\\\\\[[a-zA-Z\\$][a-zA-Z0-9\\$]*\\]/, true, false)) {\n return 'character';\n }\n\n // Match all braces separately\n if (stream.match(/(?:\\[|\\]|{|}|\\(|\\))/, true, false)) {\n return 'bracket';\n }\n\n // Catch Slots (#, ##, #3, ##9 and the V10 named slots #name). I have never seen someone using more than one digit after #, so we match\n // only one.\n if (stream.match(/(?:#[a-zA-Z\\$][a-zA-Z0-9\\$]*|#+[0-9]?)/, true, false)) {\n return 'variableName.constant';\n }\n\n // Literals like variables, keywords, functions\n if (stream.match(reIdInContext, true, false)) {\n return 'keyword';\n }\n\n // operators. Note that operators like @@ or /; are matched separately for each symbol.\n if (stream.match(/(?:\\\\|\\+|\\-|\\*|\\/|,|;|\\.|:|@|~|=|>|<|&|\\||_|`|'|\\^|\\?|!|%)/, true, false)) {\n return 'operator';\n }\n\n // everything else is an error\n stream.next(); // advance the stream.\n return 'error';\n}\n\nfunction tokenString(stream, state) {\n var next, end = false, escaped = false;\n while ((next = stream.next()) != null) {\n if (next === '\"' && !escaped) {\n end = true;\n break;\n }\n escaped = !escaped && next === '\\\\';\n }\n if (end && !escaped) {\n state.tokenize = tokenBase;\n }\n return 'string';\n};\n\nfunction tokenComment(stream, state) {\n var prev, next;\n while(state.commentLevel > 0 && (next = stream.next()) != null) {\n if (prev === '(' && next === '*') state.commentLevel++;\n if (prev === '*' && next === ')') state.commentLevel--;\n prev = next;\n }\n if (state.commentLevel <= 0) {\n state.tokenize = tokenBase;\n }\n return 'comment';\n}\n\nexport const mathematica = {\n name: \"mathematica\",\n startState: function() {return {tokenize: tokenBase, commentLevel: 0};},\n token: function(stream, state) {\n if (stream.eatSpace()) return null;\n return state.tokenize(stream, state);\n },\n languageData: {\n commentTokens: {block: {open: \"(*\", close: \"*)\"}}\n }\n}\n\n"],"names":["Identifier","pFloat","pPrecision","reBaseForm","RegExp","reFloatForm","reIdInContext","tokenBase","stream","state","ch","next","tokenize","tokenString","eat","commentLevel","tokenComment","backUp","match","end","escaped","prev","mathematica","name","startState","token","eatSpace","languageData","commentTokens","block","open","close"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/7736.index.js b/book/_build/html/_static/7736.index.js new file mode 100644 index 0000000..aaf796a --- /dev/null +++ b/book/_build/html/_static/7736.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[7736],{7736:(t,e,n)=>{var r;function a(t,e){return r=e,t}function u(t,e){var n,r=t.next();if("<"!=r||!t.eat("!")){if("<"==r&&t.eat("?"))return e.tokenize=("meta","?>",function(t,e){for(;!t.eol();){if(t.match("?>")){e.tokenize=u;break}t.next()}return"meta"}),a("meta",r);if("#"==r&&t.eatWhile(/[\w]/))return a("atom","tag");if("|"==r)return a("keyword","separator");if(r.match(/[\(\)\[\]\-\.,\+\?>]/))return a(null,r);if(r.match(/[\[\]]/))return a("rule",r);if('"'==r||"'"==r)return e.tokenize=(n=r,function(t,e){for(var r,i=!1;null!=(r=t.next());){if(r==n&&!i){e.tokenize=u;break}i=!i&&"\\"==r}return a("string","tag")}),e.tokenize(t,e);if(t.eatWhile(/[a-zA-Z\?\+\d]/)){var l=t.current();return null!==l.substr(l.length-1,l.length).match(/\?|\+/)&&t.backUp(1),a("tag","tag")}return"%"==r||"*"==r?a("number","number"):(t.eatWhile(/[\w\\\-_%.{,]/),a(null,null))}return t.eatWhile(/[\-]/)?(e.tokenize=i,i(t,e)):t.eatWhile(/[\w]/)?a("keyword","doindent"):void 0}function i(t,e){for(var n,r=0;null!=(n=t.next());){if(r>=2&&">"==n){e.tokenize=u;break}r="-"==n?r+1:0}return a("comment","comment")}n.r(e),n.d(e,{dtd:()=>l});const l={name:"dtd",startState:function(){return{tokenize:u,baseIndent:0,stack:[]}},token:function(t,e){if(t.eatSpace())return null;var n=e.tokenize(t,e),a=e.stack[e.stack.length-1];return"["==t.current()||"doindent"===r||"["==r?e.stack.push("rule"):"endtag"===r?e.stack[e.stack.length-1]="endtag":"]"==t.current()||"]"==r||">"==r&&"rule"==a?e.stack.pop():"["==r&&e.stack.push("["),n},indent:function(t,e,n){var a=t.stack.length;return"]"===e.charAt(0)?a--:">"===e.substr(e.length-1,e.length)&&("<"===e.substr(0,1)||"doindent"==r&&e.length>1||("doindent"==r?a--:">"==r&&e.length>1||"tag"==r&&">"!==e||("tag"==r&&"rule"==t.stack[t.stack.length-1]?a--:"tag"==r?a++:">"===e&&"rule"==t.stack[t.stack.length-1]&&">"===r?a--:">"===e&&"rule"==t.stack[t.stack.length-1]||("<"!==e.substr(0,1)&&">"===e.substr(0,1)?a-=1:">"===e||(a-=1)))),null!=r&&"]"!=r||a--),t.baseIndent+a*n.unit},languageData:{indentOnInput:/^\s*[\]>]$/}}}}]); +//# sourceMappingURL=7736.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/7736.index.js.map b/book/_build/html/_static/7736.index.js.map new file mode 100644 index 0000000..42c3bce --- /dev/null +++ b/book/_build/html/_static/7736.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"7736.index.js","mappings":"8FAAA,IAAIA,EACJ,SAASC,EAAIC,EAAOC,GAAgB,OAAXH,EAAOG,EAAWD,CAAM,CAEjD,SAASE,EAAUC,EAAQC,GACzB,IAwCmBC,EAxCfC,EAAKH,EAAOI,OAEhB,GAAU,KAAND,IAAaH,EAAOK,IAAI,KAKrB,IAAU,KAANF,GAAaH,EAAOK,IAAI,KAEjC,OADAJ,EAAMK,UAAmB,OAAQ,KA+C5B,SAASN,EAAQC,GACtB,MAAQD,EAAOO,OAAO,CACpB,GAAIP,EAAOQ,MAjDoB,MAiDD,CAC5BP,EAAMK,SAAWP,EACjB,KACF,CACAC,EAAOI,MACT,CACA,MAvDyB,MAwD3B,GAvDSR,EAAI,OAAQO,GACd,GAAU,KAANA,GAAaH,EAAOS,SAAS,QAAS,OAAOb,EAAI,OAAQ,OAC/D,GAAU,KAANO,EAAW,OAAOP,EAAI,UAAW,aACrC,GAAIO,EAAGK,MAAM,wBAAyB,OAAOZ,EAAI,KAAMO,GACvD,GAAIA,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AE/BwB,EAAUxB,EAAMqB,MAAMrB,EAAMqB,MAAMR,OAAO,GAK7C,MAJwB,KAApBd,EAAOY,WAA6B,aAATjB,GAA+B,KAARA,EAAaM,EAAMqB,MAAMI,KAAK,QAClE,WAAT/B,EAAmBM,EAAMqB,MAAMrB,EAAMqB,MAAMR,OAAO,GAAK,SACnC,KAApBd,EAAOY,WAA4B,KAARjB,GAAwB,KAARA,GAA0B,QAAX8B,EAAoBxB,EAAMqB,MAAMK,MAClF,KAARhC,GAAaM,EAAMqB,MAAMI,KAAK,KAChC7B,CACT,EAEA+B,OAAQ,SAAS3B,EAAO4B,EAAWC,GACjC,IAAIC,EAAI9B,EAAMqB,MAAMR,OAoBpB,MAlB4B,MAAxBe,EAAUG,OAAO,GAAYD,IACkC,MAA3DF,EAAUhB,OAAOgB,EAAUf,OAAO,EAAGe,EAAUf,UACxB,MAA1Be,EAAUhB,OAAO,EAAE,IACL,YAARlB,GAAsBkC,EAAUf,OAAS,IACjC,YAARnB,EAAmBoC,IACX,KAARpC,GAAekC,EAAUf,OAAS,GAC1B,OAARnB,GAA+B,MAAdkC,IACT,OAARlC,GAAsD,QAArCM,EAAMqB,MAAMrB,EAAMqB,MAAMR,OAAO,GAAaiB,IACrD,OAARpC,EAAcoC,IACA,MAAdF,GAA0D,QAArC5B,EAAMqB,MAAMrB,EAAMqB,MAAMR,OAAO,IAAyB,MAATnB,EAAaoC,IACnE,MAAdF,GAA0D,QAArC5B,EAAMqB,MAAMrB,EAAMqB,MAAMR,OAAO,KAC1B,MAA1Be,EAAUhB,OAAO,EAAE,IAAwC,MAA1BgB,EAAUhB,OAAO,EAAE,GAAYkB,GAAI,EACtD,MAAdF,IACJE,GAAI,MAEE,MAARpC,GAAwB,KAARA,GAAYoC,KAG1B9B,EAAMoB,WAAaU,EAAID,EAAGG,IACnC,EAEAC,aAAc,CACZC,cAAe,c","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/dtd.js"],"sourcesContent":["var type;\nfunction ret(style, tp) {type = tp; return style;}\n\nfunction tokenBase(stream, state) {\n var ch = stream.next();\n\n if (ch == \"<\" && stream.eat(\"!\") ) {\n if (stream.eatWhile(/[\\-]/)) {\n state.tokenize = tokenSGMLComment;\n return tokenSGMLComment(stream, state);\n } else if (stream.eatWhile(/[\\w]/)) return ret(\"keyword\", \"doindent\");\n } else if (ch == \"<\" && stream.eat(\"?\")) { //xml declaration\n state.tokenize = inBlock(\"meta\", \"?>\");\n return ret(\"meta\", ch);\n } else if (ch == \"#\" && stream.eatWhile(/[\\w]/)) return ret(\"atom\", \"tag\");\n else if (ch == \"|\") return ret(\"keyword\", \"separator\");\n else if (ch.match(/[\\(\\)\\[\\]\\-\\.,\\+\\?>]/)) return ret(null, ch);//if(ch === \">\") return ret(null, \"endtag\"); else\n else if (ch.match(/[\\[\\]]/)) return ret(\"rule\", ch);\n else if (ch == \"\\\"\" || ch == \"'\") {\n state.tokenize = tokenString(ch);\n return state.tokenize(stream, state);\n } else if (stream.eatWhile(/[a-zA-Z\\?\\+\\d]/)) {\n var sc = stream.current();\n if( sc.substr(sc.length-1,sc.length).match(/\\?|\\+/) !== null )stream.backUp(1);\n return ret(\"tag\", \"tag\");\n } else if (ch == \"%\" || ch == \"*\" ) return ret(\"number\", \"number\");\n else {\n stream.eatWhile(/[\\w\\\\\\-_%.{,]/);\n return ret(null, null);\n }\n}\n\nfunction tokenSGMLComment(stream, state) {\n var dashes = 0, ch;\n while ((ch = stream.next()) != null) {\n if (dashes >= 2 && ch == \">\") {\n state.tokenize = tokenBase;\n break;\n }\n dashes = (ch == \"-\") ? dashes + 1 : 0;\n }\n return ret(\"comment\", \"comment\");\n}\n\nfunction tokenString(quote) {\n return function(stream, state) {\n var escaped = false, ch;\n while ((ch = stream.next()) != null) {\n if (ch == quote && !escaped) {\n state.tokenize = tokenBase;\n break;\n }\n escaped = !escaped && ch == \"\\\\\";\n }\n return ret(\"string\", \"tag\");\n };\n}\n\nfunction inBlock(style, terminator) {\n return function(stream, state) {\n while (!stream.eol()) {\n if (stream.match(terminator)) {\n state.tokenize = tokenBase;\n break;\n }\n stream.next();\n }\n return style;\n };\n}\n\nexport const dtd = {\n name: \"dtd\",\n startState: function() {\n return {tokenize: tokenBase,\n baseIndent: 0,\n stack: []};\n },\n\n token: function(stream, state) {\n if (stream.eatSpace()) return null;\n var style = state.tokenize(stream, state);\n\n var context = state.stack[state.stack.length-1];\n if (stream.current() == \"[\" || type === \"doindent\" || type == \"[\") state.stack.push(\"rule\");\n else if (type === \"endtag\") state.stack[state.stack.length-1] = \"endtag\";\n else if (stream.current() == \"]\" || type == \"]\" || (type == \">\" && context == \"rule\")) state.stack.pop();\n else if (type == \"[\") state.stack.push(\"[\");\n return style;\n },\n\n indent: function(state, textAfter, cx) {\n var n = state.stack.length;\n\n if( textAfter.charAt(0) === ']' )n--;\n else if(textAfter.substr(textAfter.length-1, textAfter.length) === \">\"){\n if(textAfter.substr(0,1) === \"<\") {}\n else if( type == \"doindent\" && textAfter.length > 1 ) {}\n else if( type == \"doindent\")n--;\n else if( type == \">\" && textAfter.length > 1) {}\n else if( type == \"tag\" && textAfter !== \">\") {}\n else if( type == \"tag\" && state.stack[state.stack.length-1] == \"rule\")n--;\n else if( type == \"tag\")n++;\n else if( textAfter === \">\" && state.stack[state.stack.length-1] == \"rule\" && type === \">\")n--;\n else if( textAfter === \">\" && state.stack[state.stack.length-1] == \"rule\") {}\n else if( textAfter.substr(0,1) !== \"<\" && textAfter.substr(0,1) === \">\" )n=n-1;\n else if( textAfter === \">\") {}\n else n=n-1;\n //over rule them all\n if(type == null || type == \"]\")n--;\n }\n\n return state.baseIndent + n * cx.unit;\n },\n\n languageData: {\n indentOnInput: /^\\s*[\\]>]$/\n }\n};\n\n"],"names":["type","ret","style","tp","tokenBase","stream","state","quote","ch","next","eat","tokenize","eol","match","eatWhile","escaped","sc","current","substr","length","backUp","tokenSGMLComment","dashes","dtd","name","startState","baseIndent","stack","token","eatSpace","context","push","pop","indent","textAfter","cx","n","charAt","unit","languageData","indentOnInput"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/7783.index.js b/book/_build/html/_static/7783.index.js new file mode 100644 index 0000000..d5908ba --- /dev/null +++ b/book/_build/html/_static/7783.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[7783],{27783:(e,t,n)=>{n.r(t),n.d(t,{xQuery:()=>y});var r=function(){function e(e){return{type:e,style:"keyword"}}for(var t=e("operator"),n={type:"atom",style:"atom"},r={type:"axis_specifier",style:"qualifier"},a={",":{type:"punctuation",style:null}},i=["after","all","allowing","ancestor","ancestor-or-self","any","array","as","ascending","at","attribute","base-uri","before","boundary-space","by","case","cast","castable","catch","child","collation","comment","construction","contains","content","context","copy","copy-namespaces","count","decimal-format","declare","default","delete","descendant","descendant-or-self","descending","diacritics","different","distance","document","document-node","element","else","empty","empty-sequence","encoding","end","entire","every","exactly","except","external","first","following","following-sibling","for","from","ftand","ftnot","ft-option","ftor","function","fuzzy","greatest","group","if","import","in","inherit","insensitive","insert","instance","intersect","into","invoke","is","item","language","last","lax","least","let","levels","lowercase","map","modify","module","most","namespace","next","no","node","nodes","no-inherit","no-preserve","not","occurs","of","only","option","order","ordered","ordering","paragraph","paragraphs","parent","phrase","preceding","preceding-sibling","preserve","previous","processing-instruction","relationship","rename","replace","return","revalidation","same","satisfies","schema","schema-attribute","schema-element","score","self","sensitive","sentence","sentences","sequence","skip","sliding","some","stable","start","stemming","stop","strict","strip","switch","text","then","thesaurus","times","to","transform","treat","try","tumbling","type","typeswitch","union","unordered","update","updating","uppercase","using","validate","value","variable","version","weight","when","where","wildcards","window","with","without","word","words","xquery"],s=0,o=i.length;s",">=","<","<=",".","|","?","and","or","div","idiv","mod","*","/","+","-"];for(s=0,o=u.length;s\"\'\/?]/);)b+=v;return a(e,t,function(e,t){return function(n,r){return n.eatSpace(),t&&n.eat(">")?(h(r),r.tokenize=i,"tag"):(n.eat("/")||d(r,{type:"tag",name:e,tokenize:i}),n.eat(">")?(r.tokenize=i,"tag"):(r.tokenize=u,"tag"))}}(b,k))}if("{"==n)return d(t,{type:"codeblock"}),null;if("}"==n)return h(t),null;if(m(t))return">"==n?"tag":"/"==n&&e.eat(">")?(h(t),"tag"):"variable";if(/\d/.test(n))return e.match(/^\d*(?:\.\d*)?(?:E[+\-]?\d+)?/),"atom";if("("===n&&e.eat(":"))return d(t,{type:"comment"}),a(e,t,s);if(y||'"'!==n&&"'"!==n){if("$"===n)return a(e,t,c);if(":"===n&&e.eat("="))return"keyword";if("("===n)return d(t,{type:"paren"}),null;if(")"===n)return h(t),null;if("["===n)return d(t,{type:"bracket"}),null;if("]"===n)return h(t),null;var z=r.propertyIsEnumerable(n)&&r[n];if(y&&'"'===n)for(;'"'!==e.next(););if(y&&"'"===n)for(;"'"!==e.next(););z||e.eatWhile(/[\w\$_-]/);var w=e.eat(":");!e.eat(":")&&w&&e.eatWhile(/[\w\$_-]/),e.match(/^[ \t]*\(/,!1)&&(g=!0);var I=e.current();return z=r.propertyIsEnumerable(I)&&r[I],g&&!z&&(z={type:"function_call",style:"def"}),function(e){return x(e,"xmlconstructor")}(t)?(h(t),"variable"):("element"!=I&&"attribute"!=I&&"axis_specifier"!=z.type||d(t,{type:"xmlconstructor"}),z?z.style:"variable")}return a(e,t,o(n))}function s(e,t){for(var n,r=!1,a=!1,i=0;n=e.next();){if(")"==n&&r){if(!(i>0)){h(t);break}i--}else":"==n&&a&&i++;r=":"==n,a="("==n}return"comment"}function o(e,t){return function(n,r){var a;if(function(e){return x(e,"string")}(r)&&n.current()==e)return h(r),t&&(r.tokenize=t),"string";if(d(r,{type:"string",name:e,tokenize:o(e,t)}),n.match("{",!1)&&g(r))return r.tokenize=i,"string";for(;a=n.next();){if(a==e){h(r),t&&(r.tokenize=t);break}if(n.match("{",!1)&&g(r))return r.tokenize=i,"string"}return"string"}}function c(e,t){var n=/[\w\$_-]/;if(e.eat('"')){for(;'"'!==e.next(););e.eat(":")}else e.eatWhile(n),e.match(":=",!1)||e.eat(":");return e.eatWhile(n),t.tokenize=i,"variable"}function u(e,t){var n=e.next();return"/"==n&&e.eat(">")?(g(t)&&h(t),m(t)&&h(t),"tag"):">"==n?(g(t)&&h(t),"tag"):"="==n?null:'"'==n||"'"==n?a(e,t,o(n,u)):(g(t)||d(t,{type:"attribute",tokenize:u}),e.eat(/[a-zA-Z_:]/),e.eatWhile(/[-a-zA-Z0-9_:.]/),e.eatSpace(),(e.match(">",!1)||e.match("/",!1))&&(h(t),t.tokenize=i),"attribute")}function l(e,t){for(var n;n=e.next();)if("-"==n&&e.match("->",!0))return t.tokenize=i,"comment"}function f(e,t){for(var n;n=e.next();)if("]"==n&&e.match("]",!0))return t.tokenize=i,"comment"}function p(e,t){for(var n;n=e.next();)if("?"==n&&e.match(">",!0))return t.tokenize=i,"processingInstruction"}function m(e){return x(e,"tag")}function g(e){return x(e,"attribute")}function x(e,t){return e.stack.length&&e.stack[e.stack.length-1].type==t}function d(e,t){e.stack.push(t)}function h(e){e.stack.pop();var t=e.stack.length&&e.stack[e.stack.length-1].tokenize;e.tokenize=t||i}const y={name:"xquery",startState:function(){return{tokenize:i,cc:[],stack:[]}},token:function(e,t){return e.eatSpace()?null:t.tokenize(e,t)},languageData:{commentTokens:{block:{open:"(:",close:":)"}}}}}}]); +//# sourceMappingURL=7783.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/7783.index.js.map b/book/_build/html/_static/7783.index.js.map new file mode 100644 index 0000000..166feb3 --- /dev/null +++ b/book/_build/html/_static/7783.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"7783.index.js","mappings":"4HAGA,IAAIA,EAAW,WAEb,SAASC,EAAGC,GAAO,MAAO,CAACA,KAAMA,EAAMC,MAAO,UAAW,CAiCzD,IAhCA,IAAIC,EAAWH,EAAG,YAChBI,EAAO,CAACH,KAAM,OAAQC,MAAO,QAE7BG,EAAY,CAACJ,KAAM,iBAAkBC,MAAO,aAG1CI,EAAQ,CACV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2C,MAAM3C,EAAM2C,MAAMjD,OAAO,GAAGQ,SAChFF,EAAME,SAAW6C,GAAqB5C,CACxC,CAGO,MAAM6C,EAAS,CACpB7B,KAAM,SACN8B,WAAY,WACV,MAAO,CACL/C,SAAUC,EACV+C,GAAI,GACJP,MAAO,GAEX,EAEAQ,MAAO,SAASpD,EAAQC,GACtB,OAAID,EAAOiB,WAAmB,KAClBhB,EAAME,SAASH,EAAQC,EAErC,EAEAoD,aAAc,CACZC,cAAe,CAACC,MAAO,CAACC,KAAM,KAAMC,MAAO,Q","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/xquery.js"],"sourcesContent":["// The keywords object is set to the result of this self executing\n// function. Each keyword is a property of the keywords object whose\n// value is {type: atype, style: astyle}\nvar keywords = function(){\n // convenience functions used to build keywords object\n function kw(type) {return {type: type, style: \"keyword\"};}\n var operator = kw(\"operator\")\n , atom = {type: \"atom\", style: \"atom\"}\n , punctuation = {type: \"punctuation\", style: null}\n , qualifier = {type: \"axis_specifier\", style: \"qualifier\"};\n\n // kwObj is what is return from this function at the end\n var kwObj = {\n ',': punctuation\n };\n\n // a list of 'basic' keywords. For each add a property to kwObj with the value of\n // {type: basic[i], style: \"keyword\"} e.g. 'after' --> {type: \"after\", style: \"keyword\"}\n var basic = ['after', 'all', 'allowing', 'ancestor', 'ancestor-or-self', 'any', 'array', 'as',\n 'ascending', 'at', 'attribute', 'base-uri', 'before', 'boundary-space', 'by', 'case', 'cast',\n 'castable', 'catch', 'child', 'collation', 'comment', 'construction', 'contains', 'content',\n 'context', 'copy', 'copy-namespaces', 'count', 'decimal-format', 'declare', 'default', 'delete',\n 'descendant', 'descendant-or-self', 'descending', 'diacritics', 'different', 'distance',\n 'document', 'document-node', 'element', 'else', 'empty', 'empty-sequence', 'encoding', 'end',\n 'entire', 'every', 'exactly', 'except', 'external', 'first', 'following', 'following-sibling',\n 'for', 'from', 'ftand', 'ftnot', 'ft-option', 'ftor', 'function', 'fuzzy', 'greatest', 'group',\n 'if', 'import', 'in', 'inherit', 'insensitive', 'insert', 'instance', 'intersect', 'into',\n 'invoke', 'is', 'item', 'language', 'last', 'lax', 'least', 'let', 'levels', 'lowercase', 'map',\n 'modify', 'module', 'most', 'namespace', 'next', 'no', 'node', 'nodes', 'no-inherit',\n 'no-preserve', 'not', 'occurs', 'of', 'only', 'option', 'order', 'ordered', 'ordering',\n 'paragraph', 'paragraphs', 'parent', 'phrase', 'preceding', 'preceding-sibling', 'preserve',\n 'previous', 'processing-instruction', 'relationship', 'rename', 'replace', 'return',\n 'revalidation', 'same', 'satisfies', 'schema', 'schema-attribute', 'schema-element', 'score',\n 'self', 'sensitive', 'sentence', 'sentences', 'sequence', 'skip', 'sliding', 'some', 'stable',\n 'start', 'stemming', 'stop', 'strict', 'strip', 'switch', 'text', 'then', 'thesaurus', 'times',\n 'to', 'transform', 'treat', 'try', 'tumbling', 'type', 'typeswitch', 'union', 'unordered',\n 'update', 'updating', 'uppercase', 'using', 'validate', 'value', 'variable', 'version',\n 'weight', 'when', 'where', 'wildcards', 'window', 'with', 'without', 'word', 'words', 'xquery'];\n for(var i=0, l=basic.length; i < l; i++) { kwObj[basic[i]] = kw(basic[i]);};\n\n // a list of types. For each add a property to kwObj with the value of\n // {type: \"atom\", style: \"atom\"}\n var types = ['xs:anyAtomicType', 'xs:anySimpleType', 'xs:anyType', 'xs:anyURI',\n 'xs:base64Binary', 'xs:boolean', 'xs:byte', 'xs:date', 'xs:dateTime', 'xs:dateTimeStamp',\n 'xs:dayTimeDuration', 'xs:decimal', 'xs:double', 'xs:duration', 'xs:ENTITIES', 'xs:ENTITY',\n 'xs:float', 'xs:gDay', 'xs:gMonth', 'xs:gMonthDay', 'xs:gYear', 'xs:gYearMonth', 'xs:hexBinary',\n 'xs:ID', 'xs:IDREF', 'xs:IDREFS', 'xs:int', 'xs:integer', 'xs:item', 'xs:java', 'xs:language',\n 'xs:long', 'xs:Name', 'xs:NCName', 'xs:negativeInteger', 'xs:NMTOKEN', 'xs:NMTOKENS',\n 'xs:nonNegativeInteger', 'xs:nonPositiveInteger', 'xs:normalizedString', 'xs:NOTATION',\n 'xs:numeric', 'xs:positiveInteger', 'xs:precisionDecimal', 'xs:QName', 'xs:short', 'xs:string',\n 'xs:time', 'xs:token', 'xs:unsignedByte', 'xs:unsignedInt', 'xs:unsignedLong',\n 'xs:unsignedShort', 'xs:untyped', 'xs:untypedAtomic', 'xs:yearMonthDuration'];\n for(var i=0, l=types.length; i < l; i++) { kwObj[types[i]] = atom;};\n\n // each operator will add a property to kwObj with value of {type: \"operator\", style: \"keyword\"}\n var operators = ['eq', 'ne', 'lt', 'le', 'gt', 'ge', ':=', '=', '>', '>=', '<', '<=', '.', '|', '?', 'and', 'or', 'div', 'idiv', 'mod', '*', '/', '+', '-'];\n for(var i=0, l=operators.length; i < l; i++) { kwObj[operators[i]] = operator;};\n\n // each axis_specifiers will add a property to kwObj with value of {type: \"axis_specifier\", style: \"qualifier\"}\n var axis_specifiers = [\"self::\", \"attribute::\", \"child::\", \"descendant::\", \"descendant-or-self::\", \"parent::\",\n \"ancestor::\", \"ancestor-or-self::\", \"following::\", \"preceding::\", \"following-sibling::\", \"preceding-sibling::\"];\n for(var i=0, l=axis_specifiers.length; i < l; i++) { kwObj[axis_specifiers[i]] = qualifier; };\n\n return kwObj;\n}();\n\nfunction chain(stream, state, f) {\n state.tokenize = f;\n return f(stream, state);\n}\n\n// the primary mode tokenizer\nfunction tokenBase(stream, state) {\n var ch = stream.next(),\n mightBeFunction = false,\n isEQName = isEQNameAhead(stream);\n\n // an XML tag (if not in some sub, chained tokenizer)\n if (ch == \"<\") {\n if(stream.match(\"!--\", true))\n return chain(stream, state, tokenXMLComment);\n\n if(stream.match(\"![CDATA\", false)) {\n state.tokenize = tokenCDATA;\n return \"tag\";\n }\n\n if(stream.match(\"?\", false)) {\n return chain(stream, state, tokenPreProcessing);\n }\n\n var isclose = stream.eat(\"/\");\n stream.eatSpace();\n var tagName = \"\", c;\n while ((c = stream.eat(/[^\\s\\u00a0=<>\\\"\\'\\/?]/))) tagName += c;\n\n return chain(stream, state, tokenTag(tagName, isclose));\n }\n // start code block\n else if(ch == \"{\") {\n pushStateStack(state, { type: \"codeblock\"});\n return null;\n }\n // end code block\n else if(ch == \"}\") {\n popStateStack(state);\n return null;\n }\n // if we're in an XML block\n else if(isInXmlBlock(state)) {\n if(ch == \">\")\n return \"tag\";\n else if(ch == \"/\" && stream.eat(\">\")) {\n popStateStack(state);\n return \"tag\";\n }\n else\n return \"variable\";\n }\n // if a number\n else if (/\\d/.test(ch)) {\n stream.match(/^\\d*(?:\\.\\d*)?(?:E[+\\-]?\\d+)?/);\n return \"atom\";\n }\n // comment start\n else if (ch === \"(\" && stream.eat(\":\")) {\n pushStateStack(state, { type: \"comment\"});\n return chain(stream, state, tokenComment);\n }\n // quoted string\n else if (!isEQName && (ch === '\"' || ch === \"'\"))\n return chain(stream, state, tokenString(ch));\n // variable\n else if(ch === \"$\") {\n return chain(stream, state, tokenVariable);\n }\n // assignment\n else if(ch ===\":\" && stream.eat(\"=\")) {\n return \"keyword\";\n }\n // open paren\n else if(ch === \"(\") {\n pushStateStack(state, { type: \"paren\"});\n return null;\n }\n // close paren\n else if(ch === \")\") {\n popStateStack(state);\n return null;\n }\n // open paren\n else if(ch === \"[\") {\n pushStateStack(state, { type: \"bracket\"});\n return null;\n }\n // close paren\n else if(ch === \"]\") {\n popStateStack(state);\n return null;\n }\n else {\n var known = keywords.propertyIsEnumerable(ch) && keywords[ch];\n\n // if there's a EQName ahead, consume the rest of the string portion, it's likely a function\n if(isEQName && ch === '\\\"') while(stream.next() !== '\"'){}\n if(isEQName && ch === '\\'') while(stream.next() !== '\\''){}\n\n // gobble up a word if the character is not known\n if(!known) stream.eatWhile(/[\\w\\$_-]/);\n\n // gobble a colon in the case that is a lib func type call fn:doc\n var foundColon = stream.eat(\":\");\n\n // if there's not a second colon, gobble another word. Otherwise, it's probably an axis specifier\n // which should get matched as a keyword\n if(!stream.eat(\":\") && foundColon) {\n stream.eatWhile(/[\\w\\$_-]/);\n }\n // if the next non whitespace character is an open paren, this is probably a function (if not a keyword of other sort)\n if(stream.match(/^[ \\t]*\\(/, false)) {\n mightBeFunction = true;\n }\n // is the word a keyword?\n var word = stream.current();\n known = keywords.propertyIsEnumerable(word) && keywords[word];\n\n // if we think it's a function call but not yet known,\n // set style to variable for now for lack of something better\n if(mightBeFunction && !known) known = {type: \"function_call\", style: \"def\"};\n\n // if the previous word was element, attribute, axis specifier, this word should be the name of that\n if(isInXmlConstructor(state)) {\n popStateStack(state);\n return \"variable\";\n }\n // as previously checked, if the word is element,attribute, axis specifier, call it an \"xmlconstructor\" and\n // push the stack so we know to look for it on the next word\n if(word == \"element\" || word == \"attribute\" || known.type == \"axis_specifier\") pushStateStack(state, {type: \"xmlconstructor\"});\n\n // if the word is known, return the details of that else just call this a generic 'word'\n return known ? known.style : \"variable\";\n }\n}\n\n// handle comments, including nested\nfunction tokenComment(stream, state) {\n var maybeEnd = false, maybeNested = false, nestedCount = 0, ch;\n while (ch = stream.next()) {\n if (ch == \")\" && maybeEnd) {\n if(nestedCount > 0)\n nestedCount--;\n else {\n popStateStack(state);\n break;\n }\n }\n else if(ch == \":\" && maybeNested) {\n nestedCount++;\n }\n maybeEnd = (ch == \":\");\n maybeNested = (ch == \"(\");\n }\n\n return \"comment\";\n}\n\n// tokenizer for string literals\n// optionally pass a tokenizer function to set state.tokenize back to when finished\nfunction tokenString(quote, f) {\n return function(stream, state) {\n var ch;\n\n if(isInString(state) && stream.current() == quote) {\n popStateStack(state);\n if(f) state.tokenize = f;\n return \"string\";\n }\n\n pushStateStack(state, { type: \"string\", name: quote, tokenize: tokenString(quote, f) });\n\n // if we're in a string and in an XML block, allow an embedded code block\n if(stream.match(\"{\", false) && isInXmlAttributeBlock(state)) {\n state.tokenize = tokenBase;\n return \"string\";\n }\n\n\n while (ch = stream.next()) {\n if (ch == quote) {\n popStateStack(state);\n if(f) state.tokenize = f;\n break;\n }\n else {\n // if we're in a string and in an XML block, allow an embedded code block in an attribute\n if(stream.match(\"{\", false) && isInXmlAttributeBlock(state)) {\n state.tokenize = tokenBase;\n return \"string\";\n }\n\n }\n }\n\n return \"string\";\n };\n}\n\n// tokenizer for variables\nfunction tokenVariable(stream, state) {\n var isVariableChar = /[\\w\\$_-]/;\n\n // a variable may start with a quoted EQName so if the next character is quote, consume to the next quote\n if(stream.eat(\"\\\"\")) {\n while(stream.next() !== '\\\"'){};\n stream.eat(\":\");\n } else {\n stream.eatWhile(isVariableChar);\n if(!stream.match(\":=\", false)) stream.eat(\":\");\n }\n stream.eatWhile(isVariableChar);\n state.tokenize = tokenBase;\n return \"variable\";\n}\n\n// tokenizer for XML tags\nfunction tokenTag(name, isclose) {\n return function(stream, state) {\n stream.eatSpace();\n if(isclose && stream.eat(\">\")) {\n popStateStack(state);\n state.tokenize = tokenBase;\n return \"tag\";\n }\n // self closing tag without attributes?\n if(!stream.eat(\"/\"))\n pushStateStack(state, { type: \"tag\", name: name, tokenize: tokenBase});\n if(!stream.eat(\">\")) {\n state.tokenize = tokenAttribute;\n return \"tag\";\n }\n else {\n state.tokenize = tokenBase;\n }\n return \"tag\";\n };\n}\n\n// tokenizer for XML attributes\nfunction tokenAttribute(stream, state) {\n var ch = stream.next();\n\n if(ch == \"/\" && stream.eat(\">\")) {\n if(isInXmlAttributeBlock(state)) popStateStack(state);\n if(isInXmlBlock(state)) popStateStack(state);\n return \"tag\";\n }\n if(ch == \">\") {\n if(isInXmlAttributeBlock(state)) popStateStack(state);\n return \"tag\";\n }\n if(ch == \"=\")\n return null;\n // quoted string\n if (ch == '\"' || ch == \"'\")\n return chain(stream, state, tokenString(ch, tokenAttribute));\n\n if(!isInXmlAttributeBlock(state))\n pushStateStack(state, { type: \"attribute\", tokenize: tokenAttribute});\n\n stream.eat(/[a-zA-Z_:]/);\n stream.eatWhile(/[-a-zA-Z0-9_:.]/);\n stream.eatSpace();\n\n // the case where the attribute has not value and the tag was closed\n if(stream.match(\">\", false) || stream.match(\"/\", false)) {\n popStateStack(state);\n state.tokenize = tokenBase;\n }\n\n return \"attribute\";\n}\n\n// handle comments, including nested\nfunction tokenXMLComment(stream, state) {\n var ch;\n while (ch = stream.next()) {\n if (ch == \"-\" && stream.match(\"->\", true)) {\n state.tokenize = tokenBase;\n return \"comment\";\n }\n }\n}\n\n\n// handle CDATA\nfunction tokenCDATA(stream, state) {\n var ch;\n while (ch = stream.next()) {\n if (ch == \"]\" && stream.match(\"]\", true)) {\n state.tokenize = tokenBase;\n return \"comment\";\n }\n }\n}\n\n// handle preprocessing instructions\nfunction tokenPreProcessing(stream, state) {\n var ch;\n while (ch = stream.next()) {\n if (ch == \"?\" && stream.match(\">\", true)) {\n state.tokenize = tokenBase;\n return \"processingInstruction\";\n }\n }\n}\n\n\n// functions to test the current context of the state\nfunction isInXmlBlock(state) { return isIn(state, \"tag\"); }\nfunction isInXmlAttributeBlock(state) { return isIn(state, \"attribute\"); }\nfunction isInXmlConstructor(state) { return isIn(state, \"xmlconstructor\"); }\nfunction isInString(state) { return isIn(state, \"string\"); }\n\nfunction isEQNameAhead(stream) {\n // assume we've already eaten a quote (\")\n if(stream.current() === '\"')\n return stream.match(/^[^\\\"]+\\\"\\:/, false);\n else if(stream.current() === '\\'')\n return stream.match(/^[^\\\"]+\\'\\:/, false);\n else\n return false;\n}\n\nfunction isIn(state, type) {\n return (state.stack.length && state.stack[state.stack.length - 1].type == type);\n}\n\nfunction pushStateStack(state, newState) {\n state.stack.push(newState);\n}\n\nfunction popStateStack(state) {\n state.stack.pop();\n var reinstateTokenize = state.stack.length && state.stack[state.stack.length-1].tokenize;\n state.tokenize = reinstateTokenize || tokenBase;\n}\n\n// the interface for the mode API\nexport const xQuery = {\n name: \"xquery\",\n startState: function() {\n return {\n tokenize: tokenBase,\n cc: [],\n stack: []\n };\n },\n\n token: function(stream, state) {\n if (stream.eatSpace()) return null;\n var style = state.tokenize(stream, state);\n return style;\n },\n\n languageData: {\n commentTokens: {block: {open: \"(:\", close: \":)\"}}\n }\n};\n"],"names":["keywords","kw","type","style","operator","atom","qualifier","kwObj","basic","i","l","length","types","operators","axis_specifiers","chain","stream","state","f","tokenize","tokenBase","ch","next","mightBeFunction","isEQName","current","match","isEQNameAhead","tokenXMLComment","tokenCDATA","tokenPreProcessing","isclose","eat","eatSpace","c","tagName","name","popStateStack","pushStateStack","tokenAttribute","tokenTag","isInXmlBlock","test","tokenComment","tokenVariable","known","propertyIsEnumerable","eatWhile","foundColon","word","isIn","isInXmlConstructor","tokenString","maybeEnd","maybeNested","nestedCount","quote","isInString","isInXmlAttributeBlock","isVariableChar","stack","newState","push","pop","reinstateTokenize","xQuery","startState","cc","token","languageData","commentTokens","block","open","close"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/7996.index.js b/book/_build/html/_static/7996.index.js new file mode 100644 index 0000000..74ee368 --- /dev/null +++ b/book/_build/html/_static/7996.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[7996],{7996:(e,n,t)=>{t.r(n),t.d(n,{jinja2:()=>l});var a=["and","as","block","endblock","by","cycle","debug","else","elif","extends","filter","endfilter","firstof","do","for","endfor","if","endif","ifchanged","endifchanged","ifequal","endifequal","ifnotequal","set","raw","endraw","endifnotequal","in","include","load","not","now","or","parsed","regroup","reversed","spaceless","call","endcall","macro","endmacro","endspaceless","ssi","templatetag","openblock","closeblock","openvariable","closevariable","without","context","openbrace","closebrace","opencomment","closecomment","widthratio","url","with","endwith","get_current_language","trans","endtrans","noop","blocktrans","endblocktrans","get_available_languages","get_current_language_bidi","pluralize","autoescape","endautoescape"],i=/^[+\-*&%=<>!?|~^]/,r=/^[:\[\(\{]/,o=["true","false"],c=/^(\d[+\-\*\/])?\d+(\.\d+)?/;function s(e,n){var t=e.peek();if(n.incomment)return e.skipTo("#}")?(e.eatWhile(/\#|}/),n.incomment=!1):e.skipToEnd(),"comment";if(n.intag){if(n.operator){if(n.operator=!1,e.match(o))return"atom";if(e.match(c))return"number"}if(n.sign){if(n.sign=!1,e.match(o))return"atom";if(e.match(c))return"number"}if(n.instring)return t==n.instring&&(n.instring=!1),e.next(),"string";if("'"==t||'"'==t)return n.instring=t,e.next(),"string";if(n.inbraces>0&&")"==t)e.next(),n.inbraces--;else if("("==t)e.next(),n.inbraces++;else if(n.inbrackets>0&&"]"==t)e.next(),n.inbrackets--;else if("["==t)e.next(),n.inbrackets++;else{if(!n.lineTag&&(e.match(n.intag+"}")||e.eat("-")&&e.match(n.intag+"}")))return n.intag=!1,"tag";if(e.match(i))return n.operator=!0,"operator";if(e.match(r))n.sign=!0;else{if(1==e.column()&&n.lineTag&&e.match(a))return"keyword";if(e.eat(" ")||e.sol()){if(e.match(a))return"keyword";if(e.match(o))return"atom";if(e.match(c))return"number";e.sol()&&e.next()}else e.next()}}return"variable"}if(e.eat("{")){if(e.eat("#"))return n.incomment=!0,e.skipTo("#}")?(e.eatWhile(/\#|}/),n.incomment=!1):e.skipToEnd(),"comment";if(t=e.eat(/\{|%/))return n.intag=t,n.inbraces=0,n.inbrackets=0,"{"==t&&(n.intag="}"),e.eat("-"),"tag"}else if(e.eat("#")){if("#"==e.peek())return e.skipToEnd(),"comment";if(!e.eol())return n.intag=!0,n.lineTag=!0,n.inbraces=0,n.inbrackets=0,"tag"}e.next()}a=new RegExp("(("+a.join(")|(")+"))\\b"),o=new RegExp("(("+o.join(")|(")+"))\\b");const l={name:"jinja2",startState:function(){return{tokenize:s,inbrackets:0,inbraces:0}},token:function(e,n){var t=n.tokenize(e,n);return e.eol()&&n.lineTag&&!n.instring&&0==n.inbraces&&0==n.inbrackets&&(n.intag=!1,n.lineTag=!1),t},languageData:{commentTokens:{block:{open:"{#",close:"#}",line:"##"}}}}}}]); +//# sourceMappingURL=7996.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/7996.index.js.map b/book/_build/html/_static/7996.index.js.map new file mode 100644 index 0000000..93b7352 --- /dev/null +++ b/book/_build/html/_static/7996.index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P,EAAMa,SAAU,EAChBb,EAAMW,SAAW,EACjBX,EAAMY,WAAa,EACZ,KAEX,CACAb,EAAOW,MACT,CApIAjB,EAAW,IAAIyB,OAAO,KAAOzB,EAAS0B,KAAK,OAAS,SACpDvB,EAAO,IAAIsB,OAAO,KAAOtB,EAAKuB,KAAK,OAAS,SAqIrC,MAAMC,EAAS,CACpBC,KAAM,SACNC,WAAY,WACV,MAAO,CAACC,SAAUzB,EAAWc,WAAY,EAAGD,SAAU,EACxD,EACAa,MAAO,SAASzB,EAAQC,GACtB,IAAIyB,EAAQzB,EAAMuB,SAASxB,EAAQC,GAMnC,OALID,EAAOkB,OAASjB,EAAMa,UAAYb,EAAMS,UAA8B,GAAlBT,EAAMW,UAAqC,GAApBX,EAAMY,aAEnFZ,EAAMO,OAAQ,EACdP,EAAMa,SAAU,GAEXY,CACT,EACAC,aAAc,CACZC,cAAe,CAACC,MAAO,CAACC,KAAM,KAAMC,MAAO,KAAMC,KAAM,Q","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/jinja2.js"],"sourcesContent":["var keywords = [\"and\", \"as\", \"block\", \"endblock\", \"by\", \"cycle\", \"debug\", \"else\", \"elif\",\n \"extends\", \"filter\", \"endfilter\", \"firstof\", \"do\", \"for\",\n \"endfor\", \"if\", \"endif\", \"ifchanged\", \"endifchanged\",\n \"ifequal\", \"endifequal\", \"ifnotequal\", \"set\", \"raw\", \"endraw\",\n \"endifnotequal\", \"in\", \"include\", \"load\", \"not\", \"now\", \"or\",\n \"parsed\", \"regroup\", \"reversed\", \"spaceless\", \"call\", \"endcall\", \"macro\",\n \"endmacro\", \"endspaceless\", \"ssi\", \"templatetag\", \"openblock\",\n \"closeblock\", \"openvariable\", \"closevariable\", \"without\", \"context\",\n \"openbrace\", \"closebrace\", \"opencomment\",\n \"closecomment\", \"widthratio\", \"url\", \"with\", \"endwith\",\n \"get_current_language\", \"trans\", \"endtrans\", \"noop\", \"blocktrans\",\n \"endblocktrans\", \"get_available_languages\",\n \"get_current_language_bidi\", \"pluralize\", \"autoescape\", \"endautoescape\"],\n operator = /^[+\\-*&%=<>!?|~^]/,\n sign = /^[:\\[\\(\\{]/,\n atom = [\"true\", \"false\"],\n number = /^(\\d[+\\-\\*\\/])?\\d+(\\.\\d+)?/;\n\nkeywords = new RegExp(\"((\" + keywords.join(\")|(\") + \"))\\\\b\");\natom = new RegExp(\"((\" + atom.join(\")|(\") + \"))\\\\b\");\n\nfunction tokenBase (stream, state) {\n var ch = stream.peek();\n\n //Comment\n if (state.incomment) {\n if(!stream.skipTo(\"#}\")) {\n stream.skipToEnd();\n } else {\n stream.eatWhile(/\\#|}/);\n state.incomment = false;\n }\n return \"comment\";\n //Tag\n } else if (state.intag) {\n //After operator\n if(state.operator) {\n state.operator = false;\n if(stream.match(atom)) {\n return \"atom\";\n }\n if(stream.match(number)) {\n return \"number\";\n }\n }\n //After sign\n if(state.sign) {\n state.sign = false;\n if(stream.match(atom)) {\n return \"atom\";\n }\n if(stream.match(number)) {\n return \"number\";\n }\n }\n\n if(state.instring) {\n if(ch == state.instring) {\n state.instring = false;\n }\n stream.next();\n return \"string\";\n } else if(ch == \"'\" || ch == '\"') {\n state.instring = ch;\n stream.next();\n return \"string\";\n } else if (state.inbraces > 0 && ch ==\")\") {\n stream.next()\n state.inbraces--;\n }\n else if (ch == \"(\") {\n stream.next()\n state.inbraces++;\n }\n else if (state.inbrackets > 0 && ch ==\"]\") {\n stream.next()\n state.inbrackets--;\n }\n else if (ch == \"[\") {\n stream.next()\n state.inbrackets++;\n } else if (!state.lineTag && (stream.match(state.intag + \"}\") || stream.eat(\"-\") && stream.match(state.intag + \"}\"))) {\n state.intag = false;\n return \"tag\";\n } else if(stream.match(operator)) {\n state.operator = true;\n return \"operator\";\n } else if(stream.match(sign)) {\n state.sign = true;\n } else {\n if (stream.column() == 1 && state.lineTag && stream.match(keywords)) {\n //allow nospace after tag before the keyword\n return \"keyword\";\n }\n if(stream.eat(\" \") || stream.sol()) {\n if(stream.match(keywords)) {\n return \"keyword\";\n }\n if(stream.match(atom)) {\n return \"atom\";\n }\n if(stream.match(number)) {\n return \"number\";\n }\n if(stream.sol()) {\n stream.next();\n }\n } else {\n stream.next();\n }\n\n }\n return \"variable\";\n } else if (stream.eat(\"{\")) {\n if (stream.eat(\"#\")) {\n state.incomment = true;\n if(!stream.skipTo(\"#}\")) {\n stream.skipToEnd();\n } else {\n stream.eatWhile(/\\#|}/);\n state.incomment = false;\n }\n return \"comment\";\n //Open tag\n } else if (ch = stream.eat(/\\{|%/)) {\n //Cache close tag\n state.intag = ch;\n state.inbraces = 0;\n state.inbrackets = 0;\n if(ch == \"{\") {\n state.intag = \"}\";\n }\n stream.eat(\"-\");\n return \"tag\";\n }\n //Line statements\n } else if (stream.eat('#')) {\n if (stream.peek() == '#') {\n stream.skipToEnd();\n return \"comment\"\n }\n else if (!stream.eol()) {\n state.intag = true;\n state.lineTag = true;\n state.inbraces = 0;\n state.inbrackets = 0;\n return \"tag\";\n }\n }\n stream.next();\n};\n\nexport const jinja2 = {\n name: \"jinja2\",\n startState: function () {\n return {tokenize: tokenBase, inbrackets: 0, inbraces: 0};\n },\n token: function(stream, state) {\n var style = state.tokenize(stream, state);\n if (stream.eol() && state.lineTag && !state.instring && state.inbraces == 0 && state.inbrackets == 0) {\n //Close line statement at the EOL\n state.intag = false\n state.lineTag = false\n }\n return style;\n },\n languageData: {\n commentTokens: {block: {open: \"{#\", close: \"#}\", line: \"##\"}}\n }\n};\n"],"names":["keywords","operator","sign","atom","number","tokenBase","stream","state","ch","peek","incomment","skipTo","eatWhile","skipToEnd","intag","match","instring","next","inbraces","inbrackets","lineTag","eat","column","sol","eol","RegExp","join","jinja2","name","startState","tokenize","token","style","languageData","commentTokens","block","open","close","line"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/805.index.js b/book/_build/html/_static/805.index.js new file mode 100644 index 0000000..a07b5cb --- /dev/null +++ b/book/_build/html/_static/805.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[805],{90805:(e,t,n)=>{n.r(t),n.d(t,{liveScript:()=>m});var r=function(e,t){var n=t.next||"start";if(n){t.next=t.next;var r=s[n];if(r.splice){for(var o=0;o|\\b(?:e(?:lse|xport)|d(?:o|efault)|t(?:ry|hen)|finally|import(?:\\s*all)?|const|var|let|new|catch(?:\\s*"+o+")?))\\s*$"),x="(?![$\\w]|-[A-Za-z]|\\s*:(?![:=]))",g={token:"string",regex:".+"},s={start:[{token:"docComment",regex:"/\\*",next:"comment"},{token:"comment",regex:"#.*"},{token:"keyword",regex:"(?:t(?:h(?:is|row|en)|ry|ypeof!?)|c(?:on(?:tinue|st)|a(?:se|tch)|lass)|i(?:n(?:stanceof)?|mp(?:ort(?:\\s+all)?|lements)|[fs])|d(?:e(?:fault|lete|bugger)|o)|f(?:or(?:\\s+own)?|inally|unction)|s(?:uper|witch)|e(?:lse|x(?:tends|port)|val)|a(?:nd|rguments)|n(?:ew|ot)|un(?:less|til)|w(?:hile|ith)|o[fr]|return|break|let|var|loop)"+x},{token:"atom",regex:"(?:true|false|yes|no|on|off|null|void|undefined)"+x},{token:"invalid",regex:"(?:p(?:ackage|r(?:ivate|otected)|ublic)|i(?:mplements|nterface)|enum|static|yield)"+x},{token:"className.standard",regex:"(?:R(?:e(?:gExp|ferenceError)|angeError)|S(?:tring|yntaxError)|E(?:rror|valError)|Array|Boolean|Date|Function|Number|Object|TypeError|URIError)"+x},{token:"variableName.function.standard",regex:"(?:is(?:NaN|Finite)|parse(?:Int|Float)|Math|JSON|(?:en|de)codeURI(?:Component)?)"+x},{token:"variableName.standard",regex:"(?:t(?:hat|il|o)|f(?:rom|allthrough)|it|by|e)"+x},{token:"variableName",regex:o+"\\s*:(?![:=])"},{token:"variableName",regex:o},{token:"operatorKeyword",regex:"(?:\\.{3}|\\s+\\?)"},{token:"keyword",regex:"(?:@+|::|\\.\\.)",next:"key"},{token:"operatorKeyword",regex:"\\.\\s*",next:"key"},{token:"string",regex:"\\\\\\S[^\\s,;)}\\]]*"},{token:"docString",regex:"'''",next:"qdoc"},{token:"docString",regex:'"""',next:"qqdoc"},{token:"string",regex:"'",next:"qstring"},{token:"string",regex:'"',next:"qqstring"},{token:"string",regex:"`",next:"js"},{token:"string",regex:"<\\[",next:"words"},{token:"regexp",regex:"//",next:"heregex"},{token:"regexp",regex:"\\/(?:[^[\\/\\n\\\\]*(?:(?:\\\\.|\\[[^\\]\\n\\\\]*(?:\\\\.[^\\]\\n\\\\]*)*\\])[^[\\/\\n\\\\]*)*)\\/[gimy$]{0,4}",next:"key"},{token:"number",regex:"(?:0x[\\da-fA-F][\\da-fA-F_]*|(?:[2-9]|[12]\\d|3[0-6])r[\\da-zA-Z][\\da-zA-Z_]*|(?:\\d[\\d_]*(?:\\.\\d[\\d_]*)?|\\.\\d[\\d_]*)(?:e[+-]?\\d[\\d_]*)?[\\w$]*)"},{token:"paren",regex:"[({[]"},{token:"paren",regex:"[)}\\]]",next:"key"},{token:"operatorKeyword",regex:"\\S+"},{token:"content",regex:"\\s+"}],heregex:[{token:"regexp",regex:".*?//[gimy$?]{0,4}",next:"start"},{token:"regexp",regex:"\\s*#{"},{token:"comment",regex:"\\s+(?:#.*)?"},{token:"regexp",regex:"\\S+"}],key:[{token:"operatorKeyword",regex:"[.?@!]+"},{token:"variableName",regex:o,next:"start"},{token:"content",regex:"",next:"start"}],comment:[{token:"docComment",regex:".*?\\*/",next:"start"},{token:"docComment",regex:".+"}],qdoc:[{token:"string",regex:".*?'''",next:"key"},g],qqdoc:[{token:"string",regex:'.*?"""',next:"key"},g],qstring:[{token:"string",regex:"[^\\\\']*(?:\\\\.[^\\\\']*)*'",next:"key"},g],qqstring:[{token:"string",regex:'[^\\\\"]*(?:\\\\.[^\\\\"]*)*"',next:"key"},g],js:[{token:"string",regex:"[^\\\\`]*(?:\\\\.[^\\\\`]*)*`",next:"key"},g],words:[{token:"string",regex:".*?\\]>",next:"key"},g]};for(var i in s){var k=s[i];if(k.splice)for(var l=0,c=k.length;l|\\\\b(?:e(?:lse|xport)|d(?:o|efault)|t(?:ry|hen)|finally|import(?:\\\\s*all)?|const|var|let|new|catch(?:\\\\s*' + identifier + ')?))\\\\s*$');\nvar keywordend = '(?![$\\\\w]|-[A-Za-z]|\\\\s*:(?![:=]))';\nvar stringfill = {\n token: 'string',\n regex: '.+'\n};\nvar Rules = {\n start: [\n {\n token: 'docComment',\n regex: '/\\\\*',\n next: 'comment'\n }, {\n token: 'comment',\n regex: '#.*'\n }, {\n token: 'keyword',\n regex: '(?:t(?:h(?:is|row|en)|ry|ypeof!?)|c(?:on(?:tinue|st)|a(?:se|tch)|lass)|i(?:n(?:stanceof)?|mp(?:ort(?:\\\\s+all)?|lements)|[fs])|d(?:e(?:fault|lete|bugger)|o)|f(?:or(?:\\\\s+own)?|inally|unction)|s(?:uper|witch)|e(?:lse|x(?:tends|port)|val)|a(?:nd|rguments)|n(?:ew|ot)|un(?:less|til)|w(?:hile|ith)|o[fr]|return|break|let|var|loop)' + keywordend\n }, {\n token: 'atom',\n regex: '(?:true|false|yes|no|on|off|null|void|undefined)' + keywordend\n }, {\n token: 'invalid',\n regex: '(?:p(?:ackage|r(?:ivate|otected)|ublic)|i(?:mplements|nterface)|enum|static|yield)' + keywordend\n }, {\n token: 'className.standard',\n regex: '(?:R(?:e(?:gExp|ferenceError)|angeError)|S(?:tring|yntaxError)|E(?:rror|valError)|Array|Boolean|Date|Function|Number|Object|TypeError|URIError)' + keywordend\n }, {\n token: 'variableName.function.standard',\n regex: '(?:is(?:NaN|Finite)|parse(?:Int|Float)|Math|JSON|(?:en|de)codeURI(?:Component)?)' + keywordend\n }, {\n token: 'variableName.standard',\n regex: '(?:t(?:hat|il|o)|f(?:rom|allthrough)|it|by|e)' + keywordend\n }, {\n token: 'variableName',\n regex: identifier + '\\\\s*:(?![:=])'\n }, {\n token: 'variableName',\n regex: identifier\n }, {\n token: 'operatorKeyword',\n regex: '(?:\\\\.{3}|\\\\s+\\\\?)'\n }, {\n token: 'keyword',\n regex: '(?:@+|::|\\\\.\\\\.)',\n next: 'key'\n }, {\n token: 'operatorKeyword',\n regex: '\\\\.\\\\s*',\n next: 'key'\n }, {\n token: 'string',\n regex: '\\\\\\\\\\\\S[^\\\\s,;)}\\\\]]*'\n }, {\n token: 'docString',\n regex: '\\'\\'\\'',\n next: 'qdoc'\n }, {\n token: 'docString',\n regex: '\"\"\"',\n next: 'qqdoc'\n }, {\n token: 'string',\n regex: '\\'',\n next: 'qstring'\n }, {\n token: 'string',\n regex: '\"',\n next: 'qqstring'\n }, {\n token: 'string',\n regex: '`',\n next: 'js'\n }, {\n token: 'string',\n regex: '<\\\\[',\n next: 'words'\n }, {\n token: 'regexp',\n regex: '//',\n next: 'heregex'\n }, {\n token: 'regexp',\n regex: '\\\\/(?:[^[\\\\/\\\\n\\\\\\\\]*(?:(?:\\\\\\\\.|\\\\[[^\\\\]\\\\n\\\\\\\\]*(?:\\\\\\\\.[^\\\\]\\\\n\\\\\\\\]*)*\\\\])[^[\\\\/\\\\n\\\\\\\\]*)*)\\\\/[gimy$]{0,4}',\n next: 'key'\n }, {\n token: 'number',\n regex: '(?:0x[\\\\da-fA-F][\\\\da-fA-F_]*|(?:[2-9]|[12]\\\\d|3[0-6])r[\\\\da-zA-Z][\\\\da-zA-Z_]*|(?:\\\\d[\\\\d_]*(?:\\\\.\\\\d[\\\\d_]*)?|\\\\.\\\\d[\\\\d_]*)(?:e[+-]?\\\\d[\\\\d_]*)?[\\\\w$]*)'\n }, {\n token: 'paren',\n regex: '[({[]'\n }, {\n token: 'paren',\n regex: '[)}\\\\]]',\n next: 'key'\n }, {\n token: 'operatorKeyword',\n regex: '\\\\S+'\n }, {\n token: 'content',\n regex: '\\\\s+'\n }\n ],\n heregex: [\n {\n token: 'regexp',\n regex: '.*?//[gimy$?]{0,4}',\n next: 'start'\n }, {\n token: 'regexp',\n regex: '\\\\s*#{'\n }, {\n token: 'comment',\n regex: '\\\\s+(?:#.*)?'\n }, {\n token: 'regexp',\n regex: '\\\\S+'\n }\n ],\n key: [\n {\n token: 'operatorKeyword',\n regex: '[.?@!]+'\n }, {\n token: 'variableName',\n regex: identifier,\n next: 'start'\n }, {\n token: 'content',\n regex: '',\n next: 'start'\n }\n ],\n comment: [\n {\n token: 'docComment',\n regex: '.*?\\\\*/',\n next: 'start'\n }, {\n token: 'docComment',\n regex: '.+'\n }\n ],\n qdoc: [\n {\n token: 'string',\n regex: \".*?'''\",\n next: 'key'\n }, stringfill\n ],\n qqdoc: [\n {\n token: 'string',\n regex: '.*?\"\"\"',\n next: 'key'\n }, stringfill\n ],\n qstring: [\n {\n token: 'string',\n regex: '[^\\\\\\\\\\']*(?:\\\\\\\\.[^\\\\\\\\\\']*)*\\'',\n next: 'key'\n }, stringfill\n ],\n qqstring: [\n {\n token: 'string',\n regex: '[^\\\\\\\\\"]*(?:\\\\\\\\.[^\\\\\\\\\"]*)*\"',\n next: 'key'\n }, stringfill\n ],\n js: [\n {\n token: 'string',\n regex: '[^\\\\\\\\`]*(?:\\\\\\\\.[^\\\\\\\\`]*)*`',\n next: 'key'\n }, stringfill\n ],\n words: [\n {\n token: 'string',\n regex: '.*?\\\\]>',\n next: 'key'\n }, stringfill\n ]\n};\nfor (var idx in Rules) {\n var r = Rules[idx];\n if (r.splice) {\n for (var i = 0, len = r.length; i < len; ++i) {\n var rr = r[i];\n if (typeof rr.regex === 'string') {\n Rules[idx][i].regex = new RegExp('^' + rr.regex);\n }\n }\n } else if (typeof rr.regex === 'string') {\n Rules[idx].regex = new RegExp('^' + r.regex);\n }\n}\n\nexport const liveScript = {\n name: \"livescript\",\n startState: function(){\n return {\n next: 'start',\n lastToken: {style: null, indent: 0, content: \"\"}\n };\n },\n token: function(stream, state){\n while (stream.pos == stream.start)\n var style = tokenBase(stream, state);\n state.lastToken = {\n style: style,\n indent: stream.indentation(),\n content: stream.current()\n };\n return style.replace(/\\./g, ' ');\n },\n indent: function(state){\n var indentation = state.lastToken.indent;\n if (state.lastToken.content.match(indenter)) {\n indentation += 2;\n }\n return indentation;\n }\n};\n"],"names":["tokenBase","stream","state","next_rule","next","nr","Rules","splice","i$","length","r","regex","match","token","identifier","indenter","RegExp","keywordend","stringfill","start","heregex","key","comment","qdoc","qqdoc","qstring","qqstring","js","words","idx","i","len","rr","liveScript","name","startState","lastToken","style","indent","content","pos","indentation","current","replace"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/81.index.js b/book/_build/html/_static/81.index.js new file mode 100644 index 0000000..5a9d9db --- /dev/null +++ b/book/_build/html/_static/81.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[81],{50081:(r,e,t)=>{t.r(e),t.d(e,{rpmChanges:()=>o,rpmSpec:()=>h});var a=/^-+$/,n=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ?\d{1,2} \d{2}:\d{2}(:\d{2})? [A-Z]{3,4} \d{4} - /,c=/^[\w+.-]+@[\w.-]+/;const o={name:"rpmchanges",token:function(r){if(r.sol()){if(r.match(a))return"tag";if(r.match(n))return"tag"}return r.match(c)?"string":(r.next(),null)}};var i=/^(i386|i586|i686|x86_64|ppc64le|ppc64|ppc|ia64|s390x|s390|sparc64|sparcv9|sparc|noarch|alphaev6|alpha|hppa|mipsel)/,p=/^[a-zA-Z0-9()]+:/,u=/^%(debug_package|package|description|prep|build|install|files|clean|changelog|preinstall|preun|postinstall|postun|pretrans|posttrans|pre|post|triggerin|triggerun|verifyscript|check|triggerpostun|triggerprein|trigger)/,s=/^%(ifnarch|ifarch|if)/,l=/^%(else|endif)/,m=/^(\!|\?|\<\=|\<|\>\=|\>|\=\=|\&\&|\|\|)/;const h={name:"rpmspec",startState:function(){return{controlFlow:!1,macroParameters:!1,section:!1}},token:function(r,e){if("#"==r.peek())return r.skipToEnd(),"comment";if(r.sol()){if(r.match(p))return"header";if(r.match(u))return"atom"}if(r.match(/^\$\w+/))return"def";if(r.match(/^\$\{\w+\}/))return"def";if(r.match(l))return"keyword";if(r.match(s))return e.controlFlow=!0,"keyword";if(e.controlFlow){if(r.match(m))return"operator";if(r.match(/^(\d+)/))return"number";r.eol()&&(e.controlFlow=!1)}if(r.match(i))return r.eol()&&(e.controlFlow=!1),"number";if(r.match(/^%[\w]+/))return r.match("(")&&(e.macroParameters=!0),"keyword";if(e.macroParameters){if(r.match(/^\d+/))return"number";if(r.match(")"))return e.macroParameters=!1,"keyword"}return r.match(/^%\{\??[\w \-\:\!]+\}/)?(r.eol()&&(e.controlFlow=!1),"def"):(r.next(),null)}}}}]); +//# sourceMappingURL=81.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/81.index.js.map b/book/_build/html/_static/81.index.js.map new file mode 100644 index 0000000..8ac7991 --- /dev/null +++ b/book/_build/html/_static/81.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"81.index.js","mappings":"4IAAA,IAAIA,EAAkB,OAClBC,EAAa,sIACbC,EAAc,oBAEX,MAAMC,EAAa,CACxBC,KAAM,aACNC,MAAO,SAASC,GACd,GAAIA,EAAOC,MAAO,CAChB,GAAID,EAAOE,MAAMR,GAAoB,MAAO,MAC5C,GAAIM,EAAOE,MAAMP,GAAe,MAAO,KACzC,CACA,OAAIK,EAAOE,MAAMN,GAAuB,UACxCI,EAAOG,OACA,KACT,GAKF,IAAIC,EAAO,qHAEPC,EAAW,mBACXC,EAAU,2NACVC,EAAuB,wBACvBC,EAAsB,iBACtBC,EAAY,0CAET,MAAMC,EAAU,CACrBZ,KAAM,UACNa,WAAY,WACV,MAAO,CACLC,aAAa,EACbC,iBAAiB,EACjBP,SAAS,EAEb,EACAP,MAAO,SAAUC,EAAQc,GAEvB,GAAU,KADDd,EAAOe,OACqB,OAApBf,EAAOgB,YAAoB,UAE5C,GAAIhB,EAAOC,MAAO,CAChB,GAAID,EAAOE,MAAMG,GAAa,MAAO,SACrC,GAAIL,EAAOE,MAAMI,GAAY,MAAO,MACtC,CAEA,GAAIN,EAAOE,MAAM,UAAa,MAAO,MACrC,GAAIF,EAAOE,MAAM,cAAiB,MAAO,MAEzC,GAAIF,EAAOE,MAAMM,GAAwB,MAAO,UAChD,GAAIR,EAAOE,MAAMK,GAEf,OADAO,EAAMF,aAAc,EACb,UAET,GAAIE,EAAMF,YAAa,CACrB,GAAIZ,EAAOE,MAAMO,GAAc,MAAO,WACtC,GAAIT,EAAOE,MAAM,UAAa,MAAO,SACjCF,EAAOiB,QAASH,EAAMF,aAAc,EAC1C,CAEA,GAAIZ,EAAOE,MAAME,GAEf,OADIJ,EAAOiB,QAASH,EAAMF,aAAc,GACjC,SAIT,GAAIZ,EAAOE,MAAM,WAEf,OADIF,EAAOE,MAAM,OAAQY,EAAMD,iBAAkB,GAC1C,UAET,GAAIC,EAAMD,gBAAiB,CACzB,GAAIb,EAAOE,MAAM,QAAW,MAAO,SACnC,GAAIF,EAAOE,MAAM,KAEf,OADAY,EAAMD,iBAAkB,EACjB,SAEX,CAGA,OAAIb,EAAOE,MAAM,0BACXF,EAAOiB,QAASH,EAAMF,aAAc,GACjC,QAGTZ,EAAOG,OACA,KACT,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/rpm.js"],"sourcesContent":["var headerSeparator = /^-+$/;\nvar headerLine = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ?\\d{1,2} \\d{2}:\\d{2}(:\\d{2})? [A-Z]{3,4} \\d{4} - /;\nvar simpleEmail = /^[\\w+.-]+@[\\w.-]+/;\n\nexport const rpmChanges = {\n name: \"rpmchanges\",\n token: function(stream) {\n if (stream.sol()) {\n if (stream.match(headerSeparator)) { return 'tag'; }\n if (stream.match(headerLine)) { return 'tag'; }\n }\n if (stream.match(simpleEmail)) { return 'string'; }\n stream.next();\n return null;\n }\n}\n\n// Quick and dirty spec file highlighting\n\nvar arch = /^(i386|i586|i686|x86_64|ppc64le|ppc64|ppc|ia64|s390x|s390|sparc64|sparcv9|sparc|noarch|alphaev6|alpha|hppa|mipsel)/;\n\nvar preamble = /^[a-zA-Z0-9()]+:/;\nvar section = /^%(debug_package|package|description|prep|build|install|files|clean|changelog|preinstall|preun|postinstall|postun|pretrans|posttrans|pre|post|triggerin|triggerun|verifyscript|check|triggerpostun|triggerprein|trigger)/;\nvar control_flow_complex = /^%(ifnarch|ifarch|if)/; // rpm control flow macros\nvar control_flow_simple = /^%(else|endif)/; // rpm control flow macros\nvar operators = /^(\\!|\\?|\\<\\=|\\<|\\>\\=|\\>|\\=\\=|\\&\\&|\\|\\|)/; // operators in control flow macros\n\nexport const rpmSpec = {\n name: \"rpmspec\",\n startState: function () {\n return {\n controlFlow: false,\n macroParameters: false,\n section: false\n };\n },\n token: function (stream, state) {\n var ch = stream.peek();\n if (ch == \"#\") { stream.skipToEnd(); return \"comment\"; }\n\n if (stream.sol()) {\n if (stream.match(preamble)) { return \"header\"; }\n if (stream.match(section)) { return \"atom\"; }\n }\n\n if (stream.match(/^\\$\\w+/)) { return \"def\"; } // Variables like '$RPM_BUILD_ROOT'\n if (stream.match(/^\\$\\{\\w+\\}/)) { return \"def\"; } // Variables like '${RPM_BUILD_ROOT}'\n\n if (stream.match(control_flow_simple)) { return \"keyword\"; }\n if (stream.match(control_flow_complex)) {\n state.controlFlow = true;\n return \"keyword\";\n }\n if (state.controlFlow) {\n if (stream.match(operators)) { return \"operator\"; }\n if (stream.match(/^(\\d+)/)) { return \"number\"; }\n if (stream.eol()) { state.controlFlow = false; }\n }\n\n if (stream.match(arch)) {\n if (stream.eol()) { state.controlFlow = false; }\n return \"number\";\n }\n\n // Macros like '%make_install' or '%attr(0775,root,root)'\n if (stream.match(/^%[\\w]+/)) {\n if (stream.match('(')) { state.macroParameters = true; }\n return \"keyword\";\n }\n if (state.macroParameters) {\n if (stream.match(/^\\d+/)) { return \"number\";}\n if (stream.match(')')) {\n state.macroParameters = false;\n return \"keyword\";\n }\n }\n\n // Macros like '%{defined fedora}'\n if (stream.match(/^%\\{\\??[\\w \\-\\:\\!]+\\}/)) {\n if (stream.eol()) { state.controlFlow = false; }\n return \"def\";\n }\n\n stream.next();\n return null;\n }\n};\n\n"],"names":["headerSeparator","headerLine","simpleEmail","rpmChanges","name","token","stream","sol","match","next","arch","preamble","section","control_flow_complex","control_flow_simple","operators","rpmSpec","startState","controlFlow","macroParameters","state","peek","skipToEnd","eol"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/8301.index.js b/book/_build/html/_static/8301.index.js new file mode 100644 index 0000000..c1316ae --- /dev/null +++ b/book/_build/html/_static/8301.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[8301],{48301:(n,e,t)=>{t.r(e),t.d(e,{cmake:()=>c});var i=/({)?[a-zA-Z0-9_]+(})?/;function a(n,e){for(var t,i,a=!1;!n.eol()&&(t=n.next())!=e.pending;){if("$"===t&&"\\"!=i&&'"'==e.pending){a=!0;break}i=t}return a&&n.backUp(1),t==e.pending?e.continueString=!1:e.continueString=!0,"string"}const c={name:"cmake",startState:function(){return{inDefinition:!1,inInclude:!1,continueString:!1,pending:!1}},token:function(n,e){return n.eatSpace()?null:function(n,e){var t=n.next();return"$"===t?n.match(i)?"variableName.special":"variable":e.continueString?(n.backUp(1),a(n,e)):n.match(/(\s+)?\w+\(/)||n.match(/(\s+)?\w+\ \(/)?(n.backUp(1),"def"):"#"==t?(n.skipToEnd(),"comment"):"'"==t||'"'==t?(e.pending=t,a(n,e)):"("==t||")"==t?"bracket":t.match(/[0-9]/)?"number":(n.eatWhile(/[\w-]/),null)}(n,e)}}}}]); +//# sourceMappingURL=8301.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/8301.index.js.map b/book/_build/html/_static/8301.index.js.map new file mode 100644 index 0000000..2f68c21 --- /dev/null +++ b/book/_build/html/_static/8301.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"8301.index.js","mappings":"2HAAA,IAAIA,EAAiB,wBAErB,SAASC,EAAYC,EAAQC,GAE3B,IADA,IAAIC,EAASC,EAAMC,GAAY,GACvBJ,EAAOK,QAAUH,EAAUF,EAAOM,SAAWL,EAAMM,SAAS,CAClE,GAAgB,MAAZL,GAA2B,MAARC,GAAiC,KAAjBF,EAAMM,QAAgB,CAC3DH,GAAY,EACZ,KACF,CACAD,EAAOD,CACT,CASA,OARIE,GACFJ,EAAOQ,OAAO,GAEZN,GAAWD,EAAMM,QACnBN,EAAMQ,gBAAiB,EAEvBR,EAAMQ,gBAAiB,EAElB,QACT,CA4CO,MAAMC,EAAQ,CACnBC,KAAM,QACNC,WAAY,WAMV,MALY,CACZX,cAAqB,EACrBA,WAAkB,EAClBA,gBAAuB,EACvBA,SAAgB,EAElB,EACAY,MAAO,SAAUb,EAAQC,GACvB,OAAID,EAAOc,WAAmB,KArDlC,SAAkBd,EAAQC,GACxB,IAAIc,EAAKf,EAAOM,OAGhB,MAAW,MAAPS,EACEf,EAAOgB,MAAMlB,GACR,uBAEF,WAGLG,EAAMQ,gBAERT,EAAOQ,OAAO,GACPT,EAAYC,EAAQC,IAIzBD,EAAOgB,MAAM,gBAAkBhB,EAAOgB,MAAM,kBAC9ChB,EAAOQ,OAAO,GACP,OAEC,KAANO,GACFf,EAAOiB,YACA,WAGC,KAANF,GAAmB,KAANA,GAEfd,EAAMM,QAAUQ,EAEThB,EAAYC,EAAQC,IAEnB,KAANc,GAAmB,KAANA,EACR,UAELA,EAAGC,MAAM,SACJ,UAEThB,EAAOkB,SAAS,SACT,KACT,CAaWC,CAASnB,EAAQC,EAC1B,E","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/cmake.js"],"sourcesContent":["var variable_regex = /({)?[a-zA-Z0-9_]+(})?/;\n\nfunction tokenString(stream, state) {\n var current, prev, found_var = false;\n while (!stream.eol() && (current = stream.next()) != state.pending) {\n if (current === '$' && prev != '\\\\' && state.pending == '\"') {\n found_var = true;\n break;\n }\n prev = current;\n }\n if (found_var) {\n stream.backUp(1);\n }\n if (current == state.pending) {\n state.continueString = false;\n } else {\n state.continueString = true;\n }\n return \"string\";\n}\n\nfunction tokenize(stream, state) {\n var ch = stream.next();\n\n // Have we found a variable?\n if (ch === '$') {\n if (stream.match(variable_regex)) {\n return 'variableName.special';\n }\n return 'variable';\n }\n // Should we still be looking for the end of a string?\n if (state.continueString) {\n // If so, go through the loop again\n stream.backUp(1);\n return tokenString(stream, state);\n }\n // Do we just have a function on our hands?\n // In 'cmake_minimum_required (VERSION 2.8.8)', 'cmake_minimum_required' is matched\n if (stream.match(/(\\s+)?\\w+\\(/) || stream.match(/(\\s+)?\\w+\\ \\(/)) {\n stream.backUp(1);\n return 'def';\n }\n if (ch == \"#\") {\n stream.skipToEnd();\n return \"comment\";\n }\n // Have we found a string?\n if (ch == \"'\" || ch == '\"') {\n // Store the type (single or double)\n state.pending = ch;\n // Perform the looping function to find the end\n return tokenString(stream, state);\n }\n if (ch == '(' || ch == ')') {\n return 'bracket';\n }\n if (ch.match(/[0-9]/)) {\n return 'number';\n }\n stream.eatWhile(/[\\w-]/);\n return null;\n}\nexport const cmake = {\n name: \"cmake\",\n startState: function () {\n var state = {};\n state.inDefinition = false;\n state.inInclude = false;\n state.continueString = false;\n state.pending = false;\n return state;\n },\n token: function (stream, state) {\n if (stream.eatSpace()) return null;\n return tokenize(stream, state);\n }\n};\n\n"],"names":["variable_regex","tokenString","stream","state","current","prev","found_var","eol","next","pending","backUp","continueString","cmake","name","startState","token","eatSpace","ch","match","skipToEnd","eatWhile","tokenize"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/8310.index.js b/book/_build/html/_static/8310.index.js new file mode 100644 index 0000000..036fdd5 --- /dev/null +++ b/book/_build/html/_static/8310.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[8310],{28310:(e,t,n)=>{function r(e){for(var t={},n=e.split(" "),r=0;rp});var a=r("#end #else #break #stop #[[ #]] #{end} #{else} #{break} #{stop}"),i=r("#if #elseif #foreach #set #include #parse #macro #define #evaluate #{if} #{elseif} #{foreach} #{set} #{include} #{parse} #{macro} #{define} #{evaluate}"),o=r("$foreach.count $foreach.hasNext $foreach.first $foreach.last $foreach.topmost $foreach.parent.count $foreach.parent.hasNext $foreach.parent.first $foreach.parent.last $foreach.parent $velocityCount $!bodyContent $bodyContent"),s=/[+\-*&%=<>!?:\/|]/;function l(e,t,n){return t.tokenize=n,n(e,t)}function u(e,t){var n=t.beforeParams;t.beforeParams=!1;var r=e.next();if("'"==r&&!t.inString&&t.inParams)return t.lastTokenWasBuiltin=!1,l(e,t,f(r));if('"'!=r){if(/[\[\]{}\(\),;\.]/.test(r))return"("==r&&n?t.inParams=!0:")"==r&&(t.inParams=!1,t.lastTokenWasBuiltin=!0),null;if(/\d/.test(r))return t.lastTokenWasBuiltin=!1,e.eatWhile(/[\w\.]/),"number";if("#"==r&&e.eat("*"))return t.lastTokenWasBuiltin=!1,l(e,t,c);if("#"==r&&e.match(/ *\[ *\[/))return t.lastTokenWasBuiltin=!1,l(e,t,k);if("#"==r&&e.eat("#"))return t.lastTokenWasBuiltin=!1,e.skipToEnd(),"comment";if("$"==r)return e.eat("!"),e.eatWhile(/[\w\d\$_\.{}-]/),o&&o.propertyIsEnumerable(e.current())?"keyword":(t.lastTokenWasBuiltin=!0,t.beforeParams=!0,"builtin");if(s.test(r))return t.lastTokenWasBuiltin=!1,e.eatWhile(s),"operator";e.eatWhile(/[\w\$_{}@]/);var u=e.current();return a&&a.propertyIsEnumerable(u)?"keyword":i&&i.propertyIsEnumerable(u)||e.current().match(/^#@?[a-z0-9_]+ *$/i)&&"("==e.peek()&&(!i||!i.propertyIsEnumerable(u.toLowerCase()))?(t.beforeParams=!0,t.lastTokenWasBuiltin=!1,"keyword"):t.inString?(t.lastTokenWasBuiltin=!1,"string"):e.pos>u.length&&"."==e.string.charAt(e.pos-u.length-1)&&t.lastTokenWasBuiltin?"builtin":(t.lastTokenWasBuiltin=!1,null)}return t.lastTokenWasBuiltin=!1,t.inString?(t.inString=!1,"string"):t.inParams?l(e,t,f(r)):void 0}function f(e){return function(t,n){for(var r,a=!1,i=!1;null!=(r=t.next());){if(r==e&&!a){i=!0;break}if('"'==e&&"$"==t.peek()&&!a){n.inString=!0,i=!0;break}a=!a&&"\\"==r}return i&&(n.tokenize=u),"string"}}function c(e,t){for(var n,r=!1;n=e.next();){if("#"==n&&r){t.tokenize=u;break}r="*"==n}return"comment"}function k(e,t){for(var n,r=0;n=e.next();){if("#"==n&&2==r){t.tokenize=u;break}"]"==n?r++:" "!=n&&(r=0)}return"meta"}const p={name:"velocity",startState:function(){return{tokenize:u,beforeParams:!1,inParams:!1,inString:!1,lastTokenWasBuiltin:!1}},token:function(e,t){return e.eatSpace()?null:t.tokenize(e,t)},languageData:{commentTokens:{line:"##",block:{open:"#*",close:"*#"}}}}}}]); +//# sourceMappingURL=8310.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/8310.index.js.map b/book/_build/html/_static/8310.index.js.map new file mode 100644 index 0000000..598b030 --- /dev/null +++ b/book/_build/html/_static/8310.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"8310.index.js","mappings":"+FAAA,SAASA,EAAWC,GAElB,IADA,IAAIC,EAAM,CAAC,EAAGC,EAAQF,EAAIG,MAAM,KACvBC,EAAI,EAAGA,EAAIF,EAAMG,SAAUD,EAAGH,EAAIC,EAAME,KAAM,EACvD,OAAOH,CACT,C,+BAEA,IAAIK,EAAWP,EAAW,mEAEtBQ,EAAYR,EAAW,2JAEvBS,EAAWT,EAAW,oOACtBU,EAAiB,oBAErB,SAASC,EAAMC,EAAQC,EAAOC,GAE5B,OADAD,EAAME,SAAWD,EACVA,EAAEF,EAAQC,EACnB,CACA,SAASG,EAAUJ,EAAQC,GACzB,IAAII,EAAeJ,EAAMI,aACzBJ,EAAMI,cAAe,EACrB,IAAIC,E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AASlC,EAAQC,GACtB,OAAID,EAAOmC,WAAmB,KACvBlC,EAAME,SAASH,EAAQC,EAChC,EACAmC,aAAc,CACZC,cAAe,CAACC,KAAM,KAAMC,MAAO,CAACC,KAAM,KAAMC,MAAO,Q","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/velocity.js"],"sourcesContent":["function parseWords(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n}\n\nvar keywords = parseWords(\"#end #else #break #stop #[[ #]] \" +\n \"#{end} #{else} #{break} #{stop}\");\nvar functions = parseWords(\"#if #elseif #foreach #set #include #parse #macro #define #evaluate \" +\n \"#{if} #{elseif} #{foreach} #{set} #{include} #{parse} #{macro} #{define} #{evaluate}\");\nvar specials = parseWords(\"$foreach.count $foreach.hasNext $foreach.first $foreach.last $foreach.topmost $foreach.parent.count $foreach.parent.hasNext $foreach.parent.first $foreach.parent.last $foreach.parent $velocityCount $!bodyContent $bodyContent\");\nvar isOperatorChar = /[+\\-*&%=<>!?:\\/|]/;\n\nfunction chain(stream, state, f) {\n state.tokenize = f;\n return f(stream, state);\n}\nfunction tokenBase(stream, state) {\n var beforeParams = state.beforeParams;\n state.beforeParams = false;\n var ch = stream.next();\n // start of unparsed string?\n if ((ch == \"'\") && !state.inString && state.inParams) {\n state.lastTokenWasBuiltin = false;\n return chain(stream, state, tokenString(ch));\n }\n // start of parsed string?\n else if ((ch == '\"')) {\n state.lastTokenWasBuiltin = false;\n if (state.inString) {\n state.inString = false;\n return \"string\";\n }\n else if (state.inParams)\n return chain(stream, state, tokenString(ch));\n }\n // is it one of the special signs []{}().,;? Separator?\n else if (/[\\[\\]{}\\(\\),;\\.]/.test(ch)) {\n if (ch == \"(\" && beforeParams)\n state.inParams = true;\n else if (ch == \")\") {\n state.inParams = false;\n state.lastTokenWasBuiltin = true;\n }\n return null;\n }\n // start of a number value?\n else if (/\\d/.test(ch)) {\n state.lastTokenWasBuiltin = false;\n stream.eatWhile(/[\\w\\.]/);\n return \"number\";\n }\n // multi line comment?\n else if (ch == \"#\" && stream.eat(\"*\")) {\n state.lastTokenWasBuiltin = false;\n return chain(stream, state, tokenComment);\n }\n // unparsed content?\n else if (ch == \"#\" && stream.match(/ *\\[ *\\[/)) {\n state.lastTokenWasBuiltin = false;\n return chain(stream, state, tokenUnparsed);\n }\n // single line comment?\n else if (ch == \"#\" && stream.eat(\"#\")) {\n state.lastTokenWasBuiltin = false;\n stream.skipToEnd();\n return \"comment\";\n }\n // variable?\n else if (ch == \"$\") {\n stream.eat(\"!\");\n stream.eatWhile(/[\\w\\d\\$_\\.{}-]/);\n // is it one of the specials?\n if (specials && specials.propertyIsEnumerable(stream.current())) {\n return \"keyword\";\n }\n else {\n state.lastTokenWasBuiltin = true;\n state.beforeParams = true;\n return \"builtin\";\n }\n }\n // is it a operator?\n else if (isOperatorChar.test(ch)) {\n state.lastTokenWasBuiltin = false;\n stream.eatWhile(isOperatorChar);\n return \"operator\";\n }\n else {\n // get the whole word\n stream.eatWhile(/[\\w\\$_{}@]/);\n var word = stream.current();\n // is it one of the listed keywords?\n if (keywords && keywords.propertyIsEnumerable(word))\n return \"keyword\";\n // is it one of the listed functions?\n if (functions && functions.propertyIsEnumerable(word) ||\n (stream.current().match(/^#@?[a-z0-9_]+ *$/i) && stream.peek()==\"(\") &&\n !(functions && functions.propertyIsEnumerable(word.toLowerCase()))) {\n state.beforeParams = true;\n state.lastTokenWasBuiltin = false;\n return \"keyword\";\n }\n if (state.inString) {\n state.lastTokenWasBuiltin = false;\n return \"string\";\n }\n if (stream.pos > word.length && stream.string.charAt(stream.pos-word.length-1)==\".\" && state.lastTokenWasBuiltin)\n return \"builtin\";\n // default: just a \"word\"\n state.lastTokenWasBuiltin = false;\n return null;\n }\n}\n\nfunction tokenString(quote) {\n return function(stream, state) {\n var escaped = false, next, end = false;\n while ((next = stream.next()) != null) {\n if ((next == quote) && !escaped) {\n end = true;\n break;\n }\n if (quote=='\"' && stream.peek() == '$' && !escaped) {\n state.inString = true;\n end = true;\n break;\n }\n escaped = !escaped && next == \"\\\\\";\n }\n if (end) state.tokenize = tokenBase;\n return \"string\";\n };\n}\n\nfunction tokenComment(stream, state) {\n var maybeEnd = false, ch;\n while (ch = stream.next()) {\n if (ch == \"#\" && maybeEnd) {\n state.tokenize = tokenBase;\n break;\n }\n maybeEnd = (ch == \"*\");\n }\n return \"comment\";\n}\n\nfunction tokenUnparsed(stream, state) {\n var maybeEnd = 0, ch;\n while (ch = stream.next()) {\n if (ch == \"#\" && maybeEnd == 2) {\n state.tokenize = tokenBase;\n break;\n }\n if (ch == \"]\")\n maybeEnd++;\n else if (ch != \" \")\n maybeEnd = 0;\n }\n return \"meta\";\n}\n// Interface\n\nexport const velocity = {\n name: \"velocity\",\n\n startState: function() {\n return {\n tokenize: tokenBase,\n beforeParams: false,\n inParams: false,\n inString: false,\n lastTokenWasBuiltin: false\n };\n },\n\n token: function(stream, state) {\n if (stream.eatSpace()) return null;\n return state.tokenize(stream, state);\n },\n languageData: {\n commentTokens: {line: \"##\", block: {open: \"#*\", close: \"*#\"}}\n }\n};\n"],"names":["parseWords","str","obj","words","split","i","length","keywords","functions","specials","isOperatorChar","chain","stream","state","f","tokenize","tokenBase","beforeParams","ch","next","inString","inParams","lastTokenWasBuiltin","tokenString","test","eatWhile","eat","tokenComment","match","tokenUnparsed","skipToEnd","propertyIsEnumerable","current","word","peek","toLowerCase","pos","string","charAt","quote","escaped","end","maybeEnd","velocity","name","startState","token","eatSpace","languageData","commentTokens","line","block","open","close"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/8336.index.js b/book/_build/html/_static/8336.index.js new file mode 100644 index 0000000..8d08043 --- /dev/null +++ b/book/_build/html/_static/8336.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[8336],{18336:(t,r,e)=>{function o(t){return{name:"mscgen",startState:l,copyState:u,token:(r=t,function(t,e){if(t.match(s(r.brackets),!0,!0))return"bracket";if(!e.inComment){if(t.match(/\/\*[^\*\/]*/,!0,!0))return e.inComment=!0,"comment";if(t.match(s(r.singlecomment),!0,!0))return t.skipToEnd(),"comment"}if(e.inComment)return t.match(/[^\*\/]*\*\//,!0,!0)?e.inComment=!1:t.skipToEnd(),"comment";if(!e.inString&&t.match(/\"(\\\"|[^\"])*/,!0,!0))return e.inString=!0,"string";if(e.inString)return t.match(/[^\"]*\"/,!0,!0)?e.inString=!1:t.skipToEnd(),"string";if(r.keywords&&t.match(a(r.keywords),!0,!0))return"keyword";if(t.match(a(r.options),!0,!0))return"keyword";if(t.match(a(r.arcsWords),!0,!0))return"keyword";if(t.match(s(r.arcsOthers),!0,!0))return"keyword";if(r.operators&&t.match(s(r.operators),!0,!0))return"operator";if(r.constants&&t.match(s(r.constants),!0,!0))return"variable";if(!r.inAttributeList&&r.attributes&&t.match("[",!0,!0))return r.inAttributeList=!0,"bracket";if(r.inAttributeList){if(null!==r.attributes&&t.match(a(r.attributes),!0,!0))return"attribute";if(t.match("]",!0,!0))return r.inAttributeList=!1,"bracket"}return t.next(),null}),languageData:{commentTokens:{line:"#",block:{open:"/*",close:"*/"}}}};var r}e.r(r),e.d(r,{mscgen:()=>n,msgenny:()=>i,xu:()=>c});const n=o({keywords:["msc"],options:["hscale","width","arcgradient","wordwraparcs"],constants:["true","false","on","off"],attributes:["label","idurl","id","url","linecolor","linecolour","textcolor","textcolour","textbgcolor","textbgcolour","arclinecolor","arclinecolour","arctextcolor","arctextcolour","arctextbgcolor","arctextbgcolour","arcskip"],brackets:["\\{","\\}"],arcsWords:["note","abox","rbox","box"],arcsOthers:["\\|\\|\\|","\\.\\.\\.","---","--","<->","==","<<=>>","<=>","\\.\\.","<<>>","::","<:>","->","=>>","=>",">>",":>","<-","<<=","<=","<<","<:","x-","-x"],singlecomment:["//","#"],operators:["="]}),i=o({keywords:null,options:["hscale","width","arcgradient","wordwraparcs","wordwrapentities","watermark"],constants:["true","false","on","off","auto"],attributes:null,brackets:["\\{","\\}"],arcsWords:["note","abox","rbox","box","alt","else","opt","break","par","seq","strict","neg","critical","ignore","consider","assert","loop","ref","exc"],arcsOthers:["\\|\\|\\|","\\.\\.\\.","---","--","<->","==","<<=>>","<=>","\\.\\.","<<>>","::","<:>","->","=>>","=>",">>",":>","<-","<<=","<=","<<","<:","x-","-x"],singlecomment:["//","#"],operators:["="]}),c=o({keywords:["msc","xu"],options:["hscale","width","arcgradient","wordwraparcs","wordwrapentities","watermark"],constants:["true","false","on","off","auto"],attributes:["label","idurl","id","url","linecolor","linecolour","textcolor","textcolour","textbgcolor","textbgcolour","arclinecolor","arclinecolour","arctextcolor","arctextcolour","arctextbgcolor","arctextbgcolour","arcskip","title","deactivate","activate","activation"],brackets:["\\{","\\}"],arcsWords:["note","abox","rbox","box","alt","else","opt","break","par","seq","strict","neg","critical","ignore","consider","assert","loop","ref","exc"],arcsOthers:["\\|\\|\\|","\\.\\.\\.","---","--","<->","==","<<=>>","<=>","\\.\\.","<<>>","::","<:>","->","=>>","=>",">>",":>","<-","<<=","<=","<<","<:","x-","-x"],singlecomment:["//","#"],operators:["="]});function a(t){return new RegExp("^\\b("+t.join("|")+")\\b","i")}function s(t){return new RegExp("^(?:"+t.join("|")+")","i")}function l(){return{inComment:!1,inString:!1,inAttributeList:!1,inScript:!1}}function u(t){return{inComment:t.inComment,inString:t.inString,inAttributeList:t.inAttributeList,inScript:t.inScript}}}}]); +//# sourceMappingURL=8336.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/8336.index.js.map b/book/_build/html/_static/8336.index.js.map new file mode 100644 index 0000000..0bba16d --- /dev/null +++ b/book/_build/html/_static/8336.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"8336.index.js","mappings":"+FAAA,SAASA,EAASC,GAChB,MAAO,CACLC,KAAM,SACNC,WAAYC,EACZC,UAAWC,EACXC,OAqE0BC,EArEEP,EAsEvB,SAASQ,EAASC,GACvB,GAAID,EAAQE,MAAMC,EAAWJ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Aa,CAAC,MAAO,MACrB,QAAY,CAAC,SAAU,QAAS,cAAe,eAAgB,mBAAoB,aACnF,UAAc,CAAC,OAAQ,QAAS,KAAM,MAAO,QAC7C,WAAe,CAAC,QAAS,QAAS,KAAM,MAAO,YAAa,aAAc,YAAa,aAAc,cAAe,eAAgB,eAAgB,gBAAiB,eAAgB,gBAAiB,iBAAkB,kBAAmB,UAAW,QAAS,aAAc,WAAY,cACzR,SAAa,CAAC,MAAO,OACrB,UAAc,CAAC,OAAQ,OAAQ,OAAQ,MAAO,MAAO,OAAQ,MAAO,QAAS,MAAO,MAAO,SAAU,MAAO,WAAY,SAAU,WAAY,SAAU,OAAQ,MAAO,OACvK,WAAe,CAAC,YAAa,YAAa,MAAO,KAAM,MAAO,KAAM,QAAS,MAAO,SAAU,OAAQ,KAAM,MAAO,KAAM,MAAO,KAAM,KAAM,KAAM,KAAM,MAAO,KAAM,KAAM,KAAM,KAAM,MACvL,cAAkB,CAAC,KAAM,KACzB,UAAc,CAAC,OAGjB,SAASmB,EAAmBkB,GAC1B,OAAO,IAAIC,OAAO,QAAUD,EAAOE,KAAK,KAAO,OAAQ,IACzD,CAEA,SAAS3B,EAAWyB,GAClB,OAAO,IAAIC,OAAO,OAASD,EAAOE,KAAK,KAAO,IAAK,IACrD,CAEA,SAASnC,IACP,MAAO,CACLU,WAAY,EACZG,UAAW,EACXQ,iBAAkB,EAClBe,UAAW,EAEf,CAEA,SAASlC,EAAYI,GACnB,MAAO,CACLI,UAAYJ,EAAOI,UACnBG,SAAWP,EAAOO,SAClBQ,gBAAkBf,EAAOe,gBACzBe,SAAW9B,EAAO8B,SAEtB,C","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/mscgen.js"],"sourcesContent":["function mkParser(lang) {\n return {\n name: \"mscgen\",\n startState: startStateFn,\n copyState: copyStateFn,\n token: produceTokenFunction(lang),\n languageData: {\n commentTokens: {line: \"#\", block: {open: \"/*\", close: \"*/\"}}\n }\n }\n}\n\nexport const mscgen = mkParser({\n \"keywords\" : [\"msc\"],\n \"options\" : [\"hscale\", \"width\", \"arcgradient\", \"wordwraparcs\"],\n \"constants\" : [\"true\", \"false\", \"on\", \"off\"],\n \"attributes\" : [\"label\", \"idurl\", \"id\", \"url\", \"linecolor\", \"linecolour\", \"textcolor\", \"textcolour\", \"textbgcolor\", \"textbgcolour\", \"arclinecolor\", \"arclinecolour\", \"arctextcolor\", \"arctextcolour\", \"arctextbgcolor\", \"arctextbgcolour\", \"arcskip\"],\n \"brackets\" : [\"\\\\{\", \"\\\\}\"], // [ and ] are brackets too, but these get handled in with lists\n \"arcsWords\" : [\"note\", \"abox\", \"rbox\", \"box\"],\n \"arcsOthers\" : [\"\\\\|\\\\|\\\\|\", \"\\\\.\\\\.\\\\.\", \"---\", \"--\", \"<->\", \"==\", \"<<=>>\", \"<=>\", \"\\\\.\\\\.\", \"<<>>\", \"::\", \"<:>\", \"->\", \"=>>\", \"=>\", \">>\", \":>\", \"<-\", \"<<=\", \"<=\", \"<<\", \"<:\", \"x-\", \"-x\"],\n \"singlecomment\" : [\"//\", \"#\"],\n \"operators\" : [\"=\"]\n})\n\nexport const msgenny = mkParser({\n \"keywords\" : null,\n \"options\" : [\"hscale\", \"width\", \"arcgradient\", \"wordwraparcs\", \"wordwrapentities\", \"watermark\"],\n \"constants\" : [\"true\", \"false\", \"on\", \"off\", \"auto\"],\n \"attributes\" : null,\n \"brackets\" : [\"\\\\{\", \"\\\\}\"],\n \"arcsWords\" : [\"note\", \"abox\", \"rbox\", \"box\", \"alt\", \"else\", \"opt\", \"break\", \"par\", \"seq\", \"strict\", \"neg\", \"critical\", \"ignore\", \"consider\", \"assert\", \"loop\", \"ref\", \"exc\"],\n \"arcsOthers\" : [\"\\\\|\\\\|\\\\|\", \"\\\\.\\\\.\\\\.\", \"---\", \"--\", \"<->\", \"==\", \"<<=>>\", \"<=>\", \"\\\\.\\\\.\", \"<<>>\", \"::\", \"<:>\", \"->\", \"=>>\", \"=>\", \">>\", \":>\", \"<-\", \"<<=\", \"<=\", \"<<\", \"<:\", \"x-\", \"-x\"],\n \"singlecomment\" : [\"//\", \"#\"],\n \"operators\" : [\"=\"]\n})\n\nexport const xu = mkParser({\n \"keywords\" : [\"msc\", \"xu\"],\n \"options\" : [\"hscale\", \"width\", \"arcgradient\", \"wordwraparcs\", \"wordwrapentities\", \"watermark\"],\n \"constants\" : [\"true\", \"false\", \"on\", \"off\", \"auto\"],\n \"attributes\" : [\"label\", \"idurl\", \"id\", \"url\", \"linecolor\", \"linecolour\", \"textcolor\", \"textcolour\", \"textbgcolor\", \"textbgcolour\", \"arclinecolor\", \"arclinecolour\", \"arctextcolor\", \"arctextcolour\", \"arctextbgcolor\", \"arctextbgcolour\", \"arcskip\", \"title\", \"deactivate\", \"activate\", \"activation\"],\n \"brackets\" : [\"\\\\{\", \"\\\\}\"], // [ and ] are brackets too, but these get handled in with lists\n \"arcsWords\" : [\"note\", \"abox\", \"rbox\", \"box\", \"alt\", \"else\", \"opt\", \"break\", \"par\", \"seq\", \"strict\", \"neg\", \"critical\", \"ignore\", \"consider\", \"assert\", \"loop\", \"ref\", \"exc\"],\n \"arcsOthers\" : [\"\\\\|\\\\|\\\\|\", \"\\\\.\\\\.\\\\.\", \"---\", \"--\", \"<->\", \"==\", \"<<=>>\", \"<=>\", \"\\\\.\\\\.\", \"<<>>\", \"::\", \"<:>\", \"->\", \"=>>\", \"=>\", \">>\", \":>\", \"<-\", \"<<=\", \"<=\", \"<<\", \"<:\", \"x-\", \"-x\"],\n \"singlecomment\" : [\"//\", \"#\"],\n \"operators\" : [\"=\"]\n})\n\nfunction wordRegexpBoundary(pWords) {\n return new RegExp(\"^\\\\b(\" + pWords.join(\"|\") + \")\\\\b\", \"i\");\n}\n\nfunction wordRegexp(pWords) {\n return new RegExp(\"^(?:\" + pWords.join(\"|\") + \")\", \"i\");\n}\n\nfunction startStateFn() {\n return {\n inComment : false,\n inString : false,\n inAttributeList : false,\n inScript : false\n };\n}\n\nfunction copyStateFn(pState) {\n return {\n inComment : pState.inComment,\n inString : pState.inString,\n inAttributeList : pState.inAttributeList,\n inScript : pState.inScript\n };\n}\n\nfunction produceTokenFunction(pConfig) {\n return function(pStream, pState) {\n if (pStream.match(wordRegexp(pConfig.brackets), true, true)) {\n return \"bracket\";\n }\n /* comments */\n if (!pState.inComment) {\n if (pStream.match(/\\/\\*[^\\*\\/]*/, true, true)) {\n pState.inComment = true;\n return \"comment\";\n }\n if (pStream.match(wordRegexp(pConfig.singlecomment), true, true)) {\n pStream.skipToEnd();\n return \"comment\";\n }\n }\n if (pState.inComment) {\n if (pStream.match(/[^\\*\\/]*\\*\\//, true, true))\n pState.inComment = false;\n else\n pStream.skipToEnd();\n return \"comment\";\n }\n /* strings */\n if (!pState.inString && pStream.match(/\\\"(\\\\\\\"|[^\\\"])*/, true, true)) {\n pState.inString = true;\n return \"string\";\n }\n if (pState.inString) {\n if (pStream.match(/[^\\\"]*\\\"/, true, true))\n pState.inString = false;\n else\n pStream.skipToEnd();\n return \"string\";\n }\n /* keywords & operators */\n if (!!pConfig.keywords && pStream.match(wordRegexpBoundary(pConfig.keywords), true, true))\n return \"keyword\";\n\n if (pStream.match(wordRegexpBoundary(pConfig.options), true, true))\n return \"keyword\";\n\n if (pStream.match(wordRegexpBoundary(pConfig.arcsWords), true, true))\n return \"keyword\";\n\n if (pStream.match(wordRegexp(pConfig.arcsOthers), true, true))\n return \"keyword\";\n\n if (!!pConfig.operators && pStream.match(wordRegexp(pConfig.operators), true, true))\n return \"operator\";\n\n if (!!pConfig.constants && pStream.match(wordRegexp(pConfig.constants), true, true))\n return \"variable\";\n\n /* attribute lists */\n if (!pConfig.inAttributeList && !!pConfig.attributes && pStream.match('[', true, true)) {\n pConfig.inAttributeList = true;\n return \"bracket\";\n }\n if (pConfig.inAttributeList) {\n if (pConfig.attributes !== null && pStream.match(wordRegexpBoundary(pConfig.attributes), true, true)) {\n return \"attribute\";\n }\n if (pStream.match(']', true, true)) {\n pConfig.inAttributeList = false;\n return \"bracket\";\n }\n }\n\n pStream.next();\n return null\n };\n}\n"],"names":["mkParser","lang","name","startState","startStateFn","copyState","copyStateFn","token","pConfig","pStream","pState","match","wordRegexp","brackets","inComment","singlecomment","skipToEnd","inString","keywords","wordRegexpBoundary","options","arcsWords","arcsOthers","operators","constants","inAttributeList","attributes","next","languageData","commentTokens","line","block","open","close","mscgen","msgenny","xu","pWords","RegExp","join","inScript"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/8338.index.js b/book/_build/html/_static/8338.index.js new file mode 100644 index 0000000..efcd1c2 --- /dev/null +++ b/book/_build/html/_static/8338.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[8338],{58338:(e,t,n)=>{n.r(t),n.d(t,{coffeeScript:()=>b});var r="error";function o(e){return new RegExp("^(("+e.join(")|(")+"))\\b")}var c=/^(?:->|=>|\+[+=]?|-[\-=]?|\*[\*=]?|\/[\/=]?|[=!]=|<[><]?=?|>>?=?|%=?|&=?|\|=?|\^=?|\~|!|\?|(or|and|\|\||&&|\?)=)/,i=/^(?:[()\[\]{},:`=;]|\.\.?\.?)/,f=/^[_A-Za-z$][_A-Za-z$0-9]*/,a=/^@[_A-Za-z$][_A-Za-z$0-9]*/,p=o(["and","or","not","is","isnt","in","instanceof","typeof"]),s=["for","while","loop","if","unless","else","switch","try","catch","finally","class"],u=o(s.concat(["break","by","continue","debugger","delete","do","in","of","new","return","then","this","@","throw","when","until","extends"]));s=o(s);var l=/^('{3}|\"{3}|['\"])/,d=/^(\/{3}|\/)/,h=o(["Infinity","NaN","undefined","null","true","false","on","off","yes","no"]);function m(e,t){if(e.sol()){null===t.scope.align&&(t.scope.align=!1);var n=t.scope.offset;if(e.eatSpace()){var o=e.indentation();return o>n&&"coffee"==t.scope.type?"indent":o0&&y(e,t)}if(e.eatSpace())return null;var s=e.peek();if(e.match("####"))return e.skipToEnd(),"comment";if(e.match("###"))return t.tokenize=k,t.tokenize(e,t);if("#"===s)return e.skipToEnd(),"comment";if(e.match(/^-?[0-9\.]/,!1)){var m=!1;if(e.match(/^-?\d*\.\d+(e[\+\-]?\d+)?/i)&&(m=!0),e.match(/^-?\d+\.\d*/)&&(m=!0),e.match(/^-?\.\d+/)&&(m=!0),m)return"."==e.peek()&&e.backUp(1),"number";var g=!1;if(e.match(/^-?0x[0-9a-f]+/i)&&(g=!0),e.match(/^-?[1-9]\d*(e[\+\-]?\d+)?/)&&(g=!0),e.match(/^-?0(?![\dx])/i)&&(g=!0),g)return"number"}if(e.match(l))return t.tokenize=v(e.current(),!1,"string"),t.tokenize(e,t);if(e.match(d)){if("/"!=e.current()||e.match(/^.*\//,!1))return t.tokenize=v(e.current(),!0,"string.special"),t.tokenize(e,t);e.backUp(1)}return e.match(c)||e.match(p)?"operator":e.match(i)?"punctuation":e.match(h)?"atom":e.match(a)||t.prop&&e.match(f)?"property":e.match(u)?"keyword":e.match(f)?"variable":(e.next(),r)}function v(e,t,n){return function(r,o){for(;!r.eol();)if(r.eatWhile(/[^'"\/\\]/),r.eat("\\")){if(r.next(),t&&r.eol())return n}else{if(r.match(e))return o.tokenize=m,n;r.eat(/['"\/]/)}return t&&(o.tokenize=m),n}}function k(e,t){for(;!e.eol();){if(e.eatWhile(/[^#]/),e.match("###")){t.tokenize=m;break}e.eatWhile("#")}return"comment"}function g(e,t,n="coffee"){for(var r=0,o=!1,c=null,i=t.scope;i;i=i.prev)if("coffee"===i.type||"}"==i.type){r=i.offset+e.indentUnit;break}"coffee"!==n?(o=null,c=e.column()+e.current().length):t.scope.align&&(t.scope.align=!1),t.scope={offset:r,type:n,prev:t.scope,align:o,alignOffset:c}}function y(e,t){if(t.scope.prev){if("coffee"===t.scope.type){for(var n=e.indentation(),r=!1,o=t.scope;o;o=o.prev)if(n===o.offset){r=!0;break}if(!r)return!0;for(;t.scope.prev&&t.scope.offset!==n;)t.scope=t.scope.prev;return!1}return t.scope=t.scope.prev,!1}}const b={name:"coffeescript",startState:function(){return{tokenize:m,scope:{offset:0,type:"coffee",prev:null,align:!1},prop:!1,dedent:0}},token:function(e,t){var n=null===t.scope.align&&t.scope;n&&e.sol()&&(n.align=!1);var o=function(e,t){var n=t.tokenize(e,t),o=e.current();"return"===o&&(t.dedent=!0),(("->"===o||"=>"===o)&&e.eol()||"indent"===n)&&g(e,t);var c="[({".indexOf(o);if(-1!==c&&g(e,t,"])}".slice(c,c+1)),s.exec(o)&&g(e,t),"then"==o&&y(e,t),"dedent"===n&&y(e,t))return r;if(-1!==(c="])}".indexOf(o))){for(;"coffee"==t.scope.type&&t.scope.prev;)t.scope=t.scope.prev;t.scope.type==o&&(t.scope=t.scope.prev)}return t.dedent&&e.eol()&&("coffee"==t.scope.type&&t.scope.prev&&(t.scope=t.scope.prev),t.dedent=!1),"indent"==n||"dedent"==n?null:n}(e,t);return o&&"comment"!=o&&(n&&(n.align=!0),t.prop="punctuation"==o&&"."==e.current()),o},indent:function(e,t){if(e.tokenize!=m)return 0;var n=e.scope,r=t&&"])}".indexOf(t.charAt(0))>-1;if(r)for(;"coffee"==n.type&&n.prev;)n=n.prev;var o=r&&n.type===t.charAt(0);return n.align?n.alignOffset-(o?1:0):(o?n.prev:n).offset},languageData:{commentTokens:{line:"#"}}}}}]); +//# sourceMappingURL=8338.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/8338.index.js.map b/book/_build/html/_static/8338.index.js.map new file mode 100644 index 0000000..535b9a4 --- /dev/null +++ b/book/_build/html/_static/8338.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"8338.index.js","mappings":"kIAAA,IAAIA,EAAa,QAEjB,SAASC,EAAWC,GAClB,OAAO,IAAIC,OAAO,MAAQD,EAAME,KAAK,OAAS,QAChD,CAEA,IAAIC,EAAY,mHACZC,EAAa,gCACbC,EAAc,4BACdC,EAAS,6BAETC,EAAgBR,EAAW,CAAC,MAAO,KAAM,MACb,KAAM,OAAQ,KACd,aAAc,WAC1CS,EAAiB,CAAC,MAAO,QAA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M9B,EAAQA,EAAM8B,KACvE,IAAIoB,EAASF,GAAUhD,EAAMO,OAASwC,EAAKE,OAAO,GAClD,OAAIjD,EAAMC,MACDD,EAAM6B,aAAeqB,EAAS,EAAI,IAEjCA,EAASlD,EAAM8B,KAAO9B,GAAOG,MACzC,EAEAgD,aAAc,CACZC,cAAe,CAACC,KAAM,M","sources":["webpack://thebe/../../node_modules/@codemirror/legacy-modes/mode/coffeescript.js"],"sourcesContent":["var ERRORCLASS = \"error\";\n\nfunction wordRegexp(words) {\n return new RegExp(\"^((\" + words.join(\")|(\") + \"))\\\\b\");\n}\n\nvar operators = /^(?:->|=>|\\+[+=]?|-[\\-=]?|\\*[\\*=]?|\\/[\\/=]?|[=!]=|<[><]?=?|>>?=?|%=?|&=?|\\|=?|\\^=?|\\~|!|\\?|(or|and|\\|\\||&&|\\?)=)/;\nvar delimiters = /^(?:[()\\[\\]{},:`=;]|\\.\\.?\\.?)/;\nvar identifiers = /^[_A-Za-z$][_A-Za-z$0-9]*/;\nvar atProp = /^@[_A-Za-z$][_A-Za-z$0-9]*/;\n\nvar wordOperators = wordRegexp([\"and\", \"or\", \"not\",\n \"is\", \"isnt\", \"in\",\n \"instanceof\", \"typeof\"]);\nvar indentKeywords = [\"for\", \"while\", \"loop\", \"if\", \"unless\", \"else\",\n \"switch\", \"try\", \"catch\", \"finally\", \"class\"];\nvar commonKeywords = [\"break\", \"by\", \"continue\", \"debugger\", \"delete\",\n \"do\", \"in\", \"of\", \"new\", \"return\", \"then\",\n \"this\", \"@\", \"throw\", \"when\", \"until\", \"extends\"];\n\nvar keywords = wordRegexp(indentKeywords.concat(commonKeywords));\n\nindentKeywords = wordRegexp(indentKeywords);\n\n\nvar stringPrefixes = /^('{3}|\\\"{3}|['\\\"])/;\nvar regexPrefixes = /^(\\/{3}|\\/)/;\nvar commonConstants = [\"Infinity\", \"NaN\", \"undefined\", \"null\", \"true\", \"false\", \"on\", \"off\", \"yes\", \"no\"];\nvar constants = wordRegexp(commonConstants);\n\n// Tokenizers\nfunction tokenBase(stream, state) {\n // Handle scope changes\n if (stream.sol()) {\n if (state.scope.align === null) state.scope.align = false;\n var scopeOffset = state.scope.offset;\n if (stream.eatSpace()) {\n var lineOffset = stream.indentation();\n if (lineOffset > scopeOffset && state.scope.type == \"coffee\") {\n return \"indent\";\n } else if (lineOffset < scopeOffset) {\n return \"dedent\";\n }\n return null;\n } else {\n if (scopeOffset > 0) {\n dedent(stream, state);\n }\n }\n }\n if (stream.eatSpace()) {\n return null;\n }\n\n var ch = stream.peek();\n\n // Handle docco title comment (single line)\n if (stream.match(\"####\")) {\n stream.skipToEnd();\n return \"comment\";\n }\n\n // Handle multi line comments\n if (stream.match(\"###\")) {\n state.tokenize = longComment;\n return state.tokenize(stream, state);\n }\n\n // Single line comment\n if (ch === \"#\") {\n stream.skipToEnd();\n return \"comment\";\n }\n\n // Handle number literals\n if (stream.match(/^-?[0-9\\.]/, false)) {\n var floatLiteral = false;\n // Floats\n if (stream.match(/^-?\\d*\\.\\d+(e[\\+\\-]?\\d+)?/i)) {\n floatLiteral = true;\n }\n if (stream.match(/^-?\\d+\\.\\d*/)) {\n floatLiteral = true;\n }\n if (stream.match(/^-?\\.\\d+/)) {\n floatLiteral = true;\n }\n\n if (floatLiteral) {\n // prevent from getting extra . on 1..\n if (stream.peek() == \".\"){\n stream.backUp(1);\n }\n return \"number\";\n }\n // Integers\n var intLiteral = false;\n // Hex\n if (stream.match(/^-?0x[0-9a-f]+/i)) {\n intLiteral = true;\n }\n // Decimal\n if (stream.match(/^-?[1-9]\\d*(e[\\+\\-]?\\d+)?/)) {\n intLiteral = true;\n }\n // Zero by itself with no other piece of number.\n if (stream.match(/^-?0(?![\\dx])/i)) {\n intLiteral = true;\n }\n if (intLiteral) {\n return \"number\";\n }\n }\n\n // Handle strings\n if (stream.match(stringPrefixes)) {\n state.tokenize = tokenFactory(stream.current(), false, \"string\");\n return state.tokenize(stream, state);\n }\n // Handle regex literals\n if (stream.match(regexPrefixes)) {\n if (stream.current() != \"/\" || stream.match(/^.*\\//, false)) { // prevent highlight of division\n state.tokenize = tokenFactory(stream.current(), true, \"string.special\");\n return state.tokenize(stream, state);\n } else {\n stream.backUp(1);\n }\n }\n\n\n\n // Handle operators and delimiters\n if (stream.match(operators) || stream.match(wordOperators)) {\n return \"operator\";\n }\n if (stream.match(delimiters)) {\n return \"punctuation\";\n }\n\n if (stream.match(constants)) {\n return \"atom\";\n }\n\n if (stream.match(atProp) || state.prop && stream.match(identifiers)) {\n return \"property\";\n }\n\n if (stream.match(keywords)) {\n return \"keyword\";\n }\n\n if (stream.match(identifiers)) {\n return \"variable\";\n }\n\n // Handle non-detected items\n stream.next();\n return ERRORCLASS;\n}\n\nfunction tokenFactory(delimiter, singleline, outclass) {\n return function(stream, state) {\n while (!stream.eol()) {\n stream.eatWhile(/[^'\"\\/\\\\]/);\n if (stream.eat(\"\\\\\")) {\n stream.next();\n if (singleline && stream.eol()) {\n return outclass;\n }\n } else if (stream.match(delimiter)) {\n state.tokenize = tokenBase;\n return outclass;\n } else {\n stream.eat(/['\"\\/]/);\n }\n }\n if (singleline) {\n state.tokenize = tokenBase;\n }\n return outclass;\n };\n}\n\nfunction longComment(stream, state) {\n while (!stream.eol()) {\n stream.eatWhile(/[^#]/);\n if (stream.match(\"###\")) {\n state.tokenize = tokenBase;\n break;\n }\n stream.eatWhile(\"#\");\n }\n return \"comment\";\n}\n\nfunction indent(stream, state, type = \"coffee\") {\n var offset = 0, align = false, alignOffset = null;\n for (var scope = state.scope; scope; scope = scope.prev) {\n if (scope.type === \"coffee\" || scope.type == \"}\") {\n offset = scope.offset + stream.indentUnit;\n break;\n }\n }\n if (type !== \"coffee\") {\n align = null;\n alignOffset = stream.column() + stream.current().length;\n } else if (state.scope.align) {\n state.scope.align = false;\n }\n state.scope = {\n offset: offset,\n type: type,\n prev: state.scope,\n align: align,\n alignOffset: alignOffset\n };\n}\n\nfunction dedent(stream, state) {\n if (!state.scope.prev) return;\n if (state.scope.type === \"coffee\") {\n var _indent = stream.indentation();\n var matched = false;\n for (var scope = state.scope; scope; scope = scope.prev) {\n if (_indent === scope.offset) {\n matched = true;\n break;\n }\n }\n if (!matched) {\n return true;\n }\n while (state.scope.prev && state.scope.offset !== _indent) {\n state.scope = state.scope.prev;\n }\n return false;\n } else {\n state.scope = state.scope.prev;\n return false;\n }\n}\n\nfunction tokenLexer(stream, state) {\n var style = state.tokenize(stream, state);\n var current = stream.current();\n\n // Handle scope changes.\n if (current === \"return\") {\n state.dedent = true;\n }\n if (((current === \"->\" || current === \"=>\") && stream.eol())\n || style === \"indent\") {\n indent(stream, state);\n }\n var delimiter_index = \"[({\".indexOf(current);\n if (delimiter_index !== -1) {\n indent(stream, state, \"])}\".slice(delimiter_index, delimiter_index+1));\n }\n if (indentKeywords.exec(current)){\n indent(stream, state);\n }\n if (current == \"then\"){\n dedent(stream, state);\n }\n\n\n if (style === \"dedent\") {\n if (dedent(stream, state)) {\n return ERRORCLASS;\n }\n }\n delimiter_index = \"])}\".indexOf(current);\n if (delimiter_index !== -1) {\n while (state.scope.type == \"coffee\" && state.scope.prev)\n state.scope = state.scope.prev;\n if (state.scope.type == current)\n state.scope = state.scope.prev;\n }\n if (state.dedent && stream.eol()) {\n if (state.scope.type == \"coffee\" && state.scope.prev)\n state.scope = state.scope.prev;\n state.dedent = false;\n }\n\n return style == \"indent\" || style == \"dedent\" ? null : style;\n}\n\nexport const coffeeScript = {\n name: \"coffeescript\",\n startState: function() {\n return {\n tokenize: tokenBase,\n scope: {offset: 0, type:\"coffee\", prev: null, align: false},\n prop: false,\n dedent: 0\n };\n },\n\n token: function(stream, state) {\n var fillAlign = state.scope.align === null && state.scope;\n if (fillAlign && stream.sol()) fillAlign.align = false;\n\n var style = tokenLexer(stream, state);\n if (style && style != \"comment\") {\n if (fillAlign) fillAlign.align = true;\n state.prop = style == \"punctuation\" && stream.current() == \".\"\n }\n\n return style;\n },\n\n indent: function(state, text) {\n if (state.tokenize != tokenBase) return 0;\n var scope = state.scope;\n var closer = text && \"])}\".indexOf(text.charAt(0)) > -1;\n if (closer) while (scope.type == \"coffee\" && scope.prev) scope = scope.prev;\n var closes = closer && scope.type === text.charAt(0);\n if (scope.align)\n return scope.alignOffset - (closes ? 1 : 0);\n else\n return (closes ? scope.prev : scope).offset;\n },\n\n languageData: {\n commentTokens: {line: \"#\"}\n }\n};\n"],"names":["ERRORCLASS","wordRegexp","words","RegExp","join","operators","delimiters","identifiers","atProp","wordOperators","indentKeywords","keywords","concat","stringPrefixes","regexPrefixes","constants","tokenBase","stream","state","sol","scope","align","scopeOffset","offset","eatSpace","lineOffset","indentation","type","dedent","ch","peek","match","skipToEnd","tokenize","longComment","floatLiteral","backUp","intLiteral","tokenFactory","current","prop","next","delimiter","singleline","outclass","eol","eatWhile","eat","indent","alignOffset","prev","indentUnit","column","length","_indent","matched","coffeeScript","name","startState","token","fillAlign","style","delimiter_index","indexOf","slice","exec","tokenLexer","text","closer","charAt","closes","languageData","commentTokens","line"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/838.index.js b/book/_build/html/_static/838.index.js new file mode 100644 index 0000000..1525ff5 --- /dev/null +++ b/book/_build/html/_static/838.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[838],{838:(e,n,t)=>{t.r(n),t.d(n,{apl:()=>o});var l={"+":["conjugate","add"],"−":["negate","subtract"],"×":["signOf","multiply"],"÷":["reciprocal","divide"],"⌈":["ceiling","greaterOf"],"⌊":["floor","lesserOf"],"∣":["absolute","residue"],"⍳":["indexGenerate","indexOf"],"?":["roll","deal"],"⋆":["exponentiate","toThePowerOf"],"⍟":["naturalLog","logToTheBase"],"○":["piTimes","circularFuncs"],"!":["factorial","binomial"],"⌹":["matrixInverse","matrixDivide"],"<":[null,"lessThan"],"≤":[null,"lessThanOrEqual"],"=":[null,"equals"],">":[null,"greaterThan"],"≥":[null,"greaterThanOrEqual"],"≠":[null,"notEqual"],"≡":["depth","match"],"≢":[null,"notMatch"],"∈":["enlist","membership"],"⍷":[null,"find"],"∪":["unique","union"],"∩":[null,"intersection"],"∼":["not","without"],"∨":[null,"or"],"∧":[null,"and"],"⍱":[null,"nor"],"⍲":[null,"nand"],"⍴":["shapeOf","reshape"],",":["ravel","catenate"],"⍪":[null,"firstAxisCatenate"],"⌽":["reverse","rotate"],"⊖":["axis1Reverse","axis1Rotate"],"⍉":["transpose",null],"↑":["first","take"],"↓":[null,"drop"],"⊂":["enclose","partitionWithAxis"],"⊃":["diclose","pick"],"⌷":[null,"index"],"⍋":["gradeUp",null],"⍒":["gradeDown",null],"⊤":["encode",null],"⊥":["decode",null],"⍕":["format","formatByExample"],"⍎":["execute",null],"⊣":["stop","left"],"⊢":["pass","right"]},a=/[\.\/⌿⍀¨⍣]/,r=/⍬/,u=/[\+−×÷⌈⌊∣⍳\?⋆⍟○!⌹<≤=>≥≠≡≢∈⍷∪∩∼∨∧⍱⍲⍴,⍪⌽⊖⍉↑↓⊂⊃⌷⍋⍒⊤⊥⍕⍎⊣⊢]/,i=/←/,s=/[⍝#].*$/;const o={name:"apl",startState:function(){return{prev:!1,func:!1,op:!1,string:!1,escape:!1}},token:function(e,n){var t,o,c;return e.eatSpace()?null:'"'===(t=e.next())||"'"===t?(e.eatWhile((o=t,c=!1,function(e){return c=e,e!==o||"\\"===c})),e.next(),n.prev=!0,"string"):/[\[{\(]/.test(t)?(n.prev=!1,null):/[\]}\)]/.test(t)?(n.prev=!0,null):r.test(t)?(n.prev=!1,"atom"):/[¯\d]/.test(t)?(n.func?(n.func=!1,n.prev=!1):n.prev=!0,e.eatWhile(/[\w\.]/),"number"):a.test(t)||i.test(t)?"operator":u.test(t)?(n.func=!0,n.prev=!1,l[t]?"variableName.function.standard":"variableName.function"):s.test(t)?(e.skipToEnd(),"comment"):"∘"===t&&"."===e.peek()?(e.next(),"variableName.function"):(e.eatWhile(/[\w\$_]/),n.prev=!0,"keyword")}}}}]); +//# sourceMappingURL=838.index.js.map \ No newline at end of file diff --git a/book/_build/html/_static/838.index.js.map b/book/_build/html/_static/838.index.js.map new file mode 100644 index 0000000..a5e40d1 --- /dev/null +++ b/book/_build/html/_static/838.index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"838.index.js","mappings":"sHAAA,IAAIA,EAAe,CACjB,IAAK,CAAC,YAAa,OACnB,IAAK,CAAC,SAAU,YAChB,IAAK,CAAC,SAAU,YAChB,IAAK,CAAC,aAAc,UACpB,IAAK,CAAC,UAAW,aACjB,IAAK,CAAC,QAAS,YACf,IAAK,CAAC,WAAY,WAClB,IAAK,CAAC,gBAAiB,WACvB,IAAK,CAAC,OAAQ,QACd,IAAK,CAAC,eAAgB,gBACtB,IAAK,CAAC,aAAc,gBACpB,IAAK,CAAC,UAAW,iBACjB,IAAK,CAAC,YAAa,YACnB,IAAK,CAAC,gBAAiB,gBACvB,IAAK,CAAC,KAAM,YACZ,IAAK,CAAC,KAAM,mBACZ,IAAK,CAAC,KAAM,UACZ,IAAK,CAAC,KAAM,eACZ,IAAK,CAAC,KAAM,sBACZ,IAAK,CAAC,KAAM,YACZ,IAAK,CAAC,QAAS,SACf,IAAK,CAAC,KAAM,YACZ,IAAK,CAAC,SAAU,cAChB,IAAK,CAAC,KAAM,QACZ,IAAK,CAAC,SAAU,SAChB,IAAK,CAAC,KAAM,gBACZ,IAAK,CAAC,MAAO,WACb,IAAK,CAAC,KAAM,MACZ,IAAK,CAAC,KAAM,OACZ,IAAK,CAAC,KAAM,OACZ,IAAK,CAAC,KAAM,QACZ,IAAK,CAAC,UAAW,WACjB,IAAK,CAAC,QAAS,YACf,IAAK,CAAC,KAAM,qBACZ,IAAK,CAAC,UAAW,UACjB,IAAK,CAAC,eAAgB,eACtB,IAAK,CAAC,YAAa,MACnB,IAAK,CAAC,QAAS,QACf,IAAK,CAAC,KAAM,QACZ,IAAK,CAAC,UAAW,qBACjB,IAAK,CAAC,UAAW,QACjB,IAAK,CAAC,KAAM,SACZ,IAAK,CAAC,UAAW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"],"sourcesContent":["var builtInFuncs = {\n \"+\": [\"conjugate\", \"add\"],\n \"−\": [\"negate\", \"subtract\"],\n \"×\": [\"signOf\", \"multiply\"],\n \"÷\": [\"reciprocal\", \"divide\"],\n \"⌈\": [\"ceiling\", \"greaterOf\"],\n \"⌊\": [\"floor\", \"lesserOf\"],\n \"∣\": [\"absolute\", \"residue\"],\n \"⍳\": [\"indexGenerate\", \"indexOf\"],\n \"?\": [\"roll\", \"deal\"],\n \"⋆\": [\"exponentiate\", \"toThePowerOf\"],\n \"⍟\": [\"naturalLog\", \"logToTheBase\"],\n \"○\": [\"piTimes\", \"circularFuncs\"],\n \"!\": [\"factorial\", \"binomial\"],\n \"⌹\": [\"matrixInverse\", \"matrixDivide\"],\n \"<\": [null, \"lessThan\"],\n \"≤\": [null, \"lessThanOrEqual\"],\n \"=\": [null, \"equals\"],\n \">\": [null, \"greaterThan\"],\n \"≥\": [null, \"greaterThanOrEqual\"],\n \"≠\": [null, \"notEqual\"],\n \"≡\": [\"depth\", \"match\"],\n \"≢\": [null, \"notMatch\"],\n \"∈\": [\"enlist\", \"membership\"],\n \"⍷\": [null, \"find\"],\n \"∪\": [\"unique\", \"union\"],\n \"∩\": [null, \"intersection\"],\n \"∼\": [\"not\", \"without\"],\n \"∨\": [null, \"or\"],\n \"∧\": [null, \"and\"],\n \"⍱\": [null, \"nor\"],\n \"⍲\": [null, \"nand\"],\n \"⍴\": [\"shapeOf\", \"reshape\"],\n \",\": [\"ravel\", \"catenate\"],\n \"⍪\": [null, \"firstAxisCatenate\"],\n \"⌽\": [\"reverse\", \"rotate\"],\n \"⊖\": [\"axis1Reverse\", \"axis1Rotate\"],\n \"⍉\": [\"transpose\", null],\n \"↑\": [\"first\", \"take\"],\n \"↓\": [null, \"drop\"],\n \"⊂\": [\"enclose\", \"partitionWithAxis\"],\n \"⊃\": [\"diclose\", \"pick\"],\n \"⌷\": [null, \"index\"],\n \"⍋\": [\"gradeUp\", null],\n \"⍒\": [\"gradeDown\", null],\n \"⊤\": [\"encode\", null],\n \"⊥\": [\"decode\", null],\n \"⍕\": [\"format\", \"formatByExample\"],\n \"⍎\": [\"execute\", null],\n \"⊣\": [\"stop\", \"left\"],\n \"⊢\": [\"pass\", \"right\"]\n};\n\nvar isOperator = /[\\.\\/⌿⍀¨⍣]/;\nvar isNiladic = /⍬/;\nvar isFunction = /[\\+−×÷⌈⌊∣⍳\\?⋆⍟○!⌹<≤=>≥≠≡≢∈⍷∪∩∼∨∧⍱⍲⍴,⍪⌽⊖⍉↑↓⊂⊃⌷⍋⍒⊤⊥⍕⍎⊣⊢]/;\nvar isArrow = /←/;\nvar isComment = /[⍝#].*$/;\n\nvar stringEater = function(type) {\n var prev;\n prev = false;\n return function(c) {\n prev = c;\n if (c === type) {\n return prev === \"\\\\\";\n }\n return true;\n };\n};\n\nexport const apl = {\n name: \"apl\",\n startState: function() {\n return {\n prev: false,\n func: false,\n op: false,\n string: false,\n escape: false\n };\n },\n token: function(stream, state) {\n var ch;\n if (stream.eatSpace()) {\n return null;\n }\n ch = stream.next();\n if (ch === '\"' || ch === \"'\") {\n stream.eatWhile(stringEater(ch));\n stream.next();\n state.prev = true;\n return \"string\";\n }\n if (/[\\[{\\(]/.test(ch)) {\n state.prev = false;\n return null;\n }\n if (/[\\]}\\)]/.test(ch)) {\n state.prev = true;\n return null;\n }\n if (isNiladic.test(ch)) {\n state.prev = false;\n return \"atom\";\n }\n if (/[¯\\d]/.test(ch)) {\n if (state.func) {\n state.func = false;\n state.prev = false;\n } else {\n state.prev = true;\n }\n stream.eatWhile(/[\\w\\.]/);\n return \"number\";\n }\n if (isOperator.test(ch)) {\n return \"operator\"\n }\n if (isArrow.test(ch)) {\n return \"operator\";\n }\n if (isFunction.test(ch)) {\n state.func = true;\n state.prev = false;\n return builtInFuncs[ch] ? \"variableName.function.standard\" : \"variableName.function\"\n }\n if (isComment.test(ch)) {\n stream.skipToEnd();\n return \"comment\";\n }\n if (ch === \"∘\" && stream.peek() === \".\") {\n stream.next();\n return \"variableName.function\";\n }\n stream.eatWhile(/[\\w\\$_]/);\n state.prev = true;\n return \"keyword\";\n }\n}\n"],"names":["builtInFuncs","isOperator","isNiladic","isFunction","isArrow","isComment","apl","name","startState","prev","func","op","string","escape","token","stream","state","ch","type","eatSpace","next","eatWhile","c","test","skipToEnd","peek"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/8486.index.js b/book/_build/html/_static/8486.index.js new file mode 100644 index 0000000..4c295e2 --- /dev/null +++ b/book/_build/html/_static/8486.index.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[8486],{48486:(e,t,n)=>{function r(e){for(var t={},n=0,r=e.length;nb});var a,i=["alias","and","BEGIN","begin","break","case","class","def","defined?","do","else","elsif","END","end","ensure","false","for","if","in","module","next","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield","nil","raise","throw","catch","fail","loop","callcc","caller","lambda","proc","public","protected","private","require","load","require_relative","extend","autoload","__END__","__FILE__","__LINE__","__dir__"],o=r(i),u=r(["def","class","case","for","while","until","module","catch","loop","proc","begin"]),l=r(["end","until"]),f={"[":"]","{":"}","(":")"},s={"]":"[","}":"{",")":"("};function d(e,t,n){return n.tokenize.push(e),e(t,n)}function c(e,t){if(e.sol()&&e.match("=begin")&&e.eol())return t.tokenize.push(m),"comment";if(e.eatSpace())return null;var n,r,i,o=e.next();if("`"==o||"'"==o||'"'==o)return d(h(o,"string",'"'==o||"`"==o),e,t);if("/"==o)return function(e){for(var t,n=e.pos,r=0,a=!1,i=!1;null!=(t=e.next());)if(i)i=!1;else{if("[{(".indexOf(t)>-1)r++;else if("]})".indexOf(t)>-1){if(--r<0)break}else if("/"==t&&0==r){a=!0;break}i="\\"==t}return e.backUp(e.pos-n),a}(e)?d(h(o,"string.special",!0),e,t):"operator";if("%"==o){var u="string",l=!0;e.eat("s")?u="atom":e.eat(/[WQ]/)?u="string":e.eat(/[r]/)?u="string.special":e.eat(/[wxq]/)&&(u="string",l=!1);var s=e.eat(/[^\w\s=]/);return s?(f.propertyIsEnumerable(s)&&(s=f[s]),d(h(s,u,l,!0),e,t)):"operator"}if("#"==o)return e.skipToEnd(),"comment";if("<"==o&&(n=e.match(/^<([-~])[\`\"\']?([a-zA-Z_?]\w*)[\`\"\']?(?:;|$)/)))return d((r=n[2],i=n[1],function(e,t){return i&&e.eatSpace(),e.match(r)?t.tokenize.pop():e.skipToEnd(),"string"}),e,t);if("0"==o)return e.eat("x")?e.eatWhile(/[\da-fA-F]/):e.eat("b")?e.eatWhile(/[01]/):e.eatWhile(/[0-7]/),"number";if(/\d/.test(o))return e.match(/^[\d_]*(?:\.[\d_]+)?(?:[eE][+\-]?[\d_]+)?/),"number";if("?"==o){for(;e.match(/^\\[CM]-/););return e.eat("\\")?e.eatWhile(/\w/):e.next(),"string"}if(":"==o)return e.eat("'")?d(h("'","atom",!1),e,t):e.eat('"')?d(h('"',"atom",!0),e,t):e.eat(/[\<\>]/)?(e.eat(/[\<\>]/),"atom"):e.eat(/[\+\-\*\/\&\|\:\!]/)?"atom":e.eat(/[a-zA-Z$@_\xa1-\uffff]/)?(e.eatWhile(/[\w$\xa1-\uffff]/),e.eat(/[\?\!\=]/),"atom"):"operator";if("@"==o&&e.match(/^@?[a-zA-Z_\xa1-\uffff]/))return e.eat("@"),e.eatWhile(/[\w\xa1-\uffff]/),"propertyName";if("$"==o)return e.eat(/[a-zA-Z_]/)?e.eatWhile(/[\w]/):e.eat(/\d/)?e.eat(/\d/):e.next(),"variableName.special";if(/[a-zA-Z_\xa1-\uffff]/.test(o))return e.eatWhile(/[\w\xa1-\uffff]/),e.eat(/[\?\!]/),e.eat(":")?"atom":"variable";if("|"!=o||!t.varList&&"{"!=t.lastTok&&"do"!=t.lastTok){if(/[\(\)\[\]{}\\;]/.test(o))return a=o,null;if("-"==o&&e.eat(">"))return"operator";if(/[=+\-\/*:\.^%<>~|]/.test(o)){var c=e.eatWhile(/[=+\-\/*:\.^%<>~|]/);return"."!=o||c||(a="."),"operator"}return null}return a="|",null}function p(e){return e||(e=1),function(t,n){if("}"==t.peek()){if(1==e)return n.tokenize.pop(),n.tokenize[n.tokenize.length-1](t,n);n.tokenize[n.tokenize.length-1]=p(e-1)}else"{"==t.peek()&&(n.tokenize[n.tokenize.length-1]=p(e+1));return c(t,n)}}function k(){var e=!1;return function(t,n){return e?(n.tokenize.pop(),n.tokenize[n.tokenize.length-1](t,n)):(e=!0,c(t,n))}}function h(e,t,n,r){return function(a,i){var o,u=!1;for("read-quoted-paused"===i.context.type&&(i.context=i.context.prev,a.eat("}"));null!=(o=a.next());){if(o==e&&(r||!u)){i.tokenize.pop();break}if(n&&"#"==o&&!u){if(a.eat("{")){"}"==e&&(i.context={prev:i.context,type:"read-quoted-paused"}),i.tokenize.push(p());break}if(/[@\$]/.test(a.peek())){i.tokenize.push(k());break}}u=!u&&"\\"==o}return t}}function m(e,t){return e.sol()&&e.match("=end")&&e.eol()&&t.tokenize.pop(),e.skipToEnd(),"comment"}const b={name:"ruby",startState:function(e){return{tokenize:[c],indented:0,context:{type:"top",indented:-e},continuedLine:!1,lastTok:null,varList:!1}},token:function(e,t){a=null,e.sol()&&(t.indented=e.indentation());var n,r=t.tokenize[t.tokenize.length-1](e,t),i=a;if("variable"==r){var f=e.current();"keyword"==(r="."==t.lastTok?"property":o.propertyIsEnumerable(e.current())?"keyword":/^[A-Z]/.test(f)?"tag":"def"==t.lastTok||"class"==t.lastTok||t.varList?"def":"variable")&&(i=f,u.propertyIsEnumerable(f)?n="indent":l.propertyIsEnumerable(f)?n="dedent":"if"!=f&&"unless"!=f||e.column()!=e.indentation()?"do"==f&&t.context.indented :>> :< :<< are valid symbols\n if (stream.eat(/[\\<\\>]/)) {\n stream.eat(/[\\<\\>]/);\n return \"atom\";\n }\n\n // :+ :- :/ :* :| :& :! are valid symbols\n if (stream.eat(/[\\+\\-\\*\\/\\&\\|\\:\\!]/)) {\n return \"atom\";\n }\n\n // Symbols can't start by a digit\n if (stream.eat(/[a-zA-Z$@_\\xa1-\\uffff]/)) {\n stream.eatWhile(/[\\w$\\xa1-\\uffff]/);\n // Only one ? ! = is allowed and only as the last character\n stream.eat(/[\\?\\!\\=]/);\n return \"atom\";\n }\n return \"operator\";\n } else if (ch == \"@\" && stream.match(/^@?[a-zA-Z_\\xa1-\\uffff]/)) {\n stream.eat(\"@\");\n stream.eatWhile(/[\\w\\xa1-\\uffff]/);\n return \"propertyName\";\n } else if (ch == \"$\") {\n if (stream.eat(/[a-zA-Z_]/)) {\n stream.eatWhile(/[\\w]/);\n } else if (stream.eat(/\\d/)) {\n stream.eat(/\\d/);\n } else {\n stream.next(); // Must be a special global like $: or $!\n }\n return \"variableName.special\";\n } else if (/[a-zA-Z_\\xa1-\\uffff]/.test(ch)) {\n stream.eatWhile(/[\\w\\xa1-\\uffff]/);\n stream.eat(/[\\?\\!]/);\n if (stream.eat(\":\")) return \"atom\";\n return \"variable\";\n } else if (ch == \"|\" && (state.varList || state.lastTok == \"{\" || state.lastTok == \"do\")) {\n curPunc = \"|\";\n return null;\n } else if (/[\\(\\)\\[\\]{}\\\\;]/.test(ch)) {\n curPunc = ch;\n return null;\n } else if (ch == \"-\" && stream.eat(\">\")) {\n return \"operator\";\n } else if (/[=+\\-\\/*:\\.^%<>~|]/.test(ch)) {\n var more = stream.eatWhile(/[=+\\-\\/*:\\.^%<>~|]/);\n if (ch == \".\" && !more) curPunc = \".\";\n return \"operator\";\n } else {\n return null;\n }\n}\n\nfunction regexpAhead(stream) {\n var start = stream.pos, depth = 0, next, found = false, escaped = false\n while ((next = stream.next()) != null) {\n if (!escaped) {\n if (\"[{(\".indexOf(next) > -1) {\n depth++\n } else if (\"]})\".indexOf(next) > -1) {\n depth--\n if (depth < 0) break\n } else if (next == \"/\" && depth == 0) {\n found = true\n break\n }\n escaped = next == \"\\\\\"\n } else {\n escaped = false\n }\n }\n stream.backUp(stream.pos - start)\n return found\n}\n\nfunction tokenBaseUntilBrace(depth) {\n if (!depth) depth = 1;\n return function(stream, state) {\n if (stream.peek() == \"}\") {\n if (depth == 1) {\n state.tokenize.pop();\n return state.tokenize[state.tokenize.length-1](stream, state);\n } else {\n state.tokenize[state.tokenize.length - 1] = tokenBaseUntilBrace(depth - 1);\n }\n } else if (stream.peek() == \"{\") {\n state.tokenize[state.tokenize.length - 1] = tokenBaseUntilBrace(depth + 1);\n }\n return tokenBase(stream, state);\n };\n}\nfunction tokenBaseOnce() {\n var alreadyCalled = false;\n return function(stream, state) {\n if (alreadyCalled) {\n state.tokenize.pop();\n return state.tokenize[state.tokenize.length-1](stream, state);\n }\n alreadyCalled = true;\n return tokenBase(stream, state);\n };\n}\nfunction readQuoted(quote, style, embed, unescaped) {\n return function(stream, state) {\n var escaped = false, ch;\n\n if (state.context.type === 'read-quoted-paused') {\n state.context = state.context.prev;\n stream.eat(\"}\");\n }\n\n while ((ch = stream.next()) != null) {\n if (ch == quote && (unescaped || !escaped)) {\n state.tokenize.pop();\n break;\n }\n if (embed && ch == \"#\" && !escaped) {\n if (stream.eat(\"{\")) {\n if (quote == \"}\") {\n state.context = {prev: state.context, type: 'read-quoted-paused'};\n }\n state.tokenize.push(tokenBaseUntilBrace());\n break;\n } else if (/[@\\$]/.test(stream.peek())) {\n state.tokenize.push(tokenBaseOnce());\n break;\n }\n }\n escaped = !escaped && ch == \"\\\\\";\n }\n return style;\n };\n}\nfunction readHereDoc(phrase, mayIndent) {\n return function(stream, state) {\n if (mayIndent) stream.eatSpace()\n if (stream.match(phrase)) state.tokenize.pop();\n else stream.skipToEnd();\n return \"string\";\n };\n}\nfunction readBlockComment(stream, state) {\n if (stream.sol() && stream.match(\"=end\") && stream.eol())\n state.tokenize.pop();\n stream.skipToEnd();\n return \"comment\";\n}\n\nexport const ruby = {\n name: \"ruby\",\n startState: function(indentUnit) {\n return {tokenize: [tokenBase],\n indented: 0,\n context: {type: \"top\", indented: -indentUnit},\n continuedLine: false,\n lastTok: null,\n varList: false};\n },\n\n token: function(stream, state) {\n curPunc = null;\n if (stream.sol()) state.indented = stream.indentation();\n var style = state.tokenize[state.tokenize.length-1](stream, state), kwtype;\n var thisTok = curPunc;\n if (style == \"variable\") {\n var word = stream.current();\n style = state.lastTok == \".\" ? \"property\"\n : keywords.propertyIsEnumerable(stream.current()) ? \"keyword\"\n : /^[A-Z]/.test(word) ? \"tag\"\n : (state.lastTok == \"def\" || state.lastTok == \"class\" || state.varList) ? \"def\"\n : \"variable\";\n if (style == \"keyword\") {\n thisTok = word;\n if (indentWords.propertyIsEnumerable(word)) kwtype = \"indent\";\n else if (dedentWords.propertyIsEnumerable(word)) kwtype = \"dedent\";\n else if ((word == \"if\" || word == \"unless\") && stream.column() == stream.indentation())\n kwtype = \"indent\";\n else if (word == \"do\" && state.context.indented < state.indented)\n kwtype = \"indent\";\n }\n }\n if (curPunc || (style && style != \"comment\")) state.lastTok = thisTok;\n if (curPunc == \"|\") state.varList = !state.varList;\n\n if (kwtype == \"indent\" || /[\\(\\[\\{]/.test(curPunc))\n state.context = {prev: state.context, type: curPunc || style, indented: state.indented};\n else if ((kwtype == \"dedent\" || /[\\)\\]\\}]/.test(curPunc)) && state.context.prev)\n state.context = state.context.prev;\n\n if (stream.eol())\n state.continuedLine = (curPunc == \"\\\\\" || style == \"operator\");\n return style;\n },\n\n indent: function(state, textAfter, cx) {\n if (state.tokenize[state.tokenize.length-1] != tokenBase) return null;\n var firstChar = textAfter && textAfter.charAt(0);\n var ct = state.context;\n var closed = ct.type == closing[firstChar] ||\n ct.type == \"keyword\" && /^(?:end|until|else|elsif|when|rescue)\\b/.test(textAfter);\n return ct.indented + (closed ? 0 : cx.unit) +\n (state.continuedLine ? cx.unit : 0);\n },\n\n languageData: {\n indentOnInput: /^\\s*(?:end|rescue|elsif|else|\\})$/,\n commentTokens: {line: \"#\"},\n autocomplete: keywordList\n }\n};\n\n"],"names":["wordObj","words","o","i","e","length","curPunc","keywordList","keywords","indentWords","dedentWords","opening","closing","chain","newtok","stream","state","tokenize","push","tokenBase","sol","match","eol","readBlockComment","eatSpace","m","phrase","mayIndent","ch","next","readQuoted","start","pos","depth","found","escaped","indexOf","backUp","regexpAhead","style","embed","eat","delim","propertyIsEnumerable","skipToEnd","pop","eatWhile","test","varList","lastTok","more","tokenBaseUntilBrace","peek","tokenBaseOnce","alreadyCalled","quote","unescaped","context","type","prev","ruby","name","startState","indentUnit","indented","continuedLine","token","indentation","kwtype","thisTok","word","current","column","indent","textAfter","cx","firstChar","charAt","ct","closed","unit","languageData","indentOnInput","commentTokens","line","autocomplete"],"sourceRoot":""} \ No newline at end of file diff --git a/book/_build/html/_static/8514.index.js b/book/_build/html/_static/8514.index.js new file mode 100644 index 0000000..4cccdcb --- /dev/null +++ b/book/_build/html/_static/8514.index.js @@ -0,0 +1,3 @@ +/*! For license information please see 8514.index.js.LICENSE.txt */ +(self.webpackChunkthebe=self.webpackChunkthebe||[]).push([[8514],{18257:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"apathy",author:"jannik siebert (https://github.com/janniks)",base00:"#031A16",base01:"#0B342D",base02:"#184E45",base03:"#2B685E",base04:"#5F9C92",base05:"#81B5AC",base06:"#A7CEC8",base07:"#D2E7E4",base08:"#3E9688",base09:"#3E7996",base0A:"#3E4C96",base0B:"#883E96",base0C:"#963E4C",base0D:"#96883E",base0E:"#4C963E",base0F:"#3E965B"},e.exports=t.default},86546:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"ashes",author:"jannik siebert (https://github.com/janniks)",base00:"#1C2023",base01:"#393F45",base02:"#565E65",base03:"#747C84",base04:"#ADB3BA",base05:"#C7CCD1",base06:"#DFE2E5",base07:"#F3F4F5",base08:"#C7AE95",base09:"#C7C795",base0A:"#AEC795",base0B:"#95C7AE",base0C:"#95AEC7",base0D:"#AE95C7",base0E:"#C795AE",base0F:"#C79595"},e.exports=t.default},25284:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"atelier dune",author:"bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/dune)",base00:"#20201d",base01:"#292824",base02:"#6e6b5e",base03:"#7d7a68",base04:"#999580",base05:"#a6a28c",base06:"#e8e4cf",base07:"#fefbec",base08:"#d73737",base09:"#b65611",base0A:"#cfb017",base0B:"#60ac39",base0C:"#1fad83",base0D:"#6684e1",base0E:"#b854d4",base0F:"#d43552"},e.exports=t.default},15626:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"atelier forest",author:"bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/forest)",base00:"#1b1918",base01:"#2c2421",base02:"#68615e",base03:"#766e6b",base04:"#9c9491",base05:"#a8a19f",base06:"#e6e2e0",base07:"#f1efee",base08:"#f22c40",base09:"#df5320",base0A:"#d5911a",base0B:"#5ab738",base0C:"#00ad9c",base0D:"#407ee7",base0E:"#6666ea",base0F:"#c33ff3"},e.exports=t.default},47131:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"atelier heath",author:"bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/heath)",base00:"#1b181b",base01:"#292329",base02:"#695d69",base03:"#776977",base04:"#9e8f9e",base05:"#ab9bab",base06:"#d8cad8",base07:"#f7f3f7",base08:"#ca402b",base09:"#a65926",base0A:"#bb8a35",base0B:"#379a37",base0C:"#159393",base0D:"#516aec",base0E:"#7b59c0",base0F:"#cc33cc"},e.exports=t.default},98086:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"atelier lakeside",author:"bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/lakeside/)",base00:"#161b1d",base01:"#1f292e",base02:"#516d7b",base03:"#5a7b8c",base04:"#7195a8",base05:"#7ea2b4",base06:"#c1e4f6",base07:"#ebf8ff",base08:"#d22d72",base09:"#935c25",base0A:"#8a8a0f",base0B:"#568c3b",base0C:"#2d8f6f",base0D:"#257fad",base0E:"#5d5db1",base0F:"#b72dd2"},e.exports=t.default},51441:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"atelier seaside",author:"bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/seaside/)",base00:"#131513",base01:"#242924",base02:"#5e6e5e",base03:"#687d68",base04:"#809980",base05:"#8ca68c",base06:"#cfe8cf",base07:"#f0fff0",base08:"#e6193c",base09:"#87711d",base0A:"#c3c322",base0B:"#29a329",base0C:"#1999b3",base0D:"#3d62f5",base0E:"#ad2bee",base0F:"#e619c3"},e.exports=t.default},16405:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"bespin",author:"jan t. sott",base00:"#28211c",base01:"#36312e",base02:"#5e5d5c",base03:"#666666",base04:"#797977",base05:"#8a8986",base06:"#9d9b97",base07:"#baae9e",base08:"#cf6a4c",base09:"#cf7d34",base0A:"#f9ee98",base0B:"#54be0d",base0C:"#afc4db",base0D:"#5ea6ea",base0E:"#9b859d",base0F:"#937121"},e.exports=t.default},62953:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"brewer",author:"timothée poisot (http://github.com/tpoisot)",base00:"#0c0d0e",base01:"#2e2f30",base02:"#515253",base03:"#737475",base04:"#959697",base05:"#b7b8b9",base06:"#dadbdc",base07:"#fcfdfe",base08:"#e31a1c",base09:"#e6550d",base0A:"#dca060",base0B:"#31a354",base0C:"#80b1d3",base0D:"#3182bd",base0E:"#756bb1",base0F:"#b15928"},e.exports=t.default},65785:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"bright",author:"chris kempson (http://chriskempson.com)",base00:"#000000",base01:"#303030",base02:"#505050",base03:"#b0b0b0",base04:"#d0d0d0",base05:"#e0e0e0",base06:"#f5f5f5",base07:"#ffffff",base08:"#fb0120",base09:"#fc6d24",base0A:"#fda331",base0B:"#a1c659",base0C:"#76c7b7",base0D:"#6fb3d2",base0E:"#d381c3",base0F:"#be643c"},e.exports=t.default},17666:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"chalk",author:"chris kempson (http://chriskempson.com)",base00:"#151515",base01:"#202020",base02:"#303030",base03:"#505050",base04:"#b0b0b0",base05:"#d0d0d0",base06:"#e0e0e0",base07:"#f5f5f5",base08:"#fb9fb1",base09:"#eda987",base0A:"#ddb26f",base0B:"#acc267",base0C:"#12cfc0",base0D:"#6fc2ef",base0E:"#e1a3ee",base0F:"#deaf8f"},e.exports=t.default},57864:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"codeschool",author:"brettof86",base00:"#232c31",base01:"#1c3657",base02:"#2a343a",base03:"#3f4944",base04:"#84898c",base05:"#9ea7a6",base06:"#a7cfa3",base07:"#b5d8f6",base08:"#2a5491",base09:"#43820d",base0A:"#a03b1e",base0B:"#237986",base0C:"#b02f30",base0D:"#484d79",base0E:"#c59820",base0F:"#c98344"},e.exports=t.default},14449:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"colors",author:"mrmrs (http://clrs.cc)",base00:"#111111",base01:"#333333",base02:"#555555",base03:"#777777",base04:"#999999",base05:"#bbbbbb",base06:"#dddddd",base07:"#ffffff",base08:"#ff4136",base09:"#ff851b",base0A:"#ffdc00",base0B:"#2ecc40",base0C:"#7fdbff",base0D:"#0074d9",base0E:"#b10dc9",base0F:"#85144b"},e.exports=t.default},86475:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"default",author:"chris kempson (http://chriskempson.com)",base00:"#181818",base01:"#282828",base02:"#383838",base03:"#585858",base04:"#b8b8b8",base05:"#d8d8d8",base06:"#e8e8e8",base07:"#f8f8f8",base08:"#ab4642",base09:"#dc9656",base0A:"#f7ca88",base0B:"#a1b56c",base0C:"#86c1b9",base0D:"#7cafc2",base0E:"#ba8baf",base0F:"#a16946"},e.exports=t.default},92749:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"eighties",author:"chris kempson (http://chriskempson.com)",base00:"#2d2d2d",base01:"#393939",base02:"#515151",base03:"#747369",base04:"#a09f93",base05:"#d3d0c8",base06:"#e8e6df",base07:"#f2f0ec",base08:"#f2777a",base09:"#f99157",base0A:"#ffcc66",base0B:"#99cc99",base0C:"#66cccc",base0D:"#6699cc",base0E:"#cc99cc",base0F:"#d27b53"},e.exports=t.default},35951:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"embers",author:"jannik siebert (https://github.com/janniks)",base00:"#16130F",base01:"#2C2620",base02:"#433B32",base03:"#5A5047",base04:"#8A8075",base05:"#A39A90",base06:"#BEB6AE",base07:"#DBD6D1",base08:"#826D57",base09:"#828257",base0A:"#6D8257",base0B:"#57826D",base0C:"#576D82",base0D:"#6D5782",base0E:"#82576D",base0F:"#825757"},e.exports=t.default},5786:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"flat",author:"chris kempson (http://chriskempson.com)",base00:"#2C3E50",base01:"#34495E",base02:"#7F8C8D",base03:"#95A5A6",base04:"#BDC3C7",base05:"#e0e0e0",base06:"#f5f5f5",base07:"#ECF0F1",base08:"#E74C3C",base09:"#E67E22",base0A:"#F1C40F",base0B:"#2ECC71",base0C:"#1ABC9C",base0D:"#3498DB",base0E:"#9B59B6",base0F:"#be643c"},e.exports=t.default},51218:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"google",author:"seth wright (http://sethawright.com)",base00:"#1d1f21",base01:"#282a2e",base02:"#373b41",base03:"#969896",base04:"#b4b7b4",base05:"#c5c8c6",base06:"#e0e0e0",base07:"#ffffff",base08:"#CC342B",base09:"#F96A38",base0A:"#FBA922",base0B:"#198844",base0C:"#3971ED",base0D:"#3971ED",base0E:"#A36AC7",base0F:"#3971ED"},e.exports=t.default},18975:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"grayscale",author:"alexandre gavioli (https://github.com/alexx2/)",base00:"#101010",base01:"#252525",base02:"#464646",base03:"#525252",base04:"#ababab",base05:"#b9b9b9",base06:"#e3e3e3",base07:"#f7f7f7",base08:"#7c7c7c",base09:"#999999",base0A:"#a0a0a0",base0B:"#8e8e8e",base0C:"#868686",base0D:"#686868",base0E:"#747474",base0F:"#5e5e5e"},e.exports=t.default},8383:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"green screen",author:"chris kempson (http://chriskempson.com)",base00:"#001100",base01:"#003300",base02:"#005500",base03:"#007700",base04:"#009900",base05:"#00bb00",base06:"#00dd00",base07:"#00ff00",base08:"#007700",base09:"#009900",base0A:"#007700",base0B:"#00bb00",base0C:"#005500",base0D:"#009900",base0E:"#00bb00",base0F:"#005500"},e.exports=t.default},3983:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"harmonic16",author:"jannik siebert (https://github.com/janniks)",base00:"#0b1c2c",base01:"#223b54",base02:"#405c79",base03:"#627e99",base04:"#aabcce",base05:"#cbd6e2",base06:"#e5ebf1",base07:"#f7f9fb",base08:"#bf8b56",base09:"#bfbf56",base0A:"#8bbf56",base0B:"#56bf8b",base0C:"#568bbf",base0D:"#8b56bf",base0E:"#bf568b",base0F:"#bf5656"},e.exports=t.default},3233:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"hopscotch",author:"jan t. sott",base00:"#322931",base01:"#433b42",base02:"#5c545b",base03:"#797379",base04:"#989498",base05:"#b9b5b8",base06:"#d5d3d5",base07:"#ffffff",base08:"#dd464c",base09:"#fd8b19",base0A:"#fdcc59",base0B:"#8fc13e",base0C:"#149b93",base0D:"#1290bf",base0E:"#c85e7c",base0F:"#b33508"},e.exports=t.default},39366:(e,t,n)=>{"use strict";function i(e){return e&&e.__esModule?e.default:e}t.__esModule=!0;var s=n(13811);t.threezerotwofour=i(s);var r=n(18257);t.apathy=i(r);var o=n(86546);t.ashes=i(o);var a=n(25284);t.atelierDune=i(a);var l=n(15626);t.atelierForest=i(l);var h=n(47131);t.atelierHeath=i(h);var c=n(98086);t.atelierLakeside=i(c);var u=n(51441);t.atelierSeaside=i(u);var f=n(16405);t.bespin=i(f);var d=n(62953);t.brewer=i(d);var p=n(65785);t.bright=i(p);var m=n(17666);t.chalk=i(m);var g=n(57864);t.codeschool=i(g);var b=n(14449);t.colors=i(b);var y=n(86475);t.default=i(y);var v=n(92749);t.eighties=i(v);var x=n(35951);t.embers=i(x);var w=n(5786);t.flat=i(w);var k=n(51218);t.google=i(k);var S=n(18975);t.grayscale=i(S);var A=n(8383);t.greenscreen=i(A);var C=n(3983);t.harmonic=i(C);var O=n(3233);t.hopscotch=i(O);var M=n(41630);t.isotope=i(M);var T=n(80988);t.marrakesh=i(T);var _=n(94793);t.mocha=i(_);var N=n(81762);t.monokai=i(N);var D=n(27172);t.ocean=i(D);var E=n(28079);t.paraiso=i(E);var j=n(48111);t.pop=i(j);var R=n(34733);t.railscasts=i(R);var P=n(80133);t.shapeshifter=i(P);var I=n(92955);t.solarized=i(I);var B=n(5930);t.summerfruit=i(B);var L=n(86494);t.tomorrow=i(L);var $=n(2747);t.tube=i($);var z=n(87441);t.twilight=i(z)},41630:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"isotope",author:"jan t. sott",base00:"#000000",base01:"#404040",base02:"#606060",base03:"#808080",base04:"#c0c0c0",base05:"#d0d0d0",base06:"#e0e0e0",base07:"#ffffff",base08:"#ff0000",base09:"#ff9900",base0A:"#ff0099",base0B:"#33ff00",base0C:"#00ffff",base0D:"#0066ff",base0E:"#cc00ff",base0F:"#3300ff"},e.exports=t.default},80988:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"marrakesh",author:"alexandre gavioli (http://github.com/alexx2/)",base00:"#201602",base01:"#302e00",base02:"#5f5b17",base03:"#6c6823",base04:"#86813b",base05:"#948e48",base06:"#ccc37a",base07:"#faf0a5",base08:"#c35359",base09:"#b36144",base0A:"#a88339",base0B:"#18974e",base0C:"#75a738",base0D:"#477ca1",base0E:"#8868b3",base0F:"#b3588e"},e.exports=t.default},94793:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"mocha",author:"chris kempson (http://chriskempson.com)",base00:"#3B3228",base01:"#534636",base02:"#645240",base03:"#7e705a",base04:"#b8afad",base05:"#d0c8c6",base06:"#e9e1dd",base07:"#f5eeeb",base08:"#cb6077",base09:"#d28b71",base0A:"#f4bc87",base0B:"#beb55b",base0C:"#7bbda4",base0D:"#8ab3b5",base0E:"#a89bb9",base0F:"#bb9584"},e.exports=t.default},81762:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"monokai",author:"wimer hazenberg (http://www.monokai.nl)",base00:"#272822",base01:"#383830",base02:"#49483e",base03:"#75715e",base04:"#a59f85",base05:"#f8f8f2",base06:"#f5f4f1",base07:"#f9f8f5",base08:"#f92672",base09:"#fd971f",base0A:"#f4bf75",base0B:"#a6e22e",base0C:"#a1efe4",base0D:"#66d9ef",base0E:"#ae81ff",base0F:"#cc6633"},e.exports=t.default},27172:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"ocean",author:"chris kempson (http://chriskempson.com)",base00:"#2b303b",base01:"#343d46",base02:"#4f5b66",base03:"#65737e",base04:"#a7adba",base05:"#c0c5ce",base06:"#dfe1e8",base07:"#eff1f5",base08:"#bf616a",base09:"#d08770",base0A:"#ebcb8b",base0B:"#a3be8c",base0C:"#96b5b4",base0D:"#8fa1b3",base0E:"#b48ead",base0F:"#ab7967"},e.exports=t.default},28079:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"paraiso",author:"jan t. sott",base00:"#2f1e2e",base01:"#41323f",base02:"#4f424c",base03:"#776e71",base04:"#8d8687",base05:"#a39e9b",base06:"#b9b6b0",base07:"#e7e9db",base08:"#ef6155",base09:"#f99b15",base0A:"#fec418",base0B:"#48b685",base0C:"#5bc4bf",base0D:"#06b6ef",base0E:"#815ba4",base0F:"#e96ba8"},e.exports=t.default},48111:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"pop",author:"chris kempson (http://chriskempson.com)",base00:"#000000",base01:"#202020",base02:"#303030",base03:"#505050",base04:"#b0b0b0",base05:"#d0d0d0",base06:"#e0e0e0",base07:"#ffffff",base08:"#eb008a",base09:"#f29333",base0A:"#f8ca12",base0B:"#37b349",base0C:"#00aabb",base0D:"#0e5a94",base0E:"#b31e8d",base0F:"#7a2d00"},e.exports=t.default},34733:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"railscasts",author:"ryan bates (http://railscasts.com)",base00:"#2b2b2b",base01:"#272935",base02:"#3a4055",base03:"#5a647e",base04:"#d4cfc9",base05:"#e6e1dc",base06:"#f4f1ed",base07:"#f9f7f3",base08:"#da4939",base09:"#cc7833",base0A:"#ffc66d",base0B:"#a5c261",base0C:"#519f50",base0D:"#6d9cbe",base0E:"#b6b3eb",base0F:"#bc9458"},e.exports=t.default},80133:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"shapeshifter",author:"tyler benziger (http://tybenz.com)",base00:"#000000",base01:"#040404",base02:"#102015",base03:"#343434",base04:"#555555",base05:"#ababab",base06:"#e0e0e0",base07:"#f9f9f9",base08:"#e92f2f",base09:"#e09448",base0A:"#dddd13",base0B:"#0ed839",base0C:"#23edda",base0D:"#3b48e3",base0E:"#f996e2",base0F:"#69542d"},e.exports=t.default},92955:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"solarized",author:"ethan schoonover (http://ethanschoonover.com/solarized)",base00:"#002b36",base01:"#073642",base02:"#586e75",base03:"#657b83",base04:"#839496",base05:"#93a1a1",base06:"#eee8d5",base07:"#fdf6e3",base08:"#dc322f",base09:"#cb4b16",base0A:"#b58900",base0B:"#859900",base0C:"#2aa198",base0D:"#268bd2",base0E:"#6c71c4",base0F:"#d33682"},e.exports=t.default},5930:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"summerfruit",author:"christopher corley (http://cscorley.github.io/)",base00:"#151515",base01:"#202020",base02:"#303030",base03:"#505050",base04:"#B0B0B0",base05:"#D0D0D0",base06:"#E0E0E0",base07:"#FFFFFF",base08:"#FF0086",base09:"#FD8900",base0A:"#ABA800",base0B:"#00C918",base0C:"#1faaaa",base0D:"#3777E6",base0E:"#AD00A1",base0F:"#cc6633"},e.exports=t.default},13811:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"threezerotwofour",author:"jan t. sott (http://github.com/idleberg)",base00:"#090300",base01:"#3a3432",base02:"#4a4543",base03:"#5c5855",base04:"#807d7c",base05:"#a5a2a2",base06:"#d6d5d4",base07:"#f7f7f7",base08:"#db2d20",base09:"#e8bbd0",base0A:"#fded02",base0B:"#01a252",base0C:"#b5e4f4",base0D:"#01a0e4",base0E:"#a16a94",base0F:"#cdab53"},e.exports=t.default},86494:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"tomorrow",author:"chris kempson (http://chriskempson.com)",base00:"#1d1f21",base01:"#282a2e",base02:"#373b41",base03:"#969896",base04:"#b4b7b4",base05:"#c5c8c6",base06:"#e0e0e0",base07:"#ffffff",base08:"#cc6666",base09:"#de935f",base0A:"#f0c674",base0B:"#b5bd68",base0C:"#8abeb7",base0D:"#81a2be",base0E:"#b294bb",base0F:"#a3685a"},e.exports=t.default},2747:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"london tube",author:"jan t. sott",base00:"#231f20",base01:"#1c3f95",base02:"#5a5758",base03:"#737171",base04:"#959ca1",base05:"#d9d8d8",base06:"#e7e7e8",base07:"#ffffff",base08:"#ee2e24",base09:"#f386a1",base0A:"#ffd204",base0B:"#00853e",base0C:"#85cebc",base0D:"#009ddc",base0E:"#98005d",base0F:"#b06110"},e.exports=t.default},87441:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"twilight",author:"david hart (http://hart-dev.com)",base00:"#1e1e1e",base01:"#323537",base02:"#464b50",base03:"#5f5a60",base04:"#838184",base05:"#a7a7a7",base06:"#c3c3c3",base07:"#ffffff",base08:"#cf6a4c",base09:"#cda869",base0A:"#f9ee98",base0B:"#8f9d6a",base0C:"#afc4db",base0D:"#7587a6",base0E:"#9b859d",base0F:"#9b703f"},e.exports=t.default},44959:(e,t,n)=>{var i=n(11103),s={};for(var r in i)i.hasOwnProperty(r)&&(s[i[r]]=r);var o=e.exports={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};for(var a in o)if(o.hasOwnProperty(a)){if(!("channels"in o[a]))throw new Error("missing channels property: "+a);if(!("labels"in o[a]))throw new Error("missing channel labels property: "+a);if(o[a].labels.length!==o[a].channels)throw new Error("channel and label counts mismatch: "+a);var l=o[a].channels,h=o[a].labels;delete o[a].channels,delete o[a].labels,Object.defineProperty(o[a],"channels",{value:l}),Object.defineProperty(o[a],"labels",{value:h})}o.rgb.hsl=function(e){var t,n,i=e[0]/255,s=e[1]/255,r=e[2]/255,o=Math.min(i,s,r),a=Math.max(i,s,r),l=a-o;return a===o?t=0:i===a?t=(s-r)/l:s===a?t=2+(r-i)/l:r===a&&(t=4+(i-s)/l),(t=Math.min(60*t,360))<0&&(t+=360),n=(o+a)/2,[t,100*(a===o?0:n<=.5?l/(a+o):l/(2-a-o)),100*n]},o.rgb.hsv=function(e){var t,n,i,s,r,o=e[0]/255,a=e[1]/255,l=e[2]/255,h=Math.max(o,a,l),c=h-Math.min(o,a,l),u=function(e){return(h-e)/6/c+.5};return 0===c?s=r=0:(r=c/h,t=u(o),n=u(a),i=u(l),o===h?s=i-n:a===h?s=1/3+t-i:l===h&&(s=2/3+n-t),s<0?s+=1:s>1&&(s-=1)),[360*s,100*r,100*h]},o.rgb.hwb=function(e){var t=e[0],n=e[1],i=e[2];return[o.rgb.hsl(e)[0],1/255*Math.min(t,Math.min(n,i))*100,100*(i=1-1/255*Math.max(t,Math.max(n,i)))]},o.rgb.cmyk=function(e){var t,n=e[0]/255,i=e[1]/255,s=e[2]/255;return[100*((1-n-(t=Math.min(1-n,1-i,1-s)))/(1-t)||0),100*((1-i-t)/(1-t)||0),100*((1-s-t)/(1-t)||0),100*t]},o.rgb.keyword=function(e){var t=s[e];if(t)return t;var n,r,o,a=1/0;for(var l in i)if(i.hasOwnProperty(l)){var h=(r=e,o=i[l],Math.pow(r[0]-o[0],2)+Math.pow(r[1]-o[1],2)+Math.pow(r[2]-o[2],2));h.04045?Math.pow((t+.055)/1.055,2.4):t/12.92)+.3576*(n=n>.04045?Math.pow((n+.055)/1.055,2.4):n/12.92)+.1805*(i=i>.04045?Math.pow((i+.055)/1.055,2.4):i/12.92)),100*(.2126*t+.7152*n+.0722*i),100*(.0193*t+.1192*n+.9505*i)]},o.rgb.lab=function(e){var t=o.rgb.xyz(e),n=t[0],i=t[1],s=t[2];return i/=100,s/=108.883,n=(n/=95.047)>.008856?Math.pow(n,1/3):7.787*n+16/116,[116*(i=i>.008856?Math.pow(i,1/3):7.787*i+16/116)-16,500*(n-i),200*(i-(s=s>.008856?Math.pow(s,1/3):7.787*s+16/116))]},o.hsl.rgb=function(e){var t,n,i,s,r,o=e[0]/360,a=e[1]/100,l=e[2]/100;if(0===a)return[r=255*l,r,r];t=2*l-(n=l<.5?l*(1+a):l+a-l*a),s=[0,0,0];for(var h=0;h<3;h++)(i=o+1/3*-(h-1))<0&&i++,i>1&&i--,r=6*i<1?t+6*(n-t)*i:2*i<1?n:3*i<2?t+(n-t)*(2/3-i)*6:t,s[h]=255*r;return s},o.hsl.hsv=function(e){var t=e[0],n=e[1]/100,i=e[2]/100,s=n,r=Math.max(i,.01);return n*=(i*=2)<=1?i:2-i,s*=r<=1?r:2-r,[t,100*(0===i?2*s/(r+s):2*n/(i+n)),(i+n)/2*100]},o.hsv.rgb=function(e){var t=e[0]/60,n=e[1]/100,i=e[2]/100,s=Math.floor(t)%6,r=t-Math.floor(t),o=255*i*(1-n),a=255*i*(1-n*r),l=255*i*(1-n*(1-r));switch(i*=255,s){case 0:return[i,l,o];case 1:return[a,i,o];case 2:return[o,i,l];case 3:return[o,a,i];case 4:return[l,o,i];case 5:return[i,o,a]}},o.hsv.hsl=function(e){var t,n,i,s=e[0],r=e[1]/100,o=e[2]/100,a=Math.max(o,.01);return i=(2-r)*o,n=r*a,[s,100*(n=(n/=(t=(2-r)*a)<=1?t:2-t)||0),100*(i/=2)]},o.hwb.rgb=function(e){var t,n,i,s,r,o,a,l=e[0]/360,h=e[1]/100,c=e[2]/100,u=h+c;switch(u>1&&(h/=u,c/=u),i=6*l-(t=Math.floor(6*l)),0!=(1&t)&&(i=1-i),s=h+i*((n=1-c)-h),t){default:case 6:case 0:r=n,o=s,a=h;break;case 1:r=s,o=n,a=h;break;case 2:r=h,o=n,a=s;break;case 3:r=h,o=s,a=n;break;case 4:r=s,o=h,a=n;break;case 5:r=n,o=h,a=s}return[255*r,255*o,255*a]},o.cmyk.rgb=function(e){var t=e[0]/100,n=e[1]/100,i=e[2]/100,s=e[3]/100;return[255*(1-Math.min(1,t*(1-s)+s)),255*(1-Math.min(1,n*(1-s)+s)),255*(1-Math.min(1,i*(1-s)+s))]},o.xyz.rgb=function(e){var t,n,i,s=e[0]/100,r=e[1]/100,o=e[2]/100;return n=-.9689*s+1.8758*r+.0415*o,i=.0557*s+-.204*r+1.057*o,t=(t=3.2406*s+-1.5372*r+-.4986*o)>.0031308?1.055*Math.pow(t,1/2.4)-.055:12.92*t,n=n>.0031308?1.055*Math.pow(n,1/2.4)-.055:12.92*n,i=i>.0031308?1.055*Math.pow(i,1/2.4)-.055:12.92*i,[255*(t=Math.min(Math.max(0,t),1)),255*(n=Math.min(Math.max(0,n),1)),255*(i=Math.min(Math.max(0,i),1))]},o.xyz.lab=function(e){var t=e[0],n=e[1],i=e[2];return n/=100,i/=108.883,t=(t/=95.047)>.008856?Math.pow(t,1/3):7.787*t+16/116,[116*(n=n>.008856?Math.pow(n,1/3):7.787*n+16/116)-16,500*(t-n),200*(n-(i=i>.008856?Math.pow(i,1/3):7.787*i+16/116))]},o.lab.xyz=function(e){var t,n,i,s=e[0];t=e[1]/500+(n=(s+16)/116),i=n-e[2]/200;var r=Math.pow(n,3),o=Math.pow(t,3),a=Math.pow(i,3);return n=r>.008856?r:(n-16/116)/7.787,t=o>.008856?o:(t-16/116)/7.787,i=a>.008856?a:(i-16/116)/7.787,[t*=95.047,n*=100,i*=108.883]},o.lab.lch=function(e){var t,n=e[0],i=e[1],s=e[2];return(t=360*Math.atan2(s,i)/2/Math.PI)<0&&(t+=360),[n,Math.sqrt(i*i+s*s),t]},o.lch.lab=function(e){var t,n=e[0],i=e[1];return t=e[2]/360*2*Math.PI,[n,i*Math.cos(t),i*Math.sin(t)]},o.rgb.ansi16=function(e){var t=e[0],n=e[1],i=e[2],s=1 in arguments?arguments[1]:o.rgb.hsv(e)[2];if(0===(s=Math.round(s/50)))return 30;var r=30+(Math.round(i/255)<<2|Math.round(n/255)<<1|Math.round(t/255));return 2===s&&(r+=60),r},o.hsv.ansi16=function(e){return o.rgb.ansi16(o.hsv.rgb(e),e[2])},o.rgb.ansi256=function(e){var t=e[0],n=e[1],i=e[2];return t===n&&n===i?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(i/255*5)},o.ansi16.rgb=function(e){var t=e%10;if(0===t||7===t)return e>50&&(t+=3.5),[t=t/10.5*255,t,t];var n=.5*(1+~~(e>50));return[(1&t)*n*255,(t>>1&1)*n*255,(t>>2&1)*n*255]},o.ansi256.rgb=function(e){if(e>=232){var t=10*(e-232)+8;return[t,t,t]}var n;return e-=16,[Math.floor(e/36)/5*255,Math.floor((n=e%36)/6)/5*255,n%6/5*255]},o.rgb.hex=function(e){var t=(((255&Math.round(e[0]))<<16)+((255&Math.round(e[1]))<<8)+(255&Math.round(e[2]))).toString(16).toUpperCase();return"000000".substring(t.length)+t},o.hex.rgb=function(e){var t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];var n=t[0];3===t[0].length&&(n=n.split("").map((function(e){return e+e})).join(""));var i=parseInt(n,16);return[i>>16&255,i>>8&255,255&i]},o.rgb.hcg=function(e){var t,n=e[0]/255,i=e[1]/255,s=e[2]/255,r=Math.max(Math.max(n,i),s),o=Math.min(Math.min(n,i),s),a=r-o;return t=a<=0?0:r===n?(i-s)/a%6:r===i?2+(s-n)/a:4+(n-i)/a+4,t/=6,[360*(t%=1),100*a,100*(a<1?o/(1-a):0)]},o.hsl.hcg=function(e){var t,n=e[1]/100,i=e[2]/100,s=0;return(t=i<.5?2*n*i:2*n*(1-i))<1&&(s=(i-.5*t)/(1-t)),[e[0],100*t,100*s]},o.hsv.hcg=function(e){var t=e[1]/100,n=e[2]/100,i=t*n,s=0;return i<1&&(s=(n-i)/(1-i)),[e[0],100*i,100*s]},o.hcg.rgb=function(e){var t=e[0]/360,n=e[1]/100,i=e[2]/100;if(0===n)return[255*i,255*i,255*i];var s,r=[0,0,0],o=t%1*6,a=o%1,l=1-a;switch(Math.floor(o)){case 0:r[0]=1,r[1]=a,r[2]=0;break;case 1:r[0]=l,r[1]=1,r[2]=0;break;case 2:r[0]=0,r[1]=1,r[2]=a;break;case 3:r[0]=0,r[1]=l,r[2]=1;break;case 4:r[0]=a,r[1]=0,r[2]=1;break;default:r[0]=1,r[1]=0,r[2]=l}return s=(1-n)*i,[255*(n*r[0]+s),255*(n*r[1]+s),255*(n*r[2]+s)]},o.hcg.hsv=function(e){var t=e[1]/100,n=t+e[2]/100*(1-t),i=0;return n>0&&(i=t/n),[e[0],100*i,100*n]},o.hcg.hsl=function(e){var t=e[1]/100,n=e[2]/100*(1-t)+.5*t,i=0;return n>0&&n<.5?i=t/(2*n):n>=.5&&n<1&&(i=t/(2*(1-n))),[e[0],100*i,100*n]},o.hcg.hwb=function(e){var t=e[1]/100,n=t+e[2]/100*(1-t);return[e[0],100*(n-t),100*(1-n)]},o.hwb.hcg=function(e){var t=e[1]/100,n=1-e[2]/100,i=n-t,s=0;return i<1&&(s=(n-i)/(1-i)),[e[0],100*i,100*s]},o.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]},o.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]},o.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]},o.gray.hsl=o.gray.hsv=function(e){return[0,0,e[0]]},o.gray.hwb=function(e){return[0,100,e[0]]},o.gray.cmyk=function(e){return[0,0,0,e[0]]},o.gray.lab=function(e){return[e[0],0,0]},o.gray.hex=function(e){var t=255&Math.round(e[0]/100*255),n=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return"000000".substring(n.length)+n},o.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]}},50841:(e,t,n)=>{var i=n(44959),s=n(19325),r={};Object.keys(i).forEach((function(e){r[e]={},Object.defineProperty(r[e],"channels",{value:i[e].channels}),Object.defineProperty(r[e],"labels",{value:i[e].labels});var t=s(e);Object.keys(t).forEach((function(n){var i=t[n];r[e][n]=function(e){var t=function(t){if(null==t)return t;arguments.length>1&&(t=Array.prototype.slice.call(arguments));var n=e(t);if("object"==typeof n)for(var i=n.length,s=0;s1&&(t=Array.prototype.slice.call(arguments)),e(t))};return"conversion"in e&&(t.conversion=e.conversion),t}(i)}))})),e.exports=r},19325:(e,t,n)=>{var i=n(44959);function s(e,t){return function(n){return t(e(n))}}function r(e,t){for(var n=[t[e].parent,e],r=i[t[e].parent][e],o=t[e].parent;t[o].parent;)n.unshift(t[o].parent),r=s(i[t[o].parent][o],r),o=t[o].parent;return r.conversion=n,r}e.exports=function(e){for(var t=function(e){var t=function(){for(var e={},t=Object.keys(i),n=t.length,s=0;s{"use strict";e.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}},67804:(e,t,n)=>{var i=n(11103),s=n(26047),r=Object.hasOwnProperty,o=Object.create(null);for(var a in i)r.call(i,a)&&(o[i[a]]=a);var l=e.exports={to:{},get:{}};function h(e,t,n){return Math.min(Math.max(t,e),n)}function c(e){var t=Math.round(e).toString(16).toUpperCase();return t.length<2?"0"+t:t}l.get=function(e){var t,n;switch(e.substring(0,3).toLowerCase()){case"hsl":t=l.get.hsl(e),n="hsl";break;case"hwb":t=l.get.hwb(e),n="hwb";break;default:t=l.get.rgb(e),n="rgb"}return t?{model:n,value:t}:null},l.get.rgb=function(e){if(!e)return null;var t,n,s,o=[0,0,0,1];if(t=e.match(/^#([a-f0-9]{6})([a-f0-9]{2})?$/i)){for(s=t[2],t=t[1],n=0;n<3;n++){var a=2*n;o[n]=parseInt(t.slice(a,a+2),16)}s&&(o[3]=parseInt(s,16)/255)}else if(t=e.match(/^#([a-f0-9]{3,4})$/i)){for(s=(t=t[1])[3],n=0;n<3;n++)o[n]=parseInt(t[n]+t[n],16);s&&(o[3]=parseInt(s+s,16)/255)}else if(t=e.match(/^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/)){for(n=0;n<3;n++)o[n]=parseInt(t[n+1],0);t[4]&&(t[5]?o[3]=.01*parseFloat(t[4]):o[3]=parseFloat(t[4]))}else{if(!(t=e.match(/^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/)))return(t=e.match(/^(\w+)$/))?"transparent"===t[1]?[0,0,0,0]:r.call(i,t[1])?((o=i[t[1]])[3]=1,o):null:null;for(n=0;n<3;n++)o[n]=Math.round(2.55*parseFloat(t[n+1]));t[4]&&(t[5]?o[3]=.01*parseFloat(t[4]):o[3]=parseFloat(t[4]))}for(n=0;n<3;n++)o[n]=h(o[n],0,255);return o[3]=h(o[3],0,1),o},l.get.hsl=function(e){if(!e)return null;var t=e.match(/^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/);if(t){var n=parseFloat(t[4]);return[(parseFloat(t[1])%360+360)%360,h(parseFloat(t[2]),0,100),h(parseFloat(t[3]),0,100),h(isNaN(n)?1:n,0,1)]}return null},l.get.hwb=function(e){if(!e)return null;var t=e.match(/^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/);if(t){var n=parseFloat(t[4]);return[(parseFloat(t[1])%360+360)%360,h(parseFloat(t[2]),0,100),h(parseFloat(t[3]),0,100),h(isNaN(n)?1:n,0,1)]}return null},l.to.hex=function(){var e=s(arguments);return"#"+c(e[0])+c(e[1])+c(e[2])+(e[3]<1?c(Math.round(255*e[3])):"")},l.to.rgb=function(){var e=s(arguments);return e.length<4||1===e[3]?"rgb("+Math.round(e[0])+", "+Math.round(e[1])+", "+Math.round(e[2])+")":"rgba("+Math.round(e[0])+", "+Math.round(e[1])+", "+Math.round(e[2])+", "+e[3]+")"},l.to.rgb.percent=function(){var e=s(arguments),t=Math.round(e[0]/255*100),n=Math.round(e[1]/255*100),i=Math.round(e[2]/255*100);return e.length<4||1===e[3]?"rgb("+t+"%, "+n+"%, "+i+"%)":"rgba("+t+"%, "+n+"%, "+i+"%, "+e[3]+")"},l.to.hsl=function(){var e=s(arguments);return e.length<4||1===e[3]?"hsl("+e[0]+", "+e[1]+"%, "+e[2]+"%)":"hsla("+e[0]+", "+e[1]+"%, "+e[2]+"%, "+e[3]+")"},l.to.hwb=function(){var e=s(arguments),t="";return e.length>=4&&1!==e[3]&&(t=", "+e[3]),"hwb("+e[0]+", "+e[1]+"%, "+e[2]+"%"+t+")"},l.to.keyword=function(e){return o[e.slice(0,3)]}},71346:(e,t,n)=>{"use strict";var i=n(67804),s=n(50841),r=[].slice,o=["keyword","gray","hex"],a={};Object.keys(s).forEach((function(e){a[r.call(s[e].labels).sort().join("")]=e}));var l={};function h(e,t){if(!(this instanceof h))return new h(e,t);if(t&&t in o&&(t=null),t&&!(t in s))throw new Error("Unknown model: "+t);var n,c;if(null==e)this.model="rgb",this.color=[0,0,0],this.valpha=1;else if(e instanceof h)this.model=e.model,this.color=e.color.slice(),this.valpha=e.valpha;else if("string"==typeof e){var u=i.get(e);if(null===u)throw new Error("Unable to parse color from string: "+e);this.model=u.model,c=s[this.model].channels,this.color=u.value.slice(0,c),this.valpha="number"==typeof u.value[c]?u.value[c]:1}else if(e.length){this.model=t||"rgb",c=s[this.model].channels;var d=r.call(e,0,c);this.color=f(d,c),this.valpha="number"==typeof e[c]?e[c]:1}else if("number"==typeof e)e&=16777215,this.model="rgb",this.color=[e>>16&255,e>>8&255,255&e],this.valpha=1;else{this.valpha=1;var p=Object.keys(e);"alpha"in e&&(p.splice(p.indexOf("alpha"),1),this.valpha="number"==typeof e.alpha?e.alpha:0);var m=p.sort().join("");if(!(m in a))throw new Error("Unable to parse color from object: "+JSON.stringify(e));this.model=a[m];var g=s[this.model].labels,b=[];for(n=0;nn?(t+.05)/(n+.05):(n+.05)/(t+.05)},level:function(e){var t=this.contrast(e);return t>=7.1?"AAA":t>=4.5?"AA":""},isDark:function(){var e=this.rgb().color;return(299*e[0]+587*e[1]+114*e[2])/1e3<128},isLight:function(){return!this.isDark()},negate:function(){for(var e=this.rgb(),t=0;t<3;t++)e.color[t]=255-e.color[t];return e},lighten:function(e){var t=this.hsl();return t.color[2]+=t.color[2]*e,t},darken:function(e){var t=this.hsl();return t.color[2]-=t.color[2]*e,t},saturate:function(e){var t=this.hsl();return t.color[1]+=t.color[1]*e,t},desaturate:function(e){var t=this.hsl();return t.color[1]-=t.color[1]*e,t},whiten:function(e){var t=this.hwb();return t.color[1]+=t.color[1]*e,t},blacken:function(e){var t=this.hwb();return t.color[2]+=t.color[2]*e,t},grayscale:function(){var e=this.rgb().color,t=.3*e[0]+.59*e[1]+.11*e[2];return h.rgb(t,t,t)},fade:function(e){return this.alpha(this.valpha-this.valpha*e)},opaquer:function(e){return this.alpha(this.valpha+this.valpha*e)},rotate:function(e){var t=this.hsl(),n=t.color[0];return n=(n=(n+e)%360)<0?360+n:n,t.color[0]=n,t},mix:function(e,t){if(!e||!e.rgb)throw new Error('Argument to "mix" was not a Color instance, but rather an instance of '+typeof e);var n=e.rgb(),i=this.rgb(),s=void 0===t?.5:t,r=2*s-1,o=n.alpha()-i.alpha(),a=((r*o==-1?r:(r+o)/(1+r*o))+1)/2,l=1-a;return h.rgb(a*n.red()+l*i.red(),a*n.green()+l*i.green(),a*n.blue()+l*i.blue(),n.alpha()*s+i.alpha()*(1-s))}},Object.keys(s).forEach((function(e){if(-1===o.indexOf(e)){var t=s[e].channels;h.prototype[e]=function(){if(this.model===e)return new h(this);if(arguments.length)return new h(arguments,e);var n,i="number"==typeof arguments[t]?t:this.valpha;return new h((n=s[this.model][e].raw(this.color),Array.isArray(n)?n:[n]).concat(i),e)},h[e]=function(n){return"number"==typeof n&&(n=f(r.call(arguments),t)),new h(n,e)}}})),e.exports=h},29590:(e,t,n)=>{"use strict";n.r(t),n.d(t,{Cache:()=>p,FreeStyle:()=>v,Rule:()=>b,Selector:()=>m,Style:()=>g,create:()=>x});let i=0;const s=Object.create(null),r=["animation-iteration-count","border-image-outset","border-image-slice","border-image-width","box-flex","box-flex-group","box-ordinal-group","column-count","columns","counter-increment","counter-reset","flex","flex-grow","flex-positive","flex-shrink","flex-negative","flex-order","font-weight","grid-area","grid-column","grid-column-end","grid-column-span","grid-column-start","grid-row","grid-row-end","grid-row-span","grid-row-start","line-clamp","line-height","opacity","order","orphans","tab-size","widows","z-index","zoom","fill-opacity","flood-opacity","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-miterlimit","stroke-opacity","stroke-width"];for(const e of r)for(const t of["-webkit-","-ms-","-moz-","-o-",""])s[t+e]=!0;function o(e,t){return t&&"number"==typeof t&&!s[e]?`${e}:${t}px`:`${e}:${t}`}function a(e){return e.sort(((e,t)=>e[0]>t[0]?1:-1))}function l(e){return e.map((([e,t])=>Array.isArray(t)?t.map((t=>o(e,t))).join(";"):o(e,t))).join(";")}function h(e,t){return-1===e.indexOf("&")?`${t} ${e}`:e.replace(/&/g,t)}function c(e,t,n,i,s){const{style:r,nested:o,isUnique:u}=function(e,t){const n=[],i=[];for(const t of Object.keys(e)){const r=t.trim(),o=e[t];36!==r.charCodeAt(0)&&null!=o&&("object"!=typeof o||Array.isArray(o)?n.push([(s=r,s.replace(/[A-Z]/g,(e=>`-${e.toLowerCase()}`)).replace(/^ms-/,"-ms-")),o]):i.push([r,o]))}var s;return{style:l(a(n)),nested:t?i:a(i),isUnique:!!e.$unique}}(t,""!==e);let f=r;if(64===e.charCodeAt(0)){const t={selector:e,styles:[],rules:[],style:s?"":r};n.push(t),r&&s&&t.styles.push({selector:s,style:r,isUnique:u});for(const[e,n]of o)f+=e+c(e,n,t.rules,t.styles,s)}else{const t=s?h(e,s):e;r&&i.push({selector:t,style:r,isUnique:u});for(const[e,s]of o)f+=e+c(e,s,n,i,t)}return f}function u(e,t,n,s,r,o){for(const{selector:n,style:a,isUnique:l}of s){const s=o?h(n,r):n,c=l?`u\0${(++i).toString(36)}`:`s\0${t}\0${a}`,u=new g(a,c);u.add(new m(s,`k\0${t}\0${s}`)),e.add(u)}for(const{selector:i,style:s,rules:a,styles:l}of n){const n=new b(i,s,`r\0${t}\0${i}\0${s}`);u(n,t,a,l,r,o),e.add(n)}}function f(e){let t="";for(let n=0;n{},change:()=>{},remove:()=>{}};class p{constructor(e=d){this.changes=e,this.sheet=[],this.changeId=0,this._keys=[],this._children=Object.create(null),this._counters=Object.create(null)}add(e){const t=this._counters[e.id]||0,n=this._children[e.id]||e.clone();if(this._counters[e.id]=t+1,0===t)this._children[n.id]=n,this._keys.push(n.id),this.sheet.push(n.getStyles()),this.changeId++,this.changes.add(n,this._keys.length-1);else if(n instanceof p&&e instanceof p){const t=this._keys.indexOf(e.id),i=n.changeId;n.merge(e),n.changeId!==i&&(this.sheet.splice(t,1,n.getStyles()),this.changeId++,this.changes.change(n,t,t))}}remove(e){const t=this._counters[e.id];if(t){this._counters[e.id]=t-1;const n=this._children[e.id],i=this._keys.indexOf(n.id);if(1===t)delete this._counters[e.id],delete this._children[e.id],this._keys.splice(i,1),this.sheet.splice(i,1),this.changeId++,this.changes.remove(n,i);else if(n instanceof p&&e instanceof p){const t=n.changeId;n.unmerge(e),n.changeId!==t&&(this.sheet.splice(i,1,n.getStyles()),this.changeId++,this.changes.change(n,i,i))}}}values(){return this._keys.map((e=>this._children[e]))}merge(e){for(const t of e.values())this.add(t);return this}unmerge(e){for(const t of e.values())this.remove(t);return this}clone(){return(new p).merge(this)}}class m{constructor(e,t){this.selector=e,this.id=t}getStyles(){return this.selector}clone(){return this}}class g extends p{constructor(e,t){super(),this.style=e,this.id=t}getStyles(){return`${this.sheet.join(",")}{${this.style}}`}clone(){return new g(this.style,this.id).merge(this)}}class b extends p{constructor(e,t,n){super(),this.rule=e,this.style=t,this.id=n}getStyles(){return`${this.rule}{${this.style}${f(this.sheet)}}`}clone(){return new b(this.rule,this.style,this.id).merge(this)}}function y(e,t){return`f${function(e){let t=5381,n=e.length;for(;n--;)t=33*t^e.charCodeAt(n);return(t>>>0).toString(36)}(e)}`}class v extends p{constructor(e,t){super(t),this.id=e}registerStyle(e){const t=[],n=[],i=c("&",e,t,n),s=y(i);return u(this,i,t,n,`.${s}`,!0),s}registerKeyframes(e){return this.registerHashRule("@keyframes",e)}registerHashRule(e,t){const n=[],i=[],s=c("",t,n,i),r=y(s),o=new b(`${e} ${r}`,"",`h\0${s}\0${e}`);return u(o,s,n,i,"",!1),this.add(o),r}registerRule(e,t){const n=[],i=[];u(this,c(e,t,n,i),n,i,"",!1)}registerCss(e){return this.registerRule("",e)}getStyles(){return f(this.sheet)}clone(){return new v(this.id,this.changes).merge(this)}}function x(e){return new v(`f${(++i).toString(36)}`,e)}},73274:(e,t,n)=>{var i="Expected a function",s="__lodash_placeholder__",r=1,o=2,a=4,l=8,h=16,c=32,u=64,f=128,d=512,p=1/0,m=9007199254740991,g=17976931348623157e292,b=NaN,y=[["ary",f],["bind",r],["bindKey",o],["curry",l],["curryRight",h],["flip",d],["partial",c],["partialRight",u],["rearg",256]],v="[object Function]",x="[object GeneratorFunction]",w="[object Symbol]",k=/^\s+|\s+$/g,S=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,A=/\{\n\/\* \[wrapped with (.+)\] \*/,C=/,? & /,O=/^[-+]0x[0-9a-f]+$/i,M=/^0b[01]+$/i,T=/^\[object .+?Constructor\]$/,_=/^0o[0-7]+$/i,N=/^(?:0|[1-9]\d*)$/,D=parseInt,E="object"==typeof n.g&&n.g&&n.g.Object===Object&&n.g,j="object"==typeof self&&self&&self.Object===Object&&self,R=E||j||Function("return this")();function P(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}function I(e){return e!=e}function B(e,t){for(var n=-1,i=e.length,r=0,o=[];++n2?$:void 0);function Z(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var n,i=ce(n=e.prototype)?K(n):{},s=e.apply(i,t);return ce(s)?s:i}}function ee(e,t,n,i,s,a,c,u,p,m){var g=t&f,b=t&r,y=t&o,v=t&(l|h),x=t&d,w=y?void 0:Z(e);return function r(){for(var o=arguments.length,l=Array(o),h=o;h--;)l[h]=arguments[h];if(v)var f=ne(r),d=function(e,t){for(var n=e.length,i=0;n--;)e[n]===t&&i++;return i}(l,f);if(i&&(l=function(e,t,n,i){for(var s=-1,r=e.length,o=n.length,a=-1,l=t.length,h=Y(r-o,0),c=Array(l+h),u=!i;++a1&&l.reverse(),g&&p1?"& ":"")+t[i],t=t.join(n>2?", ":" "),e.replace(S,"{\n/* [wrapped with "+t+"] */\n")}function oe(e,t){return!!(t=null==t?m:t)&&("number"==typeof e||N.test(e))&&e>-1&&e%1==0&&e-1}(e,a)&&e.push(a))););var o,a}(y),e.sort()}function he(e,t,n){var s=function(e,t,n,s,a,f,d,p){var m=t&o;if(!m&&"function"!=typeof e)throw new TypeError(i);var g=s?s.length:0;if(g||(t&=~(c|u),s=a=void 0),d=void 0===d?d:Y(ue(d),0),p=void 0===p?p:ue(p),g-=a?a.length:0,t&u){var b=s,y=a;s=a=void 0}var v=[e,t,n,s,a,b,y,f,d,p];if(e=v[0],t=v[1],n=v[2],s=v[3],a=v[4],!(p=v[9]=null==v[9]?m?0:e.length:Y(v[9]-g,0))&&t&(l|h)&&(t&=~(l|h)),t&&t!=r)x=t==l||t==h?function(e,t,n){var i=Z(e);return function s(){for(var r=arguments.length,o=Array(r),a=r,l=ne(s);a--;)o[a]=arguments[a];var h=r<3&&o[0]!==l&&o[r-1]!==l?[]:B(o,l);return(r-=h.length){e.exports=function(e){var t={};function n(i){if(t[i])return t[i].exports;var s=t[i]={exports:{},id:i,loaded:!1};return e[i].call(s.exports,s,s.exports,n),s.loaded=!0,s.exports}return n.m=e,n.c=t,n.p="",n(0)}([function(e,t,n){e.exports=n(1)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i,s=(i=n(2))&&i.__esModule?i:{default:i};t.default=s.default,e.exports=t.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t=0||Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=e[i]);return n}(e,["activeClassName","activeIndex","activeStyle","autoEscape","caseSensitive","className","findChunks","highlightClassName","highlightStyle","highlightTag","sanitize","searchWords","textToHighlight","unhighlightTag","unhighlightClassName","unhighlightStyle"]),N=(0,r.findAll)({autoEscape:c,caseSensitive:f,findChunks:p,sanitize:w,searchWords:k,textToHighlight:S}),D=x,E=-1,j="",R=void 0,P=(0,l.default)((function(e){var t={};for(var n in e)t[n.toLowerCase()]=e[n];return t}));return(0,a.createElement)("span",i({className:d},_,{children:N.map((function(e,t){var i=S.substr(e.start,e.end-e.start);if(e.highlight){E++;var s;s="object"==typeof g?f?g[i]:(g=P(g))[i.toLowerCase()]:g;var r=E===+o;j=s+" "+(r?n:""),R=!0===r&&null!=h?Object.assign({},y,h):y;var l={children:i,className:j,key:t,style:R};return"string"!=typeof D&&(l.highlightIndex=E),(0,a.createElement)(D,l)}return(0,a.createElement)(C,{children:i,className:M,key:t,style:T})}))}))}h.propTypes={activeClassName:o.default.string,activeIndex:o.default.number,activeStyle:o.default.object,autoEscape:o.default.bool,className:o.default.string,findChunks:o.default.func,highlightClassName:o.default.oneOfType([o.default.object,o.default.string]),highlightStyle:o.default.object,highlightTag:o.default.oneOfType([o.default.node,o.default.func,o.default.string]),sanitize:o.default.func,searchWords:o.default.arrayOf(o.default.oneOfType([o.default.string,o.default.instanceOf(RegExp)])).isRequired,textToHighlight:o.default.string.isRequired,unhighlightTag:o.default.oneOfType([o.default.node,o.default.func,o.default.string]),unhighlightClassName:o.default.string,unhighlightStyle:o.default.object},e.exports=t.default},function(e,t){e.exports=function(e){var t={};function n(i){if(t[i])return t[i].exports;var s=t[i]={exports:{},id:i,loaded:!1};return e[i].call(s.exports,s,s.exports,n),s.loaded=!0,s.exports}return n.m=e,n.c=t,n.p="",n(0)}([function(e,t,n){e.exports=n(1)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n(2);Object.defineProperty(t,"combineChunks",{enumerable:!0,get:function(){return i.combineChunks}}),Object.defineProperty(t,"fillInChunks",{enumerable:!0,get:function(){return i.fillInChunks}}),Object.defineProperty(t,"findAll",{enumerable:!0,get:function(){return i.findAll}}),Object.defineProperty(t,"findChunks",{enumerable:!0,get:function(){return i.findChunks}})},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findAll=function(e){var t=e.autoEscape,r=e.caseSensitive,o=void 0!==r&&r,a=e.findChunks,l=void 0===a?i:a,h=e.sanitize,c=e.searchWords,u=e.textToHighlight;return s({chunksToHighlight:n({chunks:l({autoEscape:t,caseSensitive:o,sanitize:h,searchWords:c,textToHighlight:u})}),totalLength:u?u.length:0})};var n=t.combineChunks=function(e){var t=e.chunks;return t.sort((function(e,t){return e.start-t.start})).reduce((function(e,t){if(0===e.length)return[t];var n=e.pop();if(t.start<=n.end){var i=Math.max(n.end,t.end);e.push({start:n.start,end:i})}else e.push(n,t);return e}),[])},i=function(e){var t=e.autoEscape,n=e.caseSensitive,i=e.sanitize,s=void 0===i?r:i,o=e.searchWords,a=e.textToHighlight;return a=s(a),o.filter((function(e){return e})).reduce((function(e,i){i=s(i),t&&(i=i.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"));for(var r=new RegExp(i,n?"g":"gi"),o=void 0;o=r.exec(a);){var l=o.index,h=r.lastIndex;h>l&&e.push({start:l,end:h}),o.index==r.lastIndex&&r.lastIndex++}return e}),[])};t.findChunks=i;var s=t.fillInChunks=function(e){var t=e.chunksToHighlight,n=e.totalLength,i=[],s=function(e,t,n){t-e>0&&i.push({start:e,end:t,highlight:n})};if(0===t.length)s(0,n,!1);else{var r=0;t.forEach((function(e){s(r,e.start,!1),s(e.start,e.end,!0),r=e.end})),s(r,n,!1)}return i};function r(e){return e}}])},function(e,t,n){(function(t){if("production"!==t.env.NODE_ENV){var i="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103;e.exports=n(6)((function(e){return"object"==typeof e&&null!==e&&e.$$typeof===i}),!0)}else e.exports=n(13)()}).call(t,n(5))},function(e,t){var n,i,s=e.exports={};function r(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function a(e){if(n===setTimeout)return setTimeout(e,0);if((n===r||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:r}catch(e){n=r}try{i="function"==typeof clearTimeout?clearTimeout:o}catch(e){i=o}}();var l,h=[],c=!1,u=-1;function f(){c&&l&&(c=!1,l.length?h=l.concat(h):u=-1,h.length&&d())}function d(){if(!c){var e=a(f);c=!0;for(var t=h.length;t;){for(l=h,h=[];++u1)for(var n=1;n1?t-1:0),i=1;i2?n-2:0),r=2;r1&&void 0!==arguments[1]?arguments[1]:n,i=void 0,s=[],r=void 0,o=!1,a=function(e,n){return t(e,s[n])};return function(){for(var t=arguments.length,n=Array(t),l=0;l{"use strict";var i=n(30905),s=Array.prototype.concat,r=Array.prototype.slice,o=e.exports=function(e){for(var t=[],n=0,o=e.length;n{e.exports=function(e){return!(!e||"string"==typeof e)&&(e instanceof Array||Array.isArray(e)||e.length>=0&&(e.splice instanceof Function||Object.getOwnPropertyDescriptor(e,e.length-1)&&"String"!==e.constructor.name))}},66770:(e,t,n)=>{"use strict";var i=n(90223);i.TypeStyle,n(43379);var s=n(27750);s.extend,s.classes,s.media;var r=new i.TypeStyle({autoGenerateTag:!0});r.setStylesTarget,r.cssRaw,r.cssRule,r.forceRenderStyles,r.fontFace,r.getStyles,r.keyframes,r.reinit,t.oB=r.style,r.stylesheet},37024:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.convertToStyles=function e(t){var n={};for(var i in t){var s=t[i];if("$nest"===i){var r=s;for(var o in r){var a=r[o];n[o]=e(a)}}else"$debugName"===i?n.$displayName=s:n[i]=s}return n},t.convertToKeyframes=function(e){var t={};for(var n in e)"$debugName"!==n&&(t[n]=e[n]);return e.$debugName&&(t.$displayName=e.$debugName),t}},90223:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n(29590),s=n(37024),r=n(27750),o=function(){return i.create()},a=function(){function e(e){var t=this,n=e.autoGenerateTag;this.cssRaw=function(e){e&&(t._raw+=e||"",t._pendingRawChange=!0,t._styleUpdated())},this.cssRule=function(e){for(var n=[],i=1;i{"use strict";function n(){for(var e=[],t=0;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},83286:function(e,t){!function(e){"use strict";e.JSONExt=void 0,function(e){function t(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e}function n(e){return Array.isArray(e)}function i(e,s){if(e===s)return!0;if(t(e)||t(s))return!1;let r=n(e),o=n(s);return r===o&&(r&&o?function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0,s=e.length;n>>0),e[n]=255&t,t>>>=8}e.Random=void 0,(e.Random||(e.Random={})).getRandomValues=(()=>{const e="undefined"!=typeof window&&(window.crypto||window.msCrypto)||null;return e&&"function"==typeof e.getRandomValues?function(t){return e.getRandomValues(t)}:t})(),e.UUID=void 0,(e.UUID||(e.UUID={})).uuid4=function(e){const t=new Uint8Array(16),n=new Array(256);for(let e=0;e<16;++e)n[e]="0"+e.toString(16);for(let e=16;e<256;++e)n[e]=e.toString(16);return function(){return e(t),t[6]=64|15&t[6],t[8]=128|63&t[8],n[t[0]]+n[t[1]]+n[t[2]]+n[t[3]]+"-"+n[t[4]]+n[t[5]]+"-"+n[t[6]]+n[t[7]]+"-"+n[t[8]]+n[t[9]]+"-"+n[t[10]]+n[t[11]]+n[t[12]]+n[t[13]]+n[t[14]]+n[t[15]]}}(e.Random.getRandomValues),e.MimeData=class{constructor(){this._types=[],this._values=[]}types(){return this._types.slice()}hasData(e){return-1!==this._types.indexOf(e)}getData(e){let t=this._types.indexOf(e);return-1!==t?this._values[t]:void 0}setData(e,t){this.clearData(e),this._types.push(e),this._values.push(t)}clearData(e){let t=this._types.indexOf(e);-1!==t&&(this._types.splice(t,1),this._values.splice(t,1))}clear(){this._types.length=0,this._values.length=0}},e.PromiseDelegate=class{constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}resolve(e){(0,this._resolve)(e)}reject(e){(0,this._reject)(e)}},e.Token=class{constructor(e,t){this.name=e,this.description=null!=t?t:"",this._tokenStructuralPropertyT=null}}}(t)},58514:(e,t,n)=>{"use strict";n.r(t),n.d(t,{Component:()=>Fs});var i=n(1727),s=n(65329),r=n(77120),o=n(21649);function a(e,t){return({state:n,dispatch:i})=>{if(n.readOnly)return!1;let s=e(t,n);return!!s&&(i(n.update(s)),!0)}}const l=a(p,0),h=a(d,0),c=a(((e,t)=>d(e,t,function(e){let t=[];for(let n of e.selection.ranges){let i=e.doc.lineAt(n.from),s=n.to<=i.to?i:e.doc.lineAt(n.to),r=t.length-1;r>=0&&t[r].to>i.from?t[r].to=s.to:t.push({from:i.from+/^\s*/.exec(i.text)[0].length,to:s.to})}return t}(t))),0);function u(e,t){let n=e.languageDataAt("commentTokens",t);return n.length?n[0]:{}}const f=50;function d(e,t,n=t.selection.ranges){let i=n.map((e=>u(t,e.from).block));if(!i.every((e=>e)))return null;let s=n.map(((e,n)=>function(e,{open:t,close:n},i,s){let r,o,a=e.sliceDoc(i-f,i),l=e.sliceDoc(s,s+f),h=/\s*$/.exec(a)[0].length,c=/^\s*/.exec(l)[0].length,u=a.length-h;if(a.slice(u-t.length,u)==t&&l.slice(c,c+n.length)==n)return{open:{pos:i-h,margin:h&&1},close:{pos:s+c,margin:c&&1}};s-i<=2*f?r=o=e.sliceDoc(i,s):(r=e.sliceDoc(i,i+f),o=e.sliceDoc(s-f,s));let d=/^\s*/.exec(r)[0].length,p=/\s*$/.exec(o)[0].length,m=o.length-p-n.length;return r.slice(d,d+t.length)==t&&o.slice(m,m+n.length)==n?{open:{pos:i+d+t.length,margin:/\s/.test(r.charAt(d+t.length))?1:0},close:{pos:s-p-n.length,margin:/\s/.test(o.charAt(m-1))?1:0}}:null}(t,i[n],e.from,e.to)));if(2!=e&&!s.every((e=>e)))return{changes:t.changes(n.map(((e,t)=>s[t]?[]:[{from:e.from,insert:i[t].open+" "},{from:e.to,insert:" "+i[t].close}])))};if(1!=e&&s.some((e=>e))){let e=[];for(let t,n=0;ns&&(e==r||r>l.from)){s=l.from;let e=/^\s*/.exec(l.text)[0].length,t=e==l.length,n=l.text.slice(e,e+a.length)==a?e:-1;ee.comment<0&&(!e.empty||e.single)))){let e=[];for(let{line:t,token:n,indent:s,empty:r,single:o}of i)!o&&r||e.push({from:t.from+s,insert:n+" "});let n=t.changes(e);return{changes:n,selection:t.selection.map(n,1)}}if(1!=e&&i.some((e=>e.comment>=0))){let e=[];for(let{line:t,comment:n,token:s}of i)if(n>=0){let i=t.from+n,r=i+s.length;" "==t.text[r-t.from]&&r++,e.push({from:i,to:r})}return{changes:e}}return null}const m=i.q6.define(),g=i.r$.define();class b{constructor(e,t,n,i,s){this.changes=e,this.effects=t,this.mapped=n,this.startSelection=i,this.selectionsAfter=s}setSelAfter(e){return new b(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,n;return{changes:null===(e=this.changes)||void 0===e?void 0:e.toJSON(),mapped:null===(t=this.mapped)||void 0===t?void 0:t.toJSON(),startSelection:null===(n=this.startSelection)||void 0===n?void 0:n.toJSON(),selectionsAfter:this.selectionsAfter.map((e=>e.toJSON()))}}static fromJSON(e){return new b(e.changes&&i.as.fromJSON(e.changes),[],e.mapped&&i.n0.fromJSON(e.mapped),e.startSelection&&i.jT.fromJSON(e.startSelection),e.selectionsAfter.map(i.jT.fromJSON))}static fromTransaction(e,t){let n=x;for(let t of e.startState.facet(g)){let i=t(e);i.length&&(n=n.concat(i))}return!n.length&&e.changes.empty?null:new b(e.changes.invert(e.startState.doc),n,void 0,t||e.startState.selection,x)}static selection(e){return new b(void 0,x,void 0,void 0,e)}}function y(e,t,n,i){let s=t+1>n+20?t-n-1:0,r=e.slice(s,t);return r.push(i),r}function v(e,t){return e.length?t.length?e.concat(t):e:t}const x=[],w=200;function k(e){let t=e[e.length-1],n=e.slice();return n[e.length-1]=t.setSelAfter(t.selectionsAfter.slice(0,t.selectionsAfter.length-1)),n}function S(e,t){if(!e.length)return e;let n=e.length,i=x;for(;n;){let s=A(e[n-1],t,i);if(s.changes&&!s.changes.empty||s.effects.length){let t=e.slice(0,n);return t[n-1]=s,t}t=s.mapped,n--,i=s.selectionsAfter}return i.length?[b.selection(i)]:x}function A(e,t,n){let s=v(e.selectionsAfter.length?e.selectionsAfter.map((e=>e.map(t))):x,n);if(!e.changes)return b.selection(s);let r=e.changes.map(t),o=t.mapDesc(e.changes,!0),a=e.mapped?e.mapped.composeDesc(o):o;return new b(r,i.Py.mapEffects(e.effects,t),a,e.startSelection.map(o),s)}const C=/^(input\.type|delete)($|\.)/;class O{constructor(e,t,n=0,i=undefined){this.done=e,this.undone=t,this.prevTime=n,this.prevUserEvent=i}isolate(){return this.prevTime?new O(this.done,this.undone):this}addChanges(e,t,n,i,s){let r=this.done,o=r[r.length-1];return r=o&&o.changes&&!o.changes.empty&&e.changes&&(!n||C.test(n))&&(!o.selectionsAfter.length&&t-this.prevTimen.push(e,t))),t.iterChangedRanges(((e,t,s,r)=>{for(let e=0;e=t&&s<=o&&(i=!0)}})),i}(o.changes,e.changes))||"input.type.compose"==n)?y(r,r.length-1,i.minDepth,new b(e.changes.compose(o.changes),v(e.effects,o.effects),o.mapped,o.startSelection,x)):y(r,r.length,i.minDepth,e),new O(r,x,t,n)}addSelection(e,t,n,i){let s=this.done.length?this.done[this.done.length-1].selectionsAfter:x;return s.length>0&&t-this.prevTimee.empty!=o.ranges[t].empty)).length)?this:new O(function(e,t){if(e.length){let n=e[e.length-1],i=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-w));return i.length&&i[i.length-1].eq(t)?e:(i.push(t),y(e,e.length-1,1e9,n.setSelAfter(i)))}return[b.selection([t])]}(this.done,e),this.undone,t,n);var r,o}addMapping(e){return new O(S(this.done,e),S(this.undone,e),this.prevTime,this.prevUserEvent)}pop(e,t,n){let i=0==e?this.done:this.undone;if(0==i.length)return null;let s=i[i.length-1];if(n&&s.selectionsAfter.length)return t.update({selection:s.selectionsAfter[s.selectionsAfter.length-1],annotations:m.of({side:e,rest:k(i)}),userEvent:0==e?"select.undo":"select.redo",scrollIntoView:!0});if(s.changes){let n=1==i.length?x:i.slice(0,i.length-1);return s.mapped&&(n=S(n,s.mapped)),t.update({changes:s.changes,selection:s.startSelection,effects:s.effects,annotations:m.of({side:e,rest:n}),filter:!1,userEvent:0==e?"undo":"redo",scrollIntoView:!0})}return null}}function M(e,t){return i.jT.create(e.ranges.map(t),e.mainIndex)}function T(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:"select"})}function _({state:e,dispatch:t},n){let i=M(e.selection,n);return!i.eq(e.selection)&&(t(T(e,i)),!0)}function N(e,t){return i.jT.cursor(t?e.to:e.from)}function D(e,t){return _(e,(n=>n.empty?e.moveByChar(n,t):N(n,t)))}function E(e){return e.textDirectionAt(e.state.selection.main.head)==s.Nm.LTR}O.empty=new O(x,x);const j=e=>D(e,!E(e)),R=e=>D(e,E(e));function P(e,t){return _(e,(n=>n.empty?e.moveByGroup(n,t):N(n,t)))}function I(e,t,n){if(t.type.prop(n))return!0;let i=t.to-t.from;return i&&(i>2||/[^\s,.;:]/.test(e.sliceDoc(t.from,t.to)))||t.firstChild}function B(e,t,n){let s,a,l=(0,r.qz)(e).resolveInner(t.head),h=n?o.md.closedBy:o.md.openedBy;for(let i=t.head;;){let t=n?l.childAfter(i):l.childBefore(i);if(!t)break;I(e,t,h)?l=t:i=n?t.to:t.from}return a=l.type.prop(h)&&(s=n?(0,r.Um)(e,l.from,1):(0,r.Um)(e,l.to,-1))&&s.matched?n?s.end.to:s.end.from:n?l.to:l.from,i.jT.cursor(a,n?-1:1)}function L(e,t){return _(e,(n=>{if(!n.empty)return N(n,t);let i=e.moveVertically(n,t);return i.head!=n.head?i:e.moveToLineBoundary(n,t)}))}"undefined"!=typeof Intl&&Intl.Segmenter;const $=e=>L(e,!1),z=e=>L(e,!0);function F(e){let t,n=e.scrollDOM.clientHeightn.empty?e.moveVertically(n,t,i.height):N(n,t)));if(o.eq(r.selection))return!1;if(i.selfScroll){let t=e.coordsAtPos(r.selection.main.head),a=e.scrollDOM.getBoundingClientRect(),l=a.top+i.marginTop,h=a.bottom-i.marginBottom;t&&t.top>l&&t.bottomH(e,!1),W=e=>H(e,!0);function q(e,t,n){let s=e.lineBlockAt(t.head),r=e.moveToLineBoundary(t,n);if(r.head==t.head&&r.head!=(n?s.to:s.from)&&(r=e.moveToLineBoundary(t,n,!1)),!n&&r.head==s.from&&s.length){let n=/^\s*/.exec(e.state.sliceDoc(s.from,Math.min(s.from+100,s.to)))[0].length;n&&t.head!=s.from+n&&(r=i.jT.cursor(s.from+n))}return r}function J(e,t){let n=M(e.state.selection,(e=>{let n=t(e);return i.jT.range(e.anchor,n.head,n.goalColumn,n.bidiLevel||void 0)}));return!n.eq(e.state.selection)&&(e.dispatch(T(e.state,n)),!0)}function U(e,t){return J(e,(n=>e.moveByChar(n,t)))}const G=e=>U(e,!E(e)),K=e=>U(e,E(e));function Y(e,t){return J(e,(n=>e.moveByGroup(n,t)))}function X(e,t){return J(e,(n=>e.moveVertically(n,t)))}const Q=e=>X(e,!1),Z=e=>X(e,!0);function ee(e,t){return J(e,(n=>e.moveVertically(n,t,F(e).height)))}const te=e=>ee(e,!1),ne=e=>ee(e,!0),ie=({state:e,dispatch:t})=>(t(T(e,{anchor:0})),!0),se=({state:e,dispatch:t})=>(t(T(e,{anchor:e.doc.length})),!0),re=({state:e,dispatch:t})=>(t(T(e,{anchor:e.selection.main.anchor,head:0})),!0),oe=({state:e,dispatch:t})=>(t(T(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0);function ae(e,t){if(e.state.readOnly)return!1;let n="delete.selection",{state:r}=e,o=r.changeByRange((s=>{let{from:r,to:o}=s;if(r==o){let i=t(s);ir&&(n="delete.forward",i=le(e,i,!0)),r=Math.min(r,i),o=Math.max(o,i)}else r=le(e,r,!1),o=le(e,o,!0);return r==o?{range:s}:{changes:{from:r,to:o},range:i.jT.cursor(r,rt(e))))i.between(t,t,((e,i)=>{et&&(t=n?i:e)}));return t}const he=(e,t)=>ae(e,(n=>{let s,o,a=n.from,{state:l}=e,h=l.doc.lineAt(a);if(!t&&a>h.from&&ahe(e,!1),ue=e=>he(e,!0),fe=(e,t)=>ae(e,(n=>{let s=n.head,{state:r}=e,o=r.doc.lineAt(s),a=r.charCategorizer(s);for(let e=null;;){if(s==(t?o.to:o.from)){s==n.head&&o.number!=(t?r.doc.lines:1)&&(s+=t?1:-1);break}let l=(0,i.cp)(o.text,s-o.from,t)+o.from,h=o.text.slice(Math.min(s,l)-o.from,Math.max(s,l)-o.from),c=a(h);if(null!=e&&c!=e)break;" "==h&&s==n.head||(e=c),s=l}return s})),de=e=>fe(e,!1);function pe(e){let t=[],n=-1;for(let i of e.selection.ranges){let s=e.doc.lineAt(i.from),r=e.doc.lineAt(i.to);if(i.empty||i.to!=r.from||(r=e.doc.lineAt(i.to-1)),n>=s.number){let e=t[t.length-1];e.to=r.to,e.ranges.push(i)}else t.push({from:s.from,to:r.to,ranges:[i]});n=r.number+1}return t}function me(e,t,n){if(e.readOnly)return!1;let s=[],r=[];for(let t of pe(e)){if(n?t.to==e.doc.length:0==t.from)continue;let o=e.doc.lineAt(n?t.to+1:t.from-1),a=o.length+1;if(n){s.push({from:t.to,to:o.to},{from:t.from,insert:o.text+e.lineBreak});for(let n of t.ranges)r.push(i.jT.range(Math.min(e.doc.length,n.anchor+a),Math.min(e.doc.length,n.head+a)))}else{s.push({from:o.from,to:t.from},{from:t.to,insert:e.lineBreak+o.text});for(let e of t.ranges)r.push(i.jT.range(e.anchor-a,e.head-a))}}return!!s.length&&(t(e.update({changes:s,scrollIntoView:!0,selection:i.jT.create(r,e.selection.mainIndex),userEvent:"move.line"})),!0)}function ge(e,t,n){if(e.readOnly)return!1;let i=[];for(let t of pe(e))n?i.push({from:t.from,insert:e.doc.slice(t.from,t.to)+e.lineBreak}):i.push({from:t.to,insert:e.lineBreak+e.doc.slice(t.from,t.to)});return t(e.update({changes:i,scrollIntoView:!0,userEvent:"input.copyline"})),!0}const be=ye(!1);function ye(e){return({state:t,dispatch:n})=>{if(t.readOnly)return!1;let s=t.changeByRange((n=>{let{from:s,to:a}=n,l=t.doc.lineAt(s),h=!e&&s==a&&function(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n,i=(0,r.qz)(e).resolveInner(t),s=i.childBefore(t),a=i.childAfter(t);return s&&a&&s.to<=t&&a.from>=t&&(n=s.type.prop(o.md.closedBy))&&n.indexOf(a.name)>-1&&e.doc.lineAt(s.to).from==e.doc.lineAt(a.from).from&&!/\S/.test(e.sliceDoc(s.to,a.from))?{from:s.to,to:a.from}:null}(t,s);e&&(s=a=(a<=l.to?l:t.doc.lineAt(a)).to);let c=new r.Gn(t,{simulateBreak:s,simulateDoubleBreak:!!h}),u=(0,r.K0)(c,s);for(null==u&&(u=(0,i.IS)(/^\s*/.exec(t.doc.lineAt(s).text)[0],t.tabSize));al.from&&s{let r=[];for(let i=s.from;i<=s.to;){let o=e.doc.lineAt(i);o.number>n&&(s.empty||s.to>o.from)&&(t(o,r,s),n=o.number),i=o.to+1}let o=e.changes(r);return{changes:r,range:i.jT.range(o.mapPos(s.anchor,1),o.mapPos(s.head,1))}}))}const xe=({state:e,dispatch:t})=>!e.readOnly&&(t(e.update(ve(e,((t,n)=>{n.push({from:t.from,insert:e.facet(r.c)})})),{userEvent:"input.indent"})),!0),we=({state:e,dispatch:t})=>!e.readOnly&&(t(e.update(ve(e,((t,n)=>{let s=/^\s*/.exec(t.text)[0];if(!s)return;let o=(0,i.IS)(s,e.tabSize),a=0,l=(0,r.SS)(e,Math.max(0,o-(0,r.y1)(e)));for(;a_(e,(t=>B(e.state,t,!E(e)))),shift:e=>J(e,(t=>B(e.state,t,!E(e))))},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:e=>_(e,(t=>B(e.state,t,E(e)))),shift:e=>J(e,(t=>B(e.state,t,E(e))))},{key:"Alt-ArrowUp",run:({state:e,dispatch:t})=>me(e,t,!1)},{key:"Shift-Alt-ArrowUp",run:({state:e,dispatch:t})=>ge(e,t,!1)},{key:"Alt-ArrowDown",run:({state:e,dispatch:t})=>me(e,t,!0)},{key:"Shift-Alt-ArrowDown",run:({state:e,dispatch:t})=>ge(e,t,!0)},{key:"Escape",run:({state:e,dispatch:t})=>{let n=e.selection,s=null;return n.ranges.length>1?s=i.jT.create([n.main]):n.main.empty||(s=i.jT.create([i.jT.cursor(n.main.head)])),!!s&&(t(T(e,s)),!0)}},{key:"Mod-Enter",run:ye(!0)},{key:"Alt-l",mac:"Ctrl-l",run:({state:e,dispatch:t})=>{let n=pe(e).map((({from:t,to:n})=>i.jT.range(t,Math.min(n+1,e.doc.length))));return t(e.update({selection:i.jT.create(n),userEvent:"select"})),!0}},{key:"Mod-i",run:({state:e,dispatch:t})=>{let n=M(e.selection,(t=>{var n;for(let s=(0,r.qz)(e).resolveStack(t.from,1);s;s=s.next){let{node:e}=s;if((e.from=t.to||e.to>t.to&&e.from<=t.from)&&(null===(n=e.parent)||void 0===n?void 0:n.parent))return i.jT.range(e.to,e.from)}return t}));return t(T(e,n)),!0},preventDefault:!0},{key:"Mod-[",run:we},{key:"Mod-]",run:xe},{key:"Mod-Alt-\\",run:({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),i=new r.Gn(e,{overrideIndentation:e=>{let t=n[e];return null==t?-1:t}}),s=ve(e,((t,s,o)=>{let a=(0,r.K0)(i,t.from);if(null==a)return;/\S/.test(t.text)||(a=0);let l=/^\s*/.exec(t.text)[0],h=(0,r.SS)(e,a);(l!=h||o.from{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(pe(t).map((({from:e,to:n})=>(e>0?e--:ne.moveVertically(t,!0))).map(n);return e.dispatch({changes:n,selection:i,scrollIntoView:!0,userEvent:"delete.line"}),!0}},{key:"Shift-Mod-\\",run:({state:e,dispatch:t})=>function(e,t,n){let s=!1,o=M(e.selection,(t=>{let o=(0,r.Um)(e,t.head,-1)||(0,r.Um)(e,t.head,1)||t.head>0&&(0,r.Um)(e,t.head-1,1)||t.head{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),i=u(e.state,n.from);return i.line?l(e):!!i.block&&c(e)}},{key:"Alt-A",run:h}].concat([{key:"ArrowLeft",run:j,shift:G,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:e=>P(e,!E(e)),shift:e=>Y(e,!E(e)),preventDefault:!0},{mac:"Cmd-ArrowLeft",run:e=>_(e,(t=>q(e,t,!E(e)))),shift:e=>J(e,(t=>q(e,t,!E(e)))),preventDefault:!0},{key:"ArrowRight",run:R,shift:K,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:e=>P(e,E(e)),shift:e=>Y(e,E(e)),preventDefault:!0},{mac:"Cmd-ArrowRight",run:e=>_(e,(t=>q(e,t,E(e)))),shift:e=>J(e,(t=>q(e,t,E(e)))),preventDefault:!0},{key:"ArrowUp",run:$,shift:Q,preventDefault:!0},{mac:"Cmd-ArrowUp",run:ie,shift:re},{mac:"Ctrl-ArrowUp",run:V,shift:te},{key:"ArrowDown",run:z,shift:Z,preventDefault:!0},{mac:"Cmd-ArrowDown",run:se,shift:oe},{mac:"Ctrl-ArrowDown",run:W,shift:ne},{key:"PageUp",run:V,shift:te},{key:"PageDown",run:W,shift:ne},{key:"Home",run:e=>_(e,(t=>q(e,t,!1))),shift:e=>J(e,(t=>q(e,t,!1))),preventDefault:!0},{key:"Mod-Home",run:ie,shift:re},{key:"End",run:e=>_(e,(t=>q(e,t,!0))),shift:e=>J(e,(t=>q(e,t,!0))),preventDefault:!0},{key:"Mod-End",run:se,shift:oe},{key:"Enter",run:be},{key:"Mod-a",run:({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:"select"})),!0)},{key:"Backspace",run:ce,shift:ce},{key:"Delete",run:ue},{key:"Mod-Backspace",mac:"Alt-Backspace",run:de},{key:"Mod-Delete",mac:"Alt-Delete",run:e=>fe(e,!0)},{mac:"Mod-Backspace",run:e=>ae(e,(t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}))},{mac:"Mod-Delete",run:e=>ae(e,(t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head_(e,(t=>i.jT.cursor(e.lineBlockAt(t.head).from,1))),shift:e=>J(e,(t=>i.jT.cursor(e.lineBlockAt(t.head).from)))},{key:"Ctrl-e",run:e=>_(e,(t=>i.jT.cursor(e.lineBlockAt(t.head).to,-1))),shift:e=>J(e,(t=>i.jT.cursor(e.lineBlockAt(t.head).to)))},{key:"Ctrl-d",run:ue},{key:"Ctrl-h",run:ce},{key:"Ctrl-k",run:e=>ae(e,(t=>{let n=e.lineBlockAt(t.head).to;return t.head{if(e.readOnly)return!1;let n=e.changeByRange((e=>({changes:{from:e.from,to:e.to,insert:i.xv.of(["",""])},range:i.jT.cursor(e.from)})));return t(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0}},{key:"Ctrl-t",run:({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange((t=>{if(!t.empty||0==t.from||t.from==e.doc.length)return{range:t};let n=t.from,s=e.doc.lineAt(n),r=n==s.from?n-1:(0,i.cp)(s.text,n-s.from,!1)+s.from,o=n==s.to?n+1:(0,i.cp)(s.text,n-s.from,!0)+s.from;return{changes:{from:r,to:o,insert:e.doc.slice(n,o).append(e.doc.slice(r,n))},range:i.jT.cursor(o)}}));return!n.changes.empty&&(t(e.update(n,{scrollIntoView:!0,userEvent:"move.character"})),!0)}},{key:"Ctrl-v",run:W}].map((e=>({mac:e.key,run:e.run,shift:e.shift})))));var Se;!function(e){e.indentMoreOrInsertTab=function(e){const t={state:e.state,dispatch:e.dispatch},n=e.state.selection.main.from;if(n!=e.state.selection.main.to)return xe(t);const i=e.state.doc.lineAt(n),s=e.state.doc.slice(i.from,n).toString();return/^\s*$/.test(s)?xe(t):(({state:e,dispatch:t})=>e.selection.ranges.some((e=>!e.empty))?xe({state:e,dispatch:t}):(t(e.update(e.replaceSelection("\t"),{scrollIntoView:!0,userEvent:"input"})),!0))(t)}}(Se||(Se={}));var Ae=n(83286),Ce=n(27337),Oe=n(64100),Me=n(77616);const Te=i.r$.define({combine:e=>(0,i.BO)(e,{fontFamily:null,fontSize:null,lineHeight:null},{fontFamily:(e,t)=>null!=e?e:t,fontSize:(e,t)=>null!=e?e:t,lineHeight:(e,t)=>null!=e?e:t})});function _e(e){const{fontFamily:t,fontSize:n,lineHeight:i}=e.state.facet(Te);let s="";return n&&(s+=`font-size: ${n}px !important;`),t&&(s+=`font-family: ${t} !important;`),i&&(s+=`line-height: ${i.toString()} !important`),{style:s}}var Ne=n(86253);const De={InlineMathDollar:1,InlineMathBracket:3,BlockMathDollar:2,BlockMathBracket:3};Object.keys(De).reduce(((e,t)=>(e[t]={mark:`${t}Mark`,resolve:t},e)),{});const Ee="cm-rulers",je=s.tk.baseTheme({[`.${Ee}`]:{borderRight:"1px dotted gray",opacity:.7}}),Re=i.r$.define({combine:e=>e.reduce(((e,t)=>e.concat(t.filter(((n,i)=>!e.includes(n)&&i==t.lastIndexOf(n))))),[])}),Pe=s.lg.fromClass(class{constructor(e){var t,n;this.rulersContainer=e.dom.appendChild(document.createElement("div")),this.rulersContainer.style.cssText="\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n pointer-events: none;\n overflow: hidden;\n ";const i=e.defaultCharacterWidth,s=e.state.facet(Re),r=null!==(n=null===(t=e.scrollDOM.querySelector(".cm-gutters"))||void 0===t?void 0:t.clientWidth)&&void 0!==n?n:0;this.rulers=s.map((e=>{const t=this.rulersContainer.appendChild(document.createElement("div"));return t.classList.add(Ee),t.style.cssText=`\n position: absolute;\n left: ${r+e*i}px;\n height: 100%;\n `,t.style.width="6px",t}))}update(e){var t,n;const i=e.view.state.facet(Re);if(e.viewportChanged||e.geometryChanged||!Ae.JSONExt.deepEqual(i,e.startState.facet(Re))){const s=null!==(n=null===(t=e.view.scrollDOM.querySelector(".cm-gutters"))||void 0===t?void 0:t.clientWidth)&&void 0!==n?n:0,r=e.view.defaultCharacterWidth;this.rulers.forEach(((e,t)=>{e.style.left=`${s+i[t]*r}px`}))}}destroy(){this.rulers.forEach((e=>{e.remove()})),this.rulersContainer.remove()}}),Ie=i.r$.define({combine:e=>e[e.length-1]}),Be=i.q6.define();s.lg.fromClass(class{constructor(e){this.conf=e.state.facet(Ie),this._observer=(t,n)=>{var i;if(n.origin!==this.conf){const n=t.delta,s=[];let r=0;for(let e=0;e0&&e.transactions[0].annotation(Be)===this.conf)return;const t=this.conf.ytext;t.doc.transact((()=>{let n=0;e.changes.iterChanges(((e,i,s,r,o)=>{const a=o.sliceString(0,o.length,"\n");e!==i&&t.delete(e+n,i-e),a.length>0&&t.insert(e+n,a),n+=a.length-(i-e)}))}),this.conf)}destroy(){this._ytext.unobserve(this._observer)}});class Le{constructor({baseConfiguration:e,config:t,defaultExtensions:n}={}){this._configChanged=new Ce.Signal(this),this._disposed=new Ce.Signal(this),this._isDisposed=!1,this._immutables=new Set,this._baseConfig=null!=e?e:{},this._config=null!=t?t:{},this._configurableBuilderMap=new Map(n);const i=Object.keys(this._config).concat(Object.keys(this._baseConfig));this._immutables=new Set([...this._configurableBuilderMap.keys()].filter((e=>!i.includes(e))))}get configChanged(){return this._configChanged}get disposed(){return this._disposed}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,this._disposed.emit(),Ce.Signal.clearData(this))}getOption(e){var t;return null!==(t=this._config[e])&&void 0!==t?t:this._baseConfig[e]}hasOption(e){return Object.keys(this._config).includes(e)||Object.keys(this._baseConfig).includes(e)}setOption(e,t){this._config[e]!==t&&(this._config[e]=t,this._configChanged.emit({[e]:t}))}setBaseOptions(e){const t=this._getChangedOptions(e,this._baseConfig);if(t.length>0){this._baseConfig=e;const n=Object.keys(this._config),i=t.filter((e=>!n.includes(e)));i.length>0&&this._configChanged.emit(i.reduce(((e,t)=>(e[t]=this._baseConfig[t],e)),{}))}}setOptions(e){const t=this._getChangedOptions(e,this._config);t.length>0&&(this._config={...e},this._configChanged.emit(t.reduce(((e,t)=>{var n;return e[t]=null!==(n=this._config[t])&&void 0!==n?n:this._baseConfig[t],e}),{})))}reconfigureExtension(e,t,n){const i=this.getEffect(e.state,t,n);i&&e.dispatch({effects:[i]})}reconfigureExtensions(e,t){const n=Object.keys(t).filter((e=>this.has(e))).map((n=>this.getEffect(e.state,n,t[n])));e.dispatch({effects:n.filter((e=>null!==e))})}injectExtension(e,t){e.dispatch({effects:i.Py.appendConfig.of(t)})}getInitialExtensions(){const e={...this._baseConfig,...this._config},t=[...this._immutables].map((e=>{var t;return null===(t=this.get(e))||void 0===t?void 0:t.instance(void 0)})).filter((e=>e));for(const n of Object.keys(e)){const i=this.get(n);if(i){const s=e[n];t.push(i.instance(s))}}return t}get(e){return this._configurableBuilderMap.get(e)}has(e){return this._configurableBuilderMap.has(e)}getEffect(e,t,n){var i;const s=this.get(t);return null!==(i=null==s?void 0:s.reconfigure(n))&&void 0!==i?i:null}_getChangedOptions(e,t){const n=new Array,i=new Array;for(const[s,r]of Object.entries(e))i.push(s),t[s]!==r&&n.push(s);return n.push(...Object.keys(t).filter((e=>!i.includes(e)))),n}}class $e{constructor(){this.configurationBuilder=new Map,this.configurationSchema={},this.defaultOptions={},this.handlers=new Set,this.immutableExtensions=new Set,this._baseConfiguration={}}get baseConfiguration(){return{...this.defaultOptions,...this._baseConfiguration}}set baseConfiguration(e){if(!Ae.JSONExt.deepEqual(e,this._baseConfiguration)){this._baseConfiguration=e;for(const e of this.handlers)e.setBaseOptions(this.baseConfiguration)}}get defaultConfiguration(){return Object.freeze({...this.defaultOptions})}get settingsSchema(){return Object.freeze(Ae.JSONExt.deepCopy(this.configurationSchema))}addExtension(e){var t;if(this.configurationBuilder.has(e.name))throw new Error(`Extension named ${e.name} is already registered.`);this.configurationBuilder.set(e.name,e),void 0!==e.default&&(this.defaultOptions[e.name]=e.default),e.schema&&(this.configurationSchema[e.name]={default:null!==(t=e.default)&&void 0!==t?t:null,...e.schema},this.defaultOptions[e.name]=this.configurationSchema[e.name].default)}createNew(e){const t=new Array;for(const[n,i]of this.configurationBuilder.entries()){const s=i.factory(e);s&&t.push([n,s])}const n=new Le({baseConfiguration:this.baseConfiguration,config:e.config,defaultExtensions:t});return this.handlers.add(n),n.disposed.connect((()=>{this.handlers.delete(n)})),n}}var ze;!function(e){class t{constructor(e){this._compartment=new i.F6,this._builder=e}instance(e){return this._compartment.of(this._builder(e))}reconfigure(e){return this._compartment.reconfigure(this._builder(e))}}class n{constructor(e){this._extension=e}instance(){return this._extension}reconfigure(){return null}}function o(e){return new t(e)}function a(e,n=[]){return new t((t=>t?e:n))}function l(e){return new n(e)}e.createConfigurableExtension=o,e.createConditionalExtension=a,e.createImmutableExtension=l,e.getDefaultExtensions=function(e={}){const{themes:t,translator:n}=e,h=(null!=n?n:Me.Sr).load("jupyterlab"),c=[Object.freeze({name:"autoClosingBrackets",default:!1,factory:()=>a((0,Oe.vQ)()),schema:{type:"boolean",title:h.__("Auto Closing Brackets")}}),Object.freeze({name:"codeFolding",default:!1,factory:()=>a((0,r.mi)()),schema:{type:"boolean",title:h.__("Code Folding")}}),Object.freeze({name:"cursorBlinkRate",default:1200,factory:()=>o((e=>(0,s.Uw)({cursorBlinkRate:e}))),schema:{type:"number",title:h.__("Cursor blinking rate"),description:h.__("Half-period in milliseconds used for cursor blinking. The default blink rate is 1200ms. By setting this to zero, blinking can be disabled.")}}),Object.freeze({name:"highlightActiveLine",default:!1,factory:()=>a((0,s.ZO)()),schema:{type:"boolean",title:h.__("Highlight the active line")}}),Object.freeze({name:"highlightTrailingWhitespace",default:!1,factory:()=>a((0,s.pk)()),schema:{type:"boolean",title:h.__("Highlight trailing white spaces")}}),Object.freeze({name:"highlightWhitespace",default:!1,factory:()=>a((0,s.DF)()),schema:{type:"boolean",title:h.__("Highlight white spaces")}}),Object.freeze({name:"indentUnit",default:"4",factory:()=>o((e=>"Tab"==e?r.c.of("\t"):r.c.of(" ".repeat(parseInt(e,10))))),schema:{type:"string",title:h.__("Indentation unit"),description:h.__("The indentation is a `Tab` or the number of spaces. This defaults to 4 spaces."),enum:["Tab","1","2","4","8"]}}),Object.freeze({name:"keymap",default:[...ke,{key:"Tab",run:Se.indentMoreOrInsertTab,shift:we}],factory:()=>o((e=>s.$f.of(e)))}),Object.freeze({name:"lineNumbers",default:!0,factory:()=>a((0,s.Eu)()),schema:{type:"boolean",title:h.__("Line Numbers")}}),Object.freeze({name:"lineWrap",factory:()=>a(s.tk.lineWrapping),default:!0,schema:{type:"boolean",title:h.__("Line Wrap")}}),Object.freeze({name:"matchBrackets",default:!0,factory:()=>a([(0,r.n$)(),i.Wl.high(s.$f.of(Oe.GA))]),schema:{type:"boolean",title:h.__("Match Brackets")}}),Object.freeze({name:"rectangularSelection",default:!0,factory:()=>a([(0,s.Zs)(),(0,s.S2)()]),schema:{type:"boolean",title:h.__("Rectangular selection"),description:h.__("Rectangular (block) selection can be created by dragging the mouse pointer while holding the left mouse button and the Alt key. When the Alt key is pressed, a crosshair cursor will appear, indicating that the rectangular selection mode is active.")}}),Object.freeze({name:"readOnly",default:!1,factory:()=>o((e=>[i.yy.readOnly.of(e),e?s.tk.editorAttributes.of({class:"jp-mod-readOnly"}):[]]))}),Object.freeze({name:"rulers",default:[],factory:()=>o((e=>e.length>0?function(e){return[je,Re.of(e),Pe]}(e):[])),schema:{type:"array",title:h.__("Rulers"),items:{type:"number",minimum:0}}}),Object.freeze({name:"scrollPastEnd",default:!1,factory:e=>e.inline?null:a((0,s.CT)())}),Object.freeze({name:"smartIndent",default:!0,factory:()=>a((0,r.nY)()),schema:{type:"boolean",title:h.__("Smart Indentation")}}),Object.freeze({name:"tabSize",default:4,factory:()=>o((e=>i.yy.tabSize.of(e))),schema:{type:"number",title:h.__("Tab size")}}),Object.freeze({name:"tooltips",factory:()=>l((0,s.jH)({position:"absolute",parent:document.body}))}),Object.freeze({name:"allowMultipleSelections",default:!0,factory:()=>o((e=>i.yy.allowMultipleSelections.of(e))),schema:{type:"boolean",title:h.__("Multiple selections")}}),Object.freeze({name:"customStyles",factory:()=>o((e=>function(e){return[Te.of(e),s.tk.editorAttributes.of(_e)]}(e))),default:{fontFamily:null,fontSize:null,lineHeight:null},schema:{title:h.__("Custom editor styles"),type:"object",properties:{fontFamily:{type:["string","null"],title:h.__("Font Family")},fontSize:{type:["number","null"],minimum:1,maximum:100,title:h.__("Font Size")},lineHeight:{type:["number","null"],title:h.__("Line Height")}},additionalProperties:!1}})];return t&&c.push(Object.freeze({name:"theme",default:"jupyter",factory:()=>o((e=>t.getTheme(e))),schema:{type:"string",title:h.__("Theme"),description:h.__("CodeMirror theme")}})),n&&c.push(Object.freeze({name:"translation",default:{"Control character":h.__("Control character"),"Selection deleted":h.__("Selection deleted"),"Folded lines":h.__("Folded lines"),"Unfolded lines":h.__("Unfolded lines"),to:h.__("to"),"folded code":h.__("folded code"),unfold:h.__("unfold"),"Fold line":h.__("Fold line"),"Unfold line":h.__("Unfold line"),"Go to line":h.__("Go to line"),go:h.__("go"),Find:h.__("Find"),Replace:h.__("Replace"),next:h.__("next"),previous:h.__("previous"),all:h.__("all"),"match case":h.__("match case"),replace:h.__("replace"),"replace all":h.__("replace all"),close:h.__("close"),"current match":h.__("current match"),"replaced $ matches":h.__("replaced $ matches"),"replaced match on line $":h.__("replaced match on line $"),"on line":h.__("on line"),Completions:h.__("Completions"),Diagnostics:h.__("Diagnostics"),"No diagnostics":h.__("No diagnostics")},factory:()=>o((e=>i.yy.phrases.of(e)))})),c}}($e||($e={})),(ze||(ze={})).defaultMimeType="text/plain";var Fe=n(41405),He=n(51392);class Ve{constructor(e){this.start=e}}class We extends Ve{constructor(e,t,n,i,s,r,o,a,l,h,c,u,f,d,p){super(e),this.rules=t,this.topRules=n,this.tokens=i,this.localTokens=s,this.context=r,this.externalTokens=o,this.externalSpecializers=a,this.externalPropSources=l,this.precedences=h,this.mainSkip=c,this.scopedSkip=u,this.dialects=f,this.externalProps=d,this.autoDelim=p}toString(){return Object.values(this.rules).join("\n")}}class qe extends Ve{constructor(e,t,n,i,s){super(e),this.id=t,this.props=n,this.params=i,this.expr=s}toString(){return this.id.name+(this.params.length?`<${this.params.join()}>`:"")+" -> "+this.expr}}class Je extends Ve{constructor(e,t){super(e),this.items=t}}class Ue extends Ve{constructor(e,t){super(e),this.items=t}}class Ge extends Ve{constructor(e,t,n){super(e),this.a=t,this.b=n}}class Ke extends Ve{constructor(e,t,n,i,s){super(e),this.precedences=t,this.conflicts=n,this.rules=i,this.literals=s}}class Ye extends Ve{constructor(e,t,n,i){super(e),this.precedences=t,this.rules=n,this.fallback=i}}class Xe extends Ve{constructor(e,t,n){super(e),this.literal=t,this.props=n}}class Qe extends Ve{constructor(e,t,n){super(e),this.id=t,this.source=n}}class Ze extends Ve{constructor(e,t,n,i){super(e),this.id=t,this.source=n,this.tokens=i}}class et extends Ve{constructor(e,t,n,i,s,r){super(e),this.type=t,this.token=n,this.id=i,this.source=s,this.tokens=r}}class tt extends Ve{constructor(e,t,n){super(e),this.id=t,this.source=n}}class nt extends Ve{constructor(e,t,n,i){super(e),this.id=t,this.externalID=n,this.source=i}}class it extends Ve{constructor(e,t){super(e),this.name=t}toString(){return this.name}}class st extends Ve{walk(e){return e(this)}eq(e){return!1}}st.prototype.prec=10;class rt extends st{constructor(e,t,n){super(e),this.id=t,this.args=n}toString(){return this.id.name+(this.args.length?`<${this.args.join()}>`:"")}eq(e){return this.id.name==e.id.name&&vt(this.args,e.args)}walk(e){let t=mt(this.args,e);return e(t==this.args?this:new rt(this.start,this.id,t))}}class ot extends st{constructor(e,t,n,i,s){super(e),this.type=t,this.props=n,this.token=i,this.content=s}toString(){return`@${this.type}[${this.props.join(",")}]<${this.token}, ${this.content}>`}eq(e){return this.type==e.type&&xt.eqProps(this.props,e.props)&&yt(this.token,e.token)&&yt(this.content,e.content)}walk(e){let t=this.token.walk(e),n=this.content.walk(e);return e(t==this.token&&n==this.content?this:new ot(this.start,this.type,this.props,t,n))}}class at extends st{constructor(e,t){super(e),this.rule=t}toString(){let e=this.rule;return`${e.id}${e.props.length?`[${e.props.join(",")}]`:""} { ${e.expr} }`}eq(e){let t=this.rule,n=e.rule;return yt(t.expr,n.expr)&&t.id.name==n.id.name&&xt.eqProps(t.props,n.props)}walk(e){let t=this.rule,n=t.expr.walk(e);return e(n==t.expr?this:new at(this.start,new qe(t.start,t.id,t.props,[],n)))}}class lt extends st{constructor(e,t){super(e),this.exprs=t}toString(){return this.exprs.map((e=>kt(e,this))).join(" | ")}eq(e){return vt(this.exprs,e.exprs)}walk(e){let t=mt(this.exprs,e);return e(t==this.exprs?this:new lt(this.start,t))}}lt.prototype.prec=1;class ht extends st{constructor(e,t,n,i=!1){super(e),this.exprs=t,this.markers=n,this.empty=i}toString(){return this.empty?"()":this.exprs.map((e=>kt(e,this))).join(" ")}eq(e){return vt(this.exprs,e.exprs)&&this.markers.every(((t,n)=>{let i=e.markers[n];return t.length==i.length&&t.every(((e,t)=>e.eq(i[t])))}))}walk(e){let t=mt(this.exprs,e);return e(t==this.exprs?this:new ht(this.start,t,this.markers,this.empty&&!t.length))}}ht.prototype.prec=2;class ct extends Ve{constructor(e,t,n){super(e),this.id=t,this.type=n}toString(){return("ambig"==this.type?"~":"!")+this.id.name}eq(e){return this.id.name==e.id.name&&this.type==e.type}}class ut extends st{constructor(e,t,n){super(e),this.expr=t,this.kind=n}toString(){return kt(this.expr,this)+this.kind}eq(e){return yt(this.expr,e.expr)&&this.kind==e.kind}walk(e){let t=this.expr.walk(e);return e(t==this.expr?this:new ut(this.start,t,this.kind))}}ut.prototype.prec=3;class ft extends st{constructor(e,t){super(e),this.value=t}toString(){return JSON.stringify(this.value)}eq(e){return this.value==e.value}}class dt extends st{constructor(e,t,n){super(e),this.ranges=t,this.inverted=n}toString(){return`[${this.inverted?"^":""}${this.ranges.map((([e,t])=>String.fromCodePoint(e)+(t==e+1?"":"-"+String.fromCodePoint(t))))}]`}eq(e){return this.inverted==e.inverted&&this.ranges.length==e.ranges.length&&this.ranges.every((([t,n],i)=>{let[s,r]=e.ranges[i];return t==s&&n==r}))}}class pt extends st{constructor(e){super(e)}toString(){return"_"}eq(){return!0}}function mt(e,t){let n=null;for(let i=0;iyt(e,t[n])))}class xt extends Ve{constructor(e,t,n,i){super(e),this.at=t,this.name=n,this.value=i}eq(e){return this.name==e.name&&this.value.length==e.value.length&&this.value.every(((t,n)=>t.value==e.value[n].value&&t.name==e.value[n].name))}toString(){let e=(this.at?"@":"")+this.name;if(this.value.length){e+="=";for(let{name:t,value:n}of this.value)e+=t?`{${t}}`:/[^\w-]/.test(n)?JSON.stringify(n):n}return e}static eqProps(e,t){return e.length==t.length&&e.every(((e,n)=>e.eq(t[n])))}}class wt extends Ve{constructor(e,t,n){super(e),this.value=t,this.name=n}}function kt(e,t){return e.prec0}get eof(){return(4&this.flags)>0}get error(){return"error"in this.props}get top(){return(2&this.flags)>0}get interesting(){return this.flags>0||null!=this.nodeName}get repeated(){return(16&this.flags)>0}set preserve(e){this.flags=e?8|this.flags:-9&this.flags}get preserve(){return(8&this.flags)>0}set inline(e){this.flags=e?32|this.flags:-33&this.flags}get inline(){return(32&this.flags)>0}cmp(e){return this.hash-e.hash}}class Mt{constructor(){this.terms=[],this.names=Object.create(null),this.tops=[],this.eof=this.term("␄",null,5),this.error=this.term("⚠","⚠",8)}term(e,t,n=0,i={}){let s=new Ot(e,n,t,i);return this.terms.push(s),this.names[e]=s,s}makeTop(e,t){const n=this.term("@top",e,2,t);return this.tops.push(n),n}makeTerminal(e,t,n={}){return this.term(e,t,1,n)}makeNonTerminal(e,t,n={}){return this.term(e,t,0,n)}makeRepeat(e){return this.term(e,null,16)}uniqueName(e){for(let t=0;;t++){let n=t?`${e}-${t}`:e;if(!this.names[n])return n}}finish(e){for(let t of e)t.name.rules.push(t);this.terms=this.terms.filter((t=>t.terminal||t.preserve||e.some((e=>e.name==t||e.parts.includes(t)))));let t={},n=[this.error];this.error.id=0;let i=1;for(let e of this.terms)e.id<0&&e.nodeType&&!e.repeated&&(e.id=i++,n.push(e));let s=i;for(let e of this.terms)e.repeated&&(e.id=i++,n.push(e));this.eof.id=i++;for(let e of this.terms)e.id<0&&(e.id=i++),e.name&&(t[e.id]=e.name);if(i>=65534)throw new St("Too many terms");return{nodeTypes:n,names:t,minRepeatTerm:s,maxTerm:i-1}}}function Tt(e,t,n){if(e.length!=t.length)return e.length-t.length;for(let i=0;iet?1:0))||this.cut-e.cut}}function Dt(e,t){if(0==e.length||e==t)return t;if(0==t.length)return e;let n=e.slice();for(let i of t)e.includes(i)||n.push(i);return n.sort()}Nt.none=new Nt(0);let Et=0;class jt{constructor(e,t,n,i){this.name=e,this.parts=t,this.conflicts=n,this.skip=i,this.id=Et++}cmp(e){return this.id-e.id}cmpNoName(e){return this.parts.length-e.parts.length||this.skip.hash-e.skip.hash||this.parts.reduce(((t,n,i)=>t||n.cmp(e.parts[i])),0)||Tt(this.conflicts,e.conflicts,((e,t)=>e.cmp(t)))}toString(){return this.name+" -> "+this.parts.join(" ")}get isRepeatWrap(){return this.name.repeated&&2==this.parts.length&&this.parts[0]==this.name}sameReduce(e){return this.name==e.name&&this.parts.length==e.parts.length&&this.isRepeatWrap==e.isRepeatWrap}}const Rt=65535;class Pt{constructor(e,t,n){this.from=e,this.to=t,this.target=n}toString(){return`-> ${this.target.id}[label=${JSON.stringify(this.from<0?"ε":It(this.from)+(this.to>this.from+1?"-"+It(this.to-1):""))}]`}}function It(e){return e>Rt?"∞":10==e?"\\n":13==e?"\\r":e<32||e>=55296&&e<57343?"\\u{"+e.toString(16)+"}":String.fromCharCode(e)}function Bt(e,t,n){if(e.edges.length!=t.edges.length)return!1;for(let i=0;iDt(e,t.accepting)),[]),n++),o=[];for(let e of s)for(let t of e.edges)t.from>=0&&o.push(t);let a=function(e){let t=[],n=[];for(let n of e)t.includes(n.from)||t.push(n.from),t.includes(n.to)||t.push(n.to);t.sort(((e,t)=>e-t));for(let i=1;is&&t.from65535==e.from&&65535==e.to));if(i.length){let e=[];for(let t of i)for(let n of t.target.closure())e.includes(n)||e.push(n);e.length&&n.push(new Wt(65535,65535,e))}return n}(o);for(let e of a){let n=e.targets.sort(((e,t)=>e.id-t.id));r.edge(e.from,e.to,t[Vt(n)]||i(n))}return r}(this.closure().sort(((e,t)=>e.id-t.id)));return function(e,t){let n=Object.create(null),i=Object.create(null);for(let t of e){let e=Vt(t.accepting),s=i[e]||(i[e]=[]);s.push(t),n[t.id]=s}for(;;){let i=!1,s=Object.create(null);for(let t of e){if(s[t.id])continue;let e=n[t.id];if(1==e.length){s[e[0].id]=e;continue}let r=[];e:for(let t of e){for(let e of r)if(Bt(t,e[0],n)){e.push(t);continue e}r.push([t])}r.length>1&&(i=!0);for(let e of r)for(let t of e)s[t.id]=e}if(!i)return Lt(e,t,n);n=s}}(Object.values(t),i)}closure(){let e=[],t=Object.create(null);return function n(i){if(!t[i.id]){t[i.id]=!0,(i.edges.some((e=>e.from>=0))||i.accepting.length>0&&!i.edges.some((e=>function(e,t){if(e.length!=t.length)return!1;for(let n=0;nt.a==e&&t.b==n));o?o.soft!=i&&(o.soft=0):t.push(new Ft(e,n,i,Ht(s),r&&Ht(r)))}return this.reachable(((t,s)=>{if(0!=t.accepting.length){for(let e=0;e{if(r!=t)for(let a of r.accepting){let r=n.includes(a);for(let l of t.accepting)a!=l&&i(a,l,r||n.includes(l)||!e(a,l)?0:1,s,s.concat(o))}}))}})),t}cycleTerms(){let e=[];this.reachable((t=>{for(let{target:n}of t.edges)e.push(t,n)}));let t=new Map,n=[];for(let i=0;i{t.accepting.length&&(e+=` ${t.id} [label=${JSON.stringify(t.accepting.join())}];\n`);for(let n of t.edges)e+=` ${t.id} ${n};\n`})),e+"}"}toArray(e,t){let n=[],i=[];this.reachable((s=>{let r=i.length,o=r+3+2*s.accepting.length;n[s.id]=r,i.push(s.stateMask(e),o,s.edges.length),s.accepting.sort(((e,n)=>t.indexOf(e.id)-t.indexOf(n.id)));for(let t of s.accepting)i.push(t.id,e[t.id]||65535);for(let e of s.edges)i.push(e.from,e.to,-e.target.id-1)}));for(let e=0;eMath.pow(2,16))throw new St("Tokenizer tables too big to represent with 16-bit offsets.");return Uint16Array.from(i)}stateMask(e){let t=0;return this.reachable((n=>{for(let i of n.accepting)t|=e[i.id]||65535})),t}},Ft=class{constructor(e,t,n,i,s){this.a=e,this.b=t,this.soft=n,this.exampleA=i,this.exampleB=s}};function Ht(e){let t="";for(let n=0;n-1&&i-1){let e=this.lineInfo(t);n+=(n?" ":"")+e.line+":"+e.ch}return n?e+` (${n})`:e}raise(e,t=-1){throw new St(this.message(e,t))}match(e,t){let n=t.exec(this.string.slice(e));return n?e+n[0].length:-1}next(){let e=this.match(this.end,/^(\s|\/\/.*|\/\*[^]*?\*\/)*/);if(e==this.string.length)return this.set("eof",null,e,e);let t=this.string[e];if('"'==t){let t=this.match(e+1,/^(\\.|[^"\\])*"/);return-1==t&&this.raise("Unterminated string literal",e),this.set("string",bn(this.string.slice(e+1,t-1)),e,t)}if("'"==t){let t=this.match(e+1,/^(\\.|[^'\\])*'/);return-1==t&&this.raise("Unterminated string literal",e),this.set("string",bn(this.string.slice(e+1,t-1)),e,t)}if("@"==t){qt.lastIndex=e+1;let t=qt.exec(this.string);return t?this.set("at",t[0],e,e+1+t[0].length):this.raise("@ without a name",e)}if("$"!=t&&"!"!=t||"["!=this.string[e+1]){if(/[\[\]()!~+*?{}<>\.,|:$=]/.test(t))return this.set(t,null,e,e+1);{qt.lastIndex=e;let n=qt.exec(this.string);return n?this.set("id",n[0],e,e+n[0].length):this.raise("Unexpected character "+JSON.stringify(t),e)}}{let t=this.match(e+2,/^(?:\\.|[^\]\\])*\]/);return-1==t&&this.raise("Unterminated character set",e),this.set("set",this.string.slice(e+2,t-1),e,t)}}set(e,t,n,i){this.type=e,this.value=t,this.start=n,this.end=i}eat(e,t=null){return this.type==e&&(null==t||this.value===t)&&(this.next(),!0)}unexpected(){return this.raise(`Unexpected token '${this.string.slice(this.start,this.end)}'`,this.start)}expect(e,t=null){let n=this.value;return(this.type!=e||null!=t&&n!==t)&&this.unexpected(),this.next(),n}parse(){return function(e){let t=e.start,n=[],i=null,s=null,r=[],o=null,a=[],l=[],h=null,c=[],u=[],f=[],d=[],p=[],m=!1,g=!1;for(;"eof"!=e.type;){let t=e.start;if(e.eat("at","top"))"id"!=e.type&&e.raise("Top rules must have a name",e.start),p.push(Gt(e,on(e))),m=!0;else if("at"==e.type&&"tokens"==e.value)s?e.raise("Multiple @tokens declaractions",e.start):s=ln(e);else if(e.eat("at","local"))e.expect("id","tokens"),r.push(hn(e,t));else if(e.eat("at","context")){h&&e.raise("Multiple @context declarations",t);let n=on(e);e.expect("id","from");let i=e.expect("string");h=new Qe(t,n,i)}else if(e.eat("at","external"))e.eat("id","tokens")?c.push(dn(e,t)):e.eat("id","prop")?f.push(gn(e,t)):e.eat("id","extend")?u.push(pn(e,"extend",t)):e.eat("id","specialize")?u.push(pn(e,"specialize",t)):e.eat("id","propSource")?d.push(mn(e,t)):e.unexpected();else if(e.eat("at","dialects")){e.expect("{");for(let t=!0;!e.eat("}");t=!1)t||e.eat(","),l.push(on(e))}else if("at"==e.type&&"precedence"==e.value)i&&e.raise("Multiple precedence declarations",e.start),i=an(e);else if(e.eat("at","detectDelim"))g=!0;else if(e.eat("at","skip")){let t=Xt(e);if("{"==e.type){e.next();let n=[],i=[];for(;!e.eat("}");)e.eat("at","top")?(i.push(Gt(e,on(e))),m=!0):n.push(Gt(e));a.push({expr:t,topRules:i,rules:n})}else o&&e.raise("Multiple top-level skip declarations",e.start),o=t}else n.push(Gt(e))}return m?new We(t,n,p,s,r,h,c,u,d,i,o,a,l,f,g):e.raise("Missing @top declaration")}(this)}}function Gt(e,t){let n=t?t.start:e.start,i=t||on(e),s=Kt(e),r=[];if(e.eat("<"))for(;!e.eat(">");)r.length&&e.expect(","),r.push(on(e));let o=Xt(e);return new qe(n,i,s,r,o)}function Kt(e){if("["!=e.type)return Jt;let t=[];for(e.expect("[");!e.eat("]");)t.length&&e.expect(","),t.push(Yt(e));return t}function Yt(e){let t=e.start,n=[],i=e.value,s="at"==e.type;if(e.eat("at")||e.eat("id")||e.unexpected(),e.eat("="))for(;;)if("string"==e.type||"id"==e.type)n.push(new wt(e.start,e.value,null)),e.next();else if(e.eat("."))n.push(new wt(e.start,".",null));else{if(!e.eat("{"))break;n.push(new wt(e.start,null,e.expect("id"))),e.expect("}")}return new xt(t,s,i,n)}function Xt(e){e.expect("{");let t=rn(e);return e.expect("}"),t}const Qt="﷚";function Zt(e){let t=e.start;if(e.eat("(")){if(e.eat(")"))return new ht(t,Jt,[Jt,Jt]);let n=rn(e);return e.expect(")"),n}if("string"==e.type){let n=e.value;return e.next(),0==n.length?new ht(t,Jt,[Jt,Jt]):new ft(t,n)}if(e.eat("id","_"))return new pt(t);if("set"==e.type){let n=e.value,i="!"==e.string[e.start],s=bn(n.replace(/\\.|-|"/g,(e=>"-"==e?Qt:'"'==e?'\\"':e))),r=[];for(let t=0;t65535?2:1,t65535?3:2,ie[0]-t[0])),i)}if("at"!=e.type||"specialize"!=e.value&&"extend"!=e.value){if("at"==e.type&>.hasOwnProperty(e.value)){let t=new bt(e.start,e.value);return e.next(),t}if("["==e.type){let n=Gt(e,new it(t,"_anon"));return n.params.length&&e.raise("Inline rules can't have parameters",n.start),new at(t,n)}{let n=on(e);if("["==e.type||"{"==e.type){let i=Gt(e,n);return i.params.length&&e.raise("Inline rules can't have parameters",i.start),new at(t,i)}if(e.eat(".")&&"std"==n.name&>.hasOwnProperty(e.value)){let n=new bt(t,e.value);return e.next(),n}return new rt(t,n,function(e){let t=[];if(e.eat("<"))for(;!e.eat(">");)t.length&&e.expect(","),t.push(rn(e));return t}(e))}}{let{start:t,value:n}=e;e.next();let i=Kt(e);e.expect("<");let s,r=rn(e);return e.eat(",")?s=rn(e):r instanceof ft?s=r:e.raise(`@${n} requires two arguments when its first argument isn't a literal string`),e.expect(">"),new ot(t,n,i,r,s)}}function en(e,t,n,i){t.every((([e,t])=>t<=n||e>=i))||e.raise("Overlapping character range",e.start),t.push([n,i])}function tn(e){let t=e.start,n=Zt(e);for(;;){let i=e.type;if(!(e.eat("*")||e.eat("?")||e.eat("+")))return n;n=new ut(t,n,i)}}function nn(e){return"}"==e.type||")"==e.type||"|"==e.type||"/"==e.type||"/\\"==e.type||"{"==e.type||","==e.type||">"==e.type}function sn(e){let t=e.start,n=[],i=[Jt];do{for(;;){let t,n=e.start;if(e.eat("~"))t="ambig";else{if(!e.eat("!"))break;t="prec"}i[i.length-1]=i[i.length-1].concat(new ct(n,on(e),t))}if(nn(e))break;n.push(tn(e)),i.push(Jt)}while(!nn(e));return 1==n.length&&i.every((e=>0==e.length))?n[0]:new ht(t,n,i,!n.length)}function rn(e){let t=e.start,n=sn(e);if(!e.eat("|"))return n;let i=[n];do{i.push(sn(e))}while(e.eat("|"));let s=i.find((e=>e instanceof ht&&e.empty));return s&&e.raise("Empty expression in choice operator. If this is intentional, use () to make it explicit.",s.start),new lt(t,i)}function on(e){"id"!=e.type&&e.unexpected();let t=e.start,n=e.value;return e.next(),new it(t,n)}function an(e){let t=e.start;e.next(),e.expect("{");let n=[];for(;!e.eat("}");)n.length&&e.eat(","),n.push({id:on(e),type:e.eat("at","left")?"left":e.eat("at","right")?"right":e.eat("at","cut")?"cut":null});return new Je(t,n)}function ln(e){let t=e.start;e.next(),e.expect("{");let n=[],i=[],s=[],r=[];for(;!e.eat("}");)"at"==e.type&&"precedence"==e.value?s.push(cn(e)):"at"==e.type&&"conflict"==e.value?r.push(un(e)):"string"==e.type?i.push(new Xe(e.start,e.expect("string"),Kt(e))):n.push(Gt(e));return new Ke(t,s,r,n,i)}function hn(e,t){e.expect("{");let n=[],i=[],s=null;for(;!e.eat("}");)"at"==e.type&&"precedence"==e.value?i.push(cn(e)):e.eat("at","else")&&!s?s={id:on(e),props:Kt(e)}:n.push(Gt(e));return new Ye(t,i,n,s)}function cn(e){let t=e.start;e.next(),e.expect("{");let n=[];for(;!e.eat("}");){n.length&&e.eat(",");let t=Zt(e);t instanceof ft||t instanceof rt?n.push(t):e.raise("Invalid expression in token precedences",t.start)}return new Ue(t,n)}function un(e){let t=e.start;e.next(),e.expect("{");let n=Zt(e);n instanceof ft||n instanceof rt||e.raise("Invalid expression in token conflict",n.start),e.eat(",");let i=Zt(e);return i instanceof ft||i instanceof rt||e.raise("Invalid expression in token conflict",i.start),e.expect("}"),new Ge(t,n,i)}function fn(e){let t=[];for(e.expect("{");!e.eat("}");){t.length&&e.eat(",");let n=on(e),i=Kt(e);t.push({id:n,props:i})}return t}function dn(e,t){let n=on(e);e.expect("id","from");let i=e.expect("string");return new Ze(t,n,i,fn(e))}function pn(e,t,n){let i=Xt(e),s=on(e);e.expect("id","from");let r=e.expect("string");return new et(n,t,i,s,r,fn(e))}function mn(e,t){let n=on(e);return e.expect("id","from"),new tt(t,n,e.expect("string"))}function gn(e,t){let n=on(e),i=e.eat("id","as")?on(e):n;e.expect("id","from");let s=e.expect("string");return new nt(t,i,n,s)}function bn(e){let t,n=/\\(?:u\{([\da-f]+)\}|u([\da-f]{4})|x([\da-f]{2})|([ntbrf0])|(.))|[^]/giy,i="";for(;t=n.exec(e);){let[e,n,s,r,o,a]=t;i+=n||s||r?String.fromCodePoint(parseInt(n||s||r,16)):o?"n"==o?"\n":"t"==o?"\t":"0"==o?"\0":"r"==o?"\r":"f"==o?"\f":"\b":a||e}return i}function yn(e,t){return(e<<5)+e+t}function vn(e,t){for(let n=0;n{let n=Date.now(),i=t();return console.log(`${e} (${((Date.now()-n)/1e3).toFixed(2)}s)`),i}:(e,t)=>t();class Sn{constructor(e,t,n,i,s,r){this.rule=e,this.pos=t,this.ahead=n,this.ambigAhead=i,this.skipAhead=s,this.via=r,this.hash=0}finish(){let e=yn(yn(this.rule.id,this.pos),this.skipAhead.hash);for(let t of this.ahead)e=yn(e,t.hash);for(let t of this.ambigAhead)e=vn(e,t);return this.hash=e,this}get next(){return this.pose.cmp(t)))||Tt(this.ambigAhead,e.ambigAhead,On)}eqSimple(e){return e.rule==this.rule&&e.pos==this.pos}toString(){let e=this.rule.parts.map((e=>e.name));return e.splice(this.pos,0,"·"),`${this.rule.name} -> ${e.join(" ")}`}eq(e){return this==e||this.hash==e.hash&&this.rule==e.rule&&this.pos==e.pos&&this.skipAhead==e.skipAhead&&_n(this.ahead,e.ahead)&&_n(this.ambigAhead,e.ambigAhead)}trail(e=60){let t=[];for(let e=this;e;e=e.via)for(let n=e.pos-1;n>=0;n--)t.push(e.rule.parts[n]);let n=t.reverse().join(" ");return n.length>e&&(n=n.slice(n.length-e).replace(/.*? /,"… ")),n}conflicts(e=this.pos){let t=this.rule.conflicts[e];return e==this.rule.parts.length&&this.ambigAhead.length&&(t=t.join(new Nt(0,this.ambigAhead))),t}static addOrigins(e,t){let n=e.slice();for(let e=0;et?1:0}function Mn(e,t,n,i){let s=[];for(let n=t+1;ne.term+"="+e)).join(",")+(this.goto.length?" | "+this.goto.map((e=>e.term+"="+e)).join(","):"");return this.id+": "+this.set.filter((e=>e.pos>0)).join()+(this.defaultReduce?`\n always ${this.defaultReduce.name}(${this.defaultReduce.parts.length})`:e.length?"\n "+e:"")}addActionInner(e,t){e:for(let n=0;n0){this.actions.splice(n,1),this.actionPositions.splice(n,1),n--;continue e}if(l<0)return null;if(o.ambigGroups.some((e=>a.ambigGroups.includes(e))))continue e;return i}}return this.actions.push(e),this.actionPositions.push(t),null}addAction(e,t,n){let i=this.addActionInner(e,t);if(i){let s,r=this.actionPositions[this.actions.indexOf(i)][0],o=[t[0].rule.name,r.rule.name];if(n.some((e=>e.rules.some((e=>o.includes(e))))))return;s=i instanceof Nn?`shift/reduce conflict between\n ${r}\nand\n ${t[0].rule}`:`reduce/reduce conflict between\n ${r.rule}\nand\n ${t[0].rule}`,s+=`\nWith input:\n ${t[0].trail(70)} · ${e.term} …`,s+=function(e,t){if(e.eqSimple(t))return"";function n(e,t){let n=[];for(let i=t.via;!i.eqSimple(e);i=i.via)n.push(i);return n.length?(n.unshift(t),n.reverse().map(((e,n)=>"\n"+" ".repeat(n+1)+(e==t?"":"via ")+e)).join("")):""}for(let i=e;i;i=i.via)for(let s=t;s;s=s.via)if(i.eqSimple(s))return"\nShared origin: "+i+n(i,e)+n(i,t);return""}(r,t[0]),n.push(new In(s,o))}}getGoto(e){return this.goto.find((t=>t.term==e))}hasSet(e){return Tn(this.set,e)}actionsByTerm(){let e=this._actionsByTerm;if(!e){this._actionsByTerm=e=Object.create(null);for(let t of this.actions)(e[t.term.id]||(e[t.term.id]=[])).push(t)}return e}finish(){if(this.actions.length){let e=this.actions[0];if(e instanceof Dn){let{rule:t}=e;this.actions.every((e=>e instanceof Dn&&e.rule.sameReduce(t)))&&(this.defaultReduce=t)}}this.actions.sort(((e,t)=>e.cmp(t))),this.goto.sort(((e,t)=>e.cmp(t)))}eq(e){let t=this.defaultReduce,n=e.defaultReduce;return t||n?!(!t||!n)&&t.sameReduce(n):this.skip==e.skip&&this.tokenGroup==e.tokenGroup&&Tn(this.actions,e.actions)&&Tn(this.goto,e.goto)}}function Rn(e,t){t.includes(e)||t.push(e)}class Pn{constructor(e,t){this.set=e,this.state=t}}class In{constructor(e,t){this.error=e,this.rules=t}}function Bn(e){let t=null,n=1;for(let i of e){let e=i.rule.conflicts[i.pos-1].cut;en)&&(n=e,t=[]),t.push(i))}return t||e}function Ln(e,t,n){for(let i of e.goto)for(let e of t.goto)if(i.term==e.term&&n[i.target.id]!=n[e.target.id])return!1;let i=t.actionsByTerm();for(let t of e.actions){let s=i[t.term.id];if(s&&s.some((e=>!e.matches(t,n)))){if(1==s.length)return!1;let i=e.actionsByTerm()[t.term.id];if(i.length!=s.length||i.some((e=>!s.some((t=>e.matches(t,n))))))return!1}}return!0}function $n(e,t){let n=[];for(let i of e){let e=t[i.id];n[e]||(n[e]=new jn(e,i.set,0,i.skip,i.hash,i.startRule),n[e].tokenGroup=i.tokenGroup,n[e].defaultReduce=i.defaultReduce)}for(let i of e){let e=n[t[i.id]];e.flags|=i.flags;for(let s=0;se.eq(r)))||(e.actions.push(r),e.actionPositions.push(i.actionPositions[s]))}for(let s of i.goto){let i=s.map(t,n);e.goto.some((e=>e.eq(i)))||e.goto.push(i)}}return n}class zn{constructor(e,t){this.origin=e,this.members=[t]}}function Fn(e,t){if(e.length!=t.length)return!1;for(let n=0;n=34&&t++,t>=92&&t++,String.fromCharCode(t)}function Wn(e,t=65535){if(e>t)throw new Error("Trying to encode a number that's too big: "+e);if(65535==e)return String.fromCharCode(126);let n="";for(let t=46;;t=0){let i=e%46,s=e-i;if(n=Vn(i+t)+n,0==s)break;e=s/46}return n}function qn(e,t=65535){let n='"'+Wn(e.length,4294967295);for(let i=0;i{this.input=new Ut(e,t.fileName),this.ast=this.input.parse()}));let n=o.md;for(let e in n)n[e]instanceof o.md&&!n[e].perNode&&(this.knownProps[e]={prop:n[e],source:{name:e,from:null}});for(let e of this.ast.externalProps)this.knownProps[e.id.name]={prop:this.options.externalProp?this.options.externalProp(e.id.name):new o.md,source:{name:e.externalID.name,from:e.source}};this.dialects=this.ast.dialects.map((e=>e.name)),this.tokens=new hi(this,this.ast.tokens),this.localTokens=this.ast.localTokens.map((e=>new ci(this,e))),this.externalTokens=this.ast.externalTokens.map((e=>new ki(this,e))),this.externalSpecializers=this.ast.externalSpecializers.map((e=>new Si(this,e))),kn("Build rules",(()=>{let e=this.newName("%noskip",!0);this.defineRule(e,[]);let t=this.ast.mainSkip?this.newName("%mainskip",!0):e,n=[],i=[];for(let e of this.ast.rules)this.astRules.push({skip:t,rule:e});for(let e of this.ast.topRules)i.push({skip:t,rule:e});for(let s of this.ast.scopedSkip){let r=e,o=this.ast.scopedSkip.findIndex(((e,t)=>t-1?r=n[o]:this.ast.mainSkip&&yt(s.expr,this.ast.mainSkip)?r=t:yi(s.expr)||(r=this.newName("%skip",!0)),n.push(r);for(let e of s.rules)this.astRules.push({skip:r,rule:e});for(let e of s.topRules)i.push({skip:r,rule:e})}for(let{rule:e}of this.astRules)this.unique(e.id);this.currentSkip.push(e),this.skipRules=t==e?[t]:[e,t],t!=e&&this.defineRule(t,this.normalizeExpr(this.ast.mainSkip));for(let t=0;te.rule.start-t.rule.start))){this.unique(e.id),this.used(e.id.name),this.currentSkip.push(t);let{name:n,props:i}=this.nodeInfo(e.props,"a",e.id.name,Jn,Jn,e.expr),s=this.terms.makeTop(n,i);this.namedTerms[n]=s,this.defineRule(s,this.normalizeExpr(e.expr)),this.currentSkip.pop()}for(let e of this.externalSpecializers)e.finish();for(let{skip:e,rule:t}of this.astRules)this.ruleNames[t.id.name]&&Oi(t)&&!t.params.length&&(this.buildRule(t,[],e,!1),t.expr instanceof ht&&0==t.expr.exprs.length&&this.used(t.id.name))}));for(let e in this.ruleNames){let t=this.ruleNames[e];t&&this.warn(`Unused rule '${t.name}'`,t.start)}this.tokens.takePrecedences(),this.tokens.takeConflicts();for(let e of this.localTokens)e.takePrecedences();for(let{name:e,group:t,rule:n}of this.definedGroups)this.defineGroup(e,t,n);this.checkGroups()}unique(e){e.name in this.ruleNames&&this.raise(`Duplicate definition of rule '${e.name}'`,e.start),this.ruleNames[e.name]=e}used(e){this.ruleNames[e]=null}newName(e,t=null,n={}){for(let i=t?0:1;;i++){let s=i?`${e}-${i}`:e;if(!this.terms.names[s])return this.terms.makeNonTerminal(s,!0===t?null:t,n)}}prepareParser(){let e=kn("Simplify rules",(()=>function(e,t){return function(e){let t,n=Object.create(null);for(let i=0;i!n[e.name]))?t:new jt(t.name,t.parts.map((e=>n[e.name]||e)),t.conflicts,t.skip));return i}(function(e,t){for(let n=0;;n++){let i,s=Object.create(null);if(0==n)for(let o of e)if(o.name.inline&&!s[o.name.name]){let a=e.filter((e=>e.name==o.name));if(a.some((e=>e.parts.includes(o.name))))continue;i=s[o.name.name]=a}for(let l=0;le.skip==h.skip||!e.parts.includes(h.name)))||h.parts.some((e=>!!s[e.name]))||e.some(((e,t)=>t!=l&&e.name==h.name))||(i=s[h.name.name]=[h])}if(!i)return e;let r=[];for(let c of e){function u(e,t,n){if(e==c.parts.length)return void r.push(new jt(c.name,n,t,c.skip));let i=c.parts[e],o=s[i.name];if(o)for(let i of o)u(e+1,t.slice(0,t.length-1).concat(t[e].join(i.conflicts[0])).concat(i.conflicts.slice(1,i.conflicts.length-1)).concat(c.conflicts[e+1].join(i.conflicts[i.conflicts.length-1])),n.concat(i.parts));else u(e+1,t.concat(c.conflicts[e+1]),n.concat(i))}s[c.name.name]||(c.parts.some((e=>!!s[e.name]))?u(0,[c.conflicts[0]],[]):r.push(c))}e=r}}(e,t))}(this.rules,[...this.skipRules,...this.terms.tops]))),{nodeTypes:t,names:n,minRepeatTerm:i,maxTerm:s}=this.terms.finish(e);for(let e in this.namedTerms)this.termTable[e]=this.namedTerms[e].id;/\bgrammar\b/.test(xn)&&console.log(e.join("\n"));let r=this.terms.tops.slice(),o=function(e){let t=Object.create(null);for(let n of e.terms)n.terminal||(t[n.name]=[]);for(;;){let n=!1;for(let i of e.terms)if(!i.terminal)for(let e of i.rules){let s=t[i.name],r=!1,o=s.length;for(let n of e.parts){if(r=!0,n.terminal)Rn(n,s);else for(let e of t[n.name])null==e?r=!1:Rn(e,s);if(r)break}r||Rn(null,s),s.length>o&&(n=!0)}if(!n)return t}}(this.terms),a=this.skipRules.map(((e,t)=>{let n=[],i=[],s=[];for(let t of e.rules){if(!t.parts.length)continue;let e=t.parts[0];for(let t of e.terminal?[e]:o[e.name]||[])i.includes(t)||i.push(t);e.terminal&&1==t.parts.length&&!s.some((n=>n!=t&&n.parts[0]==e))?n.push(e):s.push(t)}return e.rules=s,s.length&&r.push(e),{skip:n,rule:s.length?e:null,startTokens:i,id:t}})),l=kn("Build full automaton",(()=>function(e,t,n){let i=[],s={},r={},o=Date.now();function a(e,t){if(0==e.length)return null;let a,l=En(e),h=r[l];for(let t of e)if(a){if(a!=t.skip)throw new St("Inconsistent skip sets after "+t.trail())}else a=t.skip;if(h)for(let t of h)if(Tn(e,t.set)){if(t.state.skip!=a)throw new St("Inconsistent skip sets after "+t.set[0].trail());return t.state}let c,u=function(e,t){let n=[],i=[];function s(t,s,r,o,a){for(let l of t.rules){let t=n.find((e=>e.rule==l));if(!t){let i=e.find((e=>0==e.pos&&e.rule==l));t=i?new Sn(l,0,i.ahead.slice(),i.ambigAhead,i.skipAhead,i.via):new Sn(l,0,[],Hn,o,a),n.push(t)}if(t.skipAhead!=o)throw new St("Inconsistent skip sets after "+a.trail());t.ambigAhead=Dt(t.ambigAhead,r);for(let e of s)t.ahead.includes(e)||(t.ahead.push(e),t.rule.parts.length&&!t.rule.parts[0].terminal&&Rn(t,i))}}for(let n of e){let e=n.next;e&&!e.terminal&&s(e,Mn(n.rule,n.pos,n.ahead,t),n.conflicts(n.pos+1).ambigGroups,n.pos==n.rule.parts.length-1?n.skipAhead:n.rule.skip,n)}for(;i.length;){let e=i.pop();s(e.rule.parts[0],Mn(e.rule,0,e.ahead,t),Dt(e.rule.conflicts[1].ambigGroups,1==e.rule.parts.length?e.ambigAhead:Hn),1==e.rule.parts.length?e.skipAhead:e.rule.skip,e)}let r=e.slice();for(let t of n){t.ahead.sort(((e,t)=>e.hash-t.hash)),t.finish();let n=e.findIndex((e=>0==e.pos&&e.rule==t.rule));n>-1?r[n]=t:r.push(t)}return r.sort(((e,t)=>e.cmp(t)))}(e,n),f=En(u),d=s[f]||(s[f]=[]);if(!t)for(let e of d)e.hasSet(u)&&(c=e);return c||(c=new jn(i.length,u,0,a,f,t),d.push(c),i.push(c),wn&&i.length%500==0&&console.log(`${i.length} states after ${((Date.now()-o)/1e3).toFixed(2)}s`)),(r[l]||(r[l]=[])).push(new Pn(e,c)),c}for(const n of t){const t=n.rules.length?n.rules[0].skip:e.names["%noskip"];a(n.rules.map((n=>new Sn(n,0,[e.eof],Hn,t,null).finish())),n)}let l=[];for(let e=0;ee.advance()));if(n.terminal){let s=a(Bn(i));s&&t.addAction(new Nn(n,s),r[e],l)}else{let e=a(i);e&&t.goto.push(new Nn(n,e))}}let h=!1;for(let e of o)for(let n of e.ahead){let i=t.actions.length;t.addAction(new Dn(n,e.rule),[e],l),t.actions.length==i&&(h=!0)}if(h)for(let e=0;et.actions.some((t=>t.term==e&&t instanceof Nn))))||t.goto.splice(e--,1)}if(l.length)throw new St(l.map((e=>e.error)).join("\n\n"));for(let e of i)e.finish();return wn&&console.log(`${i.length} states total.`),i}(this.terms,r,o))),h=this.localTokens.map(((e,t)=>e.buildLocalGroup(l,a,t))),{tokenGroups:c,tokenPrec:u,tokenData:f}=kn("Build token groups",(()=>this.tokens.buildTokenGroups(l,a,h.length))),d=kn("Finish automaton",(()=>function(e){for(let t=1;;t++){let n=[],i=!1,s=Date.now(),r=[];for(let t=0;ts.eq(e)));if(o<0)n[t]=r.length,r.push(s);else{n[t]=o,i=!0;let e=r[o],a=null;for(let t of s.set)e.set.some((e=>e.eqSimple(t)))||(a||(a=[])).push(t);a&&(e.set=a.concat(e.set).sort(((e,t)=>e.cmp(t))))}}if(wn&&console.log(`Merge identical pass ${t}${i?"":", done"} (${((Date.now()-s)/1e3).toFixed(2)}s)`),!i)return e;for(let e of r)e.defaultReduce||(e.actions=e.actions.map((e=>e.map(n,r))),e.goto=e.goto.map((e=>e.map(n,r))));for(let e=0;eLn(o,e[n],t))))return void n[s].members.push(o.id);t[o.id]=n.length,n.push(new zn(r.origin,o.id))}for(let s=1;;s++){let r=!1,o=Date.now();for(let s=0,o=n.length;s{n[e.id]||(n[e.id]=!0,i.push(e))};for(let n of e)n.startRule&&t.includes(n.startRule)&&s(n);for(let e=0;e!n[e]}(d,this.terms.tops);/\blr\b/.test(xn)&&console.log(d.join("\n"));let m=[];for(let e of this.externalSpecializers)m.push(e);for(let e in this.specialized)m.push({token:this.terms.names[e],table:Zn(this.specialized[e])});let g=e=>e instanceof ki?e.ast.start:this.tokens.ast?this.tokens.ast.start:-1,b=c.concat(this.externalTokens).sort(((e,t)=>g(e)-g(t))).concat(h),y=new ti,v=a.map((e=>{let t=[];for(let n of e.skip)t.push(n.id,0,4);if(e.rule){let n=d.find((t=>t.startRule==e.rule));for(let e of n.actions)t.push(e.term.id,n.id,2)}return t.push(65535,0),y.storeArray(t)})),x=kn("Finish states",(()=>{let e=new Uint32Array(6*d.length),t=this.computeForceReductions(d,a),n=new Xn(b,y,e,v,a,d,this);for(let e of d)n.finish(e,p(e.id),t[e.id]);return e})),w=Object.create(null);for(let e=0;ee.id)).concat(65535));let k=null;if(this.dynamicRulePrecedences.length){k=Object.create(null);for(let{rule:e,prec:t}of this.dynamicRulePrecedences)k[e.id]=t}let S=Object.create(null);for(let e of this.terms.tops)S[e.nodeName]=[d.find((t=>t.startRule==e)).id,e.id];let A=y.storeArray(u.concat(65535)),{nodeProps:C,skippedTypes:O}=this.gatherNodeProps(t);return{states:x,stateData:y.finish(),goto:ni(d),nodeNames:t.filter((e=>e.ide.nodeName)).join(" "),nodeProps:C,skippedTypes:O,maxTerm:s,repeatNodeCount:t.length-i,tokenizers:b,tokenData:f,topRules:S,dialects:w,dynamicPrecedences:k,specialized:m,tokenPrec:A,termNames:n}}getParser(){let{states:e,stateData:t,goto:n,nodeNames:i,nodeProps:s,skippedTypes:r,maxTerm:o,repeatNodeCount:a,tokenizers:l,tokenData:h,topRules:c,dialects:u,dynamicPrecedences:f,specialized:d,tokenPrec:p,termNames:m}=this.prepareParser(),g=d.map((e=>{if(e instanceof Si){let t=this.options.externalSpecializer(e.ast.id.name,this.termTable);return{term:e.term.id,get:(n,i)=>t(n,i)<<1|("extend"==e.ast.type?1:0),external:t,extend:"extend"==e.ast.type}}return{term:e.token.id,get:t=>e.table[t]||-1}}));return He.WQ.deserialize({version:14,states:e,stateData:t,goto:n,nodeNames:i,maxTerm:o,repeatNodeCount:a,nodeProps:s.map((({prop:e,terms:t})=>[this.knownProps[e].prop,...t])),propSources:this.options.externalPropSource?this.ast.externalPropSources.map((e=>this.options.externalPropSource(e.id.name))):void 0,skippedNodes:r,tokenData:h,tokenizers:l.map((e=>e.create())),context:this.ast.context?"function"==typeof this.options.contextTracker?this.options.contextTracker(this.termTable):this.options.contextTracker:void 0,topRules:c,dialects:u,dynamicPrecedences:f,specialized:g,tokenPrec:p,termNames:m})}getParserFile(){let{states:e,stateData:t,goto:n,nodeNames:i,nodeProps:s,skippedTypes:r,maxTerm:o,repeatNodeCount:a,tokenizers:l,tokenData:h,topRules:c,dialects:u,dynamicPrecedences:f,specialized:d,tokenPrec:p,termNames:m}=this.prepareParser(),g=this.options.moduleStyle||"es",b=this.options.typeScript?": any":"",y="// This file was generated by lezer-generator. You probably shouldn't edit it.\n",v=y,x={},w=Object.create(null),k=Object.create(null);for(let e of Ci)k[e]=!0;let S=this.options.exportName||"parser";k[S]=!0;let A=e=>{for(let t=0;;t++){let n=e+(t?"_"+t:"");if(!k[n])return n}},C=(e,t,n=e)=>{let i=e+" from "+t;if(w[i])return w[i];let s=JSON.stringify(t),r=e;return e in k&&(r=A(n),e+=`${"cjs"==g?":":" as"} ${r}`),k[r]=!0,(x[s]||(x[s]=[])).push(e),w[i]=r},O=C("LRParser","@lezer/lr"),M=l.map((e=>e.createSource(C))),T=this.ast.context?C(this.ast.context.id.name,this.ast.context.source):null,_=s.map((({prop:e,terms:t})=>{let{source:n}=this.knownProps[e];return`[${n.from?C(n.name,n.from):JSON.stringify(n.name)}, ${t.map(j).join(",")}]`})),N="",D=d.map((e=>{if(e instanceof Si){let t=C(e.ast.id.name,e.ast.source);return`{term: ${e.term.id}, get: (value${b}, stack${b}) => (${t}(value, stack) << 1)${"extend"==e.ast.type?" | 1":""}, external: ${t}${"extend"==e.ast.type?", extend: true":""}}`}{let n=A("spec_"+e.token.name.replace(/\W/g,""));return k[n]=!0,N+=`const ${n} = ${t=e.table,"{__proto__:null,"+Object.keys(t).map((e=>`${/\W/.test(e)?JSON.stringify(e):e}:${t[e]}`)).join(", ")+"}"}\n`,`{term: ${e.token.id}, get: (value${b}) => ${n}[value] || -1}`}var t})),E=this.ast.externalPropSources.map((e=>C(e.id.name,e.source)));for(let e in x)v+="cjs"==g?`const {${x[e].join(", ")}} = require(${e})\n`:`import {${x[e].join(", ")}} from ${e}\n`;function j(e){return"string"!=typeof e||/^(true|false|\d+(\.\d+)?|\.\d+)$/.test(e)?e:JSON.stringify(e)}v+=N;let R=Object.keys(u).map((e=>`${e}: ${u[e]}`)),P=`${O}.deserialize({\n version: 14,\n states: ${qn(e,4294967295)},\n stateData: ${qn(t)},\n goto: ${qn(n)},\n nodeNames: ${JSON.stringify(i)},\n maxTerm: ${o}${T?`,\n context: ${T}`:""}${_.length?`,\n nodeProps: [\n ${_.join(",\n ")}\n ]`:""}${E.length?`,\n propSources: [${E.join()}]`:""}${r.length?`,\n skippedNodes: ${JSON.stringify(r)}`:""},\n repeatNodeCount: ${a},\n tokenData: ${qn(h)},\n tokenizers: [${M.join(", ")}],\n topRules: ${JSON.stringify(c)}${R.length?`,\n dialects: {${R.join(", ")}}`:""}${f?`,\n dynamicPrecedences: ${JSON.stringify(f)}`:""}${D.length?`,\n specialized: [${D.join(",")}]`:""},\n tokenPrec: ${p}${this.options.includeNames?`,\n termNames: ${JSON.stringify(m)}`:""}\n})`,I=[];for(let e in this.termTable){let t=e;if(Ci.includes(t))for(let n=1;t="_".repeat(n)+e,t in this.termTable;n++);I.push(`${t}${"cjs"==g?":":" ="} ${this.termTable[e]}`)}for(let e=0;e{e[n.id]||(e[n.id]=!0,t.push(n))};this.terms.tops.forEach(n);for(let e=0;et.prop==e));n||i.push(n={prop:e,values:{}}),(n.values[s.props[e]]||(n.values[s.props[e]]=[])).push(s.id)}}return{nodeProps:i.map((({prop:e,values:t})=>{let n=[];for(let e in t){let i=t[e];if(1==i.length)n.push(i[0],e);else{n.push(-i.length);for(let e of i)n.push(e);n.push(e)}}return{prop:e,terms:n}})),skippedTypes:n}}makeTerminal(e,t,n){return this.terms.makeTerminal(this.terms.uniqueName(e),t,n)}computeForceReductions(e,t){let n=[],i=[],s=Object.create(null);for(let t of e){n.push(0);for(let e of t.goto){let n=s[e.term.id]||(s[e.term.id]=[]),i=n.find((t=>t.target==e.target.id));i?i.parents.push(t.id):n.push({parents:[t.id],target:e.target.id})}i[t.id]=t.set.filter((e=>e.pos>0&&!e.rule.name.top)).sort(((e,t)=>t.pos-e.pos||e.rule.parts.length-t.rule.parts.length))}let r=Object.create(null);function o(e,t,n=null){let i=s[e];return!!i&&i.some((e=>{let i=n?n.filter((t=>e.parents.includes(t))):e.parents;if(0==i.length)return!1;if(e.target==t)return!0;let s=r[e.target];return null!=s&&o(s,t,i)}))}for(let i of e)i.defaultReduce&&i.defaultReduce.parts.length>0&&(n[i.id]=ei(i.defaultReduce,t),1==i.defaultReduce.parts.length&&(r[i.id]=i.defaultReduce.name.id));for(let s=1;;s++){let a=!0;for(let l of e){if(l.defaultReduce)continue;let e=i[l.id];if(e.length==s){for(let i of e)if(1!=i.pos||!o(i.rule.name.id,l.id)){n[l.id]=ei(i.rule,t,i.pos),1==i.pos&&(r[l.id]=i.rule.name.id);break}}else e.length>s&&(a=!1)}if(a)break}return n}substituteArgs(e,t,n){return 0==t.length?e:e.walk((e=>{let i;if(e instanceof rt&&(i=n.findIndex((t=>t.name==e.id.name)))>-1){let n=t[i];if(e.args.length){if(n instanceof rt&&!n.args.length)return new rt(e.start,n.id,e.args);this.raise("Passing arguments to a parameter that already has arguments",e.start)}return n}if(e instanceof at){let i=e.rule,s=this.substituteArgsInProps(i.props,t,n);return s==i.props?e:new at(e.start,new qe(i.start,i.id,s,i.params,i.expr))}if(e instanceof ot){let i=this.substituteArgsInProps(e.props,t,n);return i==e.props?e:new ot(e.start,e.type,i,e.token,e.content)}return e}))}substituteArgsInProps(e,t,n){let i=e=>{let i=e;for(let s=0;se.name==r.name));if(o<0)continue;i==e&&(i=e.slice());let a=t[o];a instanceof rt&&!a.args.length?i[s]=new wt(r.start,a.id.name,null):a instanceof ft?i[s]=new wt(r.start,a.value,null):this.raise(`Trying to interpolate expression '${a}' into a prop`,r.start)}return i},s=e;for(let t=0;te.id.name==i.id.name)):-1;s<0&&this.raise(`Reference to unknown precedence: '${i.id.name}'`,i.id.start);let r=e.items[s],o=e.items.length-s;"cut"==r.type?t=t.join(new Nt(0,Jn,o)):(t=t.join(new Nt(o<<2)),n=n.join(new Nt((o<<2)+("left"==r.type?1:"right"==r.type?-1:0))))}return{here:t,atEnd:n}}raise(e,t=1){return this.input.raise(e,t)}warn(e,t=-1){let n=this.input.message(e,t);this.options.warn?this.options.warn(n):console.warn(n)}defineRule(e,t){let n=this.currentSkip[this.currentSkip.length-1];for(let i of t)this.rules.push(new jt(e,i.terms,i.ensureConflicts(),n))}resolve(e){for(let t of this.built)if(t.matches(e))return[Gn(t.term)];let t=this.tokens.getToken(e);if(t)return[Gn(t)];for(let t of this.localTokens){let n=t.getToken(e);if(n)return[Gn(n)]}for(let t of this.externalTokens){let n=t.getToken(e);if(n)return[Gn(n)]}for(let t of this.externalSpecializers){let n=t.getToken(e);if(n)return[Gn(n)]}let n=this.astRules.find((t=>t.rule.id.name==e.id.name));return n?(n.rule.params.length!=e.args.length&&this.raise(`Wrong number or arguments for '${e.id.name}'`,e.start),this.used(n.rule.id.name),[Gn(this.buildRule(n.rule,e.args,n.skip))]):this.raise(`Reference to undefined rule '${e.id.name}'`,e.start)}normalizeRepeat(e){let t=this.built.find((t=>t.matchesRepeat(e)));if(t)return Gn(t.term);let n=e.expr.precthis.normalizeExpr(e))),n=this;return function i(s,r,o){let{here:a,atEnd:l}=n.conflictsFor(e.markers[r]);if(r==t.length)return[s.withConflicts(s.terms.length,a.join(o))];let h=[];for(let e of t[r])for(let t of i(s.concat(e).withConflicts(s.terms.length,a),r+1,o.join(l)))h.push(t);return h}(Un.none,0,Nt.none)}normalizeExpr(e){if(e instanceof ut&&"?"==e.kind)return[Un.none,...this.normalizeExpr(e.expr)];if(e instanceof ut){let t=this.normalizeRepeat(e);return"+"==e.kind?[t]:[Un.none,t]}return e instanceof lt?e.exprs.reduce(((e,t)=>e.concat(this.normalizeExpr(t))),[]):e instanceof ht?this.normalizeSequence(e):e instanceof ft?[Gn(this.tokens.getLiteral(e))]:e instanceof rt?this.resolve(e):e instanceof ot?[Gn(this.resolveSpecialization(e))]:e instanceof at?[Gn(this.buildRule(e.rule,Jn,this.currentSkip[this.currentSkip.length-1],!0))]:this.raise(`This type of expression ('${e}') may not occur in non-token rules`,e.start)}buildRule(e,t,n,i=!1){let s=this.substituteArgs(e.expr,t,e.params),{name:r,props:o,dynamicPrec:a,inline:l,group:h,exported:c}=this.nodeInfo(e.props||Jn,i?"pg":"pgi",e.id.name,t,e.params,e.expr);c&&e.params.length&&this.warn("Can't export parameterized rules",e.start),c&&i&&this.warn("Can't export inline rule",e.start);let u=this.newName(e.id.name+(t.length?"<"+t.join(",")+">":""),r||!0,o);return l&&(u.inline=!0),a&&this.registerDynamicPrec(u,a),(u.nodeType||c)&&0==e.params.length&&(r||(u.preserve=!0),i||(this.namedTerms[c||e.id.name]=u)),i||this.built.push(new Kn(e.id.name,t,u)),this.currentSkip.push(n),this.defineRule(u,this.normalizeExpr(s)),this.currentSkip.pop(),h&&this.definedGroups.push({name:u,group:h,rule:e}),u}nodeInfo(e,t,n=null,i=Jn,s=Jn,r,o){let a={},l=n&&(t.indexOf("a")>-1||!function(e){let t=e[0];return"_"==t||t.toUpperCase()!=t}(n))&&!/ /.test(n)?n:null,h=null,c=0,u=!1,f=null,d=null;for(let r of e)if(r.at)if("name"==r.name)l=this.finishProp(r,i,s),/ /.test(l)&&this.raise(`Node names cannot have spaces ('${l}')`,r.start);else if("dialect"==r.name){t.indexOf("d")<0&&this.raise("Can't specify a dialect on non-token rules",e[0].start),1==r.value.length||r.value[0].value||this.raise("The '@dialect' rule prop must hold a plain string value");let n=this.dialects.indexOf(r.value[0].value);n<0&&this.raise(`Unknown dialect '${r.value[0].value}'`,r.value[0].start),h=n}else"dynamicPrecedence"==r.name?(t.indexOf("p")<0&&this.raise("Dynamic precedence can only be specified on nonterminals"),1==r.value.length&&/^-?(?:10|\d)$/.test(r.value[0].value)||this.raise("The '@dynamicPrecedence' rule prop must hold an integer between -10 and 10"),c=+r.value[0].value):"inline"==r.name?(r.value.length&&this.raise("'@inline' doesn't take a value",r.value[0].start),t.indexOf("i")<0&&this.raise("Inline can only be specified on nonterminals"),u=!0):"isGroup"==r.name?(t.indexOf("g")<0&&this.raise("'@isGroup' can only be specified on nonterminals"),f=r.value.length?this.finishProp(r,i,s):n):"export"==r.name?d=r.value.length?this.finishProp(r,i,s):n:this.raise(`Unknown built-in prop name '@${r.name}'`,r.start);else{if(!this.knownProps[r.name]){let e=["name","dialect","dynamicPrecedence","export","isGroup"].includes(r.name)?` (did you mean '@${r.name}'?)`:"";this.raise(`Unknown prop name '${r.name}'${e}`,r.start)}a[r.name]=this.finishProp(r,i,s)}if(r&&this.ast.autoDelim&&(l||At(a))){let e=this.findDelimiters(r);e&&(Qn(e[0],"closedBy",e[1].nodeName),Qn(e[1],"openedBy",e[0].nodeName))}if(o&&At(o))for(let e in o)e in a||(a[e]=o[e]);return At(a)&&!l&&this.raise("Node has properties but no name",e.length?e[0].start:r.start),u&&(At(a)||h||c)&&this.raise("Inline nodes can't have props, dynamic precedence, or a dialect",e[0].start),u&&l&&(l=null),{name:l,props:a,dialect:h,dynamicPrec:c,inline:u,group:f,exported:d}}finishProp(e,t,n){return e.value.map((e=>{if(e.value)return e.value;let i=n.findIndex((t=>t.name==e.name));i<0&&this.raise(`Property refers to '${e.name}', but no parameter by that name is in scope`,e.start);let s=t[i];return s instanceof rt&&!s.args.length?s.id.name:s instanceof ft?s.value:this.raise(`Expression '${s}' can not be used as part of a property value`,e.start)})).join("")}resolveSpecialization(e){let t,n=e.type,{name:i,props:s,dialect:r}=this.nodeInfo(e.props,"d"),o=this.normalizeExpr(e.token);if(1==o.length&&1==o[0].terms.length&&o[0].terms[0].terminal||this.raise(`The first argument to '${n}' must resolve to a token`,e.token.start),e.content instanceof ft)t=[e.content.value];else{if(!(e.content instanceof lt&&e.content.exprs.every((e=>e instanceof ft))))return this.raise(`The second argument to '${e.type}' must be a literal or choice of literals`,e.content.start);t=e.content.exprs.map((e=>e.value))}let a=o[0].terms[0],l=null,h=this.specialized[a.name]||(this.specialized[a.name]=[]);for(let o of t){let t=h.find((e=>e.value==o));null==t?(l||(l=this.makeTerminal(a.name+"/"+JSON.stringify(o),i,s),null!=r&&(this.tokens.byDialect[r]||(this.tokens.byDialect[r]=[])).push(l)),h.push({value:o,term:l,type:n,dialect:r,name:i}),this.tokenOrigins[l.name]={spec:a}):(t.type!=n&&this.raise(`Conflicting specialization types for ${JSON.stringify(o)} of ${a.name} (${n} vs ${t.type})`,e.start),t.dialect!=r&&this.raise(`Conflicting dialects for specialization ${JSON.stringify(o)} of ${a.name}`,e.start),t.name!=i&&this.raise(`Conflicting names for specialization ${JSON.stringify(o)} of ${a.name}`,e.start),l&&t.term!=l&&this.raise(`Conflicting specialization tokens for ${JSON.stringify(o)} of ${a.name}`,e.start),l=t.term)}return l}findDelimiters(e){if(!(e instanceof ht)||e.exprs.length<2)return null;let t=e=>{if(e instanceof ft)return{term:this.tokens.getLiteral(e),str:e.value};if(e instanceof rt&&0==e.args.length){let n=this.ast.rules.find((t=>t.id.name==e.id.name));if(n)return t(n.expr);let i=this.tokens.rules.find((t=>t.id.name==e.id.name));if(i&&i.expr instanceof ft)return{term:this.tokens.getToken(e),str:i.expr.value}}return null},n=t(e.exprs[e.exprs.length-1]);if(!n||!n.term.nodeName)return null;let i=["()","[]","{}","<>"].find((e=>n.str.indexOf(e[1])>-1&&n.str.indexOf(e[0])<0));if(!i)return null;let s=t(e.exprs[0]);return!s||!s.term.nodeName||s.str.indexOf(i[0])<0||s.str.indexOf(i[1])>-1?null:[s.term,n.term]}registerDynamicPrec(e,t){this.dynamicRulePrecedences.push({rule:e,prec:t}),e.preserve=!0}defineGroup(e,t,n){var i;let s=[],r=e=>{if(e.nodeName)return[e];s.includes(e)&&this.raise(`Rule '${n.id.name}' cannot define a group because it contains a non-named recursive rule ('${e.name}')`,n.start);let t=[];s.push(e);for(let i of this.rules)if(i.name==e){let e=i.parts.map(r).filter((e=>e.length));if(e.length>1&&this.raise(`Rule '${n.id.name}' cannot define a group because some choices produce multiple named nodes`,n.start),1==e.length)for(let n of e[0])t.push(n)}return s.pop(),t};for(let n of r(e))n.props.group=((null===(i=n.props.group)||void 0===i?void 0:i.split(" "))||[]).concat(t).sort().join(" ")}checkGroups(){let e=Object.create(null),t=Object.create(null);for(let n of this.terms.terms)if(n.nodeName&&(t[n.nodeName]=!0,n.props.group))for(let t of n.props.group.split(" "))(e[t]||(e[t]=[])).push(n);let n=Object.keys(e);for(let i=0;ii.includes(e)))&&(r.length>i.length?i.some((e=>!r.includes(e))):r.some((e=>!i.includes(e))))&&this.warn(`Groups '${s}' and '${n[t]}' overlap without one being a superset of the other`)}}}}class Xn{constructor(e,t,n,i,s,r,o){this.tokenizers=e,this.data=t,this.stateArray=n,this.skipData=i,this.skipInfo=s,this.states=r,this.builder=o,this.sharedActions=[]}findSharedActions(e){if(e.actions.length<5)return null;let t=null;for(let n of this.sharedActions)(!t||n.actions.length>t.actions.length)&&n.actions.every((t=>e.actions.some((e=>e.eq(t)))))&&(t=n);if(t)return t;let n=null,i=[];for(let t=e.id+1;t=5&&(!n||n.lengthe.eq(s))))if(s instanceof Nn)i.push(s.term.id,s.target.id,0);else{let e=ei(s.rule,this.skipInfo);e!=t&&i.push(s.term.id,65535&e,e>>16)}return i.push(65535),t>-1?i.push(2,65535&t,t>>16):n?i.push(1,65535&n.addr,n.addr>>16):i.push(0),this.data.storeArray(i)}finish(e,t,n){let i=this.builder,s=i.skipRules.indexOf(e.skip),r=this.skipData[s],o=this.skipInfo[s].startTokens,a=e.defaultReduce?ei(e.defaultReduce,this.skipInfo):0,l=t?1:0,h=-1,c=null;if(0==a){if(t)for(const t of e.actions)t instanceof Dn&&t.term.eof&&(h=ei(t.rule,this.skipInfo));h<0&&(c=this.findSharedActions(e))}e.set.some((e=>e.rule.name.top&&e.pos==e.rule.parts.length))&&(l|=2);let u=[];for(let t=0;tt.rule==e.name))?262144:0)|n<<19}class ti{constructor(){this.data=[]}storeArray(e){let t=function(e,t){e:for(let n=0;;){let i=e.indexOf(t[0],n);if(-1==i||i+t.length>e.length)break;for(let s=1;s-1)return t;let n=this.data.length;for(let t of e)this.data.push(t);return n}finish(){return Uint16Array.from(this.data)}}function ni(e){let t={},n=0;for(let i of e)for(let e of i.goto){n=Math.max(e.term.id,n);let s=t[e.term.id]||(t[e.term.id]={});(s[e.target.id]||(s[e.target.id]=[])).push(i.id)}let i=new ti,s=[],r=n+2;for(let e=0;e<=n;e++){let n=t[e];if(!n){s.push(1);continue}let o=[],a=Object.keys(n);for(let e of a){let t=n[e];o.push((e==a[a.length-1]?1:0)+(t.length<<1)),o.push(+e);for(let e of t)o.push(e)}s.push(i.storeArray(o)+r)}if(s.some((e=>e>65535)))throw new St("Goto table too large");return Uint16Array.from([n+1,...s,...i.data])}class ii{constructor(e,t){this.tokens=e,this.groupID=t}create(){return this.groupID}createSource(){return String(this.groupID)}}function si(e,t){e.includes(t)||e.push(t)}function ri(e){let t=Object.create(null);for(let n of e){let e=1<e.id.name==t));if(!n)return null;let{name:i,props:s,dialect:r,exported:o}=this.b.nodeInfo(n.props,"d",t,e.args,n.params.length!=e.args.length?Jn:n.params),a=this.b.makeTerminal(e.toString(),i,s);return null!=r&&(this.byDialect[r]||(this.byDialect[r]=[])).push(a),(a.nodeType||o)&&0==n.params.length&&(a.nodeType||(a.preserve=!0),this.b.namedTerms[o||t]=a),this.buildRule(n,e,this.startState,new zt([a])),this.built.push(new Kn(t,e.args,a)),a}buildRule(e,t,n,i,s=Jn){let r=t.id.name;e.params.length!=t.args.length&&this.b.raise(`Incorrect number of arguments for token '${r}'`,t.start);let o=this.building.find((e=>e.name==r&&vt(t.args,e.args)));if(o){if(o.to==i)return void n.nullEdge(o.start);let e=this.building.length-1;for(;this.building[e].name!=r;)e--;this.b.raise(`Invalid (non-tail) recursion in token rules: ${this.building.slice(e).map((e=>e.name)).join(" -> ")}`,t.start)}this.b.used(e.id.name);let a=new zt;n.nullEdge(a),this.building.push(new ai(r,a,i,t.args)),this.build(this.b.substituteArgs(e.expr,t.args,e.params),a,i,t.args.map(((t,n)=>new oi(e.params[n].name,t,s)))),this.building.pop()}build(e,t,n,i){if(e instanceof rt){let s,r=e.id.name,o=i.find((e=>e.name==r));if(o)return this.build(o.expr,t,n,o.scope);for(let e=0,t=this.b.localTokens;e<=t.length;e++)s=(e==t.length?this.b.tokens:t[e]).rules.find((e=>e.id.name==r));if(!s)return this.b.raise(`Reference to token rule '${e.id.name}', which isn't found`,e.start);this.buildRule(s,e,t,n,i)}else if(e instanceof bt)for(let[i,s]of gt[e.type])t.edge(i,s,n);else if(e instanceof lt)for(let s of e.exprs)this.build(s,t,n,i);else if(yi(e))t.nullEdge(n);else if(e instanceof ht){let s=e.markers.find((e=>e.length>0));s&&this.b.raise("Conflict marker in token expression",s[0].start);for(let s=0;st&&n.push([t,i]),t=s;return t<=pi&&n.push([t,pi+1]),n}(e.ranges):e.ranges)bi(t,n,i,s);else if(e instanceof ft)for(let i=0;it.id==e));n&&t.push(n.term)}t.length||this.b.warn(`Precedence specified for unknown token ${i}`,i.start);for(let i of t)wi(e,i,n);n=n.concat(t)}}}precededBy(e,t){let n=this.precedenceRelations.find((t=>t.term==e));return n&&n.after.includes(t)}buildPrecTable(e){let t=[],n=this.precedenceRelations.slice();for(let{a:t,b:i,soft:s}of e)if(s){if(!n.some((e=>e.term==t))||!n.some((e=>e.term==i)))continue;s<0&&([t,i]=[i,t]),wi(n,i,[t]),wi(n,t,[])}e:for(;n.length;){for(let e=0;et.includes(e.id)))){if(t.push(i.term.id),1==n.length)break e;n[e]=n.pop();continue e}}this.b.raise(`Cyclic token precedence relation between ${n.map((e=>e.term)).join(", ")}`)}return t}}class hi extends li{constructor(){super(...arguments),this.explicitConflicts=[]}getLiteral(e){let t=JSON.stringify(e.value);for(let e of this.built)if(e.id==t)return e.term;let n=null,i={},s=null,r=null,o=this.ast?this.ast.literals.find((t=>t.literal==e.value)):null;o&&({name:n,props:i,dialect:s,exported:r}=this.b.nodeInfo(o.props,"da",e.value));let a=this.b.makeTerminal(t,n,i);return null!=s&&(this.byDialect[s]||(this.byDialect[s]=[])).push(a),r&&(this.b.namedTerms[r]=a),this.build(e,this.startState,new zt([a]),Jn),this.built.push(new Kn(t,Jn,a)),a}takeConflicts(){var e;let t=e=>{if(e instanceof rt){for(let t of this.built)if(t.matches(e))return t.term}else{let t=JSON.stringify(e.value),n=this.built.find((e=>e.id==t));if(n)return n.term}return this.b.warn(`Precedence specified for unknown token ${e}`,e.start),null};for(let n of(null===(e=this.ast)||void 0===e?void 0:e.conflicts)||[]){let e=t(n.a),i=t(n.b);e&&i&&(e.ide.id.name==i.accepting[0].name)).start),/\btokens\b/.test(xn)&&console.log(i.toString());let s=i.findConflicts(function(e,t,n){let i=Object.create(null);function s(e,i){return e.actions.some((e=>e.term==i))||n[t.skipRules.indexOf(e.skip)].startTokens.includes(i)}return(t,n)=>{t.ids(e,t)&&s(e,n)))}}(e,this.b,t)).filter((({a:e,b:t})=>!this.precededBy(e,t)&&!this.precededBy(t,e)));for(let{a:e,b:t}of this.explicitConflicts)s.some((n=>n.a==e&&n.b==t))||s.push(new Ft(e,t,0,"",""));let r=s.filter((e=>e.soft)),o=s.filter((e=>!e.soft)),a=[],l=[];for(let i of e){if(i.defaultReduce||i.tokenGroup>-1)continue;let e=[],s=[],r=t[this.b.skipRules.indexOf(i.skip)].startTokens;for(let e of r)i.actions.some((t=>t.term==e))&&this.b.raise(`Use of token ${e.name} conflicts with skip rule`);let h=[];for(let e=0;ee.conflict==n))){let e=n.exampleA?` (example: ${JSON.stringify(n.exampleA)}${n.exampleB?` vs ${JSON.stringify(n.exampleB)}`:""})`:"";a.push({error:`Overlapping tokens ${t.name} and ${r.name} used in same context${e}\nAfter: ${i.set[0].trail()}`,conflict:n})}si(e,t),si(s,r)}}let c=null;for(let t of l)if(!s.some((e=>t.tokens.includes(e)))){for(let n of e)si(t.tokens,n);c=t;break}c||(c=new ii(e,l.length+n),l.push(c)),i.tokenGroup=c.groupID}a.length&&this.b.raise(a.map((e=>e.error)).join("\n\n")),l.length+n>16&&this.b.raise(`Too many different token groups (${l.length}) to represent them as a 16-bit bitfield`);let h=this.buildPrecTable(r);return{tokenGroups:l,tokenPrec:h,tokenData:i.toArray(ri(l),h)}}}class ci extends li{constructor(e,t){super(e,t),this.fallback=null,t.fallback&&e.unique(t.fallback.id)}getToken(e){let t=null;if(this.ast.fallback&&this.ast.fallback.id.name==e.id.name){if(e.args.length&&this.b.raise(`Incorrect number of arguments for ${e.id.name}`,e.start),!this.fallback){let{name:t,props:n,exported:i}=this.b.nodeInfo(this.ast.fallback.props,"",e.id.name,Jn,Jn),s=this.fallback=this.b.makeTerminal(e.id.name,t,n);(s.nodeType||i)&&(s.nodeType||(s.preserve=!0),this.b.namedTerms[i||e.id.name]=s),this.b.used(e.id.name)}t=this.fallback}else t=super.getToken(e);return t&&!this.b.tokenOrigins[t.name]&&(this.b.tokenOrigins[t.name]={group:this}),t}buildLocalGroup(e,t,n){let i=this.startState.compile();i.accepting.length&&this.b.raise(`Grammar contains zero-length tokens (in '${i.accepting[0].name}')`,this.rules.find((e=>e.id.name==i.accepting[0].name)).start);for(let{a:e,b:t,exampleA:n}of i.findConflicts((()=>!0)))this.precededBy(e,t)||this.precededBy(t,e)||this.b.raise(`Overlapping tokens ${e.name} and ${t.name} in local token group${n?` (example: ${JSON.stringify(n)})`:""}`);for(let i of e){if(i.defaultReduce)continue;let e=null,s=t[this.b.skipRules.indexOf(i.skip)].startTokens[0];for(let{term:t}of i.actions){let n=this.b.tokenOrigins[t.name];(null==n?void 0:n.group)==this?e=t:s=t}e&&(s&&this.b.raise(`Tokens from a local token group used together with other tokens (${e.name} with ${s.name})`),i.tokenGroup=n)}let s=this.buildPrecTable(Jn),r=i.toArray({[n]:65535},s),o=r.length,a=new Uint16Array(r.length+s.length+1);return a.set(r,0),a.set(s,o),a[a.length-1]=65535,{groupID:n,create:()=>new He.RA(a,o,this.fallback?this.fallback.id:void 0),createSource:e=>`new ${e("LocalTokenGroup","@lezer/lr")}(${qn(a)}, ${o}${this.fallback?`, ${this.fallback.id}`:""})`}}}const ui=65536,fi=55296,di=57344,pi=1114111,mi=56320,gi=57343;function bi(e,t,n,i){if(ndi&&e.edge(Math.max(n,di),Math.min(i,Rt+1),t),n=ui),i<=ui)return;let s=String.fromCodePoint(n),r=String.fromCodePoint(i-1),o=s.charCodeAt(0),a=s.charCodeAt(1),l=r.charCodeAt(0),h=r.charCodeAt(1);if(o==l){let n=new zt;e.edge(o,o+1,n),n.edge(a,h+1,t)}else{let n=o,i=l;if(a>mi){n++;let i=new zt;e.edge(o,o+1,i),i.edge(a,gi+1,t)}if(he.term==t));i<0?e.push({term:t,after:n}):e[i]={term:t,after:e[i].after.concat(n)}}class ki{constructor(e,t){this.b=e,this.ast=t,this.tokens=vi(e,t.tokens);for(let e in this.tokens)this.b.tokenOrigins[this.tokens[e].name]={external:this}}getToken(e){return xi(this.b,this.tokens,e)}create(){return this.b.options.externalTokenizer(this.ast.id.name,this.b.termTable)}createSource(e){let{source:t,id:{name:n}}=this.ast;return e(n,t)}}class Si{constructor(e,t){this.b=e,this.ast=t,this.term=null,this.tokens=vi(e,t.tokens)}finish(){let e=this.b.normalizeExpr(this.ast.token);1==e.length&&1==e[0].terms.length&&e[0].terms[0].terminal||this.b.raise(`The token expression to '@external ${this.ast.type}' must resolve to a token`,this.ast.token.start),this.term=e[0].terms[0];for(let e in this.tokens)this.b.tokenOrigins[this.tokens[e].name]={spec:this.term,external:this}}getToken(e){return xi(this.b,this.tokens,e)}}function Ai(e,t={}){let n=new Yn(e,t),i=n.getParser();return i.termTable=n.termTable,i}const Ci=["break","case","catch","continue","debugger","default","do","else","finally","for","function","if","return","switch","throw","try","var","while","with","null","true","false","instanceof","typeof","void","delete","new","in","this","const","class","extends","export","import","super","enum","implements","interface","let","package","private","protected","public","static","yield","require"];function Oi(e){return e.props.some((e=>e.at&&"export"==e.name))}const Mi=s.tk.theme({"&":{background:"var(--jp-layout-color0)",color:"var(--jp-content-font-color1)"},".jp-CodeConsole &, .jp-Notebook &":{background:"transparent"},".cm-content":{caretColor:"var(--jp-editor-cursor-color)"},".cm-scroller":{fontFamily:"inherit"},".cm-cursor, .cm-dropCursor":{borderLeft:"var(--jp-code-cursor-width0) solid var(--jp-editor-cursor-color)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"var(--jp-editor-selected-background)"},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{backgroundColor:"var(--jp-editor-selected-focused-background)"},".cm-gutters":{borderRight:"1px solid var(--jp-border-color2)",backgroundColor:"var(--jp-layout-color2)"},".cm-gutter":{backgroundColor:"var(--jp-layout-color2)"},".cm-activeLine":{backgroundColor:"color-mix(in srgb, var(--jp-layout-color3) 25%, transparent)"},".cm-lineNumbers":{color:"var(--jp-ui-font-color2)"},".cm-searchMatch":{backgroundColor:"var(--jp-search-unselected-match-background-color)",color:"var(--jp-search-unselected-match-color)"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:"var(--jp-search-selected-match-background-color) !important",color:"var(--jp-search-selected-match-color) !important"},".cm-tooltip":{backgroundColor:"var(--jp-layout-color1)"}}),Ti=r.Qf.define([{tag:Ne.pJ.meta,color:"var(--jp-mirror-editor-meta-color)"},{tag:Ne.pJ.heading,color:"var(--jp-mirror-editor-header-color)"},{tag:[Ne.pJ.heading1,Ne.pJ.heading2,Ne.pJ.heading3,Ne.pJ.heading4],color:"var(--jp-mirror-editor-header-color)",fontWeight:"bold"},{tag:Ne.pJ.keyword,color:"var(--jp-mirror-editor-keyword-color)",fontWeight:"bold"},{tag:Ne.pJ.atom,color:"var(--jp-mirror-editor-atom-color)"},{tag:Ne.pJ.number,color:"var(--jp-mirror-editor-number-color)"},{tag:[Ne.pJ.definition(Ne.pJ.name),Ne.pJ.function(Ne.pJ.definition(Ne.pJ.variableName))],color:"var(--jp-mirror-editor-def-color)"},{tag:Ne.pJ.standard(Ne.pJ.variableName),color:"var(--jp-mirror-editor-builtin-color)"},{tag:[Ne.pJ.special(Ne.pJ.variableName),Ne.pJ.self],color:"var(--jp-mirror-editor-variable-2-color)"},{tag:Ne.pJ.punctuation,color:"var(--jp-mirror-editor-punctuation-color)"},{tag:Ne.pJ.propertyName,color:"var(--jp-mirror-editor-property-color)"},{tag:Ne.pJ.operator,color:"var(--jp-mirror-editor-operator-color)",fontWeight:"bold"},{tag:Ne.pJ.comment,color:"var(--jp-mirror-editor-comment-color)",fontStyle:"italic"},{tag:Ne.pJ.string,color:"var(--jp-mirror-editor-string-color)"},{tag:[Ne.pJ.labelName,Ne.pJ.monospace,Ne.pJ.special(Ne.pJ.string)],color:"var(--jp-mirror-editor-string-2-color)"},{tag:Ne.pJ.bracket,color:"var(--jp-mirror-editor-bracket-color)"},{tag:Ne.pJ.tagName,color:"var(--jp-mirror-editor-tag-color)"},{tag:Ne.pJ.attributeName,color:"var(--jp-mirror-editor-attribute-color)"},{tag:Ne.pJ.quote,color:"var(--jp-mirror-editor-quote-color)"},{tag:Ne.pJ.link,color:"var(--jp-mirror-editor-link-color)",textDecoration:"underline"},{tag:[Ne.pJ.separator,Ne.pJ.derefOperator,Ne.pJ.paren],color:""},{tag:Ne.pJ.strong,fontWeight:"bold"},{tag:Ne.pJ.emphasis,fontStyle:"italic"},{tag:Ne.pJ.strikethrough,textDecoration:"line-through"},{tag:Ne.pJ.bool,color:"var(--jp-mirror-editor-keyword-color)",fontWeight:"bold"}]),_i=[Mi,(0,r.nF)(Ti)];class Ni{constructor(){this._themeMap=new Map([["jupyter",Object.freeze({name:"jupyter",theme:_i})]])}get themes(){return Array.from(this._themeMap.values())}defaultTheme(){return this._themeMap.get("jupyter").theme}addTheme(e){if(this._themeMap.has(e.name))throw new Error(`A theme named '${e.name}' is already registered.`);this._themeMap.set(e.name,{displayName:e.name,...e})}getTheme(e){var t;const n=null===(t=this._themeMap.get(e))||void 0===t?void 0:t.theme;return null!=n?n:this.defaultTheme()}}!function(e){e.getDefaultThemes=function(e){const t=(null!=e?e:Me.Sr).load("jupyterlab");return[Object.freeze({name:"codemirror",displayName:t.__("codemirror"),theme:[s.tk.baseTheme({}),(0,r.nF)(r.R_)]})]}}(Ni||(Ni={}));class Di{constructor(){this._modeList=[],this.addLanguage({name:"none",mime:"text/plain",support:new r.ri(r.qp.define({parser:Ai("@top Program { }")}))})}addLanguage(e){var t;if(null!==(t=this.findByName(e.name))&&void 0!==t?t:this.findByMIME(e.mime,!0))throw new Error(`${e.mime} already registered`);this._modeList.push(this.makeSpec(e))}async getLanguage(e){const t=this.findBest(e);return t&&!t.support&&(t.support=await t.load()),t}getLanguages(){return[...this._modeList]}findByMIME(e,t=!1){if(Array.isArray(e)){for(let t=0;t-1&&t.substring(n+1,t.length);return i?this.findByExtension(i):null}findBest(e,t=!0){var n,i,s,r;const o="string"==typeof e?e:e.name,a="string"!=typeof e?e.mime:o,l="string"!=typeof e&&null!==(n=e.extensions)&&void 0!==n?n:[];return null!==(r=null!==(s=null!==(i=o?this.findByName(o):null)&&void 0!==i?i:a?this.findByMIME(a):null)&&void 0!==s?s:this.findByExtension(l))&&void 0!==r?r:t?this.findByMIME(ze.defaultMimeType):null}async highlight(e,t,n){var i;t&&await this.getLanguage(t);const s=null===(i=null==t?void 0:t.support)||void 0===i?void 0:i.language;if(!s)return void n.appendChild(document.createTextNode(e));const r=s.parser.parse(e);let o=0;(0,Ne.bW)(r,Ti,((t,i,s)=>{t>o&&n.appendChild(document.createTextNode(e.slice(o,t)));const r=n.appendChild(document.createElement("span"));r.className=s,r.appendChild(document.createTextNode(e.slice(t,i))),o=i})),o(await n.e(6388).then(n.bind(n,76388))).cpp()},{name:"C++",displayName:s.__("C++"),mime:"text/x-c++src",extensions:["cpp","c++","cc","cxx","hpp","h++","hh","hxx"],load:async()=>(await n.e(6388).then(n.bind(n,76388))).cpp()},{name:"CQL",displayName:s.__("CQL"),mime:"text/x-cassandra",extensions:["cql"],load:()=>i("Cassandra")},{name:"CSS",displayName:s.__("CSS"),mime:"text/css",extensions:["css"],load:async()=>(await n.e(4211).then(n.bind(n,4211))).css()},{name:"HTML",displayName:s.__("HTML"),alias:["xhtml"],mime:"text/html",extensions:["html","htm","handlebars","hbs"],load:async()=>(await Promise.all([n.e(5983),n.e(4211),n.e(9369)]).then(n.bind(n,99369))).html()},{name:"Java",displayName:s.__("Java"),mime:"text/x-java",extensions:["java"],load:async()=>(await n.e(9675).then(n.bind(n,19675))).java()},{name:"Javascript",displayName:s.__("Javascript"),alias:["ecmascript","js","node"],mime:["text/javascript","text/ecmascript","application/javascript","application/x-javascript","application/ecmascript"],extensions:["js","mjs","cjs"],load:async()=>(await n.e(5983).then(n.bind(n,55983))).javascript()},{name:"JSON",displayName:s.__("JSON"),alias:["json5"],mime:["application/json","application/x-json"],extensions:["json","map"],load:async()=>(await n.e(6097).then(n.bind(n,56097))).json()},{name:"JSX",displayName:s.__("JSX"),mime:"text/jsx",extensions:["jsx"],load:async()=>(await n.e(5983).then(n.bind(n,55983))).javascript({jsx:!0})},{name:"MariaDB SQL",displayName:s.__("MariaDB SQL"),mime:"text/x-mariadb",load:()=>i("MariaSQL")},{name:"Markdown",displayName:s.__("Markdown"),mime:"text/x-markdown",extensions:["md","markdown","mkd"],async load(){return(await Promise.all([n.e(5983),n.e(4211),n.e(9369),n.e(7047)]).then(n.bind(n,97047))).markdown({codeLanguages:this._modeList})}},{name:"MS SQL",displayName:s.__("MS SQL"),mime:"text/x-mssql",load:()=>i("MSSQL")},{name:"MySQL",displayName:s.__("MySQL"),mime:"text/x-mysql",load:()=>i("MySQL")},{name:"PHP",displayName:s.__("PHP"),mime:["text/x-php","application/x-httpd-php","application/x-httpd-php-open"],extensions:["php","php3","php4","php5","php7","phtml"],load:async()=>(await Promise.all([n.e(5983),n.e(4211),n.e(9369),n.e(9803)]).then(n.bind(n,69803))).php()},{name:"PLSQL",displayName:s.__("PLSQL"),mime:"text/x-plsql",extensions:["pls"],load:()=>i("PLSQL")},{name:"PostgreSQL",displayName:s.__("PostgreSQL"),mime:"text/x-pgsql",load:()=>i("PostgreSQL")},{name:"Python",displayName:s.__("Python"),mime:"text/x-python",extensions:["BUILD","bzl","py","pyw"],filename:/^(BUCK|BUILD)$/,load:async()=>(await n.e(2377).then(n.bind(n,22377))).python()},{name:"ipython",displayName:s.__("ipython"),mime:"text/x-ipython",load:async()=>(await n.e(2377).then(n.bind(n,22377))).python()},{name:"Rust",displayName:s.__("Rust"),mime:"text/x-rustsrc",extensions:["rs"],load:async()=>(await n.e(6208).then(n.bind(n,46208))).rust()},{name:"SQL",displayName:s.__("SQL"),mime:["application/sql","text/x-sql"],extensions:["sql"],load:()=>i("StandardSQL")},{name:"SQLite",displayName:s.__("SQLite"),mime:"text/x-sqlite",load:()=>i("SQLite")},{name:"TSX",displayName:s.__("TSX"),alias:["TypeScript-JSX"],mime:"text/typescript-jsx",extensions:["tsx"],load:async()=>(await n.e(5983).then(n.bind(n,55983))).javascript({jsx:!0,typescript:!0})},{name:"TypeScript",displayName:s.__("TypeScript"),alias:["ts"],mime:"application/typescript",extensions:["ts"],load:async()=>(await n.e(5983).then(n.bind(n,55983))).javascript({typescript:!0})},{name:"WebAssembly",displayName:s.__("WebAssembly"),mime:"text/webassembly",extensions:["wat","wast"],load:async()=>(await n.e(6641).then(n.bind(n,56641))).wast()},{name:"XML",displayName:s.__("XML"),alias:["rss","wsdl","xsd"],mime:["application/xml","text/xml"],extensions:["xml","xsl","xsd","svg"],load:async()=>(await n.e(9839).then(n.bind(n,9839))).xml()},{name:"APL",displayName:s.__("APL"),mime:"text/apl",extensions:["dyalog","apl"],load:async()=>t((await n.e(838).then(n.bind(n,838))).apl)},{name:"PGP",displayName:s.__("PGP"),alias:["asciiarmor"],mime:["application/pgp","application/pgp-encrypted","application/pgp-keys","application/pgp-signature"],extensions:["asc","pgp","sig"],load:async()=>t((await n.e(8904).then(n.bind(n,38904))).asciiArmor)},{name:"ASN.1",displayName:s.__("ASN.1"),mime:"text/x-ttcn-asn",extensions:["asn","asn1"],load:async()=>t((await n.e(2766).then(n.bind(n,42766))).asn1({}))},{name:"Asterisk",displayName:s.__("Asterisk"),mime:"text/x-asterisk",filename:/^extensions\.conf$/i,load:async()=>t((await n.e(7561).then(n.bind(n,87561))).asterisk)},{name:"Brainfuck",displayName:s.__("Brainfuck"),mime:"text/x-brainfuck",extensions:["b","bf"],load:async()=>t((await n.e(2187).then(n.bind(n,32187))).brainfuck)},{name:"Cobol",displayName:s.__("Cobol"),mime:"text/x-cobol",extensions:["cob","cpy"],load:async()=>t((await n.e(432).then(n.bind(n,90432))).cobol)},{name:"C#",displayName:s.__("C#"),alias:["csharp","cs"],mime:"text/x-csharp",extensions:["cs"],load:async()=>t((await n.e(5571).then(n.bind(n,55571))).csharp)},{name:"Clojure",displayName:s.__("Clojure"),mime:"text/x-clojure",extensions:["clj","cljc","cljx"],load:async()=>t((await n.e(5808).then(n.bind(n,45808))).clojure)},{name:"ClojureScript",displayName:s.__("ClojureScript"),mime:"text/x-clojurescript",extensions:["cljs"],load:async()=>t((await n.e(5808).then(n.bind(n,45808))).clojure)},{name:"Closure Stylesheets (GSS)",displayName:s.__("Closure Stylesheets (GSS)"),mime:"text/x-gss",extensions:["gss"],load:async()=>t((await n.e(6007).then(n.bind(n,16007))).gss)},{name:"CMake",displayName:s.__("CMake"),mime:"text/x-cmake",extensions:["cmake","cmake.in"],filename:/^CMakeLists\.txt$/,load:async()=>t((await n.e(8301).then(n.bind(n,48301))).cmake)},{name:"CoffeeScript",displayName:s.__("CoffeeScript"),alias:["coffee","coffee-script"],mime:["application/vnd.coffeescript","text/coffeescript","text/x-coffeescript"],extensions:["coffee"],load:async()=>t((await n.e(8338).then(n.bind(n,58338))).coffeeScript)},{name:"Common Lisp",displayName:s.__("Common Lisp"),alias:["lisp"],mime:"text/x-common-lisp",extensions:["cl","lisp","el"],load:async()=>t((await n.e(386).then(n.bind(n,386))).commonLisp)},{name:"Cypher",displayName:s.__("Cypher"),mime:"application/x-cypher-query",extensions:["cyp","cypher"],load:async()=>t((await n.e(2444).then(n.bind(n,12444))).cypher)},{name:"Cython",displayName:s.__("Cython"),mime:"text/x-cython",extensions:["pyx","pxd","pxi"],load:async()=>t((await n.e(2719).then(n.bind(n,22719))).cython)},{name:"Crystal",displayName:s.__("Crystal"),mime:"text/x-crystal",extensions:["cr"],load:async()=>t((await n.e(4537).then(n.bind(n,94537))).crystal)},{name:"D",displayName:s.__("D"),mime:"text/x-d",extensions:["d"],load:async()=>t((await n.e(8828).then(n.bind(n,88828))).d)},{name:"Dart",displayName:s.__("Dart"),mime:["application/dart","text/x-dart"],extensions:["dart"],load:async()=>t((await n.e(5571).then(n.bind(n,55571))).dart)},{name:"diff",displayName:s.__("diff"),mime:"text/x-diff",extensions:["diff","patch"],load:async()=>t((await n.e(3506).then(n.bind(n,3506))).diff)},{name:"Dockerfile",displayName:s.__("Dockerfile"),mime:"text/x-dockerfile",filename:/^Dockerfile$/,load:async()=>t((await n.e(2155).then(n.bind(n,2155))).dockerFile)},{name:"DTD",displayName:s.__("DTD"),mime:"application/xml-dtd",extensions:["dtd"],load:async()=>t((await n.e(7736).then(n.bind(n,7736))).dtd)},{name:"Dylan",displayName:s.__("Dylan"),mime:"text/x-dylan",extensions:["dylan","dyl","intr"],load:async()=>t((await n.e(1620).then(n.bind(n,21620))).dylan)},{name:"EBNF",displayName:s.__("EBNF"),mime:"text/x-ebnf",load:async()=>t((await n.e(1118).then(n.bind(n,1118))).ebnf)},{name:"ECL",displayName:s.__("ECL"),mime:"text/x-ecl",extensions:["ecl"],load:async()=>t((await n.e(4844).then(n.bind(n,94844))).ecl)},{name:"edn",displayName:s.__("edn"),mime:"application/edn",extensions:["edn"],load:async()=>t((await n.e(5808).then(n.bind(n,45808))).clojure)},{name:"Eiffel",displayName:s.__("Eiffel"),mime:"text/x-eiffel",extensions:["e"],load:async()=>t((await n.e(5199).then(n.bind(n,85199))).eiffel)},{name:"Elm",displayName:s.__("Elm"),mime:"text/x-elm",extensions:["elm"],load:async()=>t((await n.e(7543).then(n.bind(n,77543))).elm)},{name:"Erlang",displayName:s.__("Erlang"),mime:"text/x-erlang",extensions:["erl"],load:async()=>t((await n.e(3560).then(n.bind(n,33560))).erlang)},{name:"Esper",displayName:s.__("Esper"),mime:"text/x-esper",load:async()=>t((await n.e(662).then(n.bind(n,30662))).esper)},{name:"Factor",displayName:s.__("Factor"),mime:"text/x-factor",extensions:["factor"],load:async()=>t((await n.e(870).then(n.bind(n,40870))).factor)},{name:"FCL",displayName:s.__("FCL"),mime:"text/x-fcl",load:async()=>t((await n.e(192).then(n.bind(n,40192))).fcl)},{name:"Forth",displayName:s.__("Forth"),mime:"text/x-forth",extensions:["forth","fth","4th"],load:async()=>t((await n.e(7358).then(n.bind(n,27358))).forth)},{name:"Fortran",displayName:s.__("Fortran"),mime:"text/x-fortran",extensions:["f","for","f77","f90","f95"],load:async()=>t((await n.e(1814).then(n.bind(n,81814))).fortran)},{name:"F#",displayName:s.__("F#"),alias:["fsharp"],mime:"text/x-fsharp",extensions:["fs"],load:async()=>t((await n.e(9751).then(n.bind(n,69751))).fSharp)},{name:"Gas",displayName:s.__("Gas"),mime:"text/x-gas",extensions:["s"],load:async()=>t((await n.e(5950).then(n.bind(n,15950))).gas)},{name:"Gherkin",displayName:s.__("Gherkin"),mime:"text/x-feature",extensions:["feature"],load:async()=>t((await n.e(1643).then(n.bind(n,31643))).gherkin)},{name:"Go",displayName:s.__("Go"),mime:"text/x-go",extensions:["go"],load:async()=>t((await n.e(3217).then(n.bind(n,3217))).go)},{name:"Groovy",displayName:s.__("Groovy"),mime:"text/x-groovy",extensions:["groovy","gradle"],filename:/^Jenkinsfile$/,load:async()=>t((await n.e(22).then(n.bind(n,22))).groovy)},{name:"Haskell",displayName:s.__("Haskell"),mime:"text/x-haskell",extensions:["hs"],load:async()=>t((await n.e(7009).then(n.bind(n,57009))).haskell)},{name:"Haxe",displayName:s.__("Haxe"),mime:"text/x-haxe",extensions:["hx"],load:async()=>t((await n.e(6047).then(n.bind(n,36047))).haxe)},{name:"HXML",displayName:s.__("HXML"),mime:"text/x-hxml",extensions:["hxml"],load:async()=>t((await n.e(6047).then(n.bind(n,36047))).hxml)},{name:"HTTP",displayName:s.__("HTTP"),mime:"message/http",load:async()=>t((await n.e(8516).then(n.bind(n,38516))).http)},{name:"IDL",displayName:s.__("IDL"),mime:"text/x-idl",extensions:["pro"],load:async()=>t((await n.e(7343).then(n.bind(n,47343))).idl)},{name:"JSON-LD",displayName:s.__("JSON-LD"),alias:["jsonld"],mime:"application/ld+json",extensions:["jsonld"],load:async()=>t((await n.e(3747).then(n.bind(n,3747))).jsonld)},{name:"Jinja2",displayName:s.__("Jinja2"),mime:"text/jinja2",extensions:["j2","jinja","jinja2"],load:async()=>t((await n.e(7996).then(n.bind(n,7996))).jinja2)},{name:"Julia",displayName:s.__("Julia"),mime:"text/x-julia",extensions:["jl"],load:async()=>t((await n.e(1078).then(n.bind(n,41078))).julia)},{name:"Kotlin",displayName:s.__("Kotlin"),mime:"text/x-kotlin",extensions:["kt"],load:async()=>t((await n.e(5571).then(n.bind(n,55571))).kotlin)},{name:"LESS",displayName:s.__("LESS"),mime:"text/x-less",extensions:["less"],load:async()=>t((await n.e(6007).then(n.bind(n,16007))).less)},{name:"LiveScript",displayName:s.__("LiveScript"),alias:["ls"],mime:"text/x-livescript",extensions:["ls"],load:async()=>t((await n.e(805).then(n.bind(n,90805))).liveScript)},{name:"Lua",displayName:s.__("Lua"),mime:"text/x-lua",extensions:["lua"],load:async()=>t((await n.e(6535).then(n.bind(n,6535))).lua)},{name:"mIRC",displayName:s.__("mIRC"),mime:"text/mirc",load:async()=>t((await n.e(5144).then(n.bind(n,15144))).mirc)},{name:"Mathematica",displayName:s.__("Mathematica"),mime:"text/x-mathematica",extensions:["m","nb","wl","wls"],load:async()=>t((await n.e(7732).then(n.bind(n,7732))).mathematica)},{name:"Modelica",displayName:s.__("Modelica"),mime:"text/x-modelica",extensions:["mo"],load:async()=>t((await n.e(7326).then(n.bind(n,67326))).modelica)},{name:"MUMPS",displayName:s.__("MUMPS"),mime:"text/x-mumps",extensions:["mps"],load:async()=>t((await n.e(7420).then(n.bind(n,77420))).mumps)},{name:"mbox",displayName:s.__("mbox"),mime:"application/mbox",extensions:["mbox"],load:async()=>t((await n.e(9460).then(n.bind(n,89460))).mbox)},{name:"Nginx",displayName:s.__("Nginx"),mime:"text/x-nginx-conf",filename:/nginx.*\.conf$/i,load:async()=>t((await n.e(6990).then(n.bind(n,96990))).nginx)},{name:"NSIS",displayName:s.__("NSIS"),mime:"text/x-nsis",extensions:["nsh","nsi"],load:async()=>t((await n.e(2870).then(n.bind(n,42870))).nsis)},{name:"NTriples",displayName:s.__("NTriples"),mime:["application/n-triples","application/n-quads","text/n-triples"],extensions:["nt","nq"],load:async()=>t((await n.e(5836).then(n.bind(n,55836))).ntriples)},{name:"Objective-C",displayName:s.__("Objective-C"),alias:["objective-c","objc"],mime:"text/x-objectivec",extensions:["m"],load:async()=>t((await n.e(5571).then(n.bind(n,55571))).objectiveC)},{name:"Objective-C++",displayName:s.__("Objective-C++"),alias:["objective-c++","objc++"],mime:"text/x-objectivec++",extensions:["mm"],load:async()=>t((await n.e(5571).then(n.bind(n,55571))).objectiveCpp)},{name:"OCaml",displayName:s.__("OCaml"),mime:"text/x-ocaml",extensions:["ml","mli","mll","mly"],load:async()=>t((await n.e(9751).then(n.bind(n,69751))).oCaml)},{name:"Octave",displayName:s.__("Octave"),mime:"text/x-octave",extensions:["m"],load:async()=>t((await n.e(4127).then(n.bind(n,14127))).octave)},{name:"Oz",displayName:s.__("Oz"),mime:"text/x-oz",extensions:["oz"],load:async()=>t((await n.e(9787).then(n.bind(n,39787))).oz)},{name:"Pascal",displayName:s.__("Pascal"),mime:"text/x-pascal",extensions:["p","pas"],load:async()=>t((await n.e(2210).then(n.bind(n,52210))).pascal)},{name:"Perl",displayName:s.__("Perl"),mime:"text/x-perl",extensions:["pl","pm"],load:async()=>t((await n.e(8847).then(n.bind(n,88847))).perl)},{name:"Pig",displayName:s.__("Pig"),mime:"text/x-pig",extensions:["pig"],load:async()=>t((await n.e(1649).then(n.bind(n,1649))).pig)},{name:"PowerShell",displayName:s.__("PowerShell"),mime:"application/x-powershell",extensions:["ps1","psd1","psm1"],load:async()=>t((await n.e(6475).then(n.bind(n,36475))).powerShell)},{name:"Properties files",displayName:s.__("Properties files"),alias:["ini","properties"],mime:"text/x-properties",extensions:["properties","ini","in"],load:async()=>t((await n.e(4393).then(n.bind(n,84393))).properties)},{name:"ProtoBuf",displayName:s.__("ProtoBuf"),mime:"text/x-protobuf",extensions:["proto"],load:async()=>t((await n.e(8967).then(n.bind(n,58967))).protobuf)},{name:"Puppet",displayName:s.__("Puppet"),mime:"text/x-puppet",extensions:["pp"],load:async()=>t((await n.e(727).then(n.bind(n,70727))).puppet)},{name:"Q",displayName:s.__("Q"),mime:"text/x-q",extensions:["q"],load:async()=>t((await n.e(6686).then(n.bind(n,76686))).q)},{name:"R",displayName:s.__("R"),alias:["rscript"],mime:"text/x-rsrc",extensions:["r","R"],load:async()=>t((await n.e(8706).then(n.bind(n,18706))).r)},{name:"RPM Changes",displayName:s.__("RPM Changes"),mime:"text/x-rpm-changes",load:async()=>t((await n.e(81).then(n.bind(n,50081))).rpmChanges)},{name:"RPM Spec",displayName:s.__("RPM Spec"),mime:"text/x-rpm-spec",extensions:["spec"],load:async()=>t((await n.e(81).then(n.bind(n,50081))).rpmSpec)},{name:"Ruby",displayName:s.__("Ruby"),alias:["jruby","macruby","rake","rb","rbx"],mime:"text/x-ruby",extensions:["rb"],load:async()=>t((await n.e(8486).then(n.bind(n,48486))).ruby)},{name:"SAS",displayName:s.__("SAS"),mime:"text/x-sas",extensions:["sas"],load:async()=>t((await n.e(5395).then(n.bind(n,25395))).sas)},{name:"Scala",displayName:s.__("Scala"),mime:"text/x-scala",extensions:["scala"],load:async()=>t((await n.e(5571).then(n.bind(n,55571))).scala)},{name:"Scheme",displayName:s.__("Scheme"),mime:"text/x-scheme",extensions:["scm","ss"],load:async()=>t((await n.e(9409).then(n.bind(n,99409))).scheme)},{name:"SCSS",displayName:s.__("SCSS"),mime:"text/x-scss",extensions:["scss"],load:async()=>t((await n.e(6007).then(n.bind(n,16007))).sCSS)},{name:"Shell",displayName:s.__("Shell"),alias:["bash","sh","zsh"],mime:["text/x-sh","application/x-sh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load:async()=>t((await n.e(545).then(n.bind(n,60545))).shell)},{name:"Sieve",displayName:s.__("Sieve"),mime:"application/sieve",extensions:["siv","sieve"],load:async()=>t((await n.e(7471).then(n.bind(n,57471))).sieve)},{name:"Smalltalk",displayName:s.__("Smalltalk"),mime:"text/x-stsrc",extensions:["st"],load:async()=>t((await n.e(8849).then(n.bind(n,68849))).smalltalk)},{name:"Solr",displayName:s.__("Solr"),mime:"text/x-solr",load:async()=>t((await n.e(7373).then(n.bind(n,47373))).solr)},{name:"SML",displayName:s.__("SML"),mime:"text/x-sml",extensions:["sml","sig","fun","smackspec"],load:async()=>t((await n.e(9751).then(n.bind(n,69751))).sml)},{name:"SPARQL",displayName:s.__("SPARQL"),alias:["sparul"],mime:"application/sparql-query",extensions:["rq","sparql"],load:async()=>t((await n.e(4651).then(n.bind(n,54651))).sparql)},{name:"Spreadsheet",displayName:s.__("Spreadsheet"),alias:["excel","formula"],mime:"text/x-spreadsheet",load:async()=>t((await n.e(2519).then(n.bind(n,62519))).spreadsheet)},{name:"Squirrel",displayName:s.__("Squirrel"),mime:"text/x-squirrel",extensions:["nut"],load:async()=>t((await n.e(5571).then(n.bind(n,55571))).squirrel)},{name:"Stylus",displayName:s.__("Stylus"),mime:"text/x-styl",extensions:["styl"],load:async()=>t((await n.e(1711).then(n.bind(n,41711))).stylus)},{name:"Swift",displayName:s.__("Swift"),mime:"text/x-swift",extensions:["swift"],load:async()=>t((await n.e(6570).then(n.bind(n,36570))).swift)},{name:"sTeX",displayName:s.__("sTeX"),mime:"text/x-stex",load:async()=>t((await n.e(2411).then(n.bind(n,32411))).stex)},{name:"LaTeX",displayName:s.__("LaTeX"),alias:["tex"],mime:"text/x-latex",extensions:["text","ltx","tex"],load:async()=>t((await n.e(2411).then(n.bind(n,32411))).stex)},{name:"SystemVerilog",displayName:s.__("SystemVerilog"),mime:"text/x-systemverilog",extensions:["v","sv","svh"],load:async()=>t((await n.e(6526).then(n.bind(n,26526))).verilog)},{name:"Tcl",displayName:s.__("Tcl"),mime:"text/x-tcl",extensions:["tcl"],load:async()=>t((await n.e(3443).then(n.bind(n,23443))).tcl)},{name:"Textile",displayName:s.__("Textile"),mime:"text/x-textile",extensions:["textile"],load:async()=>t((await n.e(6873).then(n.bind(n,96873))).textile)},{name:"TiddlyWiki",displayName:s.__("TiddlyWiki"),mime:"text/x-tiddlywiki",load:async()=>t((await n.e(8702).then(n.bind(n,98702))).tiddlyWiki)},{name:"Tiki wiki",displayName:s.__("Tiki wiki"),mime:"text/tiki",load:async()=>t((await n.e(5815).then(n.bind(n,65815))).tiki)},{name:"TOML",displayName:s.__("TOML"),mime:"text/x-toml",extensions:["toml"],load:async()=>t((await n.e(6737).then(n.bind(n,6737))).toml)},{name:"troff",displayName:s.__("troff"),mime:"text/troff",extensions:["1","2","3","4","5","6","7","8","9"],load:async()=>t((await n.e(1803).then(n.bind(n,21803))).troff)},{name:"TTCN",displayName:s.__("TTCN"),mime:"text/x-ttcn",extensions:["ttcn","ttcn3","ttcnpp"],load:async()=>t((await n.e(6842).then(n.bind(n,26842))).ttcn)},{name:"TTCN_CFG",displayName:s.__("TTCN_CFG"),mime:"text/x-ttcn-cfg",extensions:["cfg"],load:async()=>t((await n.e(1363).then(n.bind(n,71363))).ttcnCfg)},{name:"Turtle",displayName:s.__("Turtle"),mime:"text/turtle",extensions:["ttl"],load:async()=>t((await n.e(6551).then(n.bind(n,91757))).turtle)},{name:"Web IDL",displayName:s.__("Web IDL"),mime:"text/x-webidl",extensions:["webidl"],load:async()=>t((await n.e(4745).then(n.bind(n,74745))).webIDL)},{name:"VB.NET",displayName:s.__("VB.NET"),mime:"text/x-vb",extensions:["vb"],load:async()=>t((await n.e(1757).then(n.bind(n,51757))).vb)},{name:"VBScript",displayName:s.__("VBScript"),mime:"text/vbscript",extensions:["vbs"],load:async()=>t((await n.e(9822).then(n.bind(n,79822))).vbScript)},{name:"Velocity",displayName:s.__("Velocity"),mime:"text/velocity",extensions:["vtl"],load:async()=>t((await n.e(8310).then(n.bind(n,28310))).velocity)},{name:"Verilog",displayName:s.__("Verilog"),mime:"text/x-verilog",extensions:["v"],load:async()=>t((await n.e(6526).then(n.bind(n,26526))).verilog)},{name:"VHDL",displayName:s.__("VHDL"),mime:"text/x-vhdl",extensions:["vhd","vhdl"],load:async()=>t((await n.e(2795).then(n.bind(n,82795))).vhdl)},{name:"XQuery",displayName:s.__("XQuery"),mime:"application/xquery",extensions:["xy","xquery"],load:async()=>t((await n.e(7783).then(n.bind(n,27783))).xQuery)},{name:"Yacas",displayName:s.__("Yacas"),mime:"text/x-yacas",extensions:["ys"],load:async()=>t((await n.e(4140).then(n.bind(n,84140))).yacas)},{name:"YAML",displayName:s.__("YAML"),alias:["yml"],mime:["text/x-yaml","text/yaml"],extensions:["yaml","yml"],load:async()=>t((await n.e(2123).then(n.bind(n,42123))).yaml)},{name:"Z80",displayName:s.__("Z80"),mime:"text/x-z80",extensions:["z80"],load:async()=>t((await n.e(1327).then(n.bind(n,1327))).z80)},{name:"mscgen",displayName:s.__("mscgen"),mime:"text/x-mscgen",extensions:["mscgen","mscin","msc"],load:async()=>t((await n.e(8336).then(n.bind(n,18336))).mscgen)},{name:"xu",displayName:s.__("xu"),mime:"text/x-xu",extensions:["xu"],load:async()=>t((await n.e(8336).then(n.bind(n,18336))).xu)},{name:"msgenny",displayName:s.__("msgenny"),mime:"text/x-msgenny",extensions:["msgenny"],load:async()=>t((await n.e(8336).then(n.bind(n,18336))).msgenny)}]}}(Di||(Di={})),function(e){e.createEditor=function(e,t,n,r){const o=t.getInitialExtensions();return o.push(...n),new s.tk({state:i.yy.create({doc:r,extensions:o}),parent:e})}}(Ei||(Ei={})),function(e){e.findNext=function(e,t,n=0,i=1/0){for(i=Math.min(e.length-1,i);n<=i;){let s=Math.floor(.5*(n+i));const r=e[s].position;if(rt)return n}else{if(!(r>t))return s;if((i=s-1)>0&&e[i].position0?n-1:0;return e[s].position>=t?s:null}}(ji||(ji={})),new Ae.Token("@jupyterlab/codemirror:IEditorExtensionRegistry","A registry for CodeMirror extension factories."),new Ae.Token("@jupyterlab/codemirror:IEditorLanguageRegistry","A registry for CodeMirror languages."),new Ae.Token("@jupyterlab/codemirror:IEditorThemeRegistry","A registry for CodeMirror theme.");var Ri,Pi,Ii=n(2784),Bi=n(2961),Li=n(64604),$i=n(66770);function zi(...e){return function(e){return e.map((e=>e&&"object"==typeof e?Object.keys(e).map((t=>!!e[t]&&t)):"string"==typeof e?e.split(/\s+/):[])).reduce(((e,t)=>e.concat(t)),[]).filter((e=>!!e))}(e).join(" ")}!function(e){const t={breadCrumb:{container:{$nest:{"&:first-child svg":{bottom:"1px",marginLeft:"0px",position:"relative"},"&:hover":{backgroundColor:"var(--jp-layout-color2)"},".jp-mod-dropTarget&":{backgroundColor:"var(--jp-brand-color2)",opacity:.7}}},element:{borderRadius:"var(--jp-border-radius)",cursor:"pointer",margin:"0px 2px",padding:"0px 2px",height:"16px",width:"16px",verticalAlign:"middle"}},commandPaletteHeader:{container:{height:"14px",margin:"0 14px 0 auto"},element:{height:"14px",width:"14px"},options:{elementPosition:"center"}},commandPaletteItem:{element:{height:"16px",width:"16px"},options:{elementPosition:"center"}},launcherCard:{container:{height:"52px",width:"52px"},element:{height:"52px",width:"52px"},options:{elementPosition:"center"}},launcherSection:{container:{boxSizing:"border-box",marginRight:"12px",height:"32px",width:"32px"},element:{height:"32px",width:"32px"},options:{elementPosition:"center"}},listing:{container:{flex:"0 0 20px",marginRight:"4px",position:"relative"},element:{height:"16px",width:"16px"},options:{elementPosition:"center"}},listingHeaderItem:{container:{display:"inline",height:"16px",width:"16px"},element:{height:"auto",margin:"-2px 0 0 0",width:"20px"},options:{elementPosition:"center"}},mainAreaTab:{container:{$nest:{".lm-DockPanel-tabBar &":{marginRight:"4px"}}},element:{$nest:{".lm-DockPanel-tabBar &":{height:"14px",width:"14px"}}},options:{elementPosition:"center"}},menuItem:{container:{display:"inline-block",verticalAlign:"middle"},element:{height:"16px",width:"16px"},options:{elementPosition:"center"}},runningItem:{container:{margin:"0px 4px 0px 4px"},element:{height:"16px",width:"16px"},options:{elementPosition:"center"}},select:{container:{pointerEvents:"none"},element:{position:"absolute",height:"auto",width:"16px"}},settingsEditor:{container:{display:"flex",flex:"0 0 20px",margin:"0 3px 0 0",position:"relative",height:"20px",width:"20px"},element:{height:"16px",width:"16px"},options:{elementPosition:"center"}},sideBar:{element:{height:"auto",width:"20px"},options:{elementPosition:"center"}},splash:{container:{animation:"0.3s fade-in linear forwards",height:"100%",width:"100%",zIndex:1},element:{width:"100px"},options:{elementPosition:"center"}},statusBar:{element:{left:"0px",top:"0px",height:"18px",width:"20px",position:"relative"}},toolbarButton:{container:{display:"inline-block",verticalAlign:"middle"},element:{height:"16px",width:"16px"},options:{elementPosition:"center"}}};function n(e){return{container:{alignItems:"center",display:"flex"},element:{display:"block",...e}}}const i={center:n({margin:"0 auto",width:"100%"}),top:n({margin:"0 0 auto 0"}),right:n({margin:"0 0 0 auto"}),bottom:n({margin:"auto 0 0 0"}),left:n({margin:"0 auto 0 0"}),"top right":n({margin:"0 0 auto auto"}),"bottom right":n({margin:"auto 0 0 auto"}),"bottom left":n({margin:"auto auto 0 0"}),"top left":n({margin:"0 auto 0 auto"})};function s(e){return{element:{height:e,width:e}}}const r={small:s("14px"),normal:s("16px"),large:s("20px"),xlarge:s("24px")};const o=new Map;e.styleClass=function(e){if(!e||0===Object.keys(e).length)return"";let{elementPosition:n,elementSize:s,stylesheet:a,...l}=e;const h={...n&&{elementPosition:n},...s&&{elementSize:s}},c="string"==typeof a&&0===Object.keys(l).length,u=c?[a,n,s].join(","):"";if(c&&o.has(u))return o.get(u);const f=function(e){return e?(Array.isArray(e)||(e=[e]),e.map((e=>"string"==typeof e?t[e]:e))):[]}(a);f.push({element:l,options:h});const d=function(e){var t;return(0,$i.oB)({...e.container,$nest:{...null===(t=e.container)||void 0===t?void 0:t.$nest,svg:e.element}})}(function(e){const t=Object.assign({},...e.map((e=>e.options)));return t.elementPosition&&e.unshift(i[t.elementPosition]),t.elementSize&&e.unshift(r[t.elementSize]),function(e){return{container:Object.assign({},...e.map((e=>e.container))),element:Object.assign({},...e.map((e=>e.element)))}}(e)}(f));return c&&o.set(u,d),d}}(Ri||(Ri={}));class Fi{static remove(e){for(;e.firstChild;)e.firstChild.remove();return e.className="",e}static resolve({icon:e}){if(e instanceof Fi)return e;if("string"==typeof e){return Fi._instances.get(e)||(Fi._debug&&console.warn(`Lookup failed for icon, creating loading icon. icon: ${e}`),new Fi({name:e,svgstr:"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgdmlld0JveD0iMCAwIDE4IDE4Ij4KICAgIDxnIGNsYXNzPSJqcC1pY29uMyIgZmlsbD0iIzYxNjE2MSI+CiAgICAgICAgPHBhdGggZD0iTTkgMTMuNWMtMi40OSAwLTQuNS0yLjAxLTQuNS00LjVTNi41MSA0LjUgOSA0LjVjMS4yNCAwIDIuMzYuNTIgMy4xNyAxLjMzTDEwIDhoNVYzbC0xLjc2IDEuNzZDMTIuMTUgMy42OCAxMC42NiAzIDkgMyA1LjY5IDMgMy4wMSA1LjY5IDMuMDEgOVM1LjY5IDE1IDkgMTVjMi45NyAwIDUuNDMtMi4xNiA1LjktNWgtMS41MmMtLjQ2IDItMi4yNCAzLjUtNC4zOCAzLjV6Ii8+CiAgICA8L2c+Cjwvc3ZnPgo=",_loading:!0}))}return new Fi(e)}static resolveElement({icon:e,iconClass:t,fallback:n,...i}){return Pi.isResolvable(e)?Fi.resolve({icon:e}).element(i):!t&&n?n.element(i):(i.className=zi(t,i.className),Pi.blankElement(i))}static resolveReact({icon:e,iconClass:t,fallback:n,...i}){if(!Pi.isResolvable(e))return!t&&n?Ii.createElement(n.react,{...i}):(i.className=zi(t,i.className),Ii.createElement(Pi.blankReact,{...i}));const s=Fi.resolve({icon:e});return Ii.createElement(s.react,{...i})}static resolveSvg({name:e,svgstr:t}){const n=(new DOMParser).parseFromString(Pi.svgstrShim(t),"image/svg+xml"),i=n.querySelector("parsererror");if(i){const n=`SVG HTML was malformed for LabIcon instance.\nname: ${e}, svgstr: ${t}`;return Fi._debug?(console.error(n),i):(console.warn(n),null)}return n.documentElement}static toggleDebug(e){Fi._debug=null!=e?e:!Fi._debug}constructor({name:e,svgstr:t,render:n,unrender:i,_loading:s=!1}){if(this._props={},this._svgReplaced=new Ce.Signal(this),this._svgElement=void 0,this._svgInnerHTML=void 0,this._svgReactAttrs=void 0,!e||!t)return console.error(`When defining a new LabIcon, name and svgstr must both be non-empty strings. name: ${e}, svgstr: ${t}`),Hi;if(this._loading=s,Fi._instances.has(e)){const n=Fi._instances.get(e);return this._loading?(n.svgstr=t,this._loading=!1,n):(Fi._debug&&console.warn(`Redefining previously loaded icon svgstr. name: ${e}, svgstrOld: ${n.svgstr}, svgstr: ${t}`),n.svgstr=t,n)}this.name=e,this.react=this._initReact(e),this.svgstr=t,this._initRender({render:n,unrender:i}),Fi._instances.set(this.name,this)}bindprops(e){const t=Object.create(this);return t._props=e,t.react=t._initReact(t.name+"_bind"),t}element(e={}){var t;let{className:n,container:i,label:s,title:r,tag:o="div",...a}={...this._props,...e};const l=null==i?void 0:i.firstChild;if((null===(t=null==l?void 0:l.dataset)||void 0===t?void 0:t.iconId)===this._uuid)return l;if(!this.svgElement)return document.createElement("div");let h=!0;if(i)for(;i.firstChild;)i.firstChild.remove();else i=document.createElement(o),h=!1;null!=s&&(i.textContent=s),Pi.initContainer({container:i,className:n,styleProps:a,title:r});const c=this.svgElement.cloneNode(!0);return i.appendChild(c),h?c:i}render(e,t){var n;let i=null===(n=null==t?void 0:t.children)||void 0===n?void 0:n[0];"string"!=typeof i&&(i=void 0),this.element({container:e,label:i,...null==t?void 0:t.props})}get svgElement(){return void 0===this._svgElement&&(this._svgElement=this._initSvg({uuid:this._uuid})),this._svgElement}get svgInnerHTML(){return void 0===this._svgInnerHTML&&(null===this.svgElement?this._svgInnerHTML=null:this._svgInnerHTML=this.svgElement.innerHTML),this._svgInnerHTML}get svgReactAttrs(){return void 0===this._svgReactAttrs&&(null===this.svgElement?this._svgReactAttrs=null:this._svgReactAttrs=function(e,{ignore:t=[]}={}){return e.getAttributeNames().reduce(((n,i)=>("style"===i||t.includes(i)||(i.startsWith("data")?n[i]=e.getAttribute(i):n[Fe.Text.camelCase(i)]=e.getAttribute(i)),n)),{})}(this.svgElement,{ignore:["data-icon-id"]})),this._svgReactAttrs}get svgstr(){return this._svgstr}set svgstr(e){this._svgstr=e;const t=Bi.UUID.uuid4(),n=this._uuid;this._uuid=t,this._svgElement=void 0,this._svgInnerHTML=void 0,this._svgReactAttrs=void 0,document.querySelectorAll(`[data-icon-id="${n}"]`).forEach((e=>{this.svgElement&&e.replaceWith(this.svgElement.cloneNode(!0))})),this._svgReplaced.emit()}_initReact(e){const t=Ii.forwardRef(((e={},t)=>{const{className:n,container:i,label:s,title:r,tag:o="div",...a}={...this._props,...e},[,l]=Ii.useState(this._uuid);Ii.useEffect((()=>{const e=()=>{l(this._uuid)};return this._svgReplaced.connect(e),()=>{this._svgReplaced.disconnect(e)}}));const h=o;if(!this.svgInnerHTML||!this.svgReactAttrs)return Ii.createElement(Ii.Fragment,null);const c=Ii.createElement("svg",{...this.svgReactAttrs,dangerouslySetInnerHTML:{__html:this.svgInnerHTML},ref:t});return i?(Pi.initContainer({container:i,className:n,styleProps:a,title:r}),Ii.createElement(Ii.Fragment,null,c,s)):Ii.createElement(h,{className:n||a?zi(n,Ri.styleClass(a)):void 0,title:r},c,s)}));return t.displayName=`LabIcon_${e}`,t}_initRender({render:e,unrender:t}){e?(this.render=e,t&&(this.unrender=t)):t&&console.warn("In _initRender, ignoring unrender arg since render is undefined")}_initSvg({title:e,uuid:t}={}){const n=Fi.resolveSvg(this);return n?("parsererror"!==n.tagName&&(n.dataset.icon=this.name,t&&(n.dataset.iconId=t),e&&Pi.setTitleSvg(n,e)),n):n}}Fi._debug=!1,Fi._instances=new Map,function(e){function t({container:e,className:t,styleProps:n,title:i}){null!=i&&(e.title=i);const s=Ri.styleClass(n);if(null!=t){const n=zi(t,s);return e.className=n,n}return s?(e.classList.add(s),s):""}e.blankElement=function({className:t="",container:n,label:i,title:s,tag:r="div",...o}){if((null==n?void 0:n.className)===t)return n;if(n)for(;n.firstChild;)n.firstChild.remove();else n=document.createElement(r);return null!=i&&(n.textContent=i),e.initContainer({container:n,className:t,styleProps:o,title:s}),n},e.blankReact=Ii.forwardRef((({className:e="",container:n,label:i,title:s,tag:r="div",...o},a)=>{const l=r;return n?(t({container:n,className:e,styleProps:o,title:s}),Ii.createElement(Ii.Fragment,null)):Ii.createElement(l,{className:zi(e,Ri.styleClass(o))},a&&Vi.react({ref:a}),i)})),e.blankReact.displayName="BlankReact",e.initContainer=t,e.isResolvable=function(e){return!(!e||!("string"==typeof e||e.name&&e.svgstr))},e.setTitleSvg=function(e,t){const n=e.getElementsByTagName("title");if(n.length)n[0].textContent=t;else{const n=document.createElement("title");n.textContent=t,e.appendChild(n)}},e.svgstrShim=function(e,t=!0){const[,n,i]=decodeURIComponent(e).replace(/>\s*\n\s*<").replace(/\s*\n\s*/g," ").match(t?/^(?:data:.*?(;base64)?,)?(.*)/:/(?:(base64).*)?(3&&void 0!==arguments[3]?arguments[3]:0,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1/0;if("Object"===e){let e=Object.getOwnPropertyNames(t);n&&e.sort(!0===n?void 0:n),e=e.slice(s,r+1),i={entries:e.map((e=>({key:e,value:t[e]})))}}else if("Array"===e)i={entries:t.slice(s,r+1).map(((e,t)=>({key:t+s,value:e})))};else{let e=0;const n=[];let o=!0;const a=function(e){return"function"==typeof e.set}(t);for(const i of t){if(e>r){o=!1;break}s<=e&&(a&&Array.isArray(i)?"string"==typeof i[0]||"number"==typeof i[0]?n.push({key:i[0],value:i[1]}):n.push({key:`[entry ${e}]`,value:{"[key]":i[0],"[value]":i[1]}}):n.push({key:e,value:i})),e++}i={hasMore:!o,entries:n}}return i}function Xi(e,t,n){const i=[];for(;t-e>n*n;)n*=n;for(let s=e;s<=t;s+=n)i.push({from:s,to:Math.min(t,s+n-1)});return i}function Qi(e,t,n,i){let s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,r=arguments.length>5&&void 0!==arguments[5]?arguments[5]:1/0;const o=Yi.bind(null,e,t,n);if(!i)return o().entries;const a=r<1/0,l=Math.min(r-s,function(e,t){return"Object"===e?Object.keys(t).length:"Array"===e?t.length:1/0}(e,t));if("Iterable"!==e){if(l<=i||i<7)return o(s,r).entries}else if(l<=i&&!a)return o(s,r).entries;let h;if("Iterable"===e){const{hasMore:e,entries:t}=o(s,s+i-1);h=e?[...t,...Xi(s+i,s+2*i-1,i)]:t}else h=a?Xi(s,r,i):[...o(0,i-5).entries,...Xi(i-4,l-5,i),...o(l-4,l-1).entries];return h}function Zi(e){const{styling:t,from:n,to:i,renderChildNodes:s,nodeType:r}=e,[o,a]=(0,Ii.useState)(!1),l=(0,Ii.useCallback)((()=>{a(!o)}),[o]);return o?Ii.createElement("div",t("itemRange",o),s(e,n,i)):Ii.createElement("div",Gi({},t("itemRange",o),{onClick:l}),Ii.createElement(Ki,{nodeType:r,styling:t,expanded:!1,onClick:l,arrowStyle:"double"}),`${n} ... ${i}`)}function es(e,t,n){const{nodeType:i,data:s,collectionLimit:r,circularCache:o,keyPath:a,postprocessValue:l,sortObjectKeys:h}=e,c=[];return Qi(i,s,h,r,t,n).forEach((t=>{if(void 0!==t.to)c.push(Ii.createElement(Zi,Gi({},e,{key:`ItemRange--${t.from}-${t.to}`,from:t.from,to:t.to,renderChildNodes:es})));else{const{key:n,value:i}=t,s=-1!==o.indexOf(i);c.push(Ii.createElement(hs,Gi({},e,{postprocessValue:l,collectionLimit:r,key:`Node--${n}`,keyPath:[n,...a],value:l(i),circularCache:[...o,i],isCircular:s,hideRoot:!1})))}})),c}function ts(e){const{circularCache:t=[],collectionLimit:n,createItemString:i,data:s,expandable:r,getItemString:o,hideRoot:a,isCircular:l,keyPath:h,labelRenderer:c,level:u=0,nodeType:f,nodeTypeIndicator:d,shouldExpandNodeInitially:p,styling:m}=e,[g,b]=(0,Ii.useState)(!l&&p(h,s,u)),y=(0,Ii.useCallback)((()=>{r&&b(!g)}),[r,g]),v=g||a&&0===u?es({...e,circularCache:t,level:u+1}):null,x=o(f,s,Ii.createElement("span",m("nestedNodeItemType",g),d),i(s,n),h),w=[h,f,g,r];return a?Ii.createElement("li",m("rootNode",...w),Ii.createElement("ul",m("rootNodeChildren",...w),v)):Ii.createElement("li",m("nestedNode",...w),r&&Ii.createElement(Ki,{styling:m,nodeType:f,expanded:g,onClick:y}),Ii.createElement("label",Gi({},m(["label","nestedNodeLabel"],...w),{onClick:y}),c(...w)),Ii.createElement("span",Gi({},m("nestedNodeItemString",...w),{onClick:y}),x),Ii.createElement("ul",m("nestedNodeChildren",...w),v))}function ns(e){const t=Object.getOwnPropertyNames(e).length;return`${t} ${1!==t?"keys":"key"}`}function is(e){let{data:t,...n}=e;return Ii.createElement(ts,Gi({},n,{data:t,nodeType:"Object",nodeTypeIndicator:"Error"===n.nodeType?"Error()":"{}",createItemString:ns,expandable:Object.getOwnPropertyNames(t).length>0}))}function ss(e){return`${e.length} ${1!==e.length?"items":"item"}`}function rs(e){let{data:t,...n}=e;return Ii.createElement(ts,Gi({},n,{data:t,nodeType:"Array",nodeTypeIndicator:"[]",createItemString:ss,expandable:t.length>0}))}function os(e,t){let n=0,i=!1;if(Number.isSafeInteger(e.size))n=e.size;else for(const s of e){if(t&&n+1>t){i=!0;break}n+=1}return`${i?">":""}${n} ${1!==n?"entries":"entry"}`}function as(e){return Ii.createElement(ts,Gi({},e,{nodeType:"Iterable",nodeTypeIndicator:"()",createItemString:os,expandable:!0}))}function ls(e){let{nodeType:t,styling:n,labelRenderer:i,keyPath:s,valueRenderer:r,value:o,valueGetter:a=(e=>e)}=e;return Ii.createElement("li",n("value",t,s),Ii.createElement("label",n(["label","valueLabel"],t,s),i(s,t,!1,!1)),Ii.createElement("span",n("valueText",t,s),r(a(o),o,...s)))}function hs(e){let{getItemString:t,keyPath:n,labelRenderer:i,styling:s,value:r,valueRenderer:o,isCustomNode:a,...l}=e;const h=a(r)?"Custom":function(e){const t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&"function"==typeof e[Symbol.iterator]?"Iterable":"Custom"===t&&e.constructor!==Object&&e instanceof Object?"Object":t}(r),c={getItemString:t,key:n[0],keyPath:n,labelRenderer:i,nodeType:h,styling:s,value:r,valueRenderer:o},u={...l,...c,data:r,isCustomNode:a};switch(h){case"Object":case"Error":case"WeakMap":case"WeakSet":return Ii.createElement(is,u);case"Array":return Ii.createElement(rs,u);case"Iterable":case"Map":case"Set":return Ii.createElement(as,u);case"String":return Ii.createElement(ls,Gi({},c,{valueGetter:e=>`"${e}"`}));case"Number":case"Custom":return Ii.createElement(ls,c);case"Boolean":return Ii.createElement(ls,Gi({},c,{valueGetter:e=>e?"true":"false"}));case"Date":return Ii.createElement(ls,Gi({},c,{valueGetter:e=>e.toISOString()}));case"Null":return Ii.createElement(ls,Gi({},c,{valueGetter:()=>"null"}));case"Undefined":return Ii.createElement(ls,Gi({},c,{valueGetter:()=>"undefined"}));case"Function":case"Symbol":return Ii.createElement(ls,Gi({},c,{valueGetter:e=>e.toString()}));default:return Ii.createElement(ls,Gi({},c,{valueGetter:()=>`<${h}>`}))}}function cs(e){return cs="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},cs(e)}function us(e,t,n){return(t=function(e){var t=function(e,t){if("object"!==cs(e)||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,"string");if("object"!==cs(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"===cs(t)?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function fs(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=new Array(t);n2?n-2:0),s=2;s1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=t.defaultBase16,s=void 0===i?ws:i,r=t.base16Themes,o=Ts(n,void 0===r?null:r);o&&(n=xs(xs({},o),n));for(var a=ks.reduce((function(e,t){return e[t]=n[t]||s[t],e}),{}),l=function(e,t){var n=Object.keys(t);for(var i in e)-1===n.indexOf(i)&&n.push(i);return n.reduce((function(n,i){return n[i]=function(e,t){if(void 0===e)return t;if(void 0===t)return e;var n=cs(e),i=cs(t);switch(n){case"string":switch(i){case"string":return[t,e].filter(Boolean).join(" ");case"object":return Ss({className:e,style:t});case"function":return function(n){for(var i=arguments.length,s=new Array(i>1?i-1:0),r=1;r1?i-1:0),r=1;r1?i-1:0),r=1;r1?i-1:0),r=1;r1?i-1:0),r=1;r3?h-3:0),u=3;u({String:e.STRING_COLOR,Date:e.DATE_COLOR,Number:e.NUMBER_COLOR,Boolean:e.BOOLEAN_COLOR,Null:e.NULL_COLOR,Undefined:e.UNDEFINED_COLOR,Function:e.FUNCTION_COLOR,Symbol:e.SYMBOL_COLOR}),Ds=Os((e=>{const t=(e=>({BACKGROUND_COLOR:e.base00,TEXT_COLOR:e.base07,STRING_COLOR:e.base0B,DATE_COLOR:e.base0B,NUMBER_COLOR:e.base09,BOOLEAN_COLOR:e.base09,NULL_COLOR:e.base08,UNDEFINED_COLOR:e.base08,FUNCTION_COLOR:e.base08,SYMBOL_COLOR:e.base08,LABEL_COLOR:e.base0D,ARROW_COLOR:e.base0D,ITEM_STRING_COLOR:e.base0B,ITEM_STRING_EXPANDED_COLOR:e.base03}))(e);return{tree:{border:0,padding:0,marginTop:"0.5em",marginBottom:"0.5em",marginLeft:"0.125em",marginRight:0,listStyle:"none",MozUserSelect:"none",WebkitUserSelect:"none",backgroundColor:t.BACKGROUND_COLOR},value:(e,t,n)=>{let{style:i}=e;return{style:{...i,paddingTop:"0.25em",paddingRight:0,marginLeft:"0.875em",WebkitUserSelect:"text",MozUserSelect:"text",wordWrap:"break-word",paddingLeft:n.length>1?"2.125em":"1.25em",textIndent:"-0.5em",wordBreak:"break-all"}}},label:{display:"inline-block",color:t.LABEL_COLOR},valueLabel:{margin:"0 0.5em 0 0"},valueText:(e,n)=>{let{style:i}=e;return{style:{...i,color:Ns(t)[n]}}},itemRange:(e,n)=>({style:{paddingTop:n?0:"0.25em",cursor:"pointer",color:t.LABEL_COLOR}}),arrow:(e,t,n)=>{let{style:i}=e;return{style:{...i,marginLeft:0,transition:"150ms",WebkitTransition:"150ms",MozTransition:"150ms",WebkitTransform:n?"rotateZ(90deg)":"rotateZ(0deg)",MozTransform:n?"rotateZ(90deg)":"rotateZ(0deg)",transform:n?"rotateZ(90deg)":"rotateZ(0deg)",transformOrigin:"45% 50%",WebkitTransformOrigin:"45% 50%",MozTransformOrigin:"45% 50%",position:"relative",lineHeight:"1.1em",fontSize:"0.75em"}}},arrowContainer:(e,t)=>{let{style:n}=e;return{style:{...n,display:"inline-block",paddingRight:"0.5em",paddingLeft:"double"===t?"1em":0,cursor:"pointer"}}},arrowSign:{color:t.ARROW_COLOR},arrowSignInner:{position:"absolute",top:0,left:"-0.4em"},nestedNode:(e,t,n,i,s)=>{let{style:r}=e;return{style:{...r,position:"relative",paddingTop:"0.25em",marginLeft:t.length>1?"0.875em":0,paddingLeft:s?0:"1.125em"}}},rootNode:{padding:0,margin:0},nestedNodeLabel:(e,t,n,i,s)=>{let{style:r}=e;return{style:{...r,margin:0,padding:0,WebkitUserSelect:s?"inherit":"text",MozUserSelect:s?"inherit":"text",cursor:s?"pointer":"default"}}},nestedNodeItemString:(e,n,i,s)=>{let{style:r}=e;return{style:{...r,paddingLeft:"0.5em",cursor:"default",color:s?t.ITEM_STRING_EXPANDED_COLOR:t.ITEM_STRING_COLOR}}},nestedNodeItemType:{marginLeft:"0.3em",marginRight:"0.3em"},nestedNodeChildren:(e,t,n)=>{let{style:i}=e;return{style:{...i,padding:0,margin:0,listStyle:"none",display:n?"block":"none"}}},rootNodeChildren:{padding:0,margin:0,listStyle:"none"}}}),{defaultBase16:{scheme:"solarized",author:"ethan schoonover (http://ethanschoonover.com/solarized)",base00:"#002b36",base01:"#073642",base02:"#586e75",base03:"#657b83",base04:"#839496",base05:"#93a1a1",base06:"#eee8d5",base07:"#fdf6e3",base08:"#dc322f",base09:"#cb4b16",base0A:"#b58900",base0B:"#859900",base0C:"#2aa198",base0D:"#268bd2",base0E:"#6c71c4",base0F:"#d33682"}}),Es=Ds,js=e=>e,Rs=(e,t,n)=>0===n,Ps=(e,t,n,i)=>Ii.createElement("span",null,n," ",i),Is=e=>{let[t]=e;return Ii.createElement("span",null,t,":")},Bs=()=>!1;function Ls(e){let{data:t,theme:n,invertTheme:i,keyPath:s=["root"],labelRenderer:r=Is,valueRenderer:o=js,shouldExpandNodeInitially:a=Rs,hideRoot:l=!1,getItemString:h=Ps,postprocessValue:c=js,isCustomNode:u=Bs,collectionLimit:f=50,sortObjectKeys:d=!1}=e;const p=(0,Ii.useMemo)((()=>Es(i?_s(n):n)),[n,i]);return Ii.createElement("ul",p("tree"),Ii.createElement(hs,{keyPath:l?[]:s,value:c(t),isCustomNode:u,styling:p,labelRenderer:r,valueRenderer:o,shouldExpandNodeInitially:a,hideRoot:l,getItemString:h,postprocessValue:c,collectionLimit:f,sortObjectKeys:d}))}var $s=n(37207);function zs(e){var t;return null!==(t=Ti.style([e]))&&void 0!==t?t:""}class Fs extends Ii.Component{constructor(){super(...arguments),this.state={filter:"",value:""},this.timer=0,this.handleChange=e=>{const{value:t}=e.target;this.setState({value:t}),window.clearTimeout(this.timer),this.timer=window.setTimeout((()=>{this.setState({filter:t})}),300)}}componentDidMount(){$s.V.mount(document,Ti.module)}render(){const e=(this.props.translator||Me.Sr).load("jupyterlab"),{data:t,metadata:n,forwardedRef:i}=this.props,s=n&&n.root?n.root:"root",r=this.state.filter?Ws(t,this.state.filter,[s]):[s];return Ii.createElement("div",{className:"container",ref:i},Ii.createElement(Wi,{className:"filter",type:"text",placeholder:e.__("Filter…"),onChange:this.handleChange,value:this.state.value,rightIcon:"ui-components:search"}),Ii.createElement(Ls,{data:t,collectionLimit:100,theme:{extend:Hs,valueLabel:zs(Ne.pJ.variableName),valueText:zs(Ne.pJ.string),nestedNodeItemString:zs(Ne.pJ.comment)},invertTheme:!1,keyPath:[s],getItemString:(e,t,n,i)=>Array.isArray(t)?Ii.createElement("span",null,n," ",i):0===Object.keys(t).length?Ii.createElement("span",null,n):null,labelRenderer:([e,t])=>Ii.createElement("span",{className:zs(Ne.pJ.keyword)},Ii.createElement(Ui(),{searchWords:[this.state.filter],textToHighlight:`${e}`,highlightClassName:"jp-mod-selected"})),valueRenderer:e=>{let t=zs(Ne.pJ.string);return"number"==typeof e&&(t=zs(Ne.pJ.number)),"true"!==e&&"false"!==e||(t=zs(Ne.pJ.keyword)),Ii.createElement("span",{className:t},Ii.createElement(Ui(),{searchWords:[this.state.filter],textToHighlight:`${e}`,highlightClassName:"jp-mod-selected"}))},shouldExpandNodeInitially:(e,t,i)=>!(!n||!n.expanded)||r.join(",").includes(e.join(","))}))}}const Hs={scheme:"jupyter",base00:"invalid",base01:"invalid",base02:"invalid",base03:"invalid",base04:"invalid",base05:"invalid",base06:"invalid",base07:"invalid",base08:"invalid",base09:"invalid",base0A:"invalid",base0B:"invalid",base0C:"invalid",base0D:"invalid",base0E:"invalid",base0F:"invalid",author:"invalid"};function Vs(e,t){return JSON.stringify(e).includes(t)}function Ws(e,t,n=["root"]){return qi.JSONExt.isArray(e)?e.reduce(((e,i,s)=>i&&"object"==typeof i&&Vs(i,t)?[...e,[s,...n].join(","),...Ws(i,t,[s,...n])]:e),[]):qi.JSONExt.isObject(e)?Object.keys(e).reduce(((i,s)=>{const r=e[s];return r&&"object"==typeof r&&(s.includes(t)||Vs(r,t))?[...i,[s,...n].join(","),...Ws(r,t,[s,...n])]:i}),[]):[]}},56949:function(e,t){!function(e){"use strict";e.JSONExt=void 0,function(e){function t(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e}function n(e){return Array.isArray(e)}function i(e,s){if(e===s)return!0;if(t(e)||t(s))return!1;let r=n(e),o=n(s);return r===o&&(r&&o?function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0,s=e.length;n>>0),e[n]=255&t,t>>>=8}e.Random=void 0,(e.Random||(e.Random={})).getRandomValues=(()=>{const e="undefined"!=typeof window&&(window.crypto||window.msCrypto)||null;return e&&"function"==typeof e.getRandomValues?function(t){return e.getRandomValues(t)}:t})(),e.UUID=void 0,(e.UUID||(e.UUID={})).uuid4=function(e){const t=new Uint8Array(16),n=new Array(256);for(let e=0;e<16;++e)n[e]="0"+e.toString(16);for(let e=16;e<256;++e)n[e]=e.toString(16);return function(){return e(t),t[6]=64|15&t[6],t[8]=128|63&t[8],n[t[0]]+n[t[1]]+n[t[2]]+n[t[3]]+"-"+n[t[4]]+n[t[5]]+"-"+n[t[6]]+n[t[7]]+"-"+n[t[8]]+n[t[9]]+"-"+n[t[10]]+n[t[11]]+n[t[12]]+n[t[13]]+n[t[14]]+n[t[15]]}}(e.Random.getRandomValues),e.MimeData=class{constructor(){this._types=[],this._values=[]}types(){return this._types.slice()}hasData(e){return-1!==this._types.indexOf(e)}getData(e){let t=this._types.indexOf(e);return-1!==t?this._values[t]:void 0}setData(e,t){this.clearData(e),this._types.push(e),this._values.push(t)}clearData(e){let t=this._types.indexOf(e);-1!==t&&(this._types.splice(t,1),this._values.splice(t,1))}clear(){this._types.length=0,this._values.length=0}},e.PromiseDelegate=class{constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}resolve(e){(0,this._resolve)(e)}reject(e){(0,this._reject)(e)}},e.Token=class{constructor(e,t){this.name=e,this.description=null!=t?t:"",this._tokenStructuralPropertyT=null}}}(t)},2961:function(e,t){!function(e){"use strict";e.JSONExt=void 0,function(e){function t(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e}function n(e){return Array.isArray(e)}function i(e,s){if(e===s)return!0;if(t(e)||t(s))return!1;let r=n(e),o=n(s);return r===o&&(r&&o?function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0,s=e.length;n>>0),e[n]=255&t,t>>>=8}e.Random=void 0,(e.Random||(e.Random={})).getRandomValues=(()=>{const e="undefined"!=typeof window&&(window.crypto||window.msCrypto)||null;return e&&"function"==typeof e.getRandomValues?function(t){return e.getRandomValues(t)}:t})(),e.UUID=void 0,(e.UUID||(e.UUID={})).uuid4=function(e){const t=new Uint8Array(16),n=new Array(256);for(let e=0;e<16;++e)n[e]="0"+e.toString(16);for(let e=16;e<256;++e)n[e]=e.toString(16);return function(){return e(t),t[6]=64|15&t[6],t[8]=128|63&t[8],n[t[0]]+n[t[1]]+n[t[2]]+n[t[3]]+"-"+n[t[4]]+n[t[5]]+"-"+n[t[6]]+n[t[7]]+"-"+n[t[8]]+n[t[9]]+"-"+n[t[10]]+n[t[11]]+n[t[12]]+n[t[13]]+n[t[14]]+n[t[15]]}}(e.Random.getRandomValues),e.MimeData=class{constructor(){this._types=[],this._values=[]}types(){return this._types.slice()}hasData(e){return-1!==this._types.indexOf(e)}getData(e){let t=this._types.indexOf(e);return-1!==t?this._values[t]:void 0}setData(e,t){this.clearData(e),this._types.push(e),this._values.push(t)}clearData(e){let t=this._types.indexOf(e);-1!==t&&(this._types.splice(t,1),this._values.splice(t,1))}clear(){this._types.length=0,this._values.length=0}},e.PromiseDelegate=class{constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}resolve(e){(0,this._resolve)(e)}reject(e){(0,this._reject)(e)}},e.Token=class{constructor(e,t){this.name=e,this.description=null!=t?t:"",this._tokenStructuralPropertyT=null}}}(t)},64100:(e,t,n)=>{"use strict";n.d(t,{GA:()=>$,Gn:()=>M,Mb:()=>l,TK:()=>o,eC:()=>h,vQ:()=>j});var i=n(1727),s=n(65329),r=n(77120);class o{constructor(e,t,n){this.state=e,this.pos=t,this.explicit=n,this.abortListeners=[]}tokenBefore(e){let t=(0,r.qz)(this.state).resolveInner(this.pos,-1);for(;t&&e.indexOf(t.name)<0;)t=t.parent;return t?{from:t.from,to:this.pos,text:this.state.sliceDoc(t.from,this.pos),type:t.type}:null}matchBefore(e){let t=this.state.doc.lineAt(this.pos),n=Math.max(t.from,this.pos-250),i=t.text.slice(n-t.from,this.pos-t.from),s=i.search(function(e,t){var n;let{source:i}=e,s=t&&"^"!=i[0],r="$"!=i[i.length-1];return s||r?new RegExp(`${s?"^":""}(?:${i})${r?"$":""}`,null!==(n=e.flags)&&void 0!==n?n:e.ignoreCase?"i":""):e}(e,!1));return s<0?null:{from:n+s,to:this.pos,text:i.slice(s)}}get aborted(){return null==this.abortListeners}addEventListener(e,t){"abort"==e&&this.abortListeners&&this.abortListeners.push(t)}}function a(e){let t=Object.keys(e).join(""),n=/\w/.test(t);return n&&(t=t.replace(/\w/g,"")),`[${n?"\\w":""}${t.replace(/[^\w\s]/g,"\\$&")}]`}function l(e){let t=e.map((e=>"string"==typeof e?{label:e}:e)),[n,i]=t.every((e=>/^\w+$/.test(e.label)))?[/\w*$/,/\w+$/]:function(e){let t=Object.create(null),n=Object.create(null);for(let{label:i}of e){t[i[0]]=!0;for(let e=1;e{let s=e.matchBefore(i);return s||e.explicit?{from:s?s.from:e.pos,options:t,validFor:n}:null}}function h(e,t){return n=>{for(let t=(0,r.qz)(n.state).resolveInner(n.pos,-1);t;t=t.parent){if(e.indexOf(t.name)>-1)return null;if(t.type.isTop)break}return t(n)}}const c=i.q6.define(),u=s.tk.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑︎'"}},".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});class f{constructor(e,t,n,i){this.field=e,this.line=t,this.from=n,this.to=i}}class d{constructor(e,t,n){this.field=e,this.from=t,this.to=n}map(e){let t=e.mapPos(this.from,-1,i.gc.TrackDel),n=e.mapPos(this.to,1,i.gc.TrackDel);return null==t||null==n?null:new d(this.field,t,n)}}class p{constructor(e,t){this.lines=e,this.fieldPositions=t}instantiate(e,t){let n=[],i=[t],s=e.doc.lineAt(t),o=/^\s*/.exec(s.text)[0];for(let s of this.lines){if(n.length){let n=o,a=/^\t*/.exec(s)[0].length;for(let t=0;tnew d(e.field,i[e.line]+e.from,i[e.line]+e.to)));return{text:n,ranges:a}}static parse(e){let t,n=[],i=[],s=[];for(let r of e.split(/\r\n?|\n/)){for(;t=/[#$]\{(?:(\d+)(?::([^}]*))?|([^}]*))\}/.exec(r);){let e=t[1]?+t[1]:null,o=t[2]||t[3]||"",a=-1;for(let t=0;t=a&&e.field++}s.push(new f(a,i.length,t.index,t.index+o.length)),r=r.slice(0,t.index)+o+r.slice(t.index+t[0].length)}for(let e;e=/\\([{}])/.exec(r);){r=r.slice(0,e.index)+e[1]+r.slice(e.index+e[0].length);for(let t of s)t.line==i.length&&t.from>e.index&&(t.from--,t.to--)}i.push(r)}return new p(i,s)}}let m=s.p.widget({widget:new class extends s.l9{toDOM(){let e=document.createElement("span");return e.className="cm-snippetFieldPosition",e}ignoreEvent(){return!1}}}),g=s.p.mark({class:"cm-snippetField"});class b{constructor(e,t){this.ranges=e,this.active=t,this.deco=s.p.set(e.map((e=>(e.from==e.to?m:g).range(e.from,e.to))))}map(e){let t=[];for(let n of this.ranges){let i=n.map(e);if(!i)return null;t.push(i)}return new b(t,this.active)}selectionInsideField(e){return e.ranges.every((e=>this.ranges.some((t=>t.field==this.active&&t.from<=e.from&&t.to>=e.to))))}}const y=i.Py.define({map:(e,t)=>e&&e.map(t)}),v=i.Py.define(),x=i.QQ.define({create:()=>null,update(e,t){for(let n of t.effects){if(n.is(y))return n.value;if(n.is(v)&&e)return new b(e.ranges,n.value)}return e&&t.docChanged&&(e=e.map(t.changes)),e&&t.selection&&!e.selectionInsideField(t.selection)&&(e=null),e},provide:e=>s.tk.decorations.from(e,(e=>e?e.deco:s.p.none))});function w(e,t){return i.jT.create(e.filter((e=>e.field==t)).map((e=>i.jT.range(e.from,e.to))))}function k(e){let t=p.parse(e);return(e,n,s,r)=>{let{text:o,ranges:a}=t.instantiate(e.state,s),l={changes:{from:s,to:r,insert:i.xv.of(o)},scrollIntoView:!0,annotations:n?c.of(n):void 0};if(a.length&&(l.selection=w(a,0)),a.length>1){let t=new b(a,0),n=l.effects=[y.of(t)];void 0===e.state.field(x,!1)&&n.push(i.Py.appendConfig.of([x,O,T,u]))}e.dispatch(e.state.update(l))}}function S(e){return({state:t,dispatch:n})=>{let i=t.field(x,!1);if(!i||e<0&&0==i.active)return!1;let s=i.active+e,r=e>0&&!i.ranges.some((t=>t.field==s+e));return n(t.update({selection:w(i.ranges,s),effects:y.of(r?null:new b(i.ranges,s)),scrollIntoView:!0})),!0}}const A=[{key:"Tab",run:S(1),shift:S(-1)},{key:"Escape",run:({state:e,dispatch:t})=>!!e.field(x,!1)&&(t(e.update({effects:y.of(null)})),!0)}],C=i.r$.define({combine:e=>e.length?e[0]:A}),O=i.Wl.highest(s.$f.compute([C],(e=>e.facet(C))));function M(e,t){return Object.assign(Object.assign({},t),{apply:k(e)})}const T=s.tk.domEventHandlers({mousedown(e,t){let n,i=t.state.field(x,!1);if(!i||null==(n=t.posAtCoords({x:e.clientX,y:e.clientY})))return!1;let s=i.ranges.find((e=>e.from<=n&&e.to>=n));return!(!s||s.field==i.active||(t.dispatch({selection:w(i.ranges,s.field),effects:y.of(i.ranges.some((e=>e.field>s.field))?new b(i.ranges,s.field):null),scrollIntoView:!0}),0))}}),_={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},N=i.Py.define({map(e,t){let n=t.mapPos(e,-1,i.gc.TrackAfter);return null==n?void 0:n}}),D=new class extends i.uU{};D.startSide=1,D.endSide=-1;const E=i.QQ.define({create:()=>i.Xs.empty,update(e,t){if(t.selection){let n=t.state.doc.lineAt(t.selection.main.head);e=e.update({filter:e=>e>=n.from&&e<=n.to})}e=e.map(t.changes);for(let n of t.effects)n.is(N)&&(e=e.update({add:[D.range(n.value,n.value+1)]}));return e}});function j(){return[L,E]}const R="()[]{}<>";function P(e){for(let t=0;t{if((B?e.composing:e.compositionStarted)||e.state.readOnly)return!1;let r=e.state.selection.main;if(s.length>2||2==s.length&&1==(0,i.nZ)((0,i.gm)(s,0))||t!=r.from||n!=r.to)return!1;let o=function(e,t){let n=I(e,e.selection.main.head),s=n.brackets||_.brackets;for(let r of s){let o=P((0,i.gm)(r,0));if(t==r)return o==r?W(e,r,s.indexOf(r+r+r)>-1,n):H(e,r,o,n.before||_.before);if(t==o&&z(e,e.selection.main.from))return V(e,0,o)}return null}(e.state,s);return!!o&&(e.dispatch(o),!0)})),$=[{key:"Backspace",run:({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=I(e,e.selection.main.head).brackets||_.brackets,s=null,r=e.changeByRange((t=>{if(t.empty){let s=function(e,t){let n=e.sliceString(t-2,t);return(0,i.nZ)((0,i.gm)(n,0))==n.length?n:n.slice(1)}(e.doc,t.head);for(let r of n)if(r==s&&F(e.doc,t.head)==P((0,i.gm)(r,0)))return{changes:{from:t.head-r.length,to:t.head+r.length},range:i.jT.cursor(t.head-r.length)}}return{range:s=t}}));return s||t(e.update(r,{scrollIntoView:!0,userEvent:"delete.backward"})),!s}}];function z(e,t){let n=!1;return e.field(E).between(0,e.doc.length,(e=>{e==t&&(n=!0)})),n}function F(e,t){let n=e.sliceString(t,t+2);return n.slice(0,(0,i.nZ)((0,i.gm)(n,0)))}function H(e,t,n,s){let r=null,o=e.changeByRange((o=>{if(!o.empty)return{changes:[{insert:t,from:o.from},{insert:n,from:o.to}],effects:N.of(o.to+t.length),range:i.jT.range(o.anchor+t.length,o.head+t.length)};let a=F(e.doc,o.head);return!a||/\s/.test(a)||s.indexOf(a)>-1?{changes:{insert:t+n,from:o.head},effects:N.of(o.head+t.length),range:i.jT.cursor(o.head+t.length)}:{range:r=o}}));return r?null:e.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function V(e,t,n){let s=null,r=e.changeByRange((t=>t.empty&&F(e.doc,t.head)==n?{changes:{from:t.head,to:t.head+n.length,insert:n},range:i.jT.cursor(t.head+n.length)}:s={range:t}));return s?null:e.update(r,{scrollIntoView:!0,userEvent:"input.type"})}function W(e,t,n,s){let o=s.stringPrefixes||_.stringPrefixes,a=null,l=e.changeByRange((s=>{if(!s.empty)return{changes:[{insert:t,from:s.from},{insert:t,from:s.to}],effects:N.of(s.to+t.length),range:i.jT.range(s.anchor+t.length,s.head+t.length)};let l,h=s.head,c=F(e.doc,h);if(c==t){if(q(e,h))return{changes:{insert:t+t,from:h},effects:N.of(h+t.length),range:i.jT.cursor(h+t.length)};if(z(e,h)){let s=n&&e.sliceDoc(h,h+3*t.length)==t+t+t?t+t+t:t;return{changes:{from:h,to:h+s.length,insert:s},range:i.jT.cursor(h+s.length)}}}else{if(n&&e.sliceDoc(h-2*t.length,h)==t+t&&(l=J(e,h-2*t.length,o))>-1&&q(e,l))return{changes:{insert:t+t+t+t,from:h},effects:N.of(h+t.length),range:i.jT.cursor(h+t.length)};if(e.charCategorizer(h)(c)!=i.D0.Word&&J(e,h,o)>-1&&!function(e,t,n,i){let s=(0,r.qz)(e).resolveInner(t,-1),o=i.reduce(((e,t)=>Math.max(e,t.length)),0);for(let r=0;r<5;r++){let r=e.sliceDoc(s.from,Math.min(s.to,s.from+n.length+o)),a=r.indexOf(n);if(!a||a>-1&&i.indexOf(r.slice(0,a))>-1){let t=s.firstChild;for(;t&&t.from==s.from&&t.to-t.from>n.length+a;){if(e.sliceDoc(t.to-n.length,t.to)==n)return!1;t=t.firstChild}return!0}let l=s.to==t&&s.parent;if(!l)break;s=l}return!1}(e,h,t,o))return{changes:{insert:t+t,from:h},effects:N.of(h+t.length),range:i.jT.cursor(h+t.length)}}return{range:a=s}}));return a?null:e.update(l,{scrollIntoView:!0,userEvent:"input.type"})}function q(e,t){let n=(0,r.qz)(e).resolveInner(t+1);return n.parent&&n.from==t}function J(e,t,n){let s=e.charCategorizer(t);if(s(e.sliceDoc(t-1,t))!=i.D0.Word)return t;for(let r of n){let n=t-r.length;if(e.sliceDoc(n,t)==r&&s(e.sliceDoc(n-1,n))!=i.D0.Word)return n}return-1}},77120:(e,t,n)=>{"use strict";n.d(t,{Be:()=>y,Dv:()=>U,Gn:()=>E,K0:()=>D,KC:()=>u,Qf:()=>fe,R_:()=>ve,SQ:()=>f,SS:()=>N,Um:()=>Ee,a0:()=>_e,c:()=>T,c6:()=>O,il:()=>Le,kU:()=>c,mi:()=>ce,n$:()=>Te,nF:()=>ge,nY:()=>W,pp:()=>h,qp:()=>p,qz:()=>m,ri:()=>C,rs:()=>q,tC:()=>H,uj:()=>j,vw:()=>$,x0:()=>J,y1:()=>_,ze:()=>F});var i,s=n(21649),r=n(1727),o=n(65329),a=n(86253),l=n(37207);const h=new s.md;function c(e){return r.r$.define({combine:e?t=>t.concat(e):void 0})}const u=new s.md;class f{constructor(e,t,n=[],i=""){this.data=e,this.name=i,r.yy.prototype.hasOwnProperty("tree")||Object.defineProperty(r.yy.prototype,"tree",{get(){return m(this)}}),this.parser=t,this.extension=[A.of(this),r.yy.languageData.of(((e,t,n)=>{let i=d(e,t,n),s=i.type.prop(h);if(!s)return[];let r=e.facet(s),o=i.type.prop(u);if(o){let s=i.resolve(t-i.from,n);for(let t of o)if(t.test(s,e)){let n=e.facet(t.facet);return"replace"==t.type?n:n.concat(r)}}return r}))].concat(n)}isActiveAt(e,t,n=-1){return d(e,t,n).type.prop(h)==this.data}findRegions(e){let t=e.facet(A);if((null==t?void 0:t.data)==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let n=[],i=(e,t)=>{if(e.prop(h)==this.data)return void n.push({from:t,to:t+e.length});let r=e.prop(s.md.mounted);if(r){if(r.tree.prop(h)==this.data){if(r.overlay)for(let e of r.overlay)n.push({from:e.from+t,to:e.to+t});else n.push({from:t,to:t+e.length});return}if(r.overlay){let e=n.length;if(i(r.tree,r.overlay[0].from+t),n.length>e)return}}for(let n=0;ne.isTop?t:void 0))]}),e.name)}configure(e,t){return new p(this.data,this.parser.configure(e),t||this.name)}get allowsNesting(){return this.parser.hasWrappers()}}function m(e){let t=e.field(f.state,!1);return t?t.tree:s.mp.empty}class g{constructor(e){this.doc=e,this.cursorPos=0,this.string="",this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let n=this.cursorPos-this.string.length;return e=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-n,t-n)}}let b=null;class y{constructor(e,t,n=[],i,s,r,o,a){this.parser=e,this.state=t,this.fragments=n,this.tree=i,this.treeLen=s,this.viewport=r,this.skipped=o,this.scheduleOn=a,this.parse=null,this.tempSkipped=[]}static create(e,t,n){return new y(e,t,[],s.mp.empty,0,n,[],null)}startParse(){return this.parser.startParse(new g(this.state.doc),this.fragments)}work(e,t){return null!=t&&t>=this.state.doc.length&&(t=void 0),this.tree!=s.mp.empty&&this.isDone(null!=t?t:this.state.doc.length)?(this.takeTree(),!0):this.withContext((()=>{var n;if("number"==typeof e){let t=Date.now()+e;e=()=>Date.now()>t}for(this.parse||(this.parse=this.startParse()),null!=t&&(null==this.parse.stoppedAt||this.parse.stoppedAt>t)&&t=this.treeLen&&((null==this.parse.stoppedAt||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext((()=>{for(;!(t=this.parse.advance()););})),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(s.i9.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=b;b=this;try{return e()}finally{b=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=v(e,t.from,t.to);return e}changes(e,t){let{fragments:n,tree:i,treeLen:r,viewport:o,skipped:a}=this;if(this.takeTree(),!e.empty){let t=[];if(e.iterChangedRanges(((e,n,i,s)=>t.push({fromA:e,toA:n,fromB:i,toB:s}))),n=s.i9.applyChanges(n,t),i=s.mp.empty,r=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){a=[];for(let t of this.skipped){let n=e.mapPos(t.from,1),i=e.mapPos(t.to,-1);ne.from&&(this.fragments=v(this.fragments,n,i),this.skipped.splice(t--,1))}return!(this.skipped.length>=t||(this.reset(),0))}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends s._b{createParse(t,n,i){let r=i[0].from,o=i[i.length-1].to;return{parsedPos:r,advance(){let t=b;if(t){for(let e of i)t.tempSkipped.push(e);e&&(t.scheduleOn=t.scheduleOn?Promise.all([t.scheduleOn,e]):e)}return this.parsedPos=o,new s.mp(s.Jq.none,[],[],o-r)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&0==t[0].from&&t[0].to>=e}static get(){return b}}function v(e,t,n){return s.i9.applyChanges(e,[{fromA:t,toA:n,fromB:t,toB:n}])}class x{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let t=this.context.changes(e.changes,e.state),n=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,n)||t.takeTree(),new x(t)}static init(e){let t=Math.min(3e3,e.doc.length),n=y.create(e.facet(A).parser,e,{from:0,to:t});return n.work(20,t)||n.takeTree(),new x(n)}}f.state=r.QQ.define({create:x.init,update(e,t){for(let e of t.effects)if(e.is(f.setState))return e.value;return t.startState.facet(A)!=t.state.facet(A)?x.init(t.state):e.apply(t)}});let w=e=>{let t=setTimeout((()=>e()),500);return()=>clearTimeout(t)};"undefined"!=typeof requestIdleCallback&&(w=e=>{let t=-1,n=setTimeout((()=>{t=requestIdleCallback(e,{timeout:400})}),100);return()=>t<0?clearTimeout(n):cancelIdleCallback(t)});const k="undefined"!=typeof navigator&&(null===(i=navigator.scheduling)||void 0===i?void 0:i.isInputPending)?()=>navigator.scheduling.isInputPending():null,S=o.lg.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(f.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(f.state);t.tree==t.context.tree&&t.context.isDone(e.doc.length)||(this.working=w(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEndi+1e3,a=s.context.work((()=>k&&k()||Date.now()>r),i+(o?0:1e5));this.chunkBudget-=Date.now()-t,(a||this.chunkBudget<=0)&&(s.context.takeTree(),this.view.dispatch({effects:f.setState.of(new x(s.context))})),this.chunkBudget>0&&(!a||o)&&this.scheduleWork(),this.checkAsyncSchedule(s.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then((()=>this.scheduleWork())).catch((e=>(0,o.OO)(this.view.state,e))).then((()=>this.workScheduled--)),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),A=r.r$.define({combine:e=>e.length?e[0]:null,enables:e=>[f.state,S,o.tk.contentAttributes.compute([e],(t=>{let n=t.facet(e);return n&&n.name?{"data-language":n.name}:{}}))]});class C{constructor(e,t=[]){this.language=e,this.support=t,this.extension=[e,t]}}class O{constructor(e,t,n,i,s,r=undefined){this.name=e,this.alias=t,this.extensions=n,this.filename=i,this.loadFunc=s,this.support=r,this.loading=null}load(){return this.loading||(this.loading=this.loadFunc().then((e=>this.support=e),(e=>{throw this.loading=null,e})))}static of(e){let{load:t,support:n}=e;if(!t){if(!n)throw new RangeError("Must pass either 'load' or 'support' to LanguageDescription.of");t=()=>Promise.resolve(n)}return new O(e.name,(e.alias||[]).concat(e.name).map((e=>e.toLowerCase())),e.extensions||[],e.filename,t,n)}static matchFilename(e,t){for(let n of e)if(n.filename&&n.filename.test(t))return n;let n=/\.([^.]+)$/.exec(t);if(n)for(let t of e)if(t.extensions.indexOf(n[1])>-1)return t;return null}static matchLanguageName(e,t,n=!0){t=t.toLowerCase();for(let n of e)if(n.alias.some((e=>e==t)))return n;if(n)for(let n of e)for(let e of n.alias){let i=t.indexOf(e);if(i>-1&&(e.length>2||!/\w/.test(t[i-1])&&!/\w/.test(t[i+e.length])))return n}return null}}const M=r.r$.define(),T=r.r$.define({combine:e=>{if(!e.length)return" ";let t=e[0];if(!t||/\S/.test(t)||Array.from(t).some((e=>e!=t[0])))throw new Error("Invalid indent unit: "+JSON.stringify(e[0]));return t}});function _(e){let t=e.facet(T);return 9==t.charCodeAt(0)?e.tabSize*t.length:t.length}function N(e,t){let n="",i=e.tabSize,s=e.facet(T)[0];if("\t"==s){for(;t>=i;)n+="\t",t-=i;s=" "}for(let e=0;e=t?function(e,t,n){let i=t.resolveStack(n),s=i.node.enterUnfinishedNodesBefore(n);if(s!=i.node){let e=[];for(let t=s;t!=i.node;t=t.parent)e.push(t);for(let t=e.length-1;t>=0;t--)i={node:e[t],next:i}}return R(i,e,n)}(e,n,t):null}class E{constructor(e,t={}){this.state=e,this.options=t,this.unit=_(e)}lineAt(e,t=1){let n=this.state.doc.lineAt(e),{simulateBreak:i,simulateDoubleBreak:s}=this.options;return null!=i&&i>=n.from&&i<=n.to?s&&i==e?{text:"",from:e}:(t<0?i-1&&(s+=r-this.countColumn(n,n.search(/\S|$/))),s}countColumn(e,t=e.length){return(0,r.IS)(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:n,from:i}=this.lineAt(e,t),s=this.options.overrideIndentation;if(s){let e=s(i);if(e>-1)return e}return this.countColumn(n,n.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const j=new s.md;function R(e,t,n){for(let i=e;i;i=i.next){let e=P(i.node);if(e)return e(B.create(t,n,i))}return 0}function P(e){let t=e.type.prop(j);if(t)return t;let n,i=e.firstChild;if(i&&(n=i.type.prop(s.md.closedBy))){let t=e.lastChild,i=t&&n.indexOf(t.name)>-1;return e=>z(e,!0,1,void 0,i&&!function(e){return e.pos==e.options.simulateBreak&&e.options.simulateDoubleBreak}(e)?t.from:void 0)}return null==e.parent?I:null}function I(){return 0}class B extends E{constructor(e,t,n){super(e.state,e.options),this.base=e,this.pos=t,this.context=n}get node(){return this.context.node}static create(e,t,n){return new B(e,t,n)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(e){let t=this.state.doc.lineAt(e.from);for(;;){let n=e.resolve(t.from);for(;n.parent&&n.parent.from==n.from;)n=n.parent;if(L(n,e))break;t=this.state.doc.lineAt(n.from)}return this.lineIndent(t.from)}continue(){return R(this.context.next,this.base,this.pos)}}function L(e,t){for(let n=t;n;n=n.parent)if(e==n)return!0;return!1}function $({closing:e,align:t=!0,units:n=1}){return i=>z(i,t,n,e)}function z(e,t,n,i,s){let r=e.textAfter,o=r.match(/^\s*/)[0].length,a=i&&r.slice(o,o+i.length)==i||s==e.pos+o,l=t?function(e){let t=e.node,n=t.childAfter(t.from),i=t.lastChild;if(!n)return null;let s=e.options.simulateBreak,r=e.state.doc.lineAt(n.from),o=null==s||s<=r.from?r.to:Math.min(r.to,s);for(let e=n.to;;){let s=t.childAfter(e);if(!s||s==i)return null;if(!s.type.isSkipped)return s.frome.baseIndent;function H({except:e,units:t=1}={}){return n=>{let i=e&&e.test(n.textAfter);return n.baseIndent+(i?0:t*n.unit)}}const V=200;function W(){return r.yy.transactionFilter.of((e=>{if(!e.docChanged||!e.isUserEvent("input.type")&&!e.isUserEvent("input.complete"))return e;let t=e.startState.languageDataAt("indentOnInput",e.startState.selection.main.head);if(!t.length)return e;let n=e.newDoc,{head:i}=e.newSelection.main,s=n.lineAt(i);if(i>s.from+V)return e;let r=n.sliceString(s.from,i);if(!t.some((e=>e.test(r))))return e;let{state:o}=e,a=-1,l=[];for(let{head:e}of o.selection.ranges){let t=o.doc.lineAt(e);if(t.from==a)continue;a=t.from;let n=D(o,t.from);if(null==n)continue;let i=/^\s*/.exec(t.text)[0],s=N(o,n);i!=s&&l.push({from:t.from,to:t.from+i.length,insert:s})}return l.length?[e,{changes:l,sequential:!0}]:e}))}const q=r.r$.define(),J=new s.md;function U(e){let t=e.firstChild,n=e.lastChild;return t&&t.ton)continue;if(s&&o.from=t&&i.to>n&&(s=i)}}return s}(e,t,n)}function Y(e,t){let n=t.mapPos(e.from,1),i=t.mapPos(e.to,-1);return n>=i?void 0:{from:n,to:i}}const X=r.Py.define({map:Y}),Q=r.Py.define({map:Y}),Z=r.QQ.define({create:()=>o.p.none,update(e,t){e=e.map(t.changes);for(let n of t.effects)if(n.is(X)&&!te(e,n.value.from,n.value.to)){let{preparePlaceholder:i}=t.state.facet(ie),s=i?o.p.replace({widget:new ae(i(t.state,n.value))}):oe;e=e.update({add:[s.range(n.value.from,n.value.to)]})}else n.is(Q)&&(e=e.update({filter:(e,t)=>n.value.from!=e||n.value.to!=t,filterFrom:n.value.from,filterTo:n.value.to}));if(t.selection){let n=!1,{head:i}=t.selection.main;e.between(i,i,((e,t)=>{ei&&(n=!0)})),n&&(e=e.update({filterFrom:i,filterTo:i,filter:(e,t)=>t<=i||e>=i}))}return e},provide:e=>o.tk.decorations.from(e),toJSON(e,t){let n=[];return e.between(0,t.doc.length,((e,t)=>{n.push(e,t)})),n},fromJSON(e){if(!Array.isArray(e)||e.length%2)throw new RangeError("Invalid JSON for fold state");let t=[];for(let n=0;n{(!s||s.from>e)&&(s={from:e,to:t})})),s}function te(e,t,n){let i=!1;return e.between(t,t,((e,s)=>{e==t&&s==n&&(i=!0)})),i}const ne={placeholderDOM:null,preparePlaceholder:null,placeholderText:"…"},ie=r.r$.define({combine:e=>(0,r.BO)(e,ne)});function se(e){let t=[Z,ue];return e&&t.push(ie.of(e)),t}function re(e,t){let{state:n}=e,i=n.facet(ie),s=t=>{let n=e.lineBlockAt(e.posAtDOM(t.target)),i=ee(e.state,n.from,n.to);i&&e.dispatch({effects:Q.of(i)}),t.preventDefault()};if(i.placeholderDOM)return i.placeholderDOM(e,s,t);let r=document.createElement("span");return r.textContent=i.placeholderText,r.setAttribute("aria-label",n.phrase("folded code")),r.title=n.phrase("unfold"),r.className="cm-foldPlaceholder",r.onclick=s,r}const oe=o.p.replace({widget:new class extends o.l9{toDOM(e){return re(e,null)}}});class ae extends o.l9{constructor(e){super(),this.value=e}eq(e){return this.value==e.value}toDOM(e){return re(e,this.value)}}const le={openText:"⌄",closedText:"›",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1};class he extends o.SJ{constructor(e,t){super(),this.config=e,this.open=t}eq(e){return this.config==e.config&&this.open==e.open}toDOM(e){if(this.config.markerDOM)return this.config.markerDOM(this.open);let t=document.createElement("span");return t.textContent=this.open?this.config.openText:this.config.closedText,t.title=e.state.phrase(this.open?"Fold line":"Unfold line"),t}}function ce(e={}){let t=Object.assign(Object.assign({},le),e),n=new he(t,!0),i=new he(t,!1),s=o.lg.fromClass(class{constructor(e){this.from=e.viewport.from,this.markers=this.buildMarkers(e)}update(e){(e.docChanged||e.viewportChanged||e.startState.facet(A)!=e.state.facet(A)||e.startState.field(Z,!1)!=e.state.field(Z,!1)||m(e.startState)!=m(e.state)||t.foldingChanged(e))&&(this.markers=this.buildMarkers(e.view))}buildMarkers(e){let t=new r.f_;for(let s of e.viewportLineBlocks){let r=ee(e.state,s.from,s.to)?i:K(e.state,s.from,s.to)?n:null;r&&t.add(s.from,s.from,r)}return t.finish()}}),{domEventHandlers:a}=t;return[s,(0,o.v5)({class:"cm-foldGutter",markers(e){var t;return(null===(t=e.plugin(s))||void 0===t?void 0:t.markers)||r.Xs.empty},initialSpacer:()=>new he(t,!1),domEventHandlers:Object.assign(Object.assign({},a),{click:(e,t,n)=>{if(a.click&&a.click(e,t,n))return!0;let i=ee(e.state,t.from,t.to);if(i)return e.dispatch({effects:Q.of(i)}),!0;let s=K(e.state,t.from,t.to);return!!s&&(e.dispatch({effects:X.of(s)}),!0)}})}),se()]}const ue=o.tk.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}});class fe{constructor(e,t){let n;function i(e){let t=l.V.newName();return(n||(n=Object.create(null)))["."+t]=e,t}this.specs=e;const s="string"==typeof t.all?t.all:t.all?i(t.all):void 0,r=t.scope;this.scope=r instanceof f?e=>e.prop(h)==r.data:r?e=>e==r:void 0,this.style=(0,a.QR)(e.map((e=>({tag:e.tag,class:e.class||i(Object.assign({},e,{tag:null}))}))),{all:s}).style,this.module=n?new l.V(n):null,this.themeType=t.themeType}static define(e,t){return new fe(e,t||{})}}const de=r.r$.define(),pe=r.r$.define({combine:e=>e.length?[e[0]]:null});function me(e){let t=e.facet(de);return t.length?t:e.facet(pe)}function ge(e,t){let n,i=[ye];return e instanceof fe&&(e.module&&i.push(o.tk.styleModule.of(e.module)),n=e.themeType),(null==t?void 0:t.fallback)?i.push(pe.of(e)):n?i.push(de.computeN([o.tk.darkTheme],(t=>t.facet(o.tk.darkTheme)==("dark"==n)?[e]:[]))):i.push(de.of(e)),i}class be{constructor(e){this.markCache=Object.create(null),this.tree=m(e.state),this.decorations=this.buildDeco(e,me(e.state))}update(e){let t=m(e.state),n=me(e.state),i=n!=me(e.startState);t.length{n.add(e,t,this.markCache[i]||(this.markCache[i]=o.p.mark({class:i})))}),i,s);return n.finish()}}const ye=r.Wl.high(o.lg.fromClass(be,{decorations:e=>e.decorations})),ve=fe.define([{tag:a.pJ.meta,color:"#404740"},{tag:a.pJ.link,textDecoration:"underline"},{tag:a.pJ.heading,textDecoration:"underline",fontWeight:"bold"},{tag:a.pJ.emphasis,fontStyle:"italic"},{tag:a.pJ.strong,fontWeight:"bold"},{tag:a.pJ.strikethrough,textDecoration:"line-through"},{tag:a.pJ.keyword,color:"#708"},{tag:[a.pJ.atom,a.pJ.bool,a.pJ.url,a.pJ.contentSeparator,a.pJ.labelName],color:"#219"},{tag:[a.pJ.literal,a.pJ.inserted],color:"#164"},{tag:[a.pJ.string,a.pJ.deleted],color:"#a11"},{tag:[a.pJ.regexp,a.pJ.escape,a.pJ.special(a.pJ.string)],color:"#e40"},{tag:a.pJ.definition(a.pJ.variableName),color:"#00f"},{tag:a.pJ.local(a.pJ.variableName),color:"#30a"},{tag:[a.pJ.typeName,a.pJ.namespace],color:"#085"},{tag:a.pJ.className,color:"#167"},{tag:[a.pJ.special(a.pJ.variableName),a.pJ.macroName],color:"#256"},{tag:a.pJ.definition(a.pJ.propertyName),color:"#00c"},{tag:a.pJ.comment,color:"#940"},{tag:a.pJ.invalid,color:"#f00"}]),xe=o.tk.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),we=1e4,ke="()[]{}",Se=r.r$.define({combine:e=>(0,r.BO)(e,{afterCursor:!0,brackets:ke,maxScanDistance:we,renderMatch:Oe})}),Ae=o.p.mark({class:"cm-matchingBracket"}),Ce=o.p.mark({class:"cm-nonmatchingBracket"});function Oe(e){let t=[],n=e.matched?Ae:Ce;return t.push(n.range(e.start.from,e.start.to)),e.end&&t.push(n.range(e.end.from,e.end.to)),t}const Me=[r.QQ.define({create:()=>o.p.none,update(e,t){if(!t.docChanged&&!t.selection)return e;let n=[],i=t.state.facet(Se);for(let e of t.state.selection.ranges){if(!e.empty)continue;let s=Ee(t.state,e.head,-1,i)||e.head>0&&Ee(t.state,e.head-1,1,i)||i.afterCursor&&(Ee(t.state,e.head,1,i)||e.heado.tk.decorations.from(e)}),xe];function Te(e={}){return[Se.of(e),Me]}const _e=new s.md;function Ne(e,t,n){let i=e.prop(t<0?s.md.openedBy:s.md.closedBy);if(i)return i;if(1==e.name.length){let i=n.indexOf(e.name);if(i>-1&&i%2==(t<0?1:0))return[n[i+t]]}return null}function De(e){let t=e.type.prop(_e);return t?t(e.node):e}function Ee(e,t,n,i={}){let s=i.maxScanDistance||we,r=i.brackets||ke,o=m(e),a=o.resolveInner(t,n);for(let e=a;e;e=e.parent){let i=Ne(e.type,n,r);if(i&&e.from0?t>=s.from&&ts.from&&t<=s.to))return je(0,0,n,e,s,i,r)}}return function(e,t,n,i,s,r,o){let a=n<0?e.sliceDoc(t-1,t):e.sliceDoc(t,t+1),l=o.indexOf(a);if(l<0||l%2==0!=n>0)return null;let h={from:n<0?t-1:t,to:n>0?t+1:t},c=e.doc.iterRange(t,n>0?e.doc.length:0),u=0;for(let e=0;!c.next().done&&e<=r;){let r=c.value;n<0&&(e+=r.length);let a=t+e*n;for(let e=n>0?0:r.length-1,t=n>0?r.length:-1;e!=t;e+=n){let t=o.indexOf(r[e]);if(!(t<0||i.resolveInner(a+e,1).type!=s))if(t%2==0==n>0)u++;else{if(1==u)return{start:h,end:{from:a+e,to:a+e+1},matched:t>>1==l>>1};u--}}n>0&&(e+=r.length)}return c.done?{start:h,matched:!1}:null}(e,t,n,o,a.type,s,r)}function je(e,t,n,i,s,r,o){let a=i.parent,l={from:s.from,to:s.to},h=0,c=null==a?void 0:a.cursor();if(c&&(n<0?c.childBefore(i.from):c.childAfter(i.to)))do{if(n<0?c.to<=i.from:c.from>=i.to){if(0==h&&r.indexOf(c.type.name)>-1&&c.from=this.string.length}sol(){return 0==this.pos}peek(){return this.string.charAt(this.pos)||void 0}next(){if(this.post}eatSpace(){let e=this.pos;for(;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e}skipToEnd(){this.pos=this.string.length}skipTo(e){let t=this.string.indexOf(e,this.pos);if(t>-1)return this.pos=t,!0}backUp(e){this.pos-=e}column(){return this.lastColumnPosn?e.toLowerCase():e;return i(this.string.substr(this.pos,e.length))==i(e)?(!1!==t&&(this.pos+=e.length),!0):null}{let n=this.string.slice(this.pos).match(e);return n&&n.index>0?null:(n&&!1!==t&&(this.pos+=n[0].length),n)}}current(){return this.string.slice(this.start,this.pos)}}function Ie(e){if("object"!=typeof e)return e;let t={};for(let n in e){let i=e[n];t[n]=i instanceof Array?i.slice():i}return t}const Be=new WeakMap;class Le extends f{constructor(e){let t,n=c(e.languageData),i={name:(r=e).name||"",token:r.token,blankLine:r.blankLine||(()=>{}),startState:r.startState||(()=>!0),copyState:r.copyState||Ie,indent:r.indent||(()=>null),languageData:r.languageData||{},tokenTable:r.tokenTable||Ve};var r;super(n,new class extends s._b{createParse(e,n,i){return new Fe(t,e,n,i)}},[M.of(((e,t)=>this.getIndent(e,t)))],e.name),this.topNode=function(e){let t=s.Jq.define({id:We.length,name:"Document",props:[h.add((()=>e))],top:!0});return We.push(t),t}(n),t=this,this.streamParser=i,this.stateAfter=new s.md({perNode:!0}),this.tokenTable=e.tokenTable?new Ge(i.tokenTable):Ke}static define(e){return new Le(e)}getIndent(e,t){let n,i=m(e.state),s=i.resolve(t);for(;s&&s.type!=this.topNode;)s=s.parent;if(!s)return null;let{overrideIndentation:r}=e.options;r&&(n=Be.get(e.state),null!=n&&n1e4)return null;for(;o=i&&n+t.length<=r&&t.prop(e.stateAfter);if(o)return{state:e.streamParser.copyState(o),pos:n+t.length};for(let o=t.children.length-1;o>=0;o--){let a=t.children[o],l=n+t.positions[o],h=a instanceof s.mp&&l=t.length)return t;r||t.type!=e.topNode||(r=!0);for(let o=t.children.length-1;o>=0;o--){let a,l=t.positions[o],h=t.children[o];if(ln&&$e(e,i.tree,0-i.offset,n,r);if(o&&(t=ze(e,i.tree,n+i.offset,o.pos+i.offset,!1)))return{state:o.state,tree:t}}return{state:e.streamParser.startState(i?_(i):4),tree:s.mp.empty}}(e,n,o,null==r?void 0:r.state);this.state=a,this.parsedPos=this.chunkStart=o+l.length;for(let e=0;e=t?this.finish():e&&this.parsedPos>=e.viewport.to?(e.skipUntilInView(this.parsedPos,t),this.finish()):null}stopAt(e){this.stoppedAt=e}lineAfter(e){let t=this.input.chunk(e);if(this.input.lineChunks)"\n"==t&&(t="");else{let e=t.indexOf("\n");e>-1&&(t=t.slice(0,e))}return e+t.length<=this.to?t:t.slice(0,this.to-e)}nextLine(){let e=this.parsedPos,t=this.lineAfter(e),n=e+t.length;for(let e=this.rangeIndex;;){let i=this.ranges[e].to;if(i>=n)break;if(t=t.slice(0,i-(n-t.length)),e++,e==this.ranges.length)break;let s=this.ranges[e].from,r=this.lineAfter(s);t+=r,n=s+r.length}return{line:t,end:n}}skipGapsTo(e,t,n){for(;;){let i=this.ranges[this.rangeIndex].to,s=e+t;if(n>0?i>s:i>=s)break;t+=this.ranges[++this.rangeIndex].from-i}return t}moveRangeIndex(){for(;this.ranges[this.rangeIndex].to1){t+=s=this.skipGapsTo(t,s,1);let e=this.chunk.length;n+=s=this.skipGapsTo(n,s,-1),i+=this.chunk.length-e}return this.chunk.push(e,t,n,i),s}parseLine(e){let{line:t,end:n}=this.nextLine(),i=0,{streamParser:s}=this.lang,r=new Pe(t,e?e.state.tabSize:4,e?_(e.state):2);if(r.eol())s.blankLine(this.state,r.indentUnit);else for(;!r.eol();){let e=He(s.token,r,this.state);if(e&&(i=this.emitToken(this.lang.tokenTable.resolve(e),this.parsedPos+r.start,this.parsedPos+r.pos,4,i)),r.start>1e4)break}this.parsedPos=n,this.moveRangeIndex(),this.parsedPost.start)return i}throw new Error("Stream parser failed to advance stream.")}const Ve=Object.create(null),We=[s.Jq.none],qe=new s.Lj(We),Je=[],Ue=Object.create(null);for(let[e,t]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])Ue[e]=Xe(Ve,t);class Ge{constructor(e){this.extra=e,this.table=Object.assign(Object.create(null),Ue)}resolve(e){return e?this.table[e]||(this.table[e]=Xe(this.extra,e)):0}}const Ke=new Ge(Ve);function Ye(e,t){Je.indexOf(e)>-1||(Je.push(e),console.warn(t))}function Xe(e,t){let n=[];for(let i of t.split(" ")){let t=[];for(let n of i.split(".")){let i=e[n]||a.pJ[n];i?"function"==typeof i?t.length?t=t.map(i):Ye(n,`Modifier ${n} used at start of tag`):t.length?Ye(n,`Tag ${n} used as modifier`):t=Array.isArray(i)?i:[i]:Ye(n,`Unknown highlighting tag ${n}`)}for(let e of t)n.push(e)}if(!n.length)return 0;let i=t.replace(/ /g,"_"),r=s.Jq.define({id:We.length,name:i,props:[(0,a.Gv)({[i]:n})]});return We.push(r),r.id}},1727:(e,t,n)=>{"use strict";n.d(t,{BO:()=>Oe,D0:()=>ke,F6:()=>Z,Gz:()=>We,IS:()=>Ve,Py:()=>pe,QQ:()=>q,Wl:()=>X,Xs:()=>De,YW:()=>me,as:()=>M,bg:()=>k,cp:()=>g,f_:()=>Ee,gc:()=>C,gm:()=>w,jT:()=>P,n0:()=>O,nZ:()=>S,q6:()=>ue,r$:()=>L,uU:()=>Me,xv:()=>i,yy:()=>Ce});class i{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,n){let i=[];return this.decompose(0,e,i,2),n.length&&n.decompose(0,n.length,i,3),this.decompose(t,this.length,i,1),r.from(i,this.length-(t-e)+n.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){let n=[];return this.decompose(e,t,n,0),r.from(n,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),n=this.length-this.scanIdentical(e,-1),i=new l(this),s=new l(e);for(let e=t,r=t;;){if(i.next(e),s.next(e),e=0,i.lineBreak!=s.lineBreak||i.done!=s.done||i.value!=s.value)return!1;if(r+=i.value.length,i.done||r>=n)return!0}}iter(e=1){return new l(this,e)}iterRange(e,t=this.length){return new h(this,e,t)}iterLines(e,t){let n;if(null==e)n=this.iter();else{null==t&&(t=this.lines+1);let i=this.line(e).from;n=this.iterRange(i,Math.max(i,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new c(n)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(0==e.length)throw new RangeError("A document must have at least one line");return 1!=e.length||e[0]?e.length<=32?new s(e):r.from(s.split(e,[])):i.empty}}class s extends i{constructor(e,t=function(e){let t=-1;for(let n of e)t+=n.length+1;return t}(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,n,i){for(let s=0;;s++){let r=this.text[s],o=i+r.length;if((t?n:o)>=e)return new u(i,o,n,r);i=o+1,n++}}decompose(e,t,n,i){let r=e<=0&&t>=this.length?this:new s(a(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(1&i){let e=n.pop(),t=o(r.text,e.text.slice(),0,r.length);if(t.length<=32)n.push(new s(t,e.length+r.length));else{let e=t.length>>1;n.push(new s(t.slice(0,e)),new s(t.slice(e)))}}else n.push(r)}replace(e,t,n){if(!(n instanceof s))return super.replace(e,t,n);let i=o(this.text,o(n.text,a(this.text,0,e)),t),l=this.length+n.length-(t-e);return i.length<=32?new s(i,l):r.from(s.split(i,[]),l)}sliceString(e,t=this.length,n="\n"){let i="";for(let s=0,r=0;s<=t&&re&&r&&(i+=n),es&&(i+=o.slice(Math.max(0,e-s),t-s)),s=a+1}return i}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let n=[],i=-1;for(let r of e)n.push(r),i+=r.length+1,32==n.length&&(t.push(new s(n,i)),n=[],i=-1);return i>-1&&t.push(new s(n,i)),t}}class r extends i{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let t of e)this.lines+=t.lines}lineInner(e,t,n,i){for(let s=0;;s++){let r=this.children[s],o=i+r.length,a=n+r.lines-1;if((t?a:o)>=e)return r.lineInner(e,t,n,i);i=o+1,n=a+1}}decompose(e,t,n,i){for(let s=0,r=0;r<=t&&s=r){let s=i&((r<=e?1:0)|(a>=t?2:0));r>=e&&a<=t&&!s?n.push(o):o.decompose(e-r,t-r,n,s)}r=a+1}}replace(e,t,n){if(n.lines=s&&t<=a){let l=o.replace(e-s,t-s,n),h=this.lines-o.lines+l.lines;if(l.lines>4&&l.lines>h>>6){let s=this.children.slice();return s[i]=l,new r(s,this.length-(t-e)+n.length)}return super.replace(s,a,l)}s=a+1}return super.replace(e,t,n)}sliceString(e,t=this.length,n="\n"){let i="";for(let s=0,r=0;se&&s&&(i+=n),er&&(i+=o.sliceString(e-r,t-r,n)),r=a+1}return i}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof r))return 0;let n=0,[i,s,o,a]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;i+=t,s+=t){if(i==o||s==a)return n;let r=this.children[i],l=e.children[s];if(r!=l)return n+r.scanIdentical(l,t);n+=r.length+1}}static from(e,t=e.reduce(((e,t)=>e+t.length+1),-1)){let n=0;for(let t of e)n+=t.lines;if(n<32){let n=[];for(let t of e)t.flatten(n);return new s(n,t)}let i=Math.max(32,n>>5),o=i<<1,a=i>>1,l=[],h=0,c=-1,u=[];function f(e){let t;if(e.lines>o&&e instanceof r)for(let t of e.children)f(t);else e.lines>a&&(h>a||!h)?(d(),l.push(e)):e instanceof s&&h&&(t=u[u.length-1])instanceof s&&e.lines+t.lines<=32?(h+=e.lines,c+=e.length+1,u[u.length-1]=new s(t.text.concat(e.text),t.length+1+e.length)):(h+e.lines>i&&d(),h+=e.lines,c+=e.length+1,u.push(e))}function d(){0!=h&&(l.push(1==u.length?u[0]:r.from(u,c)),c=-1,h=u.length=0)}for(let t of e)f(t);return d(),1==l.length?l[0]:new r(l,t)}}function o(e,t,n=0,i=1e9){for(let s=0,r=0,o=!0;r=n&&(l>i&&(a=a.slice(0,i-s)),s0?1:(e instanceof s?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let n=this.nodes.length-1,i=this.nodes[n],r=this.offsets[n],o=r>>1,a=i instanceof s?i.text.length:i.children.length;if(o==(t>0?a:0)){if(0==n)return this.done=!0,this.value="",this;t>0&&this.offsets[n-1]++,this.nodes.pop(),this.offsets.pop()}else if((1&r)==(t>0?0:1)){if(this.offsets[n]+=t,0==e)return this.lineBreak=!0,this.value="\n",this;e--}else if(i instanceof s){let s=i.text[o+(t<0?-1:0)];if(this.offsets[n]+=t,s.length>Math.max(0,e))return this.value=0==e?s:t>0?s.slice(e):s.slice(0,s.length-e),this;e-=s.length}else{let r=i.children[o+(t<0?-1:0)];e>r.length?(e-=r.length,this.offsets[n]+=t):(t<0&&this.offsets[n]--,this.nodes.push(r),this.offsets.push(t>0?1:(r instanceof s?r.text.length:r.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class h{constructor(e,t,n){this.value="",this.done=!1,this.cursor=new l(e,t>n?-1:1),this.pos=t>n?e.length:0,this.from=Math.min(t,n),this.to=Math.max(t,n)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let n=t<0?this.pos-this.from:this.to-this.pos;e>n&&(e=n),n-=e;let{value:i}=this.cursor.next(e);return this.pos+=(i.length+e)*t,this.value=i.length<=n?i:t<0?i.slice(i.length-n):i.slice(0,n),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&""!=this.value}}class c{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:n,value:i}=this.inner.next(e);return t?(this.done=!0,this.value=""):n?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=i,this.afterBreak=!1),this}get lineBreak(){return!1}}"undefined"!=typeof Symbol&&(i.prototype[Symbol.iterator]=function(){return this.iter()},l.prototype[Symbol.iterator]=h.prototype[Symbol.iterator]=c.prototype[Symbol.iterator]=function(){return this});class u{constructor(e,t,n,i){this.from=e,this.to=t,this.number=n,this.text=i}get length(){return this.to-this.from}}let f="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map((e=>e?parseInt(e,36):1));for(let e=1;ee)return f[t-1]<=e;return!1}function p(e){return e>=127462&&e<=127487}const m=8205;function g(e,t,n=!0,i=!0){return(n?b:y)(e,t,i)}function b(e,t,n){if(t==e.length)return t;t&&v(e.charCodeAt(t))&&x(e.charCodeAt(t-1))&&t--;let i=w(e,t);for(t+=S(i);t=0&&p(w(e,i));)n++,i-=2;if(n%2==0)break;t+=2}}}return t}function y(e,t,n){for(;t>0;){let i=b(e,t-2,n);if(i=56320&&e<57344}function x(e){return e>=55296&&e<56320}function w(e,t){let n=e.charCodeAt(t);if(!x(n)||t+1==e.length)return n;let i=e.charCodeAt(t+1);return v(i)?i-56320+(n-55296<<10)+65536:n}function k(e){return e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode(55296+(e>>10),56320+(1023&e)))}function S(e){return e<65536?1:2}const A=/\r\n?|\n/;var C=function(e){return e[e.Simple=0]="Simple",e[e.TrackDel=1]="TrackDel",e[e.TrackBefore=2]="TrackBefore",e[e.TrackAfter=3]="TrackAfter",e}(C||(C={}));class O{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-i);s+=o}else{if(n!=C.Simple&&l>=e&&(n==C.TrackDel&&ie||n==C.TrackBefore&&ie))return null;if(l>e||l==e&&t<0&&!o)return e==i||t<0?s:s+a;s+=a}i=l}if(e>i)throw new RangeError(`Position ${e} is out of range for changeset of length ${i}`);return s}touchesRange(e,t=e){for(let n=0,i=0;n=0&&i<=t&&s>=e)return!(it)||"cover";i=s}return!1}toString(){let e="";for(let t=0;t=0?":"+i:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some((e=>"number"!=typeof e)))throw new RangeError("Invalid JSON representation of ChangeDesc");return new O(e)}static create(e){return new O(e)}}class M extends O{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return N(this,((t,n,i,s,r)=>e=e.replace(i,i+(n-t),r)),!1),e}mapDesc(e,t=!1){return D(this,e,t,!0)}invert(e){let t=this.sections.slice(),n=[];for(let s=0,r=0;s=0){t[s]=a,t[s+1]=o;let l=s>>1;for(;n.length0&&_(n,t,s.text),s.forward(e),o+=e}let l=e[r++];for(;o>1].toJSON()))}return e}static of(e,t,n){let s=[],r=[],o=0,a=null;function l(e=!1){if(!e&&!s.length)return;oa||e<0||a>t)throw new RangeError(`Invalid change range ${e} to ${a} (in doc of length ${t})`);let u=c?"string"==typeof c?i.of(c.split(n||A)):c:i.empty,f=u.length;if(e==a&&0==f)return;eo&&T(s,e-o,-1),T(s,a-e,f),_(r,s,u),o=a}}(e),l(!a),a}static empty(e){return new M(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],n=[];for(let s=0;st&&"string"!=typeof e)))throw new RangeError("Invalid JSON representation of ChangeSet");if(1==r.length)t.push(r[0],0);else{for(;n.length=0&&n<=0&&n==e[s+1]?e[s]+=t:0==t&&0==e[s]?e[s+1]+=n:i?(e[s]+=t,e[s+1]+=n):e.push(t,n)}function _(e,t,n){if(0==n.length)return;let s=t.length-2>>1;if(s>1])),!(n||a==e.sections.length||e.sections[a+1]<0);)l=e.sections[a++],h=e.sections[a++];t(r,c,o,u,f),r=c,o=u}}}function D(e,t,n,i=!1){let s=[],r=i?[]:null,o=new j(e),a=new j(t);for(let e=-1;;)if(-1==o.ins&&-1==a.ins){let e=Math.min(o.len,a.len);T(s,e,-1),o.forward(e),a.forward(e)}else if(a.ins>=0&&(o.ins<0||e==o.i||0==o.off&&(a.len=0&&e=0)){if(o.done&&a.done)return r?M.createSet(s,r):O.create(s);throw new Error("Mismatched change set lengths")}{let t=0,n=o.len;for(;n;)if(-1==a.ins){let e=Math.min(n,a.len);t+=e,n-=e,a.forward(e)}else{if(!(0==a.ins&&a.lent||o.ins>=0&&o.len>t)&&(e||i.length>n),r.forward2(t),o.forward(t)}}else T(i,0,o.ins,e),s&&_(s,i,o.text),o.next()}}class j{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?i.empty:e[t]}textBit(e){let{inserted:t}=this.set,n=this.i-2>>1;return n>=t.length&&!e?i.empty:t[n].slice(this.off,null==e?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){-1==this.ins?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class R{constructor(e,t,n){this.from=e,this.to=t,this.flags=n}get anchor(){return 32&this.flags?this.to:this.from}get head(){return 32&this.flags?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return 8&this.flags?-1:16&this.flags?1:0}get bidiLevel(){let e=7&this.flags;return 7==e?null:e}get goalColumn(){let e=this.flags>>6;return 16777215==e?void 0:e}map(e,t=-1){let n,i;return this.empty?n=i=e.mapPos(this.from,t):(n=e.mapPos(this.from,1),i=e.mapPos(this.to,-1)),n==this.from&&i==this.to?this:new R(n,i,this.flags)}extend(e,t=e){if(e<=this.anchor&&t>=this.anchor)return P.range(e,t);let n=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return P.range(this.anchor,n)}eq(e){return this.anchor==e.anchor&&this.head==e.head}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||"number"!=typeof e.anchor||"number"!=typeof e.head)throw new RangeError("Invalid JSON representation for SelectionRange");return P.range(e.anchor,e.head)}static create(e,t,n){return new R(e,t,n)}}class P{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:P.create(this.ranges.map((n=>n.map(e,t))),this.mainIndex)}eq(e){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let t=0;te.toJSON())),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||"number"!=typeof e.main||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new P(e.ranges.map((e=>R.fromJSON(e))),e.main)}static single(e,t=e){return new P([P.range(e,t)],0)}static create(e,t=0){if(0==e.length)throw new RangeError("A selection needs at least one range");for(let n=0,i=0;ie?8:0)|s)}static normalized(e,t=0){let n=e[t];e.sort(((e,t)=>e.from-t.from)),t=e.indexOf(n);for(let n=1;ni.head?P.range(o,r):P.range(r,o))}}return new P(e,t)}}function I(e,t){for(let n of e.ranges)if(n.to>t)throw new RangeError("Selection points outside of document")}let B=0;class L{constructor(e,t,n,i,s){this.combine=e,this.compareInput=t,this.compare=n,this.isStatic=i,this.id=B++,this.default=e([]),this.extensions="function"==typeof s?s(this):s}get reader(){return this}static define(e={}){return new L(e.combine||(e=>e),e.compareInput||((e,t)=>e===t),e.compare||(e.combine?(e,t)=>e===t:$),!!e.static,e.enables)}of(e){return new z([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new z(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new z(e,this,2,t)}from(e,t){return t||(t=e=>e),this.compute([e],(n=>t(n.field(e))))}}function $(e,t){return e==t||e.length==t.length&&e.every(((e,n)=>e===t[n]))}class z{constructor(e,t,n,i){this.dependencies=e,this.facet=t,this.type=n,this.value=i,this.id=B++}dynamicSlot(e){var t;let n=this.value,i=this.facet.compareInput,s=this.id,r=e[s]>>1,o=2==this.type,a=!1,l=!1,h=[];for(let n of this.dependencies)"doc"==n?a=!0:"selection"==n?l=!0:0==(1&(null!==(t=e[n.id])&&void 0!==t?t:1))&&h.push(e[n.id]);return{create:e=>(e.values[r]=n(e),1),update(e,t){if(a&&t.docChanged||l&&(t.docChanged||t.selection)||H(e,h)){let t=n(e);if(o?!F(t,e.values[r],i):!i(t,e.values[r]))return e.values[r]=t,1}return 0},reconfigure:(e,t)=>{let a,l=t.config.address[s];if(null!=l){let s=ie(t,l);if(this.dependencies.every((n=>n instanceof L?t.facet(n)===e.facet(n):!(n instanceof q)||t.field(n,!1)==e.field(n,!1)))||(o?F(a=n(e),s,i):i(a=n(e),s)))return e.values[r]=s,0}else a=n(e);return e.values[r]=a,1}}}}function F(e,t,n){if(e.length!=t.length)return!1;for(let i=0;ie[t.id])),s=n.map((e=>e.type)),r=i.filter((e=>!(1&e))),o=e[t.id]>>1;function a(e){let n=[];for(let t=0;te===t),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(W).find((e=>e.field==this));return((null==t?void 0:t.create)||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:e=>(e.values[t]=this.create(e),1),update:(e,n)=>{let i=e.values[t],s=this.updateF(i,n);return this.compareF(i,s)?0:(e.values[t]=s,1)},reconfigure:(e,n)=>null!=n.config.address[this.id]?(e.values[t]=n.field(this),0):(e.values[t]=this.create(e),1)}}init(e){return[this,W.of({field:this,create:e})]}get extension(){return this}}const J=4,U=3,G=2,K=1;function Y(e){return t=>new Q(t,e)}const X={highest:Y(0),high:Y(K),default:Y(G),low:Y(U),lowest:Y(J)};class Q{constructor(e,t){this.inner=e,this.prec=t}}class Z{of(e){return new ee(this,e)}reconfigure(e){return Z.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class ee{constructor(e,t){this.compartment=e,this.inner=t}}class te{constructor(e,t,n,i,s,r){for(this.base=e,this.compartments=t,this.dynamicSlots=n,this.address=i,this.staticValues=s,this.facets=r,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,n){let i=[],s=Object.create(null),r=new Map;for(let n of function(e,t,n){let i=[[],[],[],[],[]],s=new Map;return function e(r,o){let a=s.get(r);if(null!=a){if(a<=o)return;let e=i[a].indexOf(r);e>-1&&i[a].splice(e,1),r instanceof ee&&n.delete(r.compartment)}if(s.set(r,o),Array.isArray(r))for(let t of r)e(t,o);else if(r instanceof ee){if(n.has(r.compartment))throw new RangeError("Duplicate use of compartment in extensions");let i=t.get(r.compartment)||r.inner;n.set(r.compartment,i),e(i,o)}else if(r instanceof Q)e(r.inner,r.prec);else if(r instanceof q)i[o].push(r),r.provides&&e(r.provides,o);else if(r instanceof z)i[o].push(r),r.facet.extensions&&e(r.facet.extensions,G);else{let t=r.extension;if(!t)throw new Error(`Unrecognized extension value in extension set (${r}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);e(t,o)}}(e,G),i.reduce(((e,t)=>e.concat(t)))}(e,t,r))n instanceof q?i.push(n):(s[n.facet.id]||(s[n.facet.id]=[])).push(n);let o=Object.create(null),a=[],l=[];for(let e of i)o[e.id]=l.length<<1,l.push((t=>e.slot(t)));let h=null==n?void 0:n.config.facets;for(let e in s){let t=s[e],i=t[0].facet,r=h&&h[e]||[];if(t.every((e=>0==e.type)))if(o[i.id]=a.length<<1|1,$(r,t))a.push(n.facet(i));else{let e=i.combine(t.map((e=>e.value)));a.push(n&&i.compare(e,n.facet(i))?n.facet(i):e)}else{for(let e of t)0==e.type?(o[e.id]=a.length<<1|1,a.push(e.value)):(o[e.id]=l.length<<1,l.push((t=>e.dynamicSlot(t))));o[i.id]=l.length<<1,l.push((e=>V(e,i,t)))}}let c=l.map((e=>e(o)));return new te(e,r,c,o,a,s)}}function ne(e,t){if(1&t)return 2;let n=t>>1,i=e.status[n];if(4==i)throw new Error("Cyclic dependency between fields and/or facets");if(2&i)return i;e.status[n]=4;let s=e.computeSlot(e,e.config.dynamicSlots[n]);return e.status[n]=2|s}function ie(e,t){return 1&t?e.config.staticValues[t>>1]:e.values[t>>1]}const se=L.define(),re=L.define({combine:e=>e.some((e=>e)),static:!0}),oe=L.define({combine:e=>e.length?e[0]:void 0,static:!0}),ae=L.define(),le=L.define(),he=L.define(),ce=L.define({combine:e=>!!e.length&&e[0]});class ue{constructor(e,t){this.type=e,this.value=t}static define(){return new fe}}class fe{of(e){return new ue(this,e)}}class de{constructor(e){this.map=e}of(e){return new pe(this,e)}}class pe{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return void 0===t?void 0:t==this.value?this:new pe(this.type,t)}is(e){return this.type==e}static define(e={}){return new de(e.map||(e=>e))}static mapEffects(e,t){if(!e.length)return e;let n=[];for(let i of e){let e=i.map(t);e&&n.push(e)}return n}}pe.reconfigure=pe.define(),pe.appendConfig=pe.define();class me{constructor(e,t,n,i,s,r){this.startState=e,this.changes=t,this.selection=n,this.effects=i,this.annotations=s,this.scrollIntoView=r,this._doc=null,this._state=null,n&&I(n,t.newLength),s.some((e=>e.type==me.time))||(this.annotations=s.concat(me.time.of(Date.now())))}static create(e,t,n,i,s,r){return new me(e,t,n,i,s,r)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(me.userEvent);return!(!t||!(t==e||t.length>e.length&&t.slice(0,e.length)==e&&"."==t[e.length]))}}function ge(e,t){let n=[];for(let i=0,s=0;;){let r,o;if(i=e[i]))r=e[i++],o=e[i++];else{if(!(s=0;s--){let r=n[s](e);r&&Object.keys(r).length&&(i=be(i,ye(t,r,e.changes.newLength),!0))}return i==e?e:me.create(t,e.changes,e.selection,i.effects,i.annotations,i.scrollIntoView)}(n?function(e){let t=e.startState,n=!0;for(let i of t.facet(ae)){let t=i(e);if(!1===t){n=!1;break}Array.isArray(t)&&(n=!0===n?t:ge(n,t))}if(!0!==n){let i,s;if(!1===n)s=e.changes.invertedDesc,i=M.empty(t.doc.length);else{let t=e.changes.filter(n);i=t.changes,s=t.filtered.mapDesc(t.changes).invertedDesc}e=me.create(t,i,e.selection&&e.selection.map(s),pe.mapEffects(e.effects,s),e.annotations,e.scrollIntoView)}let i=t.facet(le);for(let n=i.length-1;n>=0;n--){let s=i[n](e);e=s instanceof me?s:Array.isArray(s)&&1==s.length&&s[0]instanceof me?s[0]:ve(t,we(s),!1)}return e}(s):s)}me.time=ue.define(),me.userEvent=ue.define(),me.addToHistory=ue.define(),me.remote=ue.define();const xe=[];function we(e){return null==e?xe:Array.isArray(e)?e:[e]}var ke=function(e){return e[e.Word=0]="Word",e[e.Space=1]="Space",e[e.Other=2]="Other",e}(ke||(ke={}));const Se=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Ae;try{Ae=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch(e){}class Ce{constructor(e,t,n,i,s,r){this.config=e,this.doc=t,this.selection=n,this.values=i,this.status=e.statusTemplate.slice(),this.computeSlot=s,r&&(r._state=this);for(let e=0;es.set(t,e))),n=null),s.set(t.value.compartment,t.value.extension)):t.is(pe.reconfigure)?(n=null,i=t.value):t.is(pe.appendConfig)&&(n=null,i=we(i).concat(t.value));n?t=e.startState.values.slice():(n=te.resolve(i,s,this),t=new Ce(n,this.doc,this.selection,n.dynamicSlots.map((()=>null)),((e,t)=>t.reconfigure(e,this)),null).values),new Ce(n,e.newDoc,e.newSelection,t,((t,n)=>n.update(t,e)),e)}replaceSelection(e){return"string"==typeof e&&(e=this.toText(e)),this.changeByRange((t=>({changes:{from:t.from,to:t.to,insert:e},range:P.cursor(t.from+e.length)})))}changeByRange(e){let t=this.selection,n=e(t.ranges[0]),i=this.changes(n.changes),s=[n.range],r=we(n.effects);for(let n=1;ns.spec.fromJSON(r,e))))}return Ce.create({doc:e.doc,selection:P.fromJSON(e.selection),extensions:t.extensions?i.concat([t.extensions]):i})}static create(e={}){let t=te.resolve(e.extensions||[],new Map),n=e.doc instanceof i?e.doc:i.of((e.doc||"").split(t.staticFacet(Ce.lineSeparator)||A)),s=e.selection?e.selection instanceof P?e.selection:P.single(e.selection.anchor,e.selection.head):P.single(0);return I(s,n.length),t.staticFacet(re)||(s=s.asSingle()),new Ce(t,n,s,t.dynamicSlots.map((()=>null)),((e,t)=>t.create(e)),null)}get tabSize(){return this.facet(Ce.tabSize)}get lineBreak(){return this.facet(Ce.lineSeparator)||"\n"}get readOnly(){return this.facet(ce)}phrase(e,...t){for(let t of this.facet(Ce.phrases))if(Object.prototype.hasOwnProperty.call(t,e)){e=t[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,((e,n)=>{if("$"==n)return"$";let i=+(n||1);return!i||i>t.length?e:t[i-1]}))),e}languageDataAt(e,t,n=-1){let i=[];for(let s of this.facet(se))for(let r of s(this,t,n))Object.prototype.hasOwnProperty.call(r,e)&&i.push(r[e]);return i}charCategorizer(e){return t=this.languageDataAt("wordChars",e).join(""),e=>{if(!/\S/.test(e))return ke.Space;if(function(e){if(Ae)return Ae.test(e);for(let t=0;t"€"&&(n.toUpperCase()!=n.toLowerCase()||Se.test(n)))return!0}return!1}(e))return ke.Word;for(let n=0;n-1)return ke.Word;return ke.Other};var t}wordAt(e){let{text:t,from:n,length:i}=this.doc.lineAt(e),s=this.charCategorizer(e),r=e-n,o=e-n;for(;r>0;){let e=g(t,r,!1);if(s(t.slice(e,r))!=ke.Word)break;r=e}for(;oe.length?e[0]:4}),Ce.lineSeparator=oe,Ce.readOnly=ce,Ce.phrases=L.define({compare(e,t){let n=Object.keys(e),i=Object.keys(t);return n.length==i.length&&n.every((n=>e[n]==t[n]))}}),Ce.languageData=se,Ce.changeFilter=ae,Ce.transactionFilter=le,Ce.transactionExtender=he,Z.reconfigure=pe.define();class Me{eq(e){return this==e}range(e,t=e){return Te.create(e,t,this)}}Me.prototype.startSide=Me.prototype.endSide=0,Me.prototype.point=!1,Me.prototype.mapMode=C.TrackDel;class Te{constructor(e,t,n){this.from=e,this.to=t,this.value=n}static create(e,t,n){return new Te(e,t,n)}}function _e(e,t){return e.from-t.from||e.value.startSide-t.value.startSide}class Ne{constructor(e,t,n,i){this.from=e,this.to=t,this.value=n,this.maxPoint=i}get length(){return this.to[this.to.length-1]}findIndex(e,t,n,i=0){let s=n?this.to:this.from;for(let r=i,o=s.length;;){if(r==o)return r;let i=r+o>>1,a=s[i]-e||(n?this.value[i].endSide:this.value[i].startSide)-t;if(i==r)return a>=0?r:o;a>=0?o=i:r=i+1}}between(e,t,n,i){for(let s=this.findIndex(t,-1e9,!0),r=this.findIndex(n,1e9,!1,s);sh||l==h&&c.startSide>0&&c.endSide<=0)continue;(h-l||c.endSide-c.startSide)<0||(r<0&&(r=l),c.point&&(o=Math.max(o,h-l)),n.push(c),i.push(l-r),s.push(h-r))}return{mapped:n.length?new Ne(i,s,n,o):null,pos:r}}}class De{constructor(e,t,n,i){this.chunkPos=e,this.chunk=t,this.nextLayer=n,this.maxPoint=i}static create(e,t,n,i){return new De(e,t,n,i)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:n=!1,filterFrom:i=0,filterTo:s=this.length}=e,r=e.filter;if(0==t.length&&!r)return this;if(n&&(t=t.slice().sort(_e)),this.isEmpty)return t.length?De.of(t):this;let o=new Re(this,null,-1).goto(0),a=0,l=[],h=new Ee;for(;o.value||a=0){let e=t[a++];h.addInner(e.from,e.to,e.value)||l.push(e)}else 1==o.rangeIndex&&o.chunkIndexthis.chunkEnd(o.chunkIndex)||so.to||s=s&&e<=s+r.length&&!1===r.between(s,e-s,t-s,n))return}this.nextLayer.between(e,t,n)}}iter(e=0){return Pe.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return Pe.from(e).goto(t)}static compare(e,t,n,i,s=-1){let r=e.filter((e=>e.maxPoint>0||!e.isEmpty&&e.maxPoint>=s)),o=t.filter((e=>e.maxPoint>0||!e.isEmpty&&e.maxPoint>=s)),a=je(r,o,n),l=new Be(r,a,s),h=new Be(o,a,s);n.iterGaps(((e,t,n)=>Le(l,e,h,t,n,i))),n.empty&&0==n.length&&Le(l,0,h,0,0,i)}static eq(e,t,n=0,i){null==i&&(i=999999999);let s=e.filter((e=>!e.isEmpty&&t.indexOf(e)<0)),r=t.filter((t=>!t.isEmpty&&e.indexOf(t)<0));if(s.length!=r.length)return!1;if(!s.length)return!0;let o=je(s,r),a=new Be(s,o,0).goto(n),l=new Be(r,o,0).goto(n);for(;;){if(a.to!=l.to||!$e(a.active,l.active)||a.point&&(!l.point||!a.point.eq(l.point)))return!1;if(a.to>i)return!0;a.next(),l.next()}}static spans(e,t,n,i,s=-1){let r=new Be(e,null,s).goto(t),o=t,a=r.openStart;for(;;){let e=Math.min(r.to,n);if(r.point){let n=r.activeForPoint(r.to),s=r.pointFromo&&(i.span(o,e,r.active,a),a=r.openEnd(e));if(r.to>n)return a+(r.point&&r.to>n?1:0);o=r.to,r.next()}}static of(e,t=!1){let n=new Ee;for(let i of e instanceof Te?[e]:t?function(e){if(e.length>1)for(let t=e[0],n=1;n0)return e.slice().sort(_e);t=i}return e}(e):e)n.add(i.from,i.to,i.value);return n.finish()}}De.empty=new De([],[],null,-1),De.empty.nextLayer=De.empty;class Ee{finishChunk(e){this.chunks.push(new Ne(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,t,n){this.addInner(e,t,n)||(this.nextLayer||(this.nextLayer=new Ee)).add(e,t,n)}addInner(e,t,n){let i=e-this.lastTo||n.startSide-this.last.endSide;if(i<=0&&(e-this.lastFrom||n.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return!(i<0||(250==this.from.length&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=n,this.lastFrom=e,this.lastTo=t,this.value.push(n),n.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),0))}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let n=t.value.length-1;return this.last=t.value[n],this.lastFrom=t.from[n]+e,this.lastTo=t.to[n]+e,!0}finish(){return this.finishInner(De.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),0==this.chunks.length)return e;let t=De.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}}function je(e,t,n){let i=new Map;for(let t of e)for(let e=0;e=this.minPoint)break}}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex=n&&i.push(new Re(r,t,n,s));return 1==i.length?i[0]:new Pe(i)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let n of this.heap)n.goto(e,t);for(let e=this.heap.length>>1;e>=0;e--)Ie(this.heap,e);return this.next(),this}forward(e,t){for(let n of this.heap)n.forward(e,t);for(let e=this.heap.length>>1;e>=0;e--)Ie(this.heap,e);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(0==this.heap.length)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),Ie(this.heap,0)}}}function Ie(e,t){for(let n=e[t];;){let i=1+(t<<1);if(i>=e.length)break;let s=e[i];if(i+1=0&&(s=e[i+1],i++),n.compare(s)<0)break;e[i]=n,e[t]=s,t=i}}class Be{constructor(e,t,n){this.minPoint=n,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=Pe.from(e,t,n)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){ze(this.active,e),ze(this.activeTo,e),ze(this.activeRank,e),this.minActive=He(this.active,this.activeTo)}addActive(e){let t=0,{value:n,to:i,rank:s}=this.cursor;for(;t-1&&(this.activeTo[i]-this.cursor.from||this.active[i].endSide-this.cursor.startSide)<0){if(this.activeTo[i]>e){this.to=this.activeTo[i],this.endSide=this.active[i].endSide;break}this.removeActive(i),n&&ze(n,i)}else{if(!this.cursor.value){this.to=this.endSide=1e9;break}if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}{let e=this.cursor.value;if(e.point){if(!(t&&this.cursor.to==this.to&&this.cursor.from=0&&n[t]=0&&!(this.activeRank[n]e||this.activeTo[n]==e&&this.active[n].endSide>=this.point.endSide)&&t.push(this.active[n]);return t.reverse()}openEnd(e){let t=0;for(let n=this.activeTo.length-1;n>=0&&this.activeTo[n]>e;n--)t++;return t}}function Le(e,t,n,i,s,r){e.goto(t),n.goto(i);let o=i+s,a=i,l=i-t;for(;;){let t=e.to+l-n.to||e.endSide-n.endSide,i=t<0?e.to+l:n.to,s=Math.min(i,o);if(e.point||n.point?e.point&&n.point&&(e.point==n.point||e.point.eq(n.point))&&$e(e.activeForPoint(e.to),n.activeForPoint(n.to))||r.comparePoint(a,s,e.point,n.point):s>a&&!$e(e.active,n.active)&&r.compareRange(a,s,e.active,n.active),i>o)break;a=i,t<=0&&e.next(),t>=0&&n.next()}}function $e(e,t){if(e.length!=t.length)return!1;for(let n=0;n=t;n--)e[n+1]=e[n];e[t]=n}function He(e,t){let n=-1,i=1e9;for(let s=0;s=t)return i;if(i==e.length)break;s+=9==e.charCodeAt(i)?n-s%n:1,i=g(e,i)}return!0===i?-1:e.length}},65329:(e,t,n)=>{"use strict";n.d(t,{p:()=>ce,Nm:()=>Ue,tk:()=>Gn,SJ:()=>qi,lg:()=>Re,l9:()=>le,S2:()=>ji,Uw:()=>pi,gB:()=>Wi,v5:()=>Ki,ZO:()=>Ci,pk:()=>gs,DF:()=>ps,$f:()=>ni,Eu:()=>hs,OO:()=>Ne,Zs:()=>Ni,CT:()=>Ai,hJ:()=>Vi,jH:()=>Ii});for(var i=n(1727),s=n(37207),r={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},o={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},a="undefined"!=typeof navigator&&/Mac/.test(navigator.platform),l="undefined"!=typeof navigator&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),h=0;h<10;h++)r[48+h]=r[96+h]=String(h);for(h=1;h<=24;h++)r[h+111]="F"+h;for(h=65;h<=90;h++)r[h]=String.fromCharCode(h+32),o[h]=String.fromCharCode(h);for(var c in r)o.hasOwnProperty(c)||(o[c]=r[c]);function u(e){let t;return t=11==e.nodeType?e.getSelection?e:e.ownerDocument:e,t.getSelection()}function f(e,t){return!!t&&(e==t||e.contains(1!=t.nodeType?t.parentNode:t))}function d(e,t){if(!t.anchorNode)return!1;try{return f(e,t.anchorNode)}catch(e){return!1}}function p(e){return 3==e.nodeType?C(e,0,e.nodeValue.length).getClientRects():1==e.nodeType?e.getClientRects():[]}function m(e,t,n,i){return!!n&&(b(e,t,n,i,-1)||b(e,t,n,i,1))}function g(e){for(var t=0;;t++)if(!(e=e.previousSibling))return t}function b(e,t,n,i,s){for(;;){if(e==n&&t==i)return!0;if(t==(s<0?0:y(e))){if("DIV"==e.nodeName)return!1;let n=e.parentNode;if(!n||1!=n.nodeType)return!1;t=g(e)+(s<0?0:1),e=n}else{if(1!=e.nodeType)return!1;if(1==(e=e.childNodes[t+(s<0?-1:0)]).nodeType&&"false"==e.contentEditable)return!1;t=s<0?y(e):0}}}function y(e){return 3==e.nodeType?e.nodeValue.length:e.childNodes.length}function v(e,t){let n=t?e.left:e.right;return{left:n,right:n,top:e.top,bottom:e.bottom}}function x(e){return{left:0,right:e.innerWidth,top:0,bottom:e.innerHeight}}class w{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:t,focusNode:n}=e;this.set(t,Math.min(e.anchorOffset,t?y(t):0),n,Math.min(e.focusOffset,n?y(n):0))}set(e,t,n,i){this.anchorNode=e,this.anchorOffset=t,this.focusNode=n,this.focusOffset=i}}let k,S=null;function A(e){if(e.setActive)return e.setActive();if(S)return e.focus(S);let t=[];for(let n=e;n&&(t.push(n,n.scrollTop,n.scrollLeft),n!=n.ownerDocument);n=n.parentNode);if(e.focus(null==S?{get preventScroll(){return S={preventScroll:!0},!0}}:void 0),!S){S=!1;for(let e=0;eMath.max(1,e.scrollHeight-e.clientHeight-4)}class _{constructor(e,t,n=!0){this.node=e,this.offset=t,this.precise=n}static before(e,t){return new _(e.parentNode,g(e),t)}static after(e,t){return new _(e.parentNode,g(e)+1,t)}}const N=[];class D{constructor(){this.parent=null,this.dom=null,this.flags=2}get overrideDOMText(){return null}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e){let t=this.posAtStart;for(let n of this.children){if(n==e)return t;t+=n.length+n.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}sync(e,t){if(2&this.flags){let n,i=this.dom,s=null;for(let r of this.children){if(7&r.flags){if(!r.dom&&(n=s?s.nextSibling:i.firstChild)){let e=D.get(n);(!e||!e.parent&&e.canReuseDOM(r))&&r.reuseDOM(n)}r.sync(e,t),r.flags&=-8}if(n=s?s.nextSibling:i.firstChild,t&&!t.written&&t.node==i&&n!=r.dom&&(t.written=!0),r.dom.parentNode==i)for(;n&&n!=r.dom;)n=E(n);else i.insertBefore(r.dom,n);s=r.dom}for(n=s?s.nextSibling:i.firstChild,n&&t&&t.node==i&&(t.written=!0);n;)n=E(n)}else if(1&this.flags)for(let n of this.children)7&n.flags&&(n.sync(e,t),n.flags&=-8)}reuseDOM(e){}localPosFromDOM(e,t){let n;if(e==this.dom)n=this.dom.childNodes[t];else{let i=0==y(e)?0:0==t?-1:1;for(;;){let t=e.parentNode;if(t==this.dom)break;0==i&&t.firstChild!=t.lastChild&&(i=e==t.firstChild?-1:1),e=t}n=i<0?e:e.nextSibling}if(n==this.dom.firstChild)return 0;for(;n&&!D.get(n);)n=n.nextSibling;if(!n)return this.length;for(let e=0,t=0;;e++){let i=this.children[e];if(i.dom==n)return t;t+=i.length+i.breakAfter}}domBoundsAround(e,t,n=0){let i=-1,s=-1,r=-1,o=-1;for(let a=0,l=n,h=n;at)return n.domBoundsAround(e,t,l);if(c>=e&&-1==i&&(i=a,s=l),l>t&&n.dom.parentNode==this.dom){r=a,o=h;break}h=c,l=c+n.breakAfter}return{from:s,to:o<0?n+this.length:o,startDOM:(i?this.children[i-1].dom.nextSibling:null)||this.dom.firstChild,endDOM:r=0?this.children[r].dom:null}}markDirty(e=!1){this.flags|=2,this.markParentsDirty(e)}markParentsDirty(e){for(let t=this.parent;t;t=t.parent){if(e&&(t.flags|=2),1&t.flags)return;t.flags|=1,e=!1}}setParent(e){this.parent!=e&&(this.parent=e,7&this.flags&&this.markParentsDirty(!0))}setDOM(e){this.dom!=e&&(this.dom&&(this.dom.cmView=null),this.dom=e,e.cmView=this)}get rootView(){for(let e=this;;){let t=e.parent;if(!t)return e;e=t}}replaceChildren(e,t,n=N){this.markDirty();for(let n=e;nthis.pos||e==this.pos&&(t>0||0==this.i||this.children[this.i-1].breakAfter))return this.off=e-this.pos,this;let n=this.children[--this.i];this.pos-=n.length+n.breakAfter}}}function R(e,t,n,i,s,r,o,a,l){let{children:h}=e,c=h.length?h[t]:null,u=r.length?r[r.length-1]:null,f=u?u.breakAfter:o;if(!(t==i&&c&&!o&&!f&&r.length<2&&c.merge(n,s,r.length?u:null,0==n,a,l))){if(i0&&(!o&&r.length&&c.merge(n,c.length,r[0],!1,a,0)?c.breakAfter=r.shift().breakAfter:(n2);var U={mac:J||/Mac/.test(I.platform),windows:/Win/.test(I.platform),linux:/Linux|X11/.test(I.platform),ie:F,ie_version:$?B.documentMode||6:z?+z[1]:L?+L[1]:0,gecko:H,gecko_version:H?+(/Firefox\/(\d+)/.exec(I.userAgent)||[0,0])[1]:0,chrome:!!V,chrome_version:V?+V[1]:0,ios:J,android:/Android\b/.test(I.userAgent),webkit:W,safari:q,webkit_version:W?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0,tabSize:null!=B.documentElement.style.tabSize?"tab-size":"-moz-tab-size"};class G extends D{constructor(e){super(),this.text=e}get length(){return this.text.length}createDOM(e){this.setDOM(e||document.createTextNode(this.text))}sync(e,t){this.dom||this.createDOM(),this.dom.nodeValue!=this.text&&(t&&t.node==this.dom&&(t.written=!0),this.dom.nodeValue=this.text)}reuseDOM(e){3==e.nodeType&&this.createDOM(e)}merge(e,t,n){return!(8&this.flags||n&&(!(n instanceof G)||this.length-(t-e)+n.length>256||8&n.flags)||(this.text=this.text.slice(0,e)+(n?n.text:"")+this.text.slice(t),this.markDirty(),0))}split(e){let t=new G(this.text.slice(e));return this.text=this.text.slice(0,e),this.markDirty(),t.flags|=8&this.flags,t}localPosFromDOM(e,t){return e==this.dom?t:t?this.text.length:0}domAtPos(e){return new _(this.dom,e)}domBoundsAround(e,t,n){return{from:n,to:n+this.length,startDOM:this.dom,endDOM:this.dom.nextSibling}}coordsAt(e,t){return function(e,t,n){let i=e.nodeValue.length;t>i&&(t=i);let s=t,r=t,o=0;0==t&&n<0||t==i&&n>=0?U.chrome||U.gecko||(t?(s--,o=1):r=0)?0:a.length-1];return U.safari&&!o&&0==l.width&&(l=Array.prototype.find.call(a,(e=>e.width))||l),o?v(l,o<0):l||null}(this.dom,e,t)}}class K extends D{constructor(e,t=[],n=0){super(),this.mark=e,this.children=t,this.length=n;for(let e of t)e.setParent(this)}setAttrs(e){if(M(e),this.mark.class&&(e.className=this.mark.class),this.mark.attrs)for(let t in this.mark.attrs)e.setAttribute(t,this.mark.attrs[t]);return e}canReuseDOM(e){return super.canReuseDOM(e)&&!(8&(this.flags|e.flags))}reuseDOM(e){e.nodeName==this.mark.tagName.toUpperCase()&&(this.setDOM(e),this.flags|=6)}sync(e,t){this.dom?4&this.flags&&this.setAttrs(this.dom):this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))),super.sync(e,t)}merge(e,t,n,i,s,r){return!(n&&(!(n instanceof K&&n.mark.eq(this.mark))||e&&s<=0||te&&t.push(n=e&&(i=s),n=o,s++}let r=this.length-e;return this.length=e,i>-1&&(this.children.length=i,this.markDirty()),new K(this.mark,t,r)}domAtPos(e){return Q(this,e)}coordsAt(e,t){return ee(this,e,t)}}class Y extends D{static create(e,t,n){return new Y(e,t,n)}constructor(e,t,n){super(),this.widget=e,this.length=t,this.side=n,this.prevWidget=null}split(e){let t=Y.create(this.widget,this.length-e,this.side);return this.length-=e,t}sync(e){this.dom&&this.widget.updateDOM(this.dom,e)||(this.dom&&this.prevWidget&&this.prevWidget.destroy(this.dom),this.prevWidget=null,this.setDOM(this.widget.toDOM(e)),this.dom.contentEditable="false")}getSide(){return this.side}merge(e,t,n,i,s,r){return!(n&&(!(n instanceof Y&&this.widget.compare(n.widget))||e>0&&s<=0||t0)?_.before(this.dom):_.after(this.dom,e==this.length)}domBoundsAround(){return null}coordsAt(e,t){let n=this.widget.coordsAt(this.dom,e,t);if(n)return n;let i=this.dom.getClientRects(),s=null;if(!i.length)return null;let r=this.side?this.side<0:e>0;for(let t=r?i.length-1:0;s=i[t],!(e>0?0==t:t==i.length-1||s.top0?_.before(this.dom):_.after(this.dom)}localPosFromDOM(){return 0}domBoundsAround(){return null}coordsAt(e){return this.dom.getBoundingClientRect()}get overrideDOMText(){return i.xv.empty}get isHidden(){return!0}}function Q(e,t){let n=e.dom,{children:i}=e,s=0;for(let e=0;se&&t0;e--){let t=i[e-1];if(t.dom.parentNode==n)return t.domAtPos(t.length)}for(let e=s;e0&&t instanceof K&&s.length&&(i=s[s.length-1])instanceof K&&i.mark.eq(t.mark)?Z(i,t.children[0],n-1):(s.push(t),t.setParent(e)),e.length+=t.length}function ee(e,t,n){let i=null,s=-1,r=null,o=-1;!function e(t,a){for(let l=0,h=0;l=a&&(c.children.length?e(c,a-h):(!r||r.isHidden&&n>0)&&(u>a||h==u&&c.getSide()>0)?(r=c,o=a-h):(h-1?1:0)!=s.length-(n&&s.indexOf(n)>-1?1:0))return!1;for(let r of i)if(r!=n&&(-1==s.indexOf(r)||e[r]!==t[r]))return!1;return!0}function se(e,t,n){let i=!1;if(t)for(let s in t)n&&s in n||(i=!0,"style"==s?e.style.cssText="":e.removeAttribute(s));if(n)for(let s in n)t&&t[s]==n[s]||(i=!0,"style"==s?e.style.cssText=n[s]:e.setAttribute(s,n[s]));return i}function re(e){let t=Object.create(null);for(let n=0;n0&&0==this.children[n-1].length;)this.children[--n].destroy();return this.children.length=n,this.markDirty(),this.length=e,t}transferDOM(e){this.dom&&(this.markDirty(),e.setDOM(this.dom),e.prevAttrs=void 0===this.prevAttrs?this.attrs:this.prevAttrs,this.prevAttrs=void 0,this.dom=null)}setDeco(e){ie(this.attrs,e)||(this.dom&&(this.prevAttrs=this.attrs,this.markDirty()),this.attrs=e)}append(e,t){Z(this,e,t)}addLineDeco(e){let t=e.spec.attributes,n=e.spec.class;t&&(this.attrs=te(t,this.attrs||{})),n&&(this.attrs=te({class:n},this.attrs||{}))}domAtPos(e){return Q(this,e)}reuseDOM(e){"DIV"==e.nodeName&&(this.setDOM(e),this.flags|=6)}sync(e,t){var n;this.dom?4&this.flags&&(M(this.dom),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0):(this.setDOM(document.createElement("div")),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0),void 0!==this.prevAttrs&&(se(this.dom,this.prevAttrs,this.attrs),this.dom.classList.add("cm-line"),this.prevAttrs=void 0),super.sync(e,t);let i=this.dom.lastChild;for(;i&&D.get(i)instanceof K;)i=i.lastChild;if(!(i&&this.length&&("BR"==i.nodeName||0!=(null===(n=D.get(i))||void 0===n?void 0:n.isEditable)||U.ios&&this.children.some((e=>e instanceof G))))){let e=document.createElement("BR");e.cmIgnore=!0,this.dom.appendChild(e)}}measureTextSize(){if(0==this.children.length||this.length>20)return null;let e,t=0;for(let n of this.children){if(!(n instanceof G)||/[^ -~]/.test(n.text))return null;let i=p(n.dom);if(1!=i.length)return null;t+=i[0].width,e=i[0].height}return t?{lineHeight:this.dom.getBoundingClientRect().height,charWidth:t/this.length,textHeight:e}:null}coordsAt(e,t){let n=ee(this,e,t);if(!this.children.length&&n&&this.parent){let{heightOracle:e}=this.parent.view.viewState,t=n.bottom-n.top;if(Math.abs(t-e.lineHeight)<2&&e.textHeight=t){if(s instanceof oe)return s;if(r>t)break}i=r+s.breakAfter}return null}}class ae extends D{constructor(e,t,n){super(),this.widget=e,this.length=t,this.deco=n,this.breakAfter=0,this.prevWidget=null}merge(e,t,n,i,s,r){return!(n&&(!(n instanceof ae&&this.widget.compare(n.widget))||e>0&&s<=0||t0)}}class le{eq(e){return!1}updateDOM(e,t){return!1}compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}get estimatedHeight(){return-1}get lineBreaks(){return 0}ignoreEvent(e){return!0}coordsAt(e,t,n){return null}get isHidden(){return!1}destroy(e){}}var he=function(e){return e[e.Text=0]="Text",e[e.WidgetBefore=1]="WidgetBefore",e[e.WidgetAfter=2]="WidgetAfter",e[e.WidgetRange=3]="WidgetRange",e}(he||(he={}));class ce extends i.uU{constructor(e,t,n,i){super(),this.startSide=e,this.endSide=t,this.widget=n,this.spec=i}get heightRelevant(){return!1}static mark(e){return new ue(e)}static widget(e){let t=Math.max(-1e4,Math.min(1e4,e.side||0)),n=!!e.block;return t+=n&&!e.inlineOrder?t>0?3e8:-4e8:t>0?1e8:-1e8,new de(e,t,t,n,e.widget||null,!1)}static replace(e){let t,n,i=!!e.block;if(e.isBlockGap)t=-5e8,n=4e8;else{let{start:s,end:r}=pe(e,i);t=(s?i?-3e8:-1:5e8)-1,n=1+(r?i?2e8:1:-6e8)}return new de(e,t,n,i,e.widget||null,!0)}static line(e){return new fe(e)}static set(e,t=!1){return i.Xs.of(e,t)}hasHeight(){return!!this.widget&&this.widget.estimatedHeight>-1}}ce.none=i.Xs.empty;class ue extends ce{constructor(e){let{start:t,end:n}=pe(e);super(t?-1:5e8,n?1:-6e8,null,e),this.tagName=e.tagName||"span",this.class=e.class||"",this.attrs=e.attributes||null}eq(e){var t,n;return this==e||e instanceof ue&&this.tagName==e.tagName&&(this.class||(null===(t=this.attrs)||void 0===t?void 0:t.class))==(e.class||(null===(n=e.attrs)||void 0===n?void 0:n.class))&&ie(this.attrs,e.attrs,"class")}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}}ue.prototype.point=!1;class fe extends ce{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof fe&&this.spec.class==e.spec.class&&ie(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}}fe.prototype.mapMode=i.gc.TrackBefore,fe.prototype.point=!0;class de extends ce{constructor(e,t,n,s,r,o){super(t,n,r,e),this.block=s,this.isReplace=o,this.mapMode=s?t<=0?i.gc.TrackBefore:i.gc.TrackAfter:i.gc.TrackDel}get type(){return this.startSide!=this.endSide?he.WidgetRange:this.startSide<=0?he.WidgetBefore:he.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof de&&((t=this.widget)==(n=e.widget)||!!(t&&n&&t.compare(n)))&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide;var t,n}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&t!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,t)}}function pe(e,t=!1){let{inclusiveStart:n,inclusiveEnd:i}=e;return null==n&&(n=e.inclusive),null==i&&(i=e.inclusive),{start:null!=n?n:t,end:null!=i?i:t}}function me(e,t,n,i=0){let s=n.length-1;s>=0&&n[s]+i>=e?n[s]=Math.max(n[s],t):n.push(e,t)}de.prototype.point=!0;class ge{constructor(e,t,n,i){this.doc=e,this.pos=t,this.end=n,this.disallowBlockEffectsFor=i,this.content=[],this.curLine=null,this.breakAtStart=0,this.pendingBuffer=0,this.bufferMarks=[],this.atCursorPos=!0,this.openStart=-1,this.openEnd=-1,this.text="",this.textOff=0,this.cursor=e.iter(),this.skip=t}posCovered(){if(0==this.content.length)return!this.breakAtStart&&this.doc.lineAt(this.pos).from!=this.pos;let e=this.content[this.content.length-1];return!(e.breakAfter||e instanceof ae&&e.deco.endSide<0)}getLine(){return this.curLine||(this.content.push(this.curLine=new oe),this.atCursorPos=!0),this.curLine}flushBuffer(e=this.bufferMarks){this.pendingBuffer&&(this.curLine.append(be(new X(-1),e),e.length),this.pendingBuffer=0)}addBlockWidget(e){this.flushBuffer(),this.curLine=null,this.content.push(e)}finish(e){this.pendingBuffer&&e<=this.bufferMarks.length?this.flushBuffer():this.pendingBuffer=0,this.posCovered()||e&&this.content.length&&this.content[this.content.length-1]instanceof ae||this.getLine()}buildText(e,t,n){for(;e>0;){if(this.textOff==this.text.length){let{value:t,lineBreak:n,done:i}=this.cursor.next(this.skip);if(this.skip=0,i)throw new Error("Ran out of text content when drawing inline views");if(n){this.posCovered()||this.getLine(),this.content.length?this.content[this.content.length-1].breakAfter=1:this.breakAtStart=1,this.flushBuffer(),this.curLine=null,this.atCursorPos=!0,e--;continue}this.text=t,this.textOff=0}let i=Math.min(this.text.length-this.textOff,e,512);this.flushBuffer(t.slice(t.length-n)),this.getLine().append(be(new G(this.text.slice(this.textOff,this.textOff+i)),t),n),this.atCursorPos=!0,this.textOff+=i,e-=i,n=0}}span(e,t,n,i){this.buildText(t-e,n,i),this.pos=t,this.openStart<0&&(this.openStart=i)}point(e,t,n,i,s,r){if(this.disallowBlockEffectsFor[r]&&n instanceof de){if(n.block)throw new RangeError("Block decorations may not be specified via plugins");if(t>this.doc.lineAt(this.pos).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}let o=t-e;if(n instanceof de)if(n.block)n.startSide>0&&!this.posCovered()&&this.getLine(),this.addBlockWidget(new ae(n.widget||new ye("div"),o,n));else{let r=Y.create(n.widget||new ye("span"),o,o?0:n.startSide),a=this.atCursorPos&&!r.isEditable&&s<=i.length&&(e0),l=!r.isEditable&&(ei.length||n.startSide<=0),h=this.getLine();2!=this.pendingBuffer||a||r.isEditable||(this.pendingBuffer=0),this.flushBuffer(i),a&&(h.append(be(new X(1),i),s),s=i.length+Math.max(0,s-i.length)),h.append(be(r,i),s),this.atCursorPos=l,this.pendingBuffer=l?ei.length?1:2:0,this.pendingBuffer&&(this.bufferMarks=i.slice())}else this.doc.lineAt(this.pos).from==this.pos&&this.getLine().addLineDeco(n);o&&(this.textOff+o<=this.text.length?this.textOff+=o:(this.skip+=o-(this.text.length-this.textOff),this.text="",this.textOff=0),this.pos=t),this.openStart<0&&(this.openStart=s)}static build(e,t,n,s,r){let o=new ge(e,t,n,r);return o.openEnd=i.Xs.spans(s,t,n,o),o.openStart<0&&(o.openStart=o.openEnd),o.finish(o.openEnd),o}}function be(e,t){for(let n of t)e=new K(n,[e],e.length);return e}class ye extends le{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}}const ve=i.r$.define(),xe=i.r$.define(),we=i.r$.define(),ke=i.r$.define(),Se=i.r$.define(),Ae=i.r$.define(),Ce=i.r$.define(),Oe=i.r$.define({combine:e=>e.some((e=>e))}),Me=i.r$.define({combine:e=>e.some((e=>e))});class Te{constructor(e,t="nearest",n="nearest",i=5,s=5,r=!1){this.range=e,this.y=t,this.x=n,this.yMargin=i,this.xMargin=s,this.isSnapshot=r}map(e){return e.empty?this:new Te(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new Te(i.jT.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}}const _e=i.Py.define({map:(e,t)=>e.map(t)});function Ne(e,t,n){let i=e.facet(ke);i.length?i[0](t):window.onerror?window.onerror(String(t),n,void 0,void 0,t):n?console.error(n+":",t):console.error(t)}const De=i.r$.define({combine:e=>!e.length||e[0]});let Ee=0;const je=i.r$.define();class Re{constructor(e,t,n,i,s){this.id=e,this.create=t,this.domEventHandlers=n,this.domEventObservers=i,this.extension=s(this)}static define(e,t){const{eventHandlers:n,eventObservers:i,provide:s,decorations:r}=t||{};return new Re(Ee++,e,n,i,(e=>{let t=[je.of(e)];return r&&t.push(Le.of((t=>{let n=t.plugin(e);return n?r(n):ce.none}))),s&&t.push(s(e)),t}))}static fromClass(e,t){return Re.define((t=>new e(t)),t)}}class Pe{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}update(e){if(this.value){if(this.mustUpdate){let e=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(e)}catch(t){if(Ne(e.state,t,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch(e){}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.create(e)}catch(t){Ne(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var t;if(null===(t=this.value)||void 0===t?void 0:t.destroy)try{this.value.destroy()}catch(t){Ne(e.state,t,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}}const Ie=i.r$.define(),Be=i.r$.define(),Le=i.r$.define(),$e=i.r$.define(),ze=i.r$.define();function Fe(e,t,n){let s=e.state.facet(ze);if(!s.length)return s;let r=s.map((t=>t instanceof Function?t(e):t)),o=[];return i.Xs.spans(r,t,n,{point(){},span(e,t,n,i){let s=o;for(let r=n.length-1;r>=0;r--,i--){let o,a=n[r].spec.bidiIsolate;if(null!=a)if(i>0&&s.length&&(o=s[s.length-1]).to==e&&o.direction==a)o.to=t,s=o.inner;else{let n={from:e,to:t,direction:a,inner:[]};s.push(n),s=n.inner}}}}),o}const He=i.r$.define();function Ve(e){let t=0,n=0,i=0,s=0;for(let r of e.state.facet(He)){let o=r(e);o&&(null!=o.left&&(t=Math.max(t,o.left)),null!=o.right&&(n=Math.max(n,o.right)),null!=o.top&&(i=Math.max(i,o.top)),null!=o.bottom&&(s=Math.max(s,o.bottom)))}return{left:t,right:n,top:i,bottom:s}}const We=i.r$.define();class qe{constructor(e,t,n,i){this.fromA=e,this.toA=t,this.fromB=n,this.toB=i}join(e){return new qe(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,n=this;for(;t>0;t--){let i=e[t-1];if(!(i.fromA>n.toA)){if(i.toAh)break;s+=2}if(!a)return n;new qe(a.fromA,a.toA,a.fromB,a.toB).addToSet(n),r=a.toA,o=a.toB}}}class Je{constructor(e,t,n){this.view=e,this.state=t,this.transactions=n,this.flags=0,this.startState=e.state,this.changes=i.as.empty(this.startState.doc.length);for(let e of n)this.changes=this.changes.compose(e.changes);let s=[];this.changes.iterChangedRanges(((e,t,n,i)=>s.push(new qe(e,t,n,i)))),this.changedRanges=s}static create(e,t,n){return new Je(e,t,n)}get viewportChanged(){return(4&this.flags)>0}get heightChanged(){return(2&this.flags)>0}get geometryChanged(){return this.docChanged||(10&this.flags)>0}get focusChanged(){return(1&this.flags)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some((e=>e.selection))}get empty(){return 0==this.flags&&0==this.transactions.length}}var Ue=function(e){return e[e.LTR=0]="LTR",e[e.RTL=1]="RTL",e}(Ue||(Ue={}));const Ge=Ue.LTR,Ke=Ue.RTL;function Ye(e){let t=[];for(let n=0;n=t){if(o.level==n)return r;(s<0||(0!=i?i<0?o.fromt:e[s].level>o.level))&&(s=r)}}if(s<0)throw new RangeError("Index out of range");return s}}function it(e,t){if(e.length!=t.length)return!1;for(let n=0;nl&&o.push(new nt(l,p.from,f)),ot(e,p.direction==Ge!=!(f%2)?i+1:i,s,p.inner,p.from,p.to,o),l=p.to),d=p.to}else{if(d==n||(t?st[d]!=a:st[d]==a))break;d++}u?rt(e,l,d,i+1,s,u,o):lt;){let n=!0,c=!1;if(!h||l>r[h-1].to){let e=st[l-1];e!=a&&(n=!1,c=16==e)}let u=n||1!=a?null:[],f=n?i:i+1,d=l;e:for(;;)if(h&&d==r[h-1].to){if(c)break e;let p=r[--h];if(!n)for(let e=p.from,n=h;;){if(e==t)break e;if(!n||r[n-1].to!=e){if(st[e-1]==a)break e;break}e=r[--n].from}u?u.push(p):(p.to=0;e-=3)if(et[e+1]==-n){let t=et[e+2],n=2&t?s:4&t?1&t?r:s:0;n&&(st[o]=st[et[e]]=n),a=e;break}}else{if(189==et.length)break;et[a++]=o,et[a++]=t,et[a++]=l}else if(2==(i=st[o])||1==i){let e=i==s;l=e?0:1;for(let t=a-3;t>=0;t-=3){let n=et[t+2];if(2&n)break;if(e)et[t+2]|=2;else{if(4&n)break;et[t+2]|=4}}}}}(e,s,r,i,a),function(e,t,n,i){for(let s=0,r=i;s<=n.length;s++){let o=s?n[s-1].to:e,a=sl;)t==r&&(t=n[--i].from,r=i?n[i-1].to:e),st[--t]=c;l=o}else r=o,l++}}}(s,r,i,a),rt(e,s,r,t,n,i,o)}function at(e){return[new nt(0,e,0)]}let lt="";function ht(e,t,n,s,r){var o;let a=s.head-e.from,l=-1;if(0==a){if(!r||!e.length)return null;t[0].level!=n&&(a=t[0].side(!1,n),l=0)}else if(a==e.length){if(r)return null;let e=t[t.length-1];e.level!=n&&(a=e.side(!0,n),l=t.length-1)}l<0&&(l=nt.find(t,a,null!==(o=s.bidiLevel)&&void 0!==o?o:-1,s.assoc));let h=t[l];a==h.side(r,n)&&(h=t[l+=r?1:-1],a=h.side(!r,n));let c=r==(h.dir==n),u=(0,i.cp)(e.text,a,c);if(lt=e.text.slice(Math.min(a,u),Math.max(a,u)),u!=h.side(r,n))return i.jT.cursor(u+e.from,c?-1:1,h.level);let f=l==(r?t.length-1:0)?null:t[l+(r?1:-1)];return f||h.level==n?f&&f.level0&&n.length&&(n.every((({fromA:e,toA:t})=>tthis.minWidthTo))?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0);let s=-1;this.view.inputState.composing>=0&&((null===(t=this.domChanged)||void 0===t?void 0:t.newSel)?s=this.domChanged.newSel.head:function(e,t){let n=!1;return t&&e.iterChangedRanges(((e,i)=>{et.from&&(n=!0)})),n}(e.changes,this.hasComposition)||e.selectionSet||(s=e.state.selection.main.head));let r=s>-1?function(e,t,n){let i=ft(e,n);if(!i)return null;let{node:s,from:r,to:o}=i,a=s.nodeValue;if(/[\n\r]/.test(a))return null;if(e.state.doc.sliceString(i.from,i.to)!=a)return null;let l=t.invertedDesc,h=new qe(l.mapPos(r),l.mapPos(o),r,o),c=[];for(let t=s.parentNode;;t=t.parentNode){let n=D.get(t);if(n instanceof K)c.push({node:t,deco:n.mark});else{if(n instanceof oe||"DIV"==t.nodeName&&t.parentNode==e.contentDOM)return{range:h,text:s,marks:c,line:t};if(t==e.contentDOM)return null;c.push({node:t,deco:new ue({inclusive:!0,attributes:re(t),tagName:t.tagName.toLowerCase()})})}}}(this.view,e.changes,s):null;if(this.domChanged=null,this.hasComposition){this.markedForComposition.clear();let{from:t,to:i}=this.hasComposition;n=new qe(t,i,e.changes.mapPos(t,-1),e.changes.mapPos(i,1)).addToSet(n.slice())}this.hasComposition=r?{from:r.range.fromB,to:r.range.toB}:null,(U.ie||U.chrome)&&!r&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=function(e,t,n){let s=new pt;return i.Xs.compare(e,t,n,s),s.changes}(this.decorations,this.updateDeco(),e.changes);return n=qe.extendWithRanges(n,o),!!(7&this.flags||0!=n.length)&&(this.updateInner(n,e.startState.doc.length,r),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t,n){this.view.viewState.mustMeasureContent=!0,this.updateChildren(e,t,n);let{observer:i}=this.view;i.ignore((()=>{this.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let e=U.chrome||U.ios?{node:i.selectionRange.focusNode,written:!1}:void 0;this.sync(this.view,e),this.flags&=-8,e&&(e.written||i.selectionRange.focusNode!=e.node)&&(this.forceSelection=!0),this.dom.style.height=""})),this.markedForComposition.forEach((e=>e.flags&=-9));let s=[];if(this.view.viewport.from||this.view.viewport.to=0?i[e]:null;if(!t)break;let r,o,a,l,{fromA:h,toA:c,fromB:u,toB:f}=t;if(n&&n.range.fromBu){let e=ge.build(this.view.state.doc,u,n.range.fromB,this.decorations,this.dynamicDecorationMap),t=ge.build(this.view.state.doc,n.range.toB,f,this.decorations,this.dynamicDecorationMap);o=e.breakAtStart,a=e.openStart,l=t.openEnd;let i=this.compositionView(n);t.breakAtStart?i.breakAfter=1:t.content.length&&i.merge(i.length,i.length,t.content[0],!1,t.openStart,0)&&(i.breakAfter=t.content[0].breakAfter,t.content.shift()),e.content.length&&i.merge(0,0,e.content[e.content.length-1],!0,0,e.openEnd)&&e.content.pop(),r=e.content.concat(i).concat(t.content)}else({content:r,breakAtStart:o,openStart:a,openEnd:l}=ge.build(this.view.state.doc,u,f,this.decorations,this.dynamicDecorationMap));let{i:d,off:p}=s.findPos(c,1),{i:m,off:g}=s.findPos(h,-1);R(this,m,g,d,p,r,o,a,l)}n&&this.fixCompositionDOM(n)}compositionView(e){let t=new G(e.text.nodeValue);t.flags|=8;for(let{deco:n}of e.marks)t=new K(n,[t],t.length);let n=new oe;return n.append(t,0),n}fixCompositionDOM(e){let t=(e,t)=>{t.flags|=8|(t.children.some((e=>7&e.flags))?1:0),this.markedForComposition.add(t);let n=D.get(e);n&&n!=t&&(n.dom=null),t.setDOM(e)},n=this.childPos(e.range.fromB,1),i=this.children[n.i];t(e.line,i);for(let s=e.marks.length-1;s>=-1;s--)n=i.childPos(n.off,1),i=i.children[n.i],t(s>=0?e.marks[s].node:e.text,i)}updateSelection(e=!1,t=!1){!e&&this.view.observer.selectionRange.focusNode||this.view.observer.readSelectionRange();let n=this.view.root.activeElement,i=n==this.dom,s=!i&&d(this.dom,this.view.observer.selectionRange)&&!(n&&this.dom.contains(n));if(!(i||t||s))return;let r=this.forceSelection;this.forceSelection=!1;let o=this.view.state.selection.main,a=this.moveToLine(this.domAtPos(o.anchor)),l=o.empty?a:this.moveToLine(this.domAtPos(o.head));if(U.gecko&&o.empty&&!this.hasComposition&&1==(h=a).node.nodeType&&h.node.firstChild&&(0==h.offset||"false"==h.node.childNodes[h.offset-1].contentEditable)&&(h.offset==h.node.childNodes.length||"false"==h.node.childNodes[h.offset].contentEditable)){let e=document.createTextNode("");this.view.observer.ignore((()=>a.node.insertBefore(e,a.node.childNodes[a.offset]||null))),a=l=new _(e,0),r=!0}var h;let c=this.view.observer.selectionRange;!r&&c.focusNode&&m(a.node,a.offset,c.anchorNode,c.anchorOffset)&&m(l.node,l.offset,c.focusNode,c.focusOffset)||(this.view.observer.ignore((()=>{U.android&&U.chrome&&this.dom.contains(c.focusNode)&&function(e,t){for(let n=e;n&&n!=t;n=n.assignedSlot||n.parentNode)if(1==n.nodeType&&"false"==n.contentEditable)return!0;return!1}(c.focusNode,this.dom)&&(this.dom.blur(),this.dom.focus({preventScroll:!0}));let e=u(this.view.root);if(e)if(o.empty){if(U.gecko){let e=(t=a.node,i=a.offset,1!=t.nodeType?0:(i&&"false"==t.childNodes[i-1].contentEditable?1:0)|(io.head&&([a,l]=[l,a]),t.setEnd(l.node,l.offset),t.setStart(a.node,a.offset),e.removeAllRanges(),e.addRange(t)}var t,i;s&&this.view.root.activeElement==this.dom&&(this.dom.blur(),n&&n.focus())})),this.view.observer.setSelectionRange(a,l)),this.impreciseAnchor=a.precise?null:new _(c.anchorNode,c.anchorOffset),this.impreciseHead=l.precise?null:new _(c.focusNode,c.focusOffset)}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,t=e.state.selection.main,n=u(e.root),{anchorNode:i,anchorOffset:s}=e.observer.selectionRange;if(!(n&&t.empty&&t.assoc&&n.modify))return;let r=oe.find(this,t.head);if(!r)return;let o=r.posAtStart;if(t.head==o||t.head==o+r.length)return;let a=this.coordsAt(t.head,-1),l=this.coordsAt(t.head,1);if(!a||!l||a.bottom>l.top)return;let h=this.domAtPos(t.head+t.assoc);n.collapse(h.node,h.offset),n.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let c=e.observer.selectionRange;e.docView.posFromDOM(c.anchorNode,c.anchorOffset)!=t.from&&n.collapse(i,s)}moveToLine(e){let t,n=this.dom;if(e.node!=n)return e;for(let i=e.offset;!t&&i=0;i--){let e=D.get(n.childNodes[i]);e instanceof oe&&(t=e.domAtPos(e.length))}return t?new _(t.node,t.offset,!0):e}nearest(e){for(let t=e;t;){let e=D.get(t);if(e&&e.rootView==this)return e;t=t.parentNode}return null}posFromDOM(e,t){let n=this.nearest(e);if(!n)throw new RangeError("Trying to find position for a DOM position outside of the document");return n.localPosFromDOM(e,t)+n.posAtStart}domAtPos(e){let{i:t,off:n}=this.childCursor().findPos(e,-1);for(;t=0;r--){let o=this.children[r],a=s-o.breakAfter,l=a-o.length;if(ae||o.covers(1))&&(!n||o instanceof oe&&!(n instanceof oe&&t>=0))&&(n=o,i=l),s=l}return n?n.coordsAt(e-i,t):null}coordsForChar(e){let{i:t,off:n}=this.childPos(e,1),s=this.children[t];if(!(s instanceof oe))return null;for(;s.children.length;){let{i:e,off:t}=s.childPos(n,1);for(;;e++){if(e==s.children.length)return null;if((s=s.children[e]).length)break}n=t}if(!(s instanceof G))return null;let r=(0,i.cp)(s.text,n);if(r==n)return null;let o=C(s.dom,n,r).getClientRects();for(let e=0;eMath.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,o=-1,a=this.view.textDirection==Ue.LTR;for(let e=0,l=0;li)break;if(e>=n){let n=h.dom.getBoundingClientRect();if(t.push(n.height),r){let t=h.dom.lastChild,i=t?p(t):[];if(i.length){let t=i[i.length-1],r=a?t.right-n.left:n.right-t.left;r>o&&(o=r,this.minWidth=s,this.minWidthFrom=e,this.minWidthTo=c)}}}e=c+h.breakAfter}return t}textDirectionAt(e){let{i:t}=this.childPos(e,1);return"rtl"==getComputedStyle(this.children[t].dom).direction?Ue.RTL:Ue.LTR}measureTextSize(){for(let e of this.children)if(e instanceof oe){let t=e.measureTextSize();if(t)return t}let e,t,n,i=document.createElement("div");return i.className="cm-line",i.style.width="99999px",i.style.position="absolute",i.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore((()=>{this.dom.appendChild(i);let s=p(i.firstChild)[0];e=i.getBoundingClientRect().height,t=s?s.width/27:7,n=s?s.height:e,i.remove()})),{lineHeight:e,charWidth:t,textHeight:n}}childCursor(e=this.length){let t=this.children.length;return t&&(e-=this.children[--t].length),new j(this.children,e,t)}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let n=0,i=0;;i++){let s=i==t.viewports.length?null:t.viewports[i],r=s?s.from-1:this.length;if(r>n){let i=(t.lineBlockAt(r).bottom-t.lineBlockAt(n).top)/this.view.scaleY;e.push(ce.replace({widget:new ut(i),block:!0,inclusive:!0,isBlockGap:!0}).range(n,r))}if(!s)break;n=s.to+1}return ce.set(e)}updateDeco(){let e=this.view.state.facet(Le).map(((e,t)=>(this.dynamicDecorationMap[t]="function"==typeof e)?e(this.view):e));for(let t=e.length;tn.anchor?-1:1);if(!i)return;!n.empty&&(t=this.coordsAt(n.anchor,n.anchor>n.head?-1:1))&&(i={left:Math.min(i.left,t.left),top:Math.min(i.top,t.top),right:Math.max(i.right,t.right),bottom:Math.max(i.bottom,t.bottom)});let s=Ve(this.view),r={left:i.left-s.left,top:i.top-s.top,right:i.right+s.right,bottom:i.bottom+s.bottom},{offsetWidth:o,offsetHeight:a}=this.view.scrollDOM;!function(e,t,n,i,s,r,o,a){let l=e.ownerDocument,h=l.defaultView||window;for(let c=e,u=!1;c&&!u;)if(1==c.nodeType){let e,f=c==l.body,d=1,p=1;if(f)e=x(h);else{if(/^(fixed|sticky)$/.test(getComputedStyle(c).position)&&(u=!0),c.scrollHeight<=c.clientHeight&&c.scrollWidth<=c.clientWidth){c=c.assignedSlot||c.parentNode;continue}let t=c.getBoundingClientRect();d=t.width/c.offsetWidth,p=t.height/c.offsetHeight,e={left:t.left,right:t.left+c.clientWidth*d,top:t.top,bottom:t.top+c.clientHeight*p}}let m=0,g=0;if("nearest"==s)t.top0&&t.bottom>e.bottom+g&&(g=t.bottom-e.bottom+g+o)):t.bottom>e.bottom&&(g=t.bottom-e.bottom+o,n<0&&t.top-g0&&t.right>e.right+m&&(m=t.right-e.right+m+r)):t.right>e.right&&(m=t.right-e.right+r,n<0&&t.left0))break;n=n.childNodes[i-1],i=y(n)}if(n>=0)for(let i=e,s=t;;){if(3==i.nodeType)return{node:i,offset:s};if(!(1==i.nodeType&&s=0))break;i=i.childNodes[s],s=0}return null}let pt=class{constructor(){this.changes=[]}compareRange(e,t){me(e,t,this.changes)}comparePoint(e,t){me(e,t,this.changes)}};function mt(e,t){return t.left>e?t.left-e:Math.max(0,e-t.right)}function gt(e,t){return t.top>e?t.top-e:Math.max(0,e-t.bottom)}function bt(e,t){return e.topt.top+1}function yt(e,t){return te.bottom?{top:e.top,left:e.left,right:e.right,bottom:t}:e}function xt(e,t,n){let i,s,r,o,a,l,h,c,u=!1;for(let f=e.firstChild;f;f=f.nextSibling){let e=p(f);for(let d=0;dg||o==g&&r>m){i=f,s=p,r=m,o=g;let a=g?n0?d0)}0==m?n>p.bottom&&(!h||h.bottomp.top)&&(l=f,c=p):h&&bt(h,p)?h=vt(h,p.bottom):c&&bt(c,p)&&(c=yt(c,p.top))}}if(h&&h.bottom>=n?(i=a,s=h):c&&c.top<=n&&(i=l,s=c),!i)return{node:e,offset:0};let f=Math.max(s.left,Math.min(s.right,t));return 3==i.nodeType?wt(i,f,n):u&&"false"!=i.contentEditable?xt(i,f,n):{node:e,offset:Array.prototype.indexOf.call(e.childNodes,i)+(t>=(s.left+s.right)/2?1:0)}}function wt(e,t,n){let i=e.nodeValue.length,s=-1,r=1e9,o=0;for(let a=0;an?h.top-n:n-h.bottom)-1;if(h.left-1<=t&&h.right+1>=t&&c=(h.left+h.right)/2,i=n;if((U.chrome||U.gecko)&&C(e,a).getBoundingClientRect().left==h.right&&(i=!n),c<=0)return{node:e,offset:a+(i?1:0)};s=a+(i?1:0),r=c}}}return{node:e,offset:s>-1?s:o>0?e.nodeValue.length:0}}function kt(e,t,n,i=-1){var s,r;let o,a=e.contentDOM.getBoundingClientRect(),l=a.top+e.viewState.paddingTop,{docHeight:h}=e.viewState,{x:c,y:u}=t,f=u-l;if(f<0)return 0;if(f>h)return e.state.doc.length;for(let t=e.viewState.heightOracle.textHeight/2,s=!1;o=e.elementAtHeight(f),o.type!=he.Text;)for(;f=i>0?o.bottom+t:o.top-t,!(f>=0&&f<=h);){if(s)return n?null:0;s=!0,i=-i}u=l+f;let d=o.from;if(de.viewport.to)return e.viewport.to==e.state.doc.length?e.state.doc.length:n?null:St(e,a,o,c,u);let p=e.dom.ownerDocument,m=e.root.elementFromPoint?e.root:p,g=m.elementFromPoint(c,u);g&&!e.contentDOM.contains(g)&&(g=null),g||(c=Math.max(a.left+1,Math.min(a.right-1,c)),g=m.elementFromPoint(c,u),g&&!e.contentDOM.contains(g)&&(g=null));let b,y=-1;if(g&&0!=(null===(s=e.docView.nearest(g))||void 0===s?void 0:s.isEditable))if(p.caretPositionFromPoint){let e=p.caretPositionFromPoint(c,u);e&&({offsetNode:b,offset:y}=e)}else if(p.caretRangeFromPoint){let t=p.caretRangeFromPoint(c,u);t&&(({startContainer:b,startOffset:y}=t),(!e.contentDOM.contains(b)||U.safari&&function(e,t,n){let i;if(3!=e.nodeType||t!=(i=e.nodeValue.length))return!1;for(let t=e.nextSibling;t;t=t.nextSibling)if(1!=t.nodeType||"BR"!=t.nodeName)return!1;return C(e,i-1,i).getBoundingClientRect().left>n}(b,y,c)||U.chrome&&function(e,t,n){if(0!=t)return!1;for(let t=e;;){let e=t.parentNode;if(!e||1!=e.nodeType||e.firstChild!=t)return!1;if(e.classList.contains("cm-line"))break;t=e}return n-(1==e.nodeType?e.getBoundingClientRect():C(e,0,Math.max(e.nodeValue.length,1)).getBoundingClientRect()).left>5}(b,y,c))&&(b=void 0))}if(!b||!e.docView.dom.contains(b)){let t=oe.find(e.docView,d);if(!t)return f>o.top+o.height/2?o.to:o.from;({node:b,offset:y}=xt(t.dom,c,u))}let v=e.docView.nearest(b);if(!v)return null;if(v.isWidget&&1==(null===(r=v.dom)||void 0===r?void 0:r.nodeType)){let e=v.dom.getBoundingClientRect();return t.y1.5*e.defaultLineHeight){let t=e.viewState.heightOracle.textHeight;o+=Math.floor((r-n.top-.5*(e.defaultLineHeight-t))/t)*e.viewState.heightOracle.lineLength}let a=e.state.sliceDoc(n.from,n.to);return n.from+(0,i.Gz)(a,o,e.state.tabSize)}function At(e,t){let n=e.lineBlockAt(t);if(Array.isArray(n.type))for(let e of n.type)if(e.to>t||e.to==t&&(e.to==n.to||e.type==he.Text))return e;return n}function Ct(e,t,n,s){let r=e.state.doc.lineAt(t.head),o=e.bidiSpans(r),a=e.textDirectionAt(r.from);for(let l=t,h=null;;){let t=ht(r,o,a,l,n),c=lt;if(!t){if(r.number==(n?e.state.doc.lines:1))return l;c="\n",r=e.state.doc.line(r.number+(n?1:-1)),o=e.bidiSpans(r),t=i.jT.cursor(n?r.from:r.to)}if(h){if(!h(c))return l}else{if(!s)return t;h=s(c)}l=t}}function Ot(e,t,n){for(;;){let i=0;for(let s of e)s.between(t-1,t+1,((e,s,r)=>{if(t>e&&tt(e))),n.from,t.head>n.from?-1:1);return s==n.from?n:i.jT.cursor(s,snull)),U.gecko&&function(e){tn.has(e)||(tn.add(e),e.addEventListener("copy",(()=>{})),e.addEventListener("cut",(()=>{})))}(e.contentDOM.ownerDocument)}handleEvent(e){(function(e,t){if(!t.bubbles)return!0;if(t.defaultPrevented)return!1;for(let n,i=t.target;i!=e.contentDOM;i=i.parentNode)if(!i||11==i.nodeType||(n=D.get(i))&&n.ignoreEvent(t))return!1;return!0})(this.view,e)&&!this.ignoreDuringComposition(e)&&("keydown"==e.type&&this.keydown(e)||this.runHandlers(e.type,e))}runHandlers(e,t){let n=this.handlers[e];if(n){for(let e of n.observers)e(this.view,t);for(let e of n.handlers){if(t.defaultPrevented)break;if(e(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=Nt(e),n=this.handlers,i=this.view.contentDOM;for(let e in t)if("scroll"!=e){let s=!t[e].handlers.length,r=n[e];r&&s!=!r.handlers.length&&(i.removeEventListener(e,this.handleEvent),r=null),r||i.addEventListener(e,this.handleEvent,{passive:s})}for(let e in n)"scroll"==e||t[e]||i.removeEventListener(e,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),9==e.keyCode&&Date.now()t.keyCode==e.keyCode)))&&!e.ctrlKey||Et.indexOf(e.key)>-1&&e.ctrlKey&&!e.shiftKey)?(229!=e.keyCode&&this.view.observer.forceFlush(),!1):(this.pendingIOSKey=t||e,setTimeout((()=>this.flushIOSKey()),250),!0)}flushIOSKey(){let e=this.pendingIOSKey;return!!e&&(this.pendingIOSKey=void 0,O(this.view.contentDOM,e.key,e.keyCode))}ignoreDuringComposition(e){return!!/^key/.test(e.type)&&(this.composing>0||!!(U.safari&&!U.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100)&&(this.compositionPendingKey=!1,!0))}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}}function _t(e,t){return(n,i)=>{try{return t.call(e,i,n)}catch(e){Ne(n.state,e)}}}function Nt(e){let t=Object.create(null);function n(e){return t[e]||(t[e]={observers:[],handlers:[]})}for(let t of e){let e=t.spec;if(e&&e.domEventHandlers)for(let i in e.domEventHandlers){let s=e.domEventHandlers[i];s&&n(i).handlers.push(_t(t.value,s))}if(e&&e.domEventObservers)for(let i in e.domEventObservers){let s=e.domEventObservers[i];s&&n(i).observers.push(_t(t.value,s))}}for(let e in It)n(e).handlers.push(It[e]);for(let e in Bt)n(e).observers.push(Bt[e]);return t}const Dt=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],Et="dthko",jt=[16,17,18,20,91,92,224,225];function Rt(e){return.7*Math.max(0,e)+8}class Pt{constructor(e,t,n,s){this.view=e,this.startEvent=t,this.style=n,this.mustSelect=s,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParent=function(e){let t=e.ownerDocument;for(let n=e.parentNode;n&&n!=t.body;)if(1==n.nodeType){if(n.scrollHeight>n.clientHeight||n.scrollWidth>n.clientWidth)return n;n=n.assignedSlot||n.parentNode}else{if(11!=n.nodeType)break;n=n.host}return null}(e.contentDOM),this.atoms=e.state.facet($e).map((t=>t(e)));let r=e.contentDOM.ownerDocument;r.addEventListener("mousemove",this.move=this.move.bind(this)),r.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(i.yy.allowMultipleSelections)&&function(e,t){let n=e.state.facet(ve);return n.length?n[0](t):U.mac?t.metaKey:t.ctrlKey}(e,t),this.dragging=!(!function(e,t){let{main:n}=e.state.selection;if(n.empty)return!1;let i=u(e.root);if(!i||0==i.rangeCount)return!0;let s=i.getRangeAt(0).getClientRects();for(let e=0;e=t.clientX&&n.top<=t.clientY&&n.bottom>=t.clientY)return!0}return!1}(e,t)||1!=Kt(t))&&null}start(e){!1===this.dragging&&this.select(e)}move(e){var t,n,i;if(0==e.buttons)return this.destroy();if(this.dragging||null==this.dragging&&(n=this.startEvent,i=e,Math.max(Math.abs(n.clientX-i.clientX),Math.abs(n.clientY-i.clientY))<10))return;this.select(this.lastEvent=e);let s=0,r=0,o=(null===(t=this.scrollParent)||void 0===t?void 0:t.getBoundingClientRect())||{left:0,top:0,right:this.view.win.innerWidth,bottom:this.view.win.innerHeight},a=Ve(this.view);e.clientX-a.left<=o.left+6?s=-Rt(o.left-e.clientX):e.clientX+a.right>=o.right-6&&(s=Rt(e.clientX-o.right)),e.clientY-a.top<=o.top+6?r=-Rt(o.top-e.clientY):e.clientY+a.bottom>=o.bottom-6&&(r=Rt(e.clientY-o.bottom)),this.setScrollSpeed(s,r)}up(e){null==this.dragging&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval((()=>this.scroll()),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){this.scrollParent?(this.scrollParent.scrollLeft+=this.scrollSpeed.x,this.scrollParent.scrollTop+=this.scrollSpeed.y):this.view.win.scrollBy(this.scrollSpeed.x,this.scrollSpeed.y),!1===this.dragging&&this.select(this.lastEvent)}skipAtoms(e){let t=null;for(let n=0;nthis.select(this.lastEvent)),20)}}const It=Object.create(null),Bt=Object.create(null),Lt=U.ie&&U.ie_version<15||U.ios&&U.webkit_version<604;function $t(e,t){let n,{state:s}=e,r=1,o=s.toText(t),a=o.lines==s.selection.ranges.length;if(null!=Xt&&s.selection.ranges.every((e=>e.empty))&&Xt==o.toString()){let e=-1;n=s.changeByRange((n=>{let l=s.doc.lineAt(n.from);if(l.from==e)return{range:n};e=l.from;let h=s.toText((a?o.line(r++).text:t)+s.lineBreak);return{changes:{from:l.from,insert:h},range:i.jT.cursor(n.from+h.length)}}))}else n=a?s.changeByRange((e=>{let t=o.line(r++);return{changes:{from:e.from,to:e.to,insert:t.text},range:i.jT.cursor(e.from+t.length)}})):s.replaceSelection(o);e.dispatch(n,{userEvent:"input.paste",scrollIntoView:!0})}function zt(e,t,n,s){if(1==s)return i.jT.cursor(t,n);if(2==s)return function(e,t,n=1){let s=e.charCategorizer(t),r=e.doc.lineAt(t),o=t-r.from;if(0==r.length)return i.jT.cursor(t);0==o?n=1:o==r.length&&(n=-1);let a=o,l=o;n<0?a=(0,i.cp)(r.text,o,!1):l=(0,i.cp)(r.text,o);let h=s(r.text.slice(a,l));for(;a>0;){let e=(0,i.cp)(r.text,a,!1);if(s(r.text.slice(e,a))!=h)break;a=e}for(;l{e.inputState.lastScrollTop=e.scrollDOM.scrollTop,e.inputState.lastScrollLeft=e.scrollDOM.scrollLeft},It.keydown=(e,t)=>(e.inputState.setSelectionOrigin("select"),27==t.keyCode&&(e.inputState.lastEscPress=Date.now()),!1),Bt.touchstart=(e,t)=>{e.inputState.lastTouchTime=Date.now(),e.inputState.setSelectionOrigin("select.pointer")},Bt.touchmove=e=>{e.inputState.setSelectionOrigin("select.pointer")},It.mousedown=(e,t)=>{if(e.observer.flush(),e.inputState.lastTouchTime>Date.now()-2e3)return!1;let n=null;for(let i of e.state.facet(we))if(n=i(e,t),n)break;if(n||0!=t.button||(n=function(e,t){let n=Wt(e,t),s=Kt(t),r=e.state.selection;return{update(e){e.docChanged&&(n.pos=e.changes.mapPos(n.pos),r=r.map(e.changes))},get(t,o,a){let l,h=Wt(e,t),c=zt(e,h.pos,h.bias,s);if(n.pos!=h.pos&&!o){let t=zt(e,n.pos,n.bias,s),r=Math.min(t.from,c.from),o=Math.max(t.to,c.to);c=r1&&(l=function(e,t){for(let n=0;n=t)return i.jT.create(e.ranges.slice(0,n).concat(e.ranges.slice(n+1)),e.mainIndex==n?0:e.mainIndex-(e.mainIndex>n?1:0))}return null}(r,h.pos))?l:a?r.addRange(c):i.jT.create([c])}}}(e,t)),n){let i=!e.hasFocus;e.inputState.startMouseSelection(new Pt(e,t,n,i)),i&&e.observer.ignore((()=>A(e.contentDOM)));let s=e.inputState.mouseSelection;if(s)return s.start(t),!1===s.dragging}return!1};let Ft=(e,t)=>e>=t.top&&e<=t.bottom,Ht=(e,t,n)=>Ft(t,n)&&e>=n.left&&e<=n.right;function Vt(e,t,n,i){let s=oe.find(e.docView,t);if(!s)return 1;let r=t-s.posAtStart;if(0==r)return 1;if(r==s.length)return-1;let o=s.coordsAt(r,-1);if(o&&Ht(n,i,o))return-1;let a=s.coordsAt(r,1);return a&&Ht(n,i,a)?1:o&&Ft(i,o)?-1:1}function Wt(e,t){let n=e.posAtCoords({x:t.clientX,y:t.clientY},!1);return{pos:n,bias:Vt(e,n,t.clientX,t.clientY)}}const qt=U.ie&&U.ie_version<=11;let Jt=null,Ut=0,Gt=0;function Kt(e){if(!qt)return e.detail;let t=Jt,n=Gt;return Jt=e,Gt=Date.now(),Ut=!t||n>Date.now()-400&&Math.abs(t.clientX-e.clientX)<2&&Math.abs(t.clientY-e.clientY)<2?(Ut+1)%3:1}function Yt(e,t,n,i){if(!n)return;let s=e.posAtCoords({x:t.clientX,y:t.clientY},!1),{draggedContent:r}=e.inputState,o=i&&r&&function(e,t){let n=e.state.facet(xe);return n.length?n[0](t):U.mac?!t.altKey:!t.ctrlKey}(e,t)?{from:r.from,to:r.to}:null,a={from:s,insert:n},l=e.state.changes(o?[o,a]:a);e.focus(),e.dispatch({changes:l,selection:{anchor:l.mapPos(s,-1),head:l.mapPos(s,1)},userEvent:o?"move.drop":"input.drop"}),e.inputState.draggedContent=null}It.dragstart=(e,t)=>{let{selection:{main:n}}=e.state;if(t.target.draggable){let s=e.docView.nearest(t.target);if(s&&s.isWidget){let e=s.posAtStart,t=e+s.length;(e>=n.to||t<=n.from)&&(n=i.jT.range(e,t))}}let{inputState:s}=e;return s.mouseSelection&&(s.mouseSelection.dragging=!0),s.draggedContent=n,t.dataTransfer&&(t.dataTransfer.setData("Text",e.state.sliceDoc(n.from,n.to)),t.dataTransfer.effectAllowed="copyMove"),!1},It.dragend=e=>(e.inputState.draggedContent=null,!1),It.drop=(e,t)=>{if(!t.dataTransfer)return!1;if(e.state.readOnly)return!0;let n=t.dataTransfer.files;if(n&&n.length){let i=Array(n.length),s=0,r=()=>{++s==n.length&&Yt(e,t,i.filter((e=>null!=e)).join(e.state.lineBreak),!1)};for(let e=0;e{/[\x00-\x08\x0e-\x1f]{2}/.test(t.result)||(i[e]=t.result),r()},t.readAsText(n[e])}return!0}{let n=t.dataTransfer.getData("Text");if(n)return Yt(e,t,n,!0),!0}return!1},It.paste=(e,t)=>{if(e.state.readOnly)return!0;e.observer.flush();let n=Lt?null:t.clipboardData;return n?($t(e,n.getData("text/plain")||n.getData("text/uri-text")),!0):(function(e){let t=e.dom.parentNode;if(!t)return;let n=t.appendChild(document.createElement("textarea"));n.style.cssText="position: fixed; left: -10000px; top: 10px",n.focus(),setTimeout((()=>{e.focus(),n.remove(),$t(e,n.value)}),50)}(e),!1)};let Xt=null;It.copy=It.cut=(e,t)=>{let{text:n,ranges:i,linewise:s}=function(e){let t=[],n=[],i=!1;for(let i of e.selection.ranges)i.empty||(t.push(e.sliceDoc(i.from,i.to)),n.push(i));if(!t.length){let s=-1;for(let{from:i}of e.selection.ranges){let r=e.doc.lineAt(i);r.number>s&&(t.push(r.text),n.push({from:r.from,to:Math.min(e.doc.length,r.to+1)})),s=r.number}i=!0}return{text:t.join(e.lineBreak),ranges:n,linewise:i}}(e.state);if(!n&&!s)return!1;Xt=s?n:null,"cut"!=t.type||e.state.readOnly||e.dispatch({changes:i,scrollIntoView:!0,userEvent:"delete.cut"});let r=Lt?null:t.clipboardData;return r?(r.clearData(),r.setData("text/plain",n),!0):(function(e,t){let n=e.dom.parentNode;if(!n)return;let i=n.appendChild(document.createElement("textarea"));i.style.cssText="position: fixed; left: -10000px; top: 10px",i.value=t,i.focus(),i.selectionEnd=t.length,i.selectionStart=0,setTimeout((()=>{i.remove(),e.focus()}),50)}(e,n),!1)};const Qt=i.q6.define();function Zt(e,t){let n=[];for(let i of e.facet(Ce)){let s=i(e,t);s&&n.push(s)}return n?e.update({effects:n,annotations:Qt.of(!0)}):null}function en(e){setTimeout((()=>{let t=e.hasFocus;if(t!=e.inputState.notifiedFocused){let n=Zt(e.state,t);n?e.dispatch(n):e.update([])}}),10)}Bt.focus=e=>{e.inputState.lastFocusTime=Date.now(),e.scrollDOM.scrollTop||!e.inputState.lastScrollTop&&!e.inputState.lastScrollLeft||(e.scrollDOM.scrollTop=e.inputState.lastScrollTop,e.scrollDOM.scrollLeft=e.inputState.lastScrollLeft),en(e)},Bt.blur=e=>{e.observer.clearSelectionRange(),en(e)},Bt.compositionstart=Bt.compositionupdate=e=>{null==e.inputState.compositionFirstChange&&(e.inputState.compositionFirstChange=!0),e.inputState.composing<0&&(e.inputState.composing=0)},Bt.compositionend=e=>{e.inputState.composing=-1,e.inputState.compositionEndedAt=Date.now(),e.inputState.compositionPendingKey=!0,e.inputState.compositionPendingChange=e.observer.pendingRecords().length>0,e.inputState.compositionFirstChange=null,U.chrome&&U.android?e.observer.flushSoon():e.inputState.compositionPendingChange?Promise.resolve().then((()=>e.observer.flush())):setTimeout((()=>{e.inputState.composing<0&&e.docView.hasComposition&&e.update([])}),50)},Bt.contextmenu=e=>{e.inputState.lastContextMenu=Date.now()},It.beforeinput=(e,t)=>{var n;let i;if(U.chrome&&U.android&&(i=Dt.find((e=>e.inputType==t.inputType)))&&(e.observer.delayAndroidKey(i.key,i.keyCode),"Backspace"==i.key||"Delete"==i.key)){let t=(null===(n=window.visualViewport)||void 0===n?void 0:n.height)||0;setTimeout((()=>{var n;((null===(n=window.visualViewport)||void 0===n?void 0:n.height)||0)>t+10&&e.hasFocus&&(e.contentDOM.blur(),e.focus())}),100)}return!1};const tn=new Set,nn=["pre-wrap","normal","pre-line","break-spaces"];class sn{constructor(e){this.lineWrapping=e,this.doc=i.xv.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30,this.heightChanged=!1}heightForGap(e,t){let n=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(n+=Math.max(0,Math.ceil((t-e-n*this.lineLength*.5)/this.lineLength))),this.lineHeight*n}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/(this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return nn.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let n=0;n-1,a=Math.round(t)!=Math.round(this.lineHeight)||this.lineWrapping!=o;if(this.lineWrapping=o,this.lineHeight=t,this.charWidth=n,this.textHeight=i,this.lineLength=s,a){this.heightSamples={};for(let e=0;e0}set outdated(e){this.flags=(e?2:0)|-3&this.flags}setHeight(e,t){this.height!=t&&(Math.abs(this.height-t)>ln&&(e.heightChanged=!0),this.height=t)}replace(e,t,n){return hn.of(n)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,n,i){let s=this,r=n.doc;for(let o=i.length-1;o>=0;o--){let{fromA:a,toA:l,fromB:h,toB:c}=i[o],u=s.lineAt(a,an.ByPosNoHeight,n.setDoc(t),0,0),f=u.to>=l?u:s.lineAt(l,an.ByPosNoHeight,n,0,0);for(c+=f.to-l,l=f.to;o>0&&u.from<=i[o-1].toA;)a=i[o-1].fromA,h=i[o-1].fromB,o--,a2*s){let s=e[t-1];s.break?e.splice(--t,1,s.left,null,s.right):e.splice(--t,1,s.left,s.right),n+=1+s.break,i-=s.size}else{if(!(s>2*i))break;{let t=e[n];t.break?e.splice(n,1,t.left,null,t.right):e.splice(n,1,t.left,t.right),n+=2+t.break,s-=t.size}}else if(i=s&&r(this.blockAt(0,n,i,s))}updateHeight(e,t=0,n=!1,i){return i&&i.from<=t&&i.more&&this.setHeight(e,i.heights[i.index++]),this.outdated=!1,this}toString(){return`block(${this.length})`}}class un extends cn{constructor(e,t){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0}blockAt(e,t,n,i){return new on(i,this.length,n,this.height,this.breaks)}replace(e,t,n){let i=n[0];return 1==n.length&&(i instanceof un||i instanceof fn&&4&i.flags)&&Math.abs(this.length-i.length)<10?(i instanceof fn?i=new un(i.length,this.height):i.height=this.height,this.outdated||(i.outdated=!1),i):hn.of(n)}updateHeight(e,t=0,n=!1,i){return i&&i.from<=t&&i.more?this.setHeight(e,i.heights[i.index++]):(n||this.outdated)&&this.setHeight(e,Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}}class fn extends hn{constructor(e){super(e,0)}heightMetrics(e,t){let n,i=e.doc.lineAt(t).number,s=e.doc.lineAt(t+this.length).number,r=s-i+1,o=0;if(e.lineWrapping){let t=Math.min(this.height,e.lineHeight*r);n=t/r,this.length>r+1&&(o=(this.height-t)/(this.length-r-1))}else n=this.height/r;return{firstLine:i,lastLine:s,perLine:n,perChar:o}}blockAt(e,t,n,i){let{firstLine:s,lastLine:r,perLine:o,perChar:a}=this.heightMetrics(t,i);if(t.lineWrapping){let s=i+Math.round(Math.max(0,Math.min(1,(e-n)/this.height))*this.length),r=t.doc.lineAt(s),l=o+r.length*a,h=Math.max(n,e-l/2);return new on(r.from,r.length,h,l,0)}{let i=Math.max(0,Math.min(r-s,Math.floor((e-n)/o))),{from:a,length:l}=t.doc.line(s+i);return new on(a,l,n+o*i,o,0)}}lineAt(e,t,n,i,s){if(t==an.ByHeight)return this.blockAt(e,n,i,s);if(t==an.ByPosNoHeight){let{from:t,to:i}=n.doc.lineAt(e);return new on(t,i-t,0,0,0)}let{firstLine:r,perLine:o,perChar:a}=this.heightMetrics(n,s),l=n.doc.lineAt(e),h=o+l.length*a,c=l.number-r,u=i+o*c+a*(l.from-s-c);return new on(l.from,l.length,Math.max(i,Math.min(u,i+this.height-h)),h,0)}forEachLine(e,t,n,i,s,r){e=Math.max(e,s),t=Math.min(t,s+this.length);let{firstLine:o,perLine:a,perChar:l}=this.heightMetrics(n,s);for(let h=e,c=i;h<=t;){let t=n.doc.lineAt(h);if(h==e){let n=t.number-o;c+=a*n+l*(e-s-n)}let i=a+l*t.length;r(new on(t.from,t.length,c,i,0)),c+=i,h=t.to+1}}replace(e,t,n){let i=this.length-t;if(i>0){let e=n[n.length-1];e instanceof fn?n[n.length-1]=new fn(e.length+i):n.push(null,new fn(i-1))}if(e>0){let t=n[0];t instanceof fn?n[0]=new fn(e+t.length):n.unshift(new fn(e-1),null)}return hn.of(n)}decomposeLeft(e,t){t.push(new fn(e-1),null)}decomposeRight(e,t){t.push(null,new fn(this.length-e-1))}updateHeight(e,t=0,n=!1,i){let s=t+this.length;if(i&&i.from<=t+this.length&&i.more){let n=[],r=Math.max(t,i.from),o=-1;for(i.from>t&&n.push(new fn(i.from-t-1).updateHeight(e,t));r<=s&&i.more;){let t=e.doc.lineAt(r).length;n.length&&n.push(null);let s=i.heights[i.index++];-1==o?o=s:Math.abs(s-o)>=ln&&(o=-2);let a=new un(t,s);a.outdated=!1,n.push(a),r+=t+1}r<=s&&n.push(null,new fn(s-r).updateHeight(e,r));let a=hn.of(n);return(o<0||Math.abs(a.height-this.height)>=ln||Math.abs(o-this.heightMetrics(e,t).perLine)>=ln)&&(e.heightChanged=!0),a}return(n||this.outdated)&&(this.setHeight(e,e.heightForGap(t,t+this.length)),this.outdated=!1),this}toString(){return`gap(${this.length})`}}class dn extends hn{constructor(e,t,n){super(e.length+t+n.length,e.height+n.height,t|(e.outdated||n.outdated?2:0)),this.left=e,this.right=n,this.size=e.size+n.size}get break(){return 1&this.flags}blockAt(e,t,n,i){let s=n+this.left.height;return eo))return l;let h=t==an.ByPosNoHeight?an.ByPosNoHeight:an.ByPos;return a?l.join(this.right.lineAt(o,h,n,r,o)):this.left.lineAt(o,h,n,i,s).join(l)}forEachLine(e,t,n,i,s,r){let o=i+this.left.height,a=s+this.left.length+this.break;if(this.break)e=a&&this.right.forEachLine(e,t,n,o,a,r);else{let l=this.lineAt(a,an.ByPos,n,i,s);e=e&&l.from<=t&&r(l),t>l.to&&this.right.forEachLine(l.to+1,t,n,o,a,r)}}replace(e,t,n){let i=this.left.length+this.break;if(tthis.left.length)return this.balanced(this.left,this.right.replace(e-i,t-i,n));let s=[];e>0&&this.decomposeLeft(e,s);let r=s.length;for(let e of n)s.push(e);if(e>0&&pn(s,r-1),t=n&&t.push(null)),e>n&&this.right.decomposeLeft(e-n,t)}decomposeRight(e,t){let n=this.left.length,i=n+this.break;if(e>=i)return this.right.decomposeRight(e-i,t);e2*t.size||t.size>2*e.size?hn.of(this.break?[e,null,t]:[e,t]):(this.left=e,this.right=t,this.height=e.height+t.height,this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,n=!1,i){let{left:s,right:r}=this,o=t+s.length+this.break,a=null;return i&&i.from<=t+s.length&&i.more?a=s=s.updateHeight(e,t,n,i):s.updateHeight(e,t,n),i&&i.from<=o+r.length&&i.more?a=r=r.updateHeight(e,o,n,i):r.updateHeight(e,o,n),a?this.balanced(s,r):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}}function pn(e,t){let n,i;null==e[t]&&(n=e[t-1])instanceof fn&&(i=e[t+1])instanceof fn&&e.splice(t-1,3,new fn(n.length+1+i.length))}class mn{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let e=Math.min(t,this.lineEnd),n=this.nodes[this.nodes.length-1];n instanceof un?n.length+=e-this.pos:(e>this.pos||!this.isCovered)&&this.nodes.push(new un(e-this.pos,-1)),this.writtenTo=e,t>e&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,n){if(e=5)&&this.addLineDeco(i,s,r)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenToe&&this.nodes.push(new un(this.pos-e,-1)),this.writtenTo=this.pos}blankContent(e,t){let n=new fn(t-e);return this.oracle.doc.lineAt(e).to==t&&(n.flags|=4),n}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof un)return e;let t=new un(0,-1);return this.nodes.push(t),t}addBlock(e){this.enterLine();let t=e.deco;t&&t.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,t&&t.endSide>0&&(this.covering=e)}addLineDeco(e,t,n){let i=this.ensureLine();i.length+=n,i.collapsed+=n,i.widgetHeight=Math.max(i.widgetHeight,e),i.breaks+=t,this.writtenTo=this.pos=this.pos+n}finish(e){let t=0==this.nodes.length?null:this.nodes[this.nodes.length-1];!(this.lineStart>-1)||t instanceof un||this.isCovered?(this.writtenTon.clientHeight||n.scrollWidth>n.clientWidth)&&"visible"!=i.overflow){let i=n.getBoundingClientRect();r=Math.max(r,i.left),o=Math.min(o,i.right),a=Math.max(a,i.top),l=t==e.parentNode?i.bottom:Math.min(l,i.bottom)}t="absolute"==i.position||"fixed"==i.position?n.offsetParent:n.parentNode}else{if(11!=t.nodeType)break;t=t.host}return{left:r-n.left,right:Math.max(r,o)-n.left,top:a-(n.top+t),bottom:Math.max(a,l)-(n.top+t)}}function yn(e,t){let n=e.getBoundingClientRect();return{left:0,right:n.right-n.left,top:t,bottom:n.bottom-(n.top+t)}}class vn{constructor(e,t,n){this.from=e,this.to=t,this.size=n}static same(e,t){if(e.length!=t.length)return!1;for(let n=0;n"function"!=typeof e&&"cm-lineWrapping"==e.class));this.heightOracle=new sn(t),this.stateDeco=e.facet(Le).filter((e=>"function"!=typeof e)),this.heightMap=hn.empty().applyChanges(this.stateDeco,i.xv.empty,this.heightOracle.setDoc(e.doc),[new qe(0,0,0,e.doc.length)]),this.viewport=this.getViewport(0,null),this.updateViewportLines(),this.updateForViewport(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=ce.set(this.lineGaps.map((e=>e.draw(this,!1)))),this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let n=0;n<=1;n++){let i=n?t.head:t.anchor;if(!e.some((({from:e,to:t})=>i>=e&&i<=t))){let{from:t,to:n}=this.lineBlockAt(i);e.push(new kn(t,n))}}this.viewports=e.sort(((e,t)=>e.from-t.from)),this.scaler=this.heightMap.height<=7e6?On:new Mn(this.heightOracle,this.heightMap,this.viewports)}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,(e=>{this.viewportLines.push(1==this.scaler.scale?e:Tn(e,this.scaler))}))}update(e,t=null){this.state=e.state;let n=this.stateDeco;this.stateDeco=this.state.facet(Le).filter((e=>"function"!=typeof e));let s=e.changedRanges,r=qe.extendWithRanges(s,function(e,t,n){let s=new gn;return i.Xs.compare(e,t,n,s,0),s.changes}(n,this.stateDeco,e?e.changes:i.as.empty(this.state.doc.length))),o=this.heightMap.height,a=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollTop);this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),r),this.heightMap.height!=o&&(e.flags|=2),a?(this.scrollAnchorPos=e.changes.mapPos(a.from,-1),this.scrollAnchorHeight=a.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=this.heightMap.height);let l=r.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.headl.to)||!this.viewportIsAppropriate(l))&&(l=this.getViewport(0,t));let h=!e.changes.empty||2&e.flags||l.from!=this.viewport.from||l.to!=this.viewport.to;this.viewport=l,this.updateForViewport(),h&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&e.selectionSet&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(Me)&&(this.mustEnforceCursorAssoc=!0)}measure(e){let t=e.contentDOM,n=window.getComputedStyle(t),s=this.heightOracle,r=n.whiteSpace;this.defaultTextDirection="rtl"==n.direction?Ue.RTL:Ue.LTR;let o=this.heightOracle.mustRefreshForWrapping(r),a=t.getBoundingClientRect(),l=o||this.mustMeasureContent||this.contentDOMHeight!=a.height;this.contentDOMHeight=a.height,this.mustMeasureContent=!1;let h=0,c=0;if(a.width&&a.height){let e=a.width/t.offsetWidth,n=a.height/t.offsetHeight;(e>.995&&e<1.005||!isFinite(e)||Math.abs(a.width-t.offsetWidth)<1)&&(e=1),(n>.995&&n<1.005||!isFinite(n)||Math.abs(a.height-t.offsetHeight)<1)&&(n=1),this.scaleX==e&&this.scaleY==n||(this.scaleX=e,this.scaleY=n,h|=8,o=l=!0)}let u=(parseInt(n.paddingTop)||0)*this.scaleY,f=(parseInt(n.paddingBottom)||0)*this.scaleY;this.paddingTop==u&&this.paddingBottom==f||(this.paddingTop=u,this.paddingBottom=f,h|=10),this.editorWidth!=e.scrollDOM.clientWidth&&(s.lineWrapping&&(l=!0),this.editorWidth=e.scrollDOM.clientWidth,h|=8);let d=e.scrollDOM.scrollTop*this.scaleY;this.scrollTop!=d&&(this.scrollAnchorHeight=-1,this.scrollTop=d),this.scrolledToBottom=T(e.scrollDOM);let p=(this.printing?yn:bn)(t,this.paddingTop),m=p.top-this.pixelViewport.top,g=p.bottom-this.pixelViewport.bottom;this.pixelViewport=p;let b=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(b!=this.inView&&(this.inView=b,b&&(l=!0)),!this.inView&&!this.scrollTarget)return 0;let y=a.width;if(this.contentDOMWidth==y&&this.editorHeight==e.scrollDOM.clientHeight||(this.contentDOMWidth=a.width,this.editorHeight=e.scrollDOM.clientHeight,h|=8),l){let t=e.docView.measureVisibleLineHeights(this.viewport);if(s.mustRefreshForHeights(t)&&(o=!0),o||s.lineWrapping&&Math.abs(y-this.contentDOMWidth)>s.charWidth){let{lineHeight:n,charWidth:i,textHeight:a}=e.docView.measureTextSize();o=n>0&&s.refresh(r,n,i,a,y/i,t),o&&(e.docView.minWidth=0,h|=8)}m>0&&g>0?c=Math.max(m,g):m<0&&g<0&&(c=Math.min(m,g)),s.heightChanged=!1;for(let n of this.viewports){let r=n.from==this.viewport.from?t:e.docView.measureVisibleLineHeights(n);this.heightMap=(o?hn.empty().applyChanges(this.stateDeco,i.xv.empty,this.heightOracle,[new qe(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(s,0,o,new rn(n.from,r))}s.heightChanged&&(h|=2)}let v=!this.viewportIsAppropriate(this.viewport,c)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return v&&(this.viewport=this.getViewport(c,this.scrollTarget)),this.updateForViewport(),(2&h||v)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),h|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),h}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let n=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),i=this.heightMap,s=this.heightOracle,{visibleTop:r,visibleBottom:o}=this,a=new kn(i.lineAt(r-1e3*n,an.ByHeight,s,0,0).from,i.lineAt(o+1e3*(1-n),an.ByHeight,s,0,0).to);if(t){let{head:e}=t.range;if(ea.to){let n,r=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),o=i.lineAt(e,an.ByPos,s,0,0);n="center"==t.y?(o.top+o.bottom)/2-r/2:"start"==t.y||"nearest"==t.y&&e=o+Math.max(10,Math.min(n,250)))&&i>r-2e3&&s>1,o=s<<1;if(this.defaultTextDirection!=Ue.LTR&&!n)return[];let a=[],l=(s,o,h,c)=>{if(o-ss&&ee.from>=h.from&&e.to<=h.to&&Math.abs(e.from-s)e.fromt))));if(!d){if(oe.from<=o&&e.to>=o))){let e=t.moveToLineBoundary(i.jT.cursor(o),!1,!0).head;e>s&&(o=e)}d=new vn(s,o,this.gapSize(h,s,o,c))}a.push(d)};for(let e of this.viewportLines){if(e.lengthe.from&&l(e.from,i,e,t),re.draw(this,this.heightOracle.lineWrapping)))))}computeVisibleRanges(){let e=this.stateDeco;this.lineGaps.length&&(e=e.concat(this.lineGapDeco));let t=[];i.Xs.spans(e,this.viewport.from,this.viewport.to,{span(e,n){t.push({from:e,to:n})},point(){}},20);let n=t.length!=this.visibleRanges.length||this.visibleRanges.some(((e,n)=>e.from!=t[n].from||e.to!=t[n].to));return this.visibleRanges=t,n?4:0}lineBlockAt(e){return e>=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find((t=>t.from<=e&&t.to>=e))||Tn(this.heightMap.lineAt(e,an.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return Tn(this.heightMap.lineAt(this.scaler.fromDOM(e),an.ByHeight,this.heightOracle,0,0),this.scaler)}scrollAnchorAt(e){let t=this.lineBlockAtHeight(e+8);return t.from>=this.viewport.from||this.viewportLines[0].top-e>200?t:this.viewportLines[0]}elementAtHeight(e){return Tn(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}}class kn{constructor(e,t){this.from=e,this.to=t}}function Sn(e,t,n){let s=[],r=e,o=0;return i.Xs.spans(n,e,t,{span(){},point(e,t){e>r&&(s.push({from:r,to:e}),o+=e-r),r=t}},20),r=1)return t[t.length-1].to;let i=Math.floor(e*n);for(let e=0;;e++){let{from:n,to:s}=t[e],r=s-n;if(i<=r)return n+i;i-=r}}function Cn(e,t){let n=0;for(let{from:i,to:s}of e.ranges){if(t<=s){n+=t-i;break}n+=s-i}return n/e.total}const On={toDOM:e=>e,fromDOM:e=>e,scale:1};class Mn{constructor(e,t,n){let i=0,s=0,r=0;this.viewports=n.map((({from:n,to:s})=>{let r=t.lineAt(n,an.ByPos,e,0,0).top,o=t.lineAt(s,an.ByPos,e,0,0).bottom;return i+=o-r,{from:n,to:s,top:r,bottom:o,domTop:0,domBottom:0}})),this.scale=(7e6-i)/(t.height-i);for(let e of this.viewports)e.domTop=r+(e.top-s)*this.scale,r=e.domBottom=e.domTop+(e.bottom-e.top),s=e.bottom}toDOM(e){for(let t=0,n=0,i=0;;t++){let s=tTn(e,t))):e._content)}const _n=i.r$.define({combine:e=>e.join(" ")}),Nn=i.r$.define({combine:e=>e.indexOf(!0)>-1}),Dn=s.V.newName(),En=s.V.newName(),jn=s.V.newName(),Rn={"&light":"."+En,"&dark":"."+jn};function Pn(e,t,n){return new s.V(t,{finish:t=>/&/.test(t)?t.replace(/&\w*/,(t=>{if("&"==t)return e;if(!n||!n[t])throw new RangeError(`Unsupported selector: ${t}`);return n[t]})):e+" "+t})}const In=Pn("."+Dn,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#444"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",insetInlineStart:0,zIndex:200},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",borderRight:"1px solid #ddd"},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top"},".cm-highlightSpace:before":{content:"attr(data-display)",position:"absolute",pointerEvents:"none",color:"#888"},".cm-highlightTab":{backgroundImage:'url(\'data:image/svg+xml,\')',backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},Rn),Bn="￿";class Ln{constructor(e,t){this.points=e,this.text="",this.lineSeparator=t.facet(i.yy.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=Bn}readRange(e,t){if(!e)return this;let n=e.parentNode;for(let i=e;;){this.findPointBefore(n,i);let e=this.text.length;this.readNode(i);let s=i.nextSibling;if(s==t)break;let r=D.get(i),o=D.get(s);(r&&o?r.breakAfter:(r?r.breakAfter:zn(i))||zn(s)&&("BR"!=i.nodeName||i.cmIgnore)&&this.text.length>e)&&this.lineBreak(),i=s}return this.findPointBefore(n,t),this}readTextNode(e){let t=e.nodeValue;for(let n of this.points)n.node==e&&(n.pos=this.text.length+Math.min(n.offset,t.length));for(let n=0,i=this.lineSeparator?null:/\r\n?|\n/g;;){let s,r=-1,o=1;if(this.lineSeparator?(r=t.indexOf(this.lineSeparator,n),o=this.lineSeparator.length):(s=i.exec(t))&&(r=s.index,o=s[0].length),this.append(t.slice(n,r<0?t.length:r)),r<0)break;if(this.lineBreak(),o>1)for(let t of this.points)t.node==e&&t.pos>this.text.length&&(t.pos-=o-1);n=r+o}}readNode(e){if(e.cmIgnore)return;let t=D.get(e),n=t&&t.overrideDOMText;if(null!=n){this.findPointInside(e,n.length);for(let e=n.iter();!e.next().done;)e.lineBreak?this.lineBreak():this.append(e.value)}else 3==e.nodeType?this.readTextNode(e):"BR"==e.nodeName?e.nextSibling&&this.lineBreak():1==e.nodeType&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let n of this.points)n.node==e&&e.childNodes[n.offset]==t&&(n.pos=this.text.length)}findPointInside(e,t){for(let n of this.points)(3==e.nodeType?n.node==e:e.contains(n.node))&&(n.pos=this.text.length+($n(e,n.node,n.offset)?t:0))}}function $n(e,t,n){for(;;){if(!t||n-1)this.newSel=null;else if(t>-1&&(this.bounds=e.docView.domBoundsAround(t,n,0))){let t=r||o?[]:function(e){let t=[];if(e.root.activeElement!=e.contentDOM)return t;let{anchorNode:n,anchorOffset:i,focusNode:s,focusOffset:r}=e.observer.selectionRange;return n&&(t.push(new Fn(n,i)),s==n&&r==i||t.push(new Fn(s,r))),t}(e),n=new Ln(t,e.state);n.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=n.text,this.newSel=function(e,t){if(0==e.length)return null;let n=e[0].pos,s=2==e.length?e[1].pos:n;return n>-1&&s>-1?i.jT.single(n+t,s+t):null}(t,this.bounds.from)}else{let t=e.observer.selectionRange,n=r&&r.node==t.focusNode&&r.offset==t.focusOffset||!f(e.contentDOM,t.focusNode)?e.state.selection.main.head:e.docView.posFromDOM(t.focusNode,t.focusOffset),s=o&&o.node==t.anchorNode&&o.offset==t.anchorOffset||!f(e.contentDOM,t.anchorNode)?e.state.selection.main.anchor:e.docView.posFromDOM(t.anchorNode,t.anchorOffset);this.newSel=i.jT.single(s,n)}}}function Vn(e,t){let n,{newSel:s}=t,r=e.state.selection.main,o=e.inputState.lastKeyTime>Date.now()-100?e.inputState.lastKeyCode:-1;if(t.bounds){let{from:s,to:a}=t.bounds,l=r.from,h=null;(8===o||U.android&&t.text.length0&&a>0&&e.charCodeAt(o-1)==t.charCodeAt(a-1);)o--,a--;return"end"==i&&(n-=o+Math.max(0,r-Math.min(o,a))-r),o=o?r-n:0,a=r+(a-o),o=r):a=a?r-n:0,o=r+(o-a),a=r),{from:r,toA:o,toB:a}}(e.state.doc.sliceString(s,a,Bn),t.text,l-s,h);c&&(U.chrome&&13==o&&c.toB==c.from+2&&t.text.slice(c.from,c.toB)==Bn+Bn&&c.toB--,n={from:s+c.from,to:s+c.toA,insert:i.xv.of(t.text.slice(c.from,c.toB).split(Bn))})}else s&&(!e.hasFocus&&e.state.facet(De)||s.main.eq(r))&&(s=null);if(!n&&!s)return!1;if(!n&&t.typeOver&&!r.empty&&s&&s.main.empty?n={from:r.from,to:r.to,insert:e.state.doc.slice(r.from,r.to)}:n&&n.from>=r.from&&n.to<=r.to&&(n.from!=r.from||n.to!=r.to)&&r.to-r.from-(n.to-n.from)<=4?n={from:r.from,to:r.to,insert:e.state.doc.slice(r.from,n.from).append(n.insert).append(e.state.doc.slice(n.to,r.to))}:(U.mac||U.android)&&n&&n.from==n.to&&n.from==r.head-1&&/^\. ?$/.test(n.insert.toString())&&"off"==e.contentDOM.getAttribute("autocorrect")?(s&&2==n.insert.length&&(s=i.jT.single(s.main.anchor-1,s.main.head-1)),n={from:r.from,to:r.to,insert:i.xv.of([" "])}):U.chrome&&n&&n.from==n.to&&n.from==r.head&&"\n "==n.insert.toString()&&e.lineWrapping&&(s&&(s=i.jT.single(s.main.anchor-1,s.main.head-1)),n={from:r.from,to:r.to,insert:i.xv.of([" "])}),n){if(U.ios&&e.inputState.flushIOSKey())return!0;if(U.android&&(n.from==r.from&&n.to==r.to&&1==n.insert.length&&2==n.insert.lines&&O(e.contentDOM,"Enter",13)||(n.from==r.from-1&&n.to==r.to&&0==n.insert.length||8==o&&n.insert.lengthr.head)&&O(e.contentDOM,"Backspace",8)||n.from==r.from&&n.to==r.to+1&&0==n.insert.length&&O(e.contentDOM,"Delete",46)))return!0;let t,a=n.insert.toString();e.inputState.composing>=0&&e.inputState.composing++;let l=()=>t||(t=function(e,t,n){let s,r=e.state,o=r.selection.main;if(t.from>=o.from&&t.to<=o.to&&t.to-t.from>=(o.to-o.from)/3&&(!n||n.main.empty&&n.main.from==t.from+t.insert.length)&&e.inputState.composing<0){let n=o.fromt.to?r.sliceDoc(t.to,o.to):"";s=r.replaceSelection(e.state.toText(n+t.insert.sliceString(0,void 0,e.state.lineBreak)+i))}else{let a=r.changes(t),l=n&&n.main.to<=a.newLength?n.main:void 0;if(r.selection.ranges.length>1&&e.inputState.composing>=0&&t.to<=o.to&&t.to>=o.to-10){let h,c=e.state.sliceDoc(t.from,t.to),u=n&&ft(e,n.main.head);if(u){let e=t.insert.length-(t.to-t.from);h={from:u.from,to:u.to-e}}else h=e.state.doc.lineAt(o.head);let f=o.to-t.to,d=o.to-o.from;s=r.changeByRange((n=>{if(n.from==o.from&&n.to==o.to)return{changes:a,range:l||n.map(a)};let s=n.to-f,u=s-c.length;if(n.to-n.from!=d||e.state.sliceDoc(u,s)!=c||n.to>=h.from&&n.from<=h.to)return{range:n};let p=r.changes({from:u,to:s,insert:t.insert}),m=n.to-o.to;return{changes:p,range:l?i.jT.range(Math.max(0,l.anchor+m),Math.max(0,l.head+m)):n.map(p)}}))}else s={changes:a,selection:l&&r.selection.replaceRange(l)}}let a="input.type";return(e.composing||e.inputState.compositionPendingChange&&e.inputState.compositionEndedAt>Date.now()-50)&&(e.inputState.compositionPendingChange=!1,a+=".compose",e.inputState.compositionFirstChange&&(a+=".start",e.inputState.compositionFirstChange=!1)),r.update(s,{userEvent:a,scrollIntoView:!0})}(e,n,s));return e.state.facet(Ae).some((t=>t(e,n.from,n.to,a,l)))||e.dispatch(l()),!0}if(s&&!s.main.eq(r)){let t=!1,n="select";return e.inputState.lastSelectionTime>Date.now()-50&&("select"==e.inputState.lastSelectionOrigin&&(t=!0),n=e.inputState.lastSelectionOrigin),e.dispatch({selection:s,scrollIntoView:t,userEvent:n}),!0}return!1}const Wn={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},qn=U.ie&&U.ie_version<=11;class Jn{constructor(e){this.view=e,this.active=!1,this.selectionRange=new w,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver((t=>{for(let e of t)this.queue.push(e);(U.ie&&U.ie_version<=11||U.ios&&e.composing)&&t.some((e=>"childList"==e.type&&e.removedNodes.length||"characterData"==e.type&&e.oldValue.length>e.target.nodeValue.length))?this.flushSoon():this.flush()})),qn&&(this.onCharData=e=>{this.queue.push({target:e.target,type:"characterData",oldValue:e.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),"function"==typeof ResizeObserver&&(this.resizeScroll=new ResizeObserver((()=>{var e;(null===(e=this.view.docView)||void 0===e?void 0:e.lastUpdate){this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),e.length>0&&e[e.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))}),{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver((e=>{e.length>0&&e[e.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))}),{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout((()=>{this.resizeTimeout=-1,this.view.requestMeasure()}),50))}onPrint(){this.view.viewState.printing=!0,this.view.measure(),setTimeout((()=>{this.view.viewState.printing=!1,this.view.requestMeasure()}),500)}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some(((t,n)=>t!=e[n])))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:n}=this,i=this.selectionRange;if(n.state.facet(De)?n.root.activeElement!=this.dom:!d(n.dom,i))return;let s=i.anchorNode&&n.docView.nearest(i.anchorNode);s&&s.ignoreEvent(e)?t||(this.selectionChanged=!1):(U.ie&&U.ie_version<=11||U.android&&U.chrome)&&!n.state.selection.main.empty&&i.focusNode&&m(i.focusNode,i.focusOffset,i.anchorNode,i.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=U.safari&&11==e.root.nodeType&&function(e){let t=e.activeElement;for(;t&&t.shadowRoot;)t=t.shadowRoot.activeElement;return t}(this.dom.ownerDocument)==this.dom&&function(e){let t=null;function n(e){e.preventDefault(),e.stopImmediatePropagation(),t=e.getTargetRanges()[0]}if(e.contentDOM.addEventListener("beforeinput",n,!0),e.dom.ownerDocument.execCommand("indent"),e.contentDOM.removeEventListener("beforeinput",n,!0),!t)return null;let i=t.startContainer,s=t.startOffset,r=t.endContainer,o=t.endOffset,a=e.docView.domAtPos(e.state.selection.main.anchor);return m(a.node,a.offset,r,o)&&([i,s,r,o]=[r,o,i,s]),{anchorNode:i,anchorOffset:s,focusNode:r,focusOffset:o}}(this.view)||u(e.root);if(!t||this.selectionRange.eq(t))return!1;let n=d(this.dom,t);return n&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime{let e=this.delayedAndroidKey;e&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=e.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&e.force&&O(this.dom,e.key,e.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(e)}this.delayedAndroidKey&&"Enter"!=e||(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange{this.delayedFlush=-1,this.flush()})))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let t=-1,n=-1,i=!1;for(let s of e){let e=this.readMutation(s);e&&(e.typeOver&&(i=!0),-1==t?({from:t,to:n}=e):(t=Math.min(e.from,t),n=Math.max(e.to,n)))}return{from:t,to:n,typeOver:i}}readChange(){let{from:e,to:t,typeOver:n}=this.processRecords(),i=this.selectionChanged&&d(this.dom,this.selectionRange);if(e<0&&!i)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let s=new Hn(this.view,e,t,n);return this.view.docView.domChanged={newSel:s.newSel?s.newSel.main:null},s}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return this.view.requestMeasure(),!1;let n=this.view.state,i=Vn(this.view,t);return this.view.state==n&&this.view.update([]),i}readMutation(e){let t=this.view.docView.nearest(e.target);if(!t||t.ignoreMutation(e))return null;if(t.markDirty("attributes"==e.type),"attributes"==e.type&&(t.flags|=4),"childList"==e.type){let n=Un(t,e.previousSibling||e.target.previousSibling,-1),i=Un(t,e.nextSibling||e.target.nextSibling,1);return{from:n?t.posAfter(n):t.posAtStart,to:i?t.posBefore(i):t.posAtEnd,typeOver:!1}}return"characterData"==e.type?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}destroy(){var e,t,n;this.stop(),null===(e=this.intersection)||void 0===e||e.disconnect(),null===(t=this.gapIntersection)||void 0===t||t.disconnect(),null===(n=this.resizeScroll)||void 0===n||n.disconnect();for(let e of this.scrollTargets)e.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey)}}function Un(e,t,n){for(;t;){let i=D.get(t);if(i&&i.parent==e)return i;let s=t.parentNode;t=s!=e.dom?s:n>0?t.nextSibling:t.previousSibling}return null}class Gn{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return this.inputState.composing>0}get compositionStarted(){return this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.style.cssText="position: fixed; top: -10000px",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM);let{dispatch:t}=e;this.dispatchTransactions=e.dispatchTransactions||t&&(e=>e.forEach((e=>t(e,this))))||(e=>this.update(e)),this.dispatch=this.dispatch.bind(this),this._root=e.root||function(e){for(;e;){if(e&&(9==e.nodeType||11==e.nodeType&&e.host))return e;e=e.assignedSlot||e.parentNode}return null}(e.parent)||document,this.viewState=new wn(e.state||i.yy.create(e)),e.scrollTo&&e.scrollTo.is(_e)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(je).map((e=>new Pe(e)));for(let e of this.plugins)e.update(this);this.observer=new Jn(this),this.inputState=new Tt(this),this.inputState.ensureHandlers(this.plugins),this.docView=new ct(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),e.parent&&e.parent.appendChild(this.dom)}dispatch(...e){let t=1==e.length&&e[0]instanceof i.YW?e:1==e.length&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(e){if(0!=this.updateState)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t,n=!1,s=!1,r=this.state;for(let t of e){if(t.startState!=r)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");r=t.state}if(this.destroyed)return void(this.viewState.state=r);let o=this.hasFocus,a=0,l=null;e.some((e=>e.annotation(Qt)))?(this.inputState.notifiedFocused=o,a=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,l=Zt(r,o),l||(a=1));let h=this.observer.delayedAndroidKey,c=null;if(h?(this.observer.clearDelayedAndroidKey(),c=this.observer.readChange(),(c&&!this.state.doc.eq(r.doc)||!this.state.selection.eq(r.selection))&&(c=null)):this.observer.clear(),r.facet(i.yy.phrases)!=this.state.facet(i.yy.phrases))return this.setState(r);t=Je.create(this,r,e),t.flags|=a;let u=this.viewState.scrollTarget;try{this.updateState=2;for(let t of e){if(u&&(u=u.map(t.changes)),t.scrollIntoView){let{main:e}=t.state.selection;u=new Te(e.empty?e:i.jT.cursor(e.head,e.head>e.anchor?-1:1))}for(let e of t.effects)e.is(_e)&&(u=e.value.clip(this.state))}this.viewState.update(t,u),this.bidiCache=Xn.update(this.bidiCache,t.changes),t.empty||(this.updatePlugins(t),this.inputState.update(t)),n=this.docView.update(t),this.state.facet(We)!=this.styleModules&&this.mountStyles(),s=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(n,e.some((e=>e.isUserEvent("select.pointer"))))}finally{this.updateState=0}if(t.startState.facet(_n)!=t.state.facet(_n)&&(this.viewState.mustMeasureContent=!0),(n||s||u||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),!t.empty)for(let e of this.state.facet(Se))try{e(t)}catch(e){Ne(this.state,e,"update listener")}(l||c)&&Promise.resolve().then((()=>{l&&this.state==l.startState&&this.dispatch(l),c&&!Vn(this,c)&&h.force&&O(this.contentDOM,h.key,h.keyCode)}))}setState(e){if(0!=this.updateState)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed)return void(this.viewState.state=e);this.updateState=2;let t=this.hasFocus;try{for(let e of this.plugins)e.destroy(this);this.viewState=new wn(e),this.plugins=e.facet(je).map((e=>new Pe(e))),this.pluginMap.clear();for(let e of this.plugins)e.update(this);this.docView=new ct(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(je),n=e.state.facet(je);if(t!=n){let i=[];for(let s of n){let n=t.indexOf(s);if(n<0)i.push(new Pe(s));else{let t=this.plugins[n];t.mustUpdate=e,i.push(t)}}for(let t of this.plugins)t.mustUpdate!=e&&t.destroy(this);this.plugins=i,this.pluginMap.clear()}else for(let t of this.plugins)t.mustUpdate=e;for(let e=0;e-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey)return this.measureScheduled=-1,void this.requestMeasure();this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,n=this.scrollDOM,i=n.scrollTop*this.scaleY,{scrollAnchorPos:s,scrollAnchorHeight:r}=this.viewState;Math.abs(i-this.viewState.scrollTop)>1&&(r=-1),this.viewState.scrollAnchorHeight=-1;try{for(let e=0;;e++){if(r<0)if(T(n))s=-1,r=this.viewState.heightMap.height;else{let e=this.viewState.scrollAnchorAt(i);s=e.from,r=e.top}this.updateState=1;let o=this.viewState.measure(this);if(!o&&!this.measureRequests.length&&null==this.viewState.scrollTarget)break;if(e>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let a=[];4&o||([this.measureRequests,a]=[a,this.measureRequests]);let l=a.map((e=>{try{return e.read(this)}catch(e){return Ne(this.state,e),Yn}})),h=Je.create(this,this.state,[]),c=!1;h.flags|=o,t?t.flags|=o:t=h,this.updateState=2,h.empty||(this.updatePlugins(h),this.inputState.update(h),this.updateAttrs(),c=this.docView.update(h));for(let e=0;e1||e<-1){i+=e,n.scrollTop=i/this.scaleY,r=-1;continue}}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let e of this.state.facet(Se))e(t)}get themeClasses(){return Dn+" "+(this.state.facet(Nn)?jn:En)+" "+this.state.facet(_n)}updateAttrs(){let e=Qn(this,Ie,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",translate:"no",contenteditable:this.state.facet(De)?"true":"false",class:"cm-content",style:`${U.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),Qn(this,Be,t);let n=this.observer.ignore((()=>{let n=se(this.contentDOM,this.contentAttrs,t),i=se(this.dom,this.editorAttrs,e);return n||i}));return this.editorAttrs=e,this.contentAttrs=t,n}showAnnouncements(e){let t=!0;for(let n of e)for(let e of n.effects)e.is(Gn.announce)&&(t&&(this.announceDOM.textContent=""),t=!1,this.announceDOM.appendChild(document.createElement("div")).textContent=e.value)}mountStyles(){this.styleModules=this.state.facet(We);let e=this.state.facet(Gn.cspNonce);s.V.mount(this.root,this.styleModules.concat(In).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(2==this.updateState)throw new Error("Reading the editor layout isn't allowed during an update");0==this.updateState&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame((()=>this.measure()))),e){if(this.measureRequests.indexOf(e)>-1)return;if(null!=e.key)for(let t=0;tt.spec==e))||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,n){return Mt(this,e,Ct(this,e,t,n))}moveByGroup(e,t){return Mt(this,e,Ct(this,e,t,(t=>function(e,t,n){let s=e.state.charCategorizer(t),r=s(n);return e=>{let t=s(e);return r==i.D0.Space&&(r=t),r==t}}(this,e.head,t))))}moveToLineBoundary(e,t,n=!0){return function(e,t,n,s){let r=At(e,t.head),o=s&&r.type==he.Text&&(e.lineWrapping||r.widgetLineBreaks)?e.coordsAtPos(t.assoc<0&&t.head>r.from?t.head-1:t.head):null;if(o){let t=e.dom.getBoundingClientRect(),s=e.textDirectionAt(r.from),a=e.posAtCoords({x:n==(s==Ue.LTR)?t.right-1:t.left+1,y:(o.top+o.bottom)/2});if(null!=a)return i.jT.cursor(a,n?-1:1)}return i.jT.cursor(n?r.to:r.from,n?-1:1)}(this,e,t,n)}moveVertically(e,t,n){return Mt(this,e,function(e,t,n,s){let r=t.head,o=n?1:-1;if(r==(n?e.state.doc.length:0))return i.jT.cursor(r,t.assoc);let a,l=t.goalColumn,h=e.contentDOM.getBoundingClientRect(),c=e.coordsAtPos(r,t.assoc||-1),u=e.documentTop;if(c)null==l&&(l=c.left-h.left),a=o<0?c.top:c.bottom;else{let t=e.viewState.lineBlockAt(r);null==l&&(l=Math.min(h.right-h.left,e.defaultCharacterWidth*(r-t.from))),a=(o<0?t.top:t.bottom)+u}let f=h.left+l,d=null!=s?s:e.viewState.heightOracle.textHeight>>1;for(let t=0;;t+=10){let n=a+(d+t)*o,s=kt(e,{x:f,y:n},!1,o);if(nh.bottom||(o<0?sr)){let t=e.docView.coordsForChar(s),r=!t||n0)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(Oe)||ethis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>Kn)return at(e.length);let t,n=this.textDirectionAt(e.from);for(let i of this.bidiCache)if(i.from==e.from&&i.dir==n&&(i.fresh||it(i.isolates,t=Fe(this,e.from,e.to))))return i.order;t||(t=Fe(this,e.from,e.to));let i=function(e,t,n){if(!e)return[new nt(0,0,t==Ke?1:0)];if(t==Ge&&!n.length&&!tt.test(e))return at(e.length);if(n.length)for(;e.length>st.length;)st[st.length]=256;let i=[],s=t==Ge?0:1;return ot(e,s,s,n,0,e.length,i),i}(e.text,n,t);return this.bidiCache.push(new Xn(e.from,e.to,n,t,!0,i)),i}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||U.safari&&(null===(e=this.inputState)||void 0===e?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore((()=>{A(this.contentDOM),this.docView.updateSelection()}))}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((9==e.nodeType?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){return _e.of(new Te("number"==typeof e?i.jT.cursor(e):e,t.y,t.x,t.yMargin,t.xMargin))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,n=this.viewState.scrollAnchorAt(e);return _e.of(new Te(i.jT.cursor(n.from),"start","start",n.top-e,t,!0))}static domEventHandlers(e){return Re.define((()=>({})),{eventHandlers:e})}static domEventObservers(e){return Re.define((()=>({})),{eventObservers:e})}static theme(e,t){let n=s.V.newName(),i=[_n.of(n),We.of(Pn(`.${n}`,e))];return t&&t.dark&&i.push(Nn.of(!0)),i}static baseTheme(e){return i.Wl.lowest(We.of(Pn("."+Dn,e,Rn)))}static findFromDOM(e){var t;let n=e.querySelector(".cm-content"),i=n&&D.get(n)||D.get(e);return(null===(t=null==i?void 0:i.rootView)||void 0===t?void 0:t.view)||null}}Gn.styleModule=We,Gn.inputHandler=Ae,Gn.focusChangeEffect=Ce,Gn.perLineTextDirection=Oe,Gn.exceptionSink=ke,Gn.updateListener=Se,Gn.editable=De,Gn.mouseSelectionStyle=we,Gn.dragMovesSelection=xe,Gn.clickAddsSelectionRange=ve,Gn.decorations=Le,Gn.atomicRanges=$e,Gn.bidiIsolatedRanges=ze,Gn.scrollMargins=He,Gn.darkTheme=Nn,Gn.cspNonce=i.r$.define({combine:e=>e.length?e[0]:""}),Gn.contentAttributes=Be,Gn.editorAttributes=Ie,Gn.lineWrapping=Gn.contentAttributes.of({class:"cm-lineWrapping"}),Gn.announce=i.Py.define();const Kn=4096,Yn={};class Xn{constructor(e,t,n,i,s,r){this.from=e,this.to=t,this.dir=n,this.isolates=i,this.fresh=s,this.order=r}static update(e,t){if(t.empty&&!e.some((e=>e.fresh)))return e;let n=[],i=e.length?e[e.length-1].dir:Ue.LTR;for(let s=Math.max(0,e.length-10);s=0;s--){let t=i[s],r="function"==typeof t?t(e):t;r&&te(r,n)}return n}const Zn=U.mac?"mac":U.windows?"win":U.linux?"linux":"key";function ei(e,t,n){return t.altKey&&(e="Alt-"+e),t.ctrlKey&&(e="Ctrl-"+e),t.metaKey&&(e="Meta-"+e),!1!==n&&t.shiftKey&&(e="Shift-"+e),e}const ti=i.Wl.default(Gn.domEventHandlers({keydown:(e,t)=>function(e,t,n,s){let h=function(e){var t=!(a&&e.metaKey&&e.shiftKey&&!e.ctrlKey&&!e.altKey||l&&e.shiftKey&&e.key&&1==e.key.length||"Unidentified"==e.key)&&e.key||(e.shiftKey?o:r)[e.keyCode]||e.key||"Unidentified";return"Esc"==t&&(t="Escape"),"Del"==t&&(t="Delete"),"Left"==t&&(t="ArrowLeft"),"Up"==t&&(t="ArrowUp"),"Right"==t&&(t="ArrowRight"),"Down"==t&&(t="ArrowDown"),t}(t),c=(0,i.gm)(h,0),u=(0,i.nZ)(c)==h.length&&" "!=h,f="",d=!1,p=!1,m=!1;si&&si.view==n&&si.scope==s&&(f=si.prefix+" ",jt.indexOf(t.keyCode)<0&&(p=!0,si=null));let g,b,y=new Set,v=e=>{if(e){for(let i of e.run)if(!y.has(i)&&(y.add(i),i(n,t)))return e.stopPropagation&&(m=!0),!0;e.preventDefault&&(e.stopPropagation&&(m=!0),p=!0)}return!1},x=e[s];return x&&(v(x[f+ei(h,t,!u)])?d=!0:u&&(t.altKey||t.metaKey||t.ctrlKey)&&!(U.windows&&t.ctrlKey&&t.altKey)&&(g=r[t.keyCode])&&g!=h?(v(x[f+ei(g,t,!0)])||t.shiftKey&&(b=o[t.keyCode])!=h&&b!=g&&v(x[f+ei(b,t,!1)]))&&(d=!0):u&&t.shiftKey&&v(x[f+ei(h,t,!0)])&&(d=!0),!d&&v(x._any)&&(d=!0)),p&&(d=!0),d&&m&&t.stopPropagation(),d}(function(e){let t=e.facet(ni),n=ii.get(t);return n||ii.set(t,n=function(e,t=Zn){let n=Object.create(null),i=Object.create(null),s=(e,t)=>{let n=i[e];if(null==n)i[e]=t;else if(n!=t)throw new Error("Key binding "+e+" is used both as a regular binding and as a multi-stroke prefix")},r=(e,i,r,o,a)=>{var l,h;let c=n[e]||(n[e]=Object.create(null)),u=i.split(/ (?!$)/).map((e=>function(e,t){const n=e.split(/-(?!$)/);let i,s,r,o,a=n[n.length-1];"Space"==a&&(a=" ");for(let e=0;e{let i=si={view:t,prefix:n,scope:e};return setTimeout((()=>{si==i&&(si=null)}),ri),!0}]})}let f=u.join(" ");s(f,!1);let d=c[f]||(c[f]={preventDefault:!1,stopPropagation:!1,run:(null===(h=null===(l=c._any)||void 0===l?void 0:l.run)||void 0===h?void 0:h.slice())||[]});r&&d.run.push(r),o&&(d.preventDefault=!0),a&&(d.stopPropagation=!0)};for(let i of e){let e=i.scope?i.scope.split(" "):["editor"];if(i.any)for(let t of e){let e=n[t]||(n[t]=Object.create(null));e._any||(e._any={preventDefault:!1,stopPropagation:!1,run:[]});for(let t in e)e[t].run.push(i.any)}let s=i[t]||i.key;if(s)for(let t of e)r(t,s,i.run,i.preventDefault,i.stopPropagation),i.shift&&r(t,"Shift-"+s,i.shift,i.preventDefault,i.stopPropagation)}return n}(t.reduce(((e,t)=>e.concat(t)),[]))),n}(t.state),e,t,"editor")})),ni=i.r$.define({enables:ti}),ii=new WeakMap;let si=null;const ri=4e3;class oi{constructor(e,t,n,i,s){this.className=e,this.left=t,this.top=n,this.width=i,this.height=s}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}update(e,t){return t.className==this.className&&(this.adjust(e),!0)}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",null!=this.width&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(e,t,n){if(n.empty){let i=e.coordsAtPos(n.head,n.assoc||1);if(!i)return[];let s=ai(e);return[new oi(t,i.left-s.left,i.top-s.top,null,i.bottom-i.top)]}return function(e,t,n){if(n.to<=e.viewport.from||n.from>=e.viewport.to)return[];let i=Math.max(n.from,e.viewport.from),s=Math.min(n.to,e.viewport.to),r=e.textDirection==Ue.LTR,o=e.contentDOM,a=o.getBoundingClientRect(),l=ai(e),h=o.querySelector(".cm-line"),c=h&&window.getComputedStyle(h),u=a.left+(c?parseInt(c.paddingLeft)+Math.min(0,parseInt(c.textIndent)):0),f=a.right-(c?parseInt(c.paddingRight):0),d=At(e,i),p=At(e,s),m=d.type==he.Text?d:null,g=p.type==he.Text?p:null;if(m&&(e.lineWrapping||d.widgetLineBreaks)&&(m=li(e,i,m)),g&&(e.lineWrapping||p.widgetLineBreaks)&&(g=li(e,s,g)),m&&g&&m.from==g.from)return y(v(n.from,n.to,m));{let t=m?v(n.from,null,m):x(d,!1),i=g?v(null,n.to,g):x(p,!0),s=[];return(m||d).to<(g||p).from-(m&&g?1:0)||d.widgetLineBreaks>1&&t.bottom+e.defaultLineHeight/2h&&i.from=r)break;a>s&&l(Math.max(e,s),null==t&&e<=h,Math.min(a,r),null==n&&a>=c,o.dir)}if(s=i.to+1,s>=r)break}return 0==a.length&&l(h,null==t,c,null==n,e.textDirection),{top:s,bottom:o,horizontal:a}}function x(e,t){let n=a.top+(t?e.top:e.bottom);return{top:n,bottom:n,horizontal:[]}}}(e,t,n)}}function ai(e){let t=e.scrollDOM.getBoundingClientRect();return{left:(e.textDirection==Ue.LTR?t.left:t.right-e.scrollDOM.clientWidth*e.scaleX)-e.scrollDOM.scrollLeft*e.scaleX,top:t.top-e.scrollDOM.scrollTop*e.scaleY}}function li(e,t,n){let s=i.jT.cursor(t);return{from:Math.max(n.from,e.moveToLineBoundary(s,!1,!0).from),to:Math.min(n.to,e.moveToLineBoundary(s,!0,!0).from),type:he.Text}}class hi{constructor(e,t){this.view=e,this.layer=t,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),t.above&&this.dom.classList.add("cm-layer-above"),t.class&&this.dom.classList.add(t.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(e.state),e.requestMeasure(this.measureReq),t.mount&&t.mount(this.dom,e)}update(e){e.startState.facet(ci)!=e.state.facet(ci)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&(this.scale(),e.view.requestMeasure(this.measureReq))}setOrder(e){let t=0,n=e.facet(ci);for(;t{return n=e,i=this.drawn[t],!(n.constructor==i.constructor&&n.eq(i));var n,i}))){let t=this.dom.firstChild,n=0;for(let i of e)i.update&&t&&i.constructor&&this.drawn[n].constructor&&i.update(t,this.drawn[n])?(t=t.nextSibling,n++):this.dom.insertBefore(i.draw(),t);for(;t;){let e=t.nextSibling;t.remove(),t=e}this.drawn=e}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}}const ci=i.r$.define();function ui(e){return[Re.define((t=>new hi(t,e))),ci.of(e)]}const fi=!U.ios,di=i.r$.define({combine:e=>(0,i.BO)(e,{cursorBlinkRate:1200,drawRangeCursor:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})});function pi(e={}){return[di.of(e),gi,yi,xi,Me.of(!0)]}function mi(e){return e.startState.facet(di)!=e.state.facet(di)}const gi=ui({above:!0,markers(e){let{state:t}=e,n=t.facet(di),s=[];for(let r of t.selection.ranges){let o=r==t.selection.main;if(r.empty?!o||fi:n.drawRangeCursor){let t=o?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",n=r.empty?r:i.jT.cursor(r.head,r.head>r.anchor?-1:1);for(let i of oi.forRange(e,t,n))s.push(i)}}return s},update(e,t){e.transactions.some((e=>e.selection))&&(t.style.animationName="cm-blink"==t.style.animationName?"cm-blink2":"cm-blink");let n=mi(e);return n&&bi(e.state,t),e.docChanged||e.selectionSet||n},mount(e,t){bi(t.state,e)},class:"cm-cursorLayer"});function bi(e,t){t.style.animationDuration=e.facet(di).cursorBlinkRate+"ms"}const yi=ui({above:!1,markers:e=>e.state.selection.ranges.map((t=>t.empty?[]:oi.forRange(e,"cm-selectionBackground",t))).reduce(((e,t)=>e.concat(t))),update:(e,t)=>e.docChanged||e.selectionSet||e.viewportChanged||mi(e),class:"cm-selectionLayer"}),vi={".cm-line":{"& ::selection":{backgroundColor:"transparent !important"},"&::selection":{backgroundColor:"transparent !important"}}};fi&&(vi[".cm-line"].caretColor="transparent !important");const xi=i.Wl.highest(Gn.theme(vi));function wi(e,t,n,i,s){t.lastIndex=0;for(let r,o=e.iterRange(n,i),a=n;!o.next().done;a+=o.value.length)if(!o.lineBreak)for(;r=t.exec(o.value);)s(a+r.index,r)}class ki{constructor(e){const{regexp:t,decoration:n,decorate:i,boundary:s,maxLength:r=1e3}=e;if(!t.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=t,i)this.addMatch=(e,t,n,s)=>i(s,n,n+e[0].length,e,t);else if("function"==typeof n)this.addMatch=(e,t,i,s)=>{let r=n(e,t,i);r&&s(i,i+e[0].length,r)};else{if(!n)throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.addMatch=(e,t,i,s)=>s(i,i+e[0].length,n)}this.boundary=s,this.maxLength=r}createDeco(e){let t=new i.f_,n=t.add.bind(t);for(let{from:t,to:i}of function(e,t){let n=e.visibleRanges;if(1==n.length&&n[0].from==e.viewport.from&&n[0].to==e.viewport.to)return n;let i=[];for(let{from:s,to:r}of n)s=Math.max(e.state.doc.lineAt(s).from,s-t),r=Math.min(e.state.doc.lineAt(r).to,r+t),i.length&&i[i.length-1].to>=s?i[i.length-1].to=r:i.push({from:s,to:r});return i}(e,this.maxLength))wi(e.state.doc,this.regexp,t,i,((t,i)=>this.addMatch(i,e,t,n)));return t.finish()}updateDeco(e,t){let n=1e9,i=-1;return e.docChanged&&e.changes.iterChanges(((t,s,r,o)=>{o>e.view.viewport.from&&r1e3?this.createDeco(e.view):i>-1?this.updateRange(e.view,t.map(e.changes),n,i):t}updateRange(e,t,n,i){for(let s of e.visibleRanges){let r=Math.max(s.from,n),o=Math.min(s.to,i);if(o>r){let n=e.state.doc.lineAt(r),i=n.ton.from;r--)if(this.boundary.test(n.text[r-1-n.from])){a=r;break}for(;oc.push(n.range(e,t));if(n==i)for(this.regexp.lastIndex=a-n.from;(h=this.regexp.exec(n.text))&&h.indexthis.addMatch(n,e,t,u)));t=t.update({filterFrom:a,filterTo:l,filter:(e,t)=>el,add:c})}}return t}}const Si=Re.fromClass(class{constructor(){this.height=1e3,this.attrs={style:"padding-bottom: 1000px"}}update(e){let{view:t}=e,n=t.viewState.editorHeight*t.scaleY-t.defaultLineHeight-t.documentPadding.top-.5;n>=0&&n!=this.height&&(this.height=n,this.attrs={style:`padding-bottom: ${n}px`})}});function Ai(){return[Si,Be.of((e=>{var t;return(null===(t=e.plugin(Si))||void 0===t?void 0:t.attrs)||null}))]}function Ci(){return Mi}const Oi=ce.line({class:"cm-activeLine"}),Mi=Re.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.docChanged||e.selectionSet)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let t=-1,n=[];for(let i of e.state.selection.ranges){let s=e.lineBlockAt(i.head);s.from>t&&(n.push(Oi.range(s.from)),t=s.from)}return ce.set(n)}},{decorations:e=>e.decorations}),Ti=2e3;function _i(e,t){let n=e.posAtCoords({x:t.clientX,y:t.clientY},!1),s=e.state.doc.lineAt(n),r=n-s.from,o=r>Ti?-1:r==s.length?function(e,t){let n=e.coordsAtPos(e.viewport.from);return n?Math.round(Math.abs((n.left-t)/e.defaultCharacterWidth)):-1}(e,t.clientX):(0,i.IS)(s.text,e.state.tabSize,n-s.from);return{line:s.number,col:o,off:r}}function Ni(e){let t=(null==e?void 0:e.eventFilter)||(e=>e.altKey&&0==e.button);return Gn.mouseSelectionStyle.of(((e,n)=>t(n)?function(e,t){let n=_i(e,t),s=e.state.selection;return n?{update(e){if(e.docChanged){let t=e.changes.mapPos(e.startState.doc.line(n.line).from),i=e.state.doc.lineAt(t);n={line:i.number,col:n.col,off:Math.min(n.off,i.length)},s=s.map(e.changes)}},get(t,r,o){let a=_i(e,t);if(!a)return s;let l=function(e,t,n){let s=Math.min(t.line,n.line),r=Math.max(t.line,n.line),o=[];if(t.off>Ti||n.off>Ti||t.col<0||n.col<0){let a=Math.min(t.off,n.off),l=Math.max(t.off,n.off);for(let t=s;t<=r;t++){let n=e.doc.line(t);n.length<=l&&o.push(i.jT.range(n.from+a,n.to+l))}}else{let a=Math.min(t.col,n.col),l=Math.max(t.col,n.col);for(let t=s;t<=r;t++){let n=e.doc.line(t),s=(0,i.Gz)(n.text,a,e.tabSize,!0);if(s<0)o.push(i.jT.cursor(n.to));else{let t=(0,i.Gz)(n.text,l,e.tabSize);o.push(i.jT.range(n.from+s,n.from+t))}}}return o}(e.state,n,a);return l.length?o?i.jT.create(l.concat(s.ranges)):i.jT.create(l):s}}:null}(e,n):null))}const Di={Alt:[18,e=>!!e.altKey],Control:[17,e=>!!e.ctrlKey],Shift:[16,e=>!!e.shiftKey],Meta:[91,e=>!!e.metaKey]},Ei={style:"cursor: crosshair"};function ji(e={}){let[t,n]=Di[e.key||"Alt"],i=Re.fromClass(class{constructor(e){this.view=e,this.isDown=!1}set(e){this.isDown!=e&&(this.isDown=e,this.view.update([]))}},{eventObservers:{keydown(e){this.set(e.keyCode==t||n(e))},keyup(e){e.keyCode!=t&&n(e)||this.set(!1)},mousemove(e){this.set(n(e))}}});return[i,Gn.contentAttributes.of((e=>{var t;return(null===(t=e.plugin(i))||void 0===t?void 0:t.isDown)?Ei:null}))]}const Ri="-10000px";class Pi{constructor(e,t,n){this.facet=t,this.createTooltipView=n,this.input=e.state.facet(t),this.tooltips=this.input.filter((e=>e)),this.tooltipViews=this.tooltips.map(n)}update(e,t){var n;let i=e.state.facet(this.facet),s=i.filter((e=>e));if(i===this.input){for(let t of this.tooltipViews)t.update&&t.update(e);return!1}let r=[],o=t?[]:null;for(let n=0;nt[n]=e)),t.length=o.length),this.input=i,this.tooltips=s,this.tooltipViews=r,!0}}function Ii(e={}){return Li.of(e)}function Bi(e){let{win:t}=e;return{top:0,left:0,bottom:t.innerHeight,right:t.innerWidth}}const Li=i.r$.define({combine:e=>{var t,n,i;return{position:U.ios?"absolute":(null===(t=e.find((e=>e.position)))||void 0===t?void 0:t.position)||"fixed",parent:(null===(n=e.find((e=>e.parent)))||void 0===n?void 0:n.parent)||null,tooltipSpace:(null===(i=e.find((e=>e.tooltipSpace)))||void 0===i?void 0:i.tooltipSpace)||Bi}}}),$i=new WeakMap,zi=Re.fromClass(class{constructor(e){this.view=e,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let t=e.state.facet(Li);this.position=t.position,this.parent=t.parent,this.classes=e.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.manager=new Pi(e,Vi,(e=>this.createTooltip(e))),this.intersectionObserver="function"==typeof IntersectionObserver?new IntersectionObserver((e=>{Date.now()>this.lastTransaction-50&&e.length>0&&e[e.length-1].intersectionRatio<1&&this.measureSoon()}),{threshold:[1]}):null,this.observeIntersection(),e.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let e of this.manager.tooltipViews)this.intersectionObserver.observe(e.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout((()=>{this.measureTimeout=-1,this.maybeMeasure()}),50))}update(e){e.transactions.length&&(this.lastTransaction=Date.now());let t=this.manager.update(e,this.above);t&&this.observeIntersection();let n=t||e.geometryChanged,i=e.state.facet(Li);if(i.position!=this.position&&!this.madeAbsolute){this.position=i.position;for(let e of this.manager.tooltipViews)e.dom.style.position=this.position;n=!0}if(i.parent!=this.parent){this.parent&&this.container.remove(),this.parent=i.parent,this.createContainer();for(let e of this.manager.tooltipViews)this.container.appendChild(e.dom);n=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);n&&this.maybeMeasure()}createTooltip(e){let t=e.create(this.view);if(t.dom.classList.add("cm-tooltip"),e.arrow&&!t.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let e=document.createElement("div");e.className="cm-tooltip-arrow",t.dom.appendChild(e)}return t.dom.style.position=this.position,t.dom.style.top=Ri,t.dom.style.left="0px",this.container.appendChild(t.dom),t.mount&&t.mount(this.view),t}destroy(){var e,t;this.view.win.removeEventListener("resize",this.measureSoon);for(let t of this.manager.tooltipViews)t.dom.remove(),null===(e=t.destroy)||void 0===e||e.call(t);this.parent&&this.container.remove(),null===(t=this.intersectionObserver)||void 0===t||t.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let e=this.view.dom.getBoundingClientRect(),t=1,n=1,i=!1;if("fixed"==this.position&&this.manager.tooltipViews.length){let{dom:e}=this.manager.tooltipViews[0];if(U.gecko)i=e.offsetParent!=this.container.ownerDocument.body;else if(1!=this.view.scaleX||1!=this.view.scaleY)i=!0;else if(e.style.top==Ri&&"0px"==e.style.left){let t=e.getBoundingClientRect();i=Math.abs(t.top+1e4)>1||Math.abs(t.left)>1}}if(i||"absolute"==this.position)if(this.parent){let e=this.parent.getBoundingClientRect();e.width&&e.height&&(t=e.width/this.parent.offsetWidth,n=e.height/this.parent.offsetHeight)}else({scaleX:t,scaleY:n}=this.view.viewState);return{editor:e,parent:this.parent?this.container.getBoundingClientRect():e,pos:this.manager.tooltips.map(((e,t)=>{let n=this.manager.tooltipViews[t];return n.getCoords?n.getCoords(e.pos):this.view.coordsAtPos(e.pos)})),size:this.manager.tooltipViews.map((({dom:e})=>e.getBoundingClientRect())),space:this.view.state.facet(Li).tooltipSpace(this.view),scaleX:t,scaleY:n,makeAbsolute:i}}writeMeasure(e){var t;if(e.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let e of this.manager.tooltipViews)e.dom.style.position="absolute"}let{editor:n,space:i,scaleX:s,scaleY:r}=e,o=[];for(let a=0;a=Math.min(n.bottom,i.bottom)||u.rightMath.min(n.right,i.right)+.1){c.style.top=Ri;continue}let d=l.arrow?h.dom.querySelector(".cm-tooltip-arrow"):null,p=d?7:0,m=f.right-f.left,g=null!==(t=$i.get(h))&&void 0!==t?t:f.bottom-f.top,b=h.offset||Hi,y=this.view.textDirection==Ue.LTR,v=f.width>i.right-i.left?y?i.left:i.right-f.width:y?Math.min(u.left-(d?14:0)+b.x,i.right-m):Math.max(i.left,u.left-m+(d?14:0)-b.x),x=this.above[a];!l.strictSide&&(x?u.top-(f.bottom-f.top)-b.yi.bottom)&&x==i.bottom-u.bottom>u.top-i.top&&(x=this.above[a]=!x);let w=(x?u.top-i.top:i.bottom-u.bottom)-p;if(wv&&e.topk&&(k=x?e.top-g-2-p:e.bottom+p+2);if("absolute"==this.position?(c.style.top=(k-e.parent.top)/r+"px",c.style.left=(v-e.parent.left)/s+"px"):(c.style.top=k/r+"px",c.style.left=v/s+"px"),d){let e=u.left+(y?b.x:-b.x)-(v+14-7);d.style.left=e/s+"px"}!0!==h.overlap&&o.push({left:v,top:k,right:S,bottom:k+g}),c.classList.toggle("cm-tooltip-above",x),c.classList.toggle("cm-tooltip-below",!x),h.positioned&&h.positioned(e.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let e of this.manager.tooltipViews)e.dom.style.top=Ri}},{eventObservers:{scroll(){this.maybeMeasure()}}}),Fi=Gn.baseTheme({".cm-tooltip":{zIndex:100,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:"14px",position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),Hi={x:0,y:0},Vi=i.r$.define({enables:[zi,Fi]});function Wi(e,t){let n=e.plugin(zi);if(!n)return null;let i=n.manager.tooltips.indexOf(t);return i<0?null:n.manager.tooltipViews[i]}class qi extends i.uU{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}}qi.prototype.elementClass="",qi.prototype.toDOM=void 0,qi.prototype.mapMode=i.gc.TrackBefore,qi.prototype.startSide=qi.prototype.endSide=-1,qi.prototype.point=!0;const Ji=i.r$.define(),Ui={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>i.Xs.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{}},Gi=i.r$.define();function Ki(e){return[Xi(),Gi.of(Object.assign(Object.assign({},Ui),e))]}const Yi=i.r$.define({combine:e=>e.some((e=>e))});function Xi(e){let t=[Qi];return e&&!1===e.fixed&&t.push(Yi.of(!0)),t}const Qi=Re.fromClass(class{constructor(e){this.view=e,this.prevViewport=e.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=e.state.facet(Gi).map((t=>new ns(e,t)));for(let e of this.gutters)this.dom.appendChild(e.dom);this.fixed=!e.state.facet(Yi),this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),e.scrollDOM.insertBefore(this.dom,e.contentDOM)}update(e){if(this.updateGutters(e)){let t=this.prevViewport,n=e.view.viewport,i=Math.min(t.to,n.to)-Math.max(t.from,n.from);this.syncGutters(i<.8*(n.to-n.from))}e.geometryChanged&&(this.dom.style.minHeight=this.view.contentHeight+"px"),this.view.state.facet(Yi)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":""),this.prevViewport=e.view.viewport}syncGutters(e){let t=this.dom.nextSibling;e&&this.dom.remove();let n=i.Xs.iter(this.view.state.facet(Ji),this.view.viewport.from),s=[],r=this.gutters.map((e=>new ts(e,this.view.viewport,-this.view.documentPadding.top)));for(let e of this.view.viewportLineBlocks)if(s.length&&(s=[]),Array.isArray(e.type)){let t=!0;for(let i of e.type)if(i.type==he.Text&&t){es(n,s,i.from);for(let e of r)e.line(this.view,i,s);t=!1}else if(i.widget)for(let e of r)e.widget(this.view,i)}else if(e.type==he.Text){es(n,s,e.from);for(let t of r)t.line(this.view,e,s)}else if(e.widget)for(let t of r)t.widget(this.view,e);for(let e of r)e.finish();e&&this.view.scrollDOM.insertBefore(this.dom,t)}updateGutters(e){let t=e.startState.facet(Gi),n=e.state.facet(Gi),s=e.docChanged||e.heightChanged||e.viewportChanged||!i.Xs.eq(e.startState.facet(Ji),e.state.facet(Ji),e.view.viewport.from,e.view.viewport.to);if(t==n)for(let t of this.gutters)t.update(e)&&(s=!0);else{s=!0;let i=[];for(let s of n){let n=t.indexOf(s);n<0?i.push(new ns(this.view,s)):(this.gutters[n].update(e),i.push(this.gutters[n]))}for(let e of this.gutters)e.dom.remove(),i.indexOf(e)<0&&e.destroy();for(let e of i)this.dom.appendChild(e.dom);this.gutters=i}return s}destroy(){for(let e of this.gutters)e.destroy();this.dom.remove()}},{provide:e=>Gn.scrollMargins.of((t=>{let n=t.plugin(e);return n&&0!=n.gutters.length&&n.fixed?t.textDirection==Ue.LTR?{left:n.dom.offsetWidth*t.scaleX}:{right:n.dom.offsetWidth*t.scaleX}:null}))});function Zi(e){return Array.isArray(e)?e:[e]}function es(e,t,n){for(;e.value&&e.from<=n;)e.from==n&&t.push(e.value),e.next()}class ts{constructor(e,t,n){this.gutter=e,this.height=n,this.i=0,this.cursor=i.Xs.iter(e.markers,t.from)}addElement(e,t,n){let{gutter:i}=this,s=(t.top-this.height)/e.scaleY,r=t.height/e.scaleY;if(this.i==i.elements.length){let t=new is(e,r,s,n);i.elements.push(t),i.dom.appendChild(t.dom)}else i.elements[this.i].update(e,r,s,n);this.height=t.bottom,this.i++}line(e,t,n){let i=[];es(this.cursor,i,t.from),n.length&&(i=i.concat(n));let s=this.gutter.config.lineMarker(e,t,i);s&&i.unshift(s);let r=this.gutter;(0!=i.length||r.config.renderEmptyElements)&&this.addElement(e,t,i)}widget(e,t){let n=this.gutter.config.widgetMarker(e,t.widget,t);n&&this.addElement(e,t,[n])}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}}class ns{constructor(e,t){this.view=e,this.config=t,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let n in t.domEventHandlers)this.dom.addEventListener(n,(i=>{let s,r=i.target;if(r!=this.dom&&this.dom.contains(r)){for(;r.parentNode!=this.dom;)r=r.parentNode;let e=r.getBoundingClientRect();s=(e.top+e.bottom)/2}else s=i.clientY;let o=e.lineBlockAtHeight(s-e.documentTop);t.domEventHandlers[n](e,o,i)&&i.preventDefault()}));this.markers=Zi(t.markers(e)),t.initialSpacer&&(this.spacer=new is(e,0,0,[t.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let t=this.markers;if(this.markers=Zi(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let t=this.config.updateSpacer(this.spacer.markers[0],e);t!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[t])}let n=e.view.viewport;return!i.Xs.eq(this.markers,t,n.from,n.to)||!!this.config.lineMarkerChange&&this.config.lineMarkerChange(e)}destroy(){for(let e of this.elements)e.destroy()}}class is{constructor(e,t,n,i){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,n,i)}update(e,t,n,i){this.height!=t&&(this.height=t,this.dom.style.height=t+"px"),this.above!=n&&(this.dom.style.marginTop=(this.above=n)?n+"px":""),function(e,t){if(e.length!=t.length)return!1;for(let n=0;n(0,i.BO)(e,{formatNumber:String,domEventHandlers:{}},{domEventHandlers(e,t){let n=Object.assign({},e);for(let e in t){let i=n[e],s=t[e];n[e]=i?(e,t,n)=>i(e,t,n)||s(e,t,n):s}return n}})});class os extends qi{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}}function as(e,t){return e.state.facet(rs).formatNumber(t,e.state)}const ls=Gi.compute([rs],(e=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers:e=>e.state.facet(ss),lineMarker:(e,t,n)=>n.some((e=>e.toDOM))?null:new os(as(e,e.state.doc.lineAt(t.from).number)),widgetMarker:()=>null,lineMarkerChange:e=>e.startState.facet(rs)!=e.state.facet(rs),initialSpacer:e=>new os(as(e,cs(e.state.doc.lines))),updateSpacer(e,t){let n=as(t.view,cs(t.view.state.doc.lines));return n==e.number?e:new os(n)},domEventHandlers:e.facet(rs).domEventHandlers})));function hs(e={}){return[rs.of(e),Xi(),ls]}function cs(e){let t=9;for(;t({decorations:e.createDeco(t),update(t){this.decorations=e.updateDeco(t,this.decorations)}})),{decorations:e=>e.decorations})}const ds=fs(new ki({regexp:/\t| +/g,decoration:e=>function(e){let t=us.get(e);return t||us.set(e,t=ce.mark({attributes:"\t"===e?{class:"cm-highlightTab"}:{class:"cm-highlightSpace","data-display":e.replace(/ /g,"·")}})),t}(e[0]),boundary:/\S/}));function ps(){return ds}const ms=fs(new ki({regexp:/\s+$/g,decoration:ce.mark({class:"cm-trailingSpace"}),boundary:/\S/}));function gs(){return ms}},21649:(e,t,n)=>{"use strict";n.d(t,{FE:()=>I,Jq:()=>h,L3:()=>i,Lj:()=>c,_b:()=>R,hr:()=>E,i9:()=>j,md:()=>o,mp:()=>p,vj:()=>d});const i=1024;let s=0;class r{constructor(e,t){this.from=e,this.to=t}}class o{constructor(e={}){this.id=s++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")})}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return"function"!=typeof e&&(e=h.match(e)),t=>{let n=e(t);return void 0===n?null:[this,n]}}}o.closedBy=new o({deserialize:e=>e.split(" ")}),o.openedBy=new o({deserialize:e=>e.split(" ")}),o.group=new o({deserialize:e=>e.split(" ")}),o.contextHash=new o({perNode:!0}),o.lookAhead=new o({perNode:!0}),o.mounted=new o({perNode:!0});class a{constructor(e,t,n){this.tree=e,this.overlay=t,this.parser=n}static get(e){return e&&e.props&&e.props[o.mounted.id]}}const l=Object.create(null);class h{constructor(e,t,n,i=0){this.name=e,this.props=t,this.id=n,this.flags=i}static define(e){let t=e.props&&e.props.length?Object.create(null):l,n=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(null==e.name?8:0),i=new h(e.name||"",t,e.id,n);if(e.props)for(let n of e.props)if(Array.isArray(n)||(n=n(i)),n){if(n[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[n[0].id]=n[1]}return i}prop(e){return this.props[e.id]}get isTop(){return(1&this.flags)>0}get isSkipped(){return(2&this.flags)>0}get isError(){return(4&this.flags)>0}get isAnonymous(){return(8&this.flags)>0}is(e){if("string"==typeof e){if(this.name==e)return!0;let t=this.prop(o.group);return!!t&&t.indexOf(e)>-1}return this.id==e}static match(e){let t=Object.create(null);for(let n in e)for(let i of n.split(" "))t[i]=e[n];return e=>{for(let n=e.prop(o.group),i=-1;i<(n?n.length:0);i++){let s=t[i<0?e.name:n[i]];if(s)return s}}}}h.none=new h("",Object.create(null),0,8);class c{constructor(e){this.types=e;for(let t=0;t=t){let o=new x(r.tree,r.overlay[0].from+e.from,-1,e);(s||(s=[i])).push(y(o,t,n,!1))}}return s?C(s):i}(this,e,t)}iterate(e){let{enter:t,leave:n,from:i=0,to:s=this.length}=e,r=e.mode||0,o=(r&d.IncludeAnonymous)>0;for(let e=this.cursor(r|d.IncludeAnonymous);;){let r=!1;if(e.from<=s&&e.to>=i&&(!o&&e.type.isAnonymous||!1!==t(e))){if(e.firstChild())continue;r=!0}for(;r&&n&&(o||!e.type.isAnonymous)&&n(e),!e.nextSibling();){if(!e.parent())return;r=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:D(h.none,this.children,this.positions,0,this.children.length,0,this.length,((e,t,n)=>new p(this.type,e,t,n,this.propValues)),e.makeTree||((e,t,n)=>new p(h.none,e,t,n)))}static build(e){return function(e){var t;let{buffer:n,nodeSet:s,maxBufferLength:r=i,reused:a=[],minRepeatType:l=s.types.length}=e,h=Array.isArray(n)?new m(n,n.length):n,c=s.types,u=0,f=0;function d(e,t,n,i,m,w){let{id:k,start:S,end:A,size:C}=h,O=f;for(;C<0;){if(h.next(),-1==C){let t=a[k];return n.push(t),void i.push(S-e)}if(-3==C)return void(u=k);if(-4==C)return void(f=k);throw new RangeError(`Unrecognized record size: ${C}`)}let M,T,_=c[k],N=S-e;if(A-S<=r&&(T=function(e,t){let n=h.fork(),i=0,s=0,o=0,a=n.end-r,c={size:0,start:0,skip:0};e:for(let r=n.pos-e;n.pos>r;){let e=n.size;if(n.id==t&&e>=0){c.size=i,c.start=s,c.skip=o,o+=4,i+=4,n.next();continue}let h=n.pos-e;if(e<0||h=l?4:0,f=n.start;for(n.next();n.pos>h;){if(n.size<0){if(-3!=n.size)break e;u+=4}else n.id>=l&&(u+=4);n.next()}s=f,i+=e,o+=u}return(t<0||i==e)&&(c.size=i,c.start=s,c.skip=o),c.size>4?c:void 0}(h.pos-t,m))){let t=new Uint16Array(T.size-T.skip),n=h.pos-T.size,i=t.length;for(;h.pos>n;)i=x(T.start,t,i);M=new g(t,A-T.start,s),N=T.start-e}else{let e=h.pos-C;h.next();let t=[],n=[],i=k>=l?k:-1,s=0,a=A;for(;h.pos>e;)i>=0&&h.id==i&&h.size>=0?(h.end<=a-r&&(y(t,n,S,s,h.end,a,i,O),s=t.length,a=h.end),h.next()):w>2500?b(S,e,t,n):d(S,e,t,n,i,w+1);if(i>=0&&s>0&&s-1&&s>0){let e=function(e){return(t,n,i)=>{let s,r,a=0,l=t.length-1;if(l>=0&&(s=t[l])instanceof p){if(!l&&s.type==e&&s.length==i)return s;(r=s.prop(o.lookAhead))&&(a=n[l]+s.length+r)}return v(e,t,n,i,a)}}(_);M=D(_,t,n,0,t.length,0,A-S,e,e)}else M=v(_,t,n,A-S,O-A)}n.push(M),i.push(N)}function b(e,t,n,i){let o=[],a=0,l=-1;for(;h.pos>t;){let{id:e,start:t,end:n,size:i}=h;if(i>4)h.next();else{if(l>-1&&t=0;e-=3)t[n++]=o[e],t[n++]=o[e+1]-r,t[n++]=o[e+2]-r,t[n++]=n;n.push(new g(t,o[2]-r,s)),i.push(r-e)}}function y(e,t,n,i,r,o,a,l){let h=[],c=[];for(;e.length>i;)h.push(e.pop()),c.push(t.pop()+n-r);e.push(v(s.types[a],h,c,o-r,l-o)),t.push(r-n)}function v(e,t,n,i,s=0,r){if(u){let e=[o.contextHash,u];r=r?[e].concat(r):[e]}if(s>25){let e=[o.lookAhead,s];r=r?[e].concat(r):[e]}return new p(e,t,n,i,r)}function x(e,t,n){let{id:i,start:s,end:r,size:o}=h;if(h.next(),o>=0&&i4){let i=h.pos-(o-4);for(;h.pos>i;)n=x(e,t,n)}t[--n]=a,t[--n]=r-e,t[--n]=s-e,t[--n]=i}else-3==o?u=i:-4==o&&(f=i);return n}let w=[],k=[];for(;h.pos>0;)d(e.start||0,e.bufferStart||0,w,k,-1,0);let S=null!==(t=e.length)&&void 0!==t?t:w.length?k[0]+w[0].length:0;return new p(c[e.topID],w.reverse(),k.reverse(),S)}(e)}}p.empty=new p(h.none,[],[],0);class m{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new m(this.buffer,this.index)}}class g{constructor(e,t,n){this.buffer=e,this.length=t,this.set=n}get type(){return h.none}toString(){let e=[];for(let t=0;t0));a=r[a+3]);return o}slice(e,t,n){let i=this.buffer,s=new Uint16Array(t-e),r=0;for(let o=e,a=0;o=t&&nt;case 1:return n<=t&&i>t;case 2:return i>t;case 4:return!0}}function y(e,t,n,i){for(var s;e.from==e.to||(n<1?e.from>=t:e.from>t)||(n>-1?e.to<=t:e.to0?o.length:-1;e!=h;e+=t){let h=o[e],c=l[e]+r.from;if(b(i,n,c,c+h.length))if(h instanceof g){if(s&d.ExcludeBuffers)continue;let o=h.findChild(0,h.buffer.length,t,n-c,i);if(o>-1)return new A(new S(r,h,e,c),null,o)}else if(s&d.IncludeAnonymous||!h.type.isAnonymous||T(h)){let o;if(!(s&d.IgnoreMounts)&&(o=a.get(h))&&!o.overlay)return new x(o.tree,c,e,r);let l=new x(h,c,e,r);return s&d.IncludeAnonymous||!l.type.isAnonymous?l:l.nextChild(t<0?h.children.length-1:0,t,n,i)}}if(s&d.IncludeAnonymous||!r.type.isAnonymous)return null;if(e=r.index>=0?r.index+t:t<0?-1:r._parent._tree.children.length,r=r._parent,!r)return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}enter(e,t,n=0){let i;if(!(n&d.IgnoreOverlays)&&(i=a.get(this._tree))&&i.overlay){let n=e-this.from;for(let{from:e,to:s}of i.overlay)if((t>0?e<=n:e=n:s>n))return new x(i.tree,i.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,n)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}}function w(e,t,n,i){let s=e.cursor(),r=[];if(!s.firstChild())return r;if(null!=n)for(;!s.type.is(n);)if(!s.nextSibling())return r;for(;;){if(null!=i&&s.type.is(i))return r;if(s.type.is(t)&&r.push(s.node),!s.nextSibling())return null==i?r:[]}}function k(e,t,n=t.length-1){for(let i=e.parent;n>=0;i=i.parent){if(!i)return!1;if(!i.type.isAnonymous){if(t[n]&&t[n]!=i.name)return!1;n--}}return!0}class S{constructor(e,t,n,i){this.parent=e,this.buffer=t,this.index=n,this.start=i}}class A extends v{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,n){super(),this.context=e,this._parent=t,this.index=n,this.type=e.buffer.set.types[e.buffer.buffer[n]]}child(e,t,n){let{buffer:i}=this.context,s=i.findChild(this.index+4,i.buffer[this.index+3],e,t-this.context.start,n);return s<0?null:new A(this.context,this,s)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}enter(e,t,n=0){if(n&d.ExcludeBuffers)return null;let{buffer:i}=this.context,s=i.findChild(this.index+4,i.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return s<0?null:new A(this.context,this,s)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new A(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new A(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:n}=this.context,i=this.index+4,s=n.buffer[this.index+3];if(s>i){let r=n.buffer[this.index+1];e.push(n.slice(i,s,r)),t.push(0)}return new p(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}}function C(e){if(!e.length)return null;let t=0,n=e[0];for(let i=1;in.from||s.to0){if(this.index-1)for(let i=t+e,s=e<0?-1:n._tree.children.length;i!=s;i+=e){let e=n._tree.children[i];if(this.mode&d.IncludeAnonymous||e instanceof g||!e.type.isAnonymous||T(e))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let r=e;r;r=r._parent)if(r.index==i){if(i==this.index)return r;t=r,n=s+1;break e}i=this.stack[--s]}for(let e=n;e=0;s--){if(s<0)return k(this.node,e,i);let r=n[t.buffer[this.stack[s]]];if(!r.isAnonymous){if(e[i]&&e[i]!=r.name)return!1;i--}}return!0}}function T(e){return e.children.some((e=>e instanceof g||!e.type.isAnonymous||T(e)))}const _=new WeakMap;function N(e,t){if(!e.isAnonymous||t instanceof g||t.type!=e)return 1;let n=_.get(t);if(null==n){n=1;for(let i of t.children){if(i.type!=e||!(i instanceof p)){n=1;break}n+=N(e,i)}_.set(t,n)}return n}function D(e,t,n,i,s,r,o,a,l){let h=0;for(let n=i;n=c)break;p+=t}if(h==s+1){if(p>c){let e=n[s];t(e.children,e.positions,0,e.children.length,i[s]+a);continue}u.push(n[s])}else{let t=i[h-1]+n[h-1].length-d;u.push(D(e,n,i,s,h,d,t,null,l))}f.push(d+a-r)}}(t,n,i,s,0),(a||l)(u,f,o)}class E{constructor(){this.map=new WeakMap}setBuffer(e,t,n){let i=this.map.get(e);i||this.map.set(e,i=new Map),i.set(t,n)}getBuffer(e,t){let n=this.map.get(e);return n&&n.get(t)}set(e,t){e instanceof A?this.setBuffer(e.context.buffer,e.index,t):e instanceof x&&this.map.set(e.tree,t)}get(e){return e instanceof A?this.getBuffer(e.context.buffer,e.index):e instanceof x?this.map.get(e.tree):void 0}cursorSet(e,t){e.buffer?this.setBuffer(e.buffer.buffer,e.index,t):this.map.set(e.tree,t)}cursorGet(e){return e.buffer?this.getBuffer(e.buffer.buffer,e.index):this.map.get(e.tree)}}class j{constructor(e,t,n,i,s=!1,r=!1){this.from=e,this.to=t,this.tree=n,this.offset=i,this.open=(s?1:0)|(r?2:0)}get openStart(){return(1&this.open)>0}get openEnd(){return(2&this.open)>0}static addTree(e,t=[],n=!1){let i=[new j(0,e.length,e,0,!1,n)];for(let n of t)n.to>e.length&&i.push(n);return i}static applyChanges(e,t,n=128){if(!t.length)return e;let i=[],s=1,r=e.length?e[0]:null;for(let o=0,a=0,l=0;;o++){let h=o=n)for(;r&&r.from=t.from||c<=t.to||l){let e=Math.max(t.from,a)-l,n=Math.min(t.to,c)-l;t=e>=n?null:new j(e,n,t.tree,t.offset+l,o>0,!!h)}if(t&&i.push(t),r.to>c)break;r=snew r(e.from,e.to))):[new r(0,0)]:[new r(0,e.length)],this.createParse(e,t||[],n)}parse(e,t,n){let i=this.startParse(e,t,n);for(;;){let e=i.advance();if(e)return e}}}class P{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}function I(e){return(t,n,i,s)=>new F(t,e,n,i,s)}class B{constructor(e,t,n,i,s){this.parser=e,this.parse=t,this.overlay=n,this.target=i,this.from=s}}function L(e){if(!e.length||e.some((e=>e.from>=e.to)))throw new RangeError("Invalid inner parse ranges given: "+JSON.stringify(e))}class ${constructor(e,t,n,i,s,r,o){this.parser=e,this.predicate=t,this.mounts=n,this.index=i,this.start=s,this.target=r,this.prev=o,this.depth=0,this.ranges=[]}}const z=new o({perNode:!0});class F{constructor(e,t,n,i,s){this.nest=t,this.input=n,this.fragments=i,this.ranges=s,this.inner=[],this.innerDone=0,this.baseTree=null,this.stoppedAt=null,this.baseParse=e}advance(){if(this.baseParse){let e=this.baseParse.advance();if(!e)return null;if(this.baseParse=null,this.baseTree=e,this.startInner(),null!=this.stoppedAt)for(let e of this.inner)e.parse.stopAt(this.stoppedAt)}if(this.innerDone==this.inner.length){let e=this.baseTree;return null!=this.stoppedAt&&(e=new p(e.type,e.children,e.positions,e.length,e.propValues.concat([[z,this.stoppedAt]]))),e}let e=this.inner[this.innerDone],t=e.parse.advance();if(t){this.innerDone++;let n=Object.assign(Object.create(null),e.target.props);n[o.mounted.id]=new a(t,e.overlay,e.parser),e.target.props=n}return null}get parsedPos(){if(this.baseParse)return 0;let e=this.input.length;for(let t=this.innerDone;t=this.stoppedAt)l=!1;else if(e.hasNode(i)){if(t){let e=t.mounts.find((e=>e.frag.from<=i.from&&e.frag.to>=i.to&&e.mount.overlay));if(e)for(let n of e.mount.overlay){let s=n.from+e.pos,r=n.to+e.pos;s>=i.from&&r<=i.to&&!t.ranges.some((e=>e.froms))&&t.ranges.push({from:s,to:r})}}l=!1}else if(n&&(o=H(n.ranges,i.from,i.to)))l=2!=o;else if(!i.type.isAnonymous&&(s=this.nest(i,this.input))&&(i.fromnew r(e.from-i.from,e.to-i.from))):null,i.tree,e.length?e[0].from:i.from)),s.overlay?e.length&&(n={ranges:e,depth:0,prev:n}):l=!1}}else t&&(a=t.predicate(i))&&(!0===a&&(a=new r(i.from,i.to)),a.fromnew r(e.from-t.start,e.to-t.start))),t.target,e[0].from))),t=t.prev}n&&!--n.depth&&(n=n.prev)}}}}function H(e,t,n){for(let i of e){if(i.from>=n)break;if(i.to>t)return i.from<=t&&i.to>=n?2:1}return 0}function V(e,t,n,i,s,r){if(t=t.to);i++);let o=s.children[i],a=o.buffer,l=[i];s.children[i]=function e(i,s,r,h,c,u){let f=n[u],d=[],m=[];V(o,i,f,d,m,h);let g=a[f+1],b=a[f+2];l.push(d.length);let y=u?e(f+4,a[f+3],o.set.types[a[f]],g,b-g,u-1):t.toTree();return d.push(y),m.push(g-h),V(o,a[f+3],s,d,m,h),new p(r,d,m,c)}(0,a.length,h.none,0,o.length,n.length-1);for(let t of l){let n=e.tree.children[t],i=e.tree.positions[t];e.yield(new x(n,i+e.from,t,e._tree))}}class q{constructor(e,t){this.offset=t,this.done=!1,this.cursor=e.cursor(d.IncludeAnonymous|d.IgnoreMounts)}moveTo(e){let{cursor:t}=this,n=e-this.offset;for(;!this.done&&t.from=e&&t.enter(n,1,d.IgnoreOverlays|d.ExcludeBuffers)||t.next(!1)||(this.done=!0)}hasNode(e){if(this.moveTo(e.from),!this.done&&this.cursor.from+this.offset==e.from&&this.cursor.tree)for(let t=this.cursor.tree;;){if(t==e.tree)return!0;if(!(t.children.length&&0==t.positions[0]&&t.children[0]instanceof p))break;t=t.children[0]}return!1}}class J{constructor(e){var t;if(this.fragments=e,this.curTo=0,this.fragI=0,e.length){let n=this.curFrag=e[0];this.curTo=null!==(t=n.tree.prop(z))&&void 0!==t?t:n.to,this.inner=new q(n.tree,-n.offset)}else this.curFrag=this.inner=null}hasNode(e){for(;this.curFrag&&e.from>=this.curTo;)this.nextFrag();return this.curFrag&&this.curFrag.from<=e.from&&this.curTo>=e.to&&this.inner.hasNode(e)}nextFrag(){var e;if(this.fragI++,this.fragI==this.fragments.length)this.curFrag=this.inner=null;else{let t=this.curFrag=this.fragments[this.fragI];this.curTo=null!==(e=t.tree.prop(z))&&void 0!==e?e:t.to,this.inner=new q(t.tree,-t.offset)}}findMounts(e,t){var n;let i=[];if(this.inner){this.inner.cursor.moveTo(e,1);for(let e=this.inner.cursor.node;e;e=e.parent){let s=null===(n=e.tree)||void 0===n?void 0:n.prop(o.mounted);if(s&&s.parser==t)for(let t=this.fragI;t=e.to)break;n.tree==this.curFrag.tree&&i.push({frag:n,pos:e.from-n.offset,mount:s})}}}return i}}function U(e,t){let n=null,i=t;for(let s=1,o=0;s=l)break;e.to<=a||(n||(i=n=t.slice()),e.froml&&n.splice(o+1,0,new r(l,e.to))):e.to>l?n[o--]=new r(l,e.to):n.splice(o--,1))}}return i}function G(e,t,n,i){let s=0,o=0,a=!1,l=!1,h=-1e9,c=[];for(;;){let u=s==e.length?1e9:a?e[s].to:e[s].from,f=o==t.length?1e9:l?t[o].to:t[o].from;if(a!=l){let e=Math.max(h,n),t=Math.min(u,f,i);enew r(e.from+i,e.to+i))),l,h);for(let t=0,i=l;;t++){let r=t==a.length,l=r?h:a[t].from;if(l>i&&n.push(new j(i,l,s.tree,-e,o.from>=i||o.openStart,o.to<=l||o.openEnd)),r)break;i=a[t].to}}else n.push(new j(l,h,s.tree,-e,o.from>=e||o.openStart,o.to<=a||o.openEnd))}return n}},86253:(e,t,n)=>{"use strict";n.d(t,{Gv:()=>l,QR:()=>u,Vp:()=>r,bW:()=>f,pJ:()=>_});var i=n(21649);let s=0;class r{constructor(e,t,n){this.set=e,this.base=t,this.modified=n,this.id=s++}static define(e){if(null==e?void 0:e.base)throw new Error("Can not derive from a modified tag");let t=new r([],null,[]);if(t.set.push(t),e)for(let n of e.set)t.set.push(n);return t}static defineModifier(){let e=new a;return t=>t.modified.indexOf(e)>-1?t:a.get(t.base||t,t.modified.concat(e).sort(((e,t)=>e.id-t.id)))}}let o=0;class a{constructor(){this.instances=[],this.id=o++}static get(e,t){if(!t.length)return e;let n=t[0].instances.find((n=>{return n.base==e&&(i=t,s=n.modified,i.length==s.length&&i.every(((e,t)=>e==s[t])));var i,s}));if(n)return n;let i=[],s=new r(i,e,t);for(let e of t)e.instances.push(s);let o=function(e){let t=[[]];for(let n=0;nt.length-e.length))}(t);for(let t of e.set)if(!t.modified.length)for(let e of o)i.push(a.get(t,e));return s}}function l(e){let t=Object.create(null);for(let n in e){let i=e[n];Array.isArray(i)||(i=[i]);for(let e of n.split(" "))if(e){let n=[],s=2,r=e;for(let t=0;;){if("..."==r&&t>0&&t+3==e.length){s=1;break}let i=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(r);if(!i)throw new RangeError("Invalid path: "+e);if(n.push("*"==i[0]?"":'"'==i[0][0]?JSON.parse(i[0]):i[0]),t+=i[0].length,t==e.length)break;let o=e[t++];if(t==e.length&&"!"==o){s=0;break}if("/"!=o)throw new RangeError("Invalid path: "+e);r=e.slice(t)}let o=n.length-1,a=n[o];if(!a)throw new RangeError("Invalid path: "+e);let l=new c(i,s,o>0?n.slice(0,o):null);t[a]=l.sort(t[a])}}return h.add(t)}const h=new i.md;class c{constructor(e,t,n,i){this.tags=e,this.mode=t,this.context=n,this.next=i}get opaque(){return 0==this.mode}get inherit(){return 1==this.mode}sort(e){return!e||e.depth{let t=s;for(let i of e)for(let e of i.set){let i=n[e.id];if(i){t=t?t+" "+i:i;break}}return t},scope:i}}function f(e,t,n,i=0,s=e.length){let r=new d(i,Array.isArray(t)?t:[t],n);r.highlightRange(e.cursor(),i,s,"",r.highlighters),r.flush(s)}c.empty=new c([],2,null);class d{constructor(e,t,n){this.at=e,this.highlighters=t,this.span=n,this.class=""}startSpan(e,t){t!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=t)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,t,n,s,r){let{type:o,from:a,to:l}=e;if(a>=n||l<=t)return;o.isTop&&(r=this.highlighters.filter((e=>!e.scope||e.scope(o))));let u=s,f=function(e){let t=e.type.prop(h);for(;t&&t.context&&!e.matchContext(t.context);)t=t.next;return t||null}(e)||c.empty,d=function(e,t){let n=null;for(let i of e){let e=i.style(t);e&&(n=n?n+" "+e:e)}return n}(r,f.tags);if(d&&(u&&(u+=" "),u+=d,1==f.mode&&(s+=(s?" ":"")+d)),this.startSpan(Math.max(t,a),u),f.opaque)return;let p=e.tree&&e.tree.prop(i.md.mounted);if(p&&p.overlay){let i=e.node.enter(p.overlay[0].from+a,1),o=this.highlighters.filter((e=>!e.scope||e.scope(p.tree.type))),h=e.firstChild();for(let c=0,f=a;;c++){let d=c=m)&&e.nextSibling()););if(!d||m>n)break;f=d.to+a,f>t&&(this.highlightRange(i.cursor(),Math.max(t,d.from+a),Math.min(n,f),"",o),this.startSpan(Math.min(n,f),u))}h&&e.parent()}else if(e.firstChild()){p&&(s="");do{if(!(e.to<=t)){if(e.from>=n)break;this.highlightRange(e,t,n,s,r),this.startSpan(Math.min(n,e.to),u)}}while(e.nextSibling());e.parent()}}}const p=r.define,m=p(),g=p(),b=p(g),y=p(g),v=p(),x=p(v),w=p(v),k=p(),S=p(k),A=p(),C=p(),O=p(),M=p(O),T=p(),_={comment:m,lineComment:p(m),blockComment:p(m),docComment:p(m),name:g,variableName:p(g),typeName:b,tagName:p(b),propertyName:y,attributeName:p(y),className:p(g),labelName:p(g),namespace:p(g),macroName:p(g),literal:v,string:x,docString:p(x),character:p(x),attributeValue:p(x),number:w,integer:p(w),float:p(w),bool:p(v),regexp:p(v),escape:p(v),color:p(v),url:p(v),keyword:A,self:p(A),null:p(A),atom:p(A),unit:p(A),modifier:p(A),operatorKeyword:p(A),controlKeyword:p(A),definitionKeyword:p(A),moduleKeyword:p(A),operator:C,derefOperator:p(C),arithmeticOperator:p(C),logicOperator:p(C),bitwiseOperator:p(C),compareOperator:p(C),updateOperator:p(C),definitionOperator:p(C),typeOperator:p(C),controlOperator:p(C),punctuation:O,separator:p(O),bracket:M,angleBracket:p(M),squareBracket:p(M),paren:p(M),brace:p(M),content:k,heading:S,heading1:p(S),heading2:p(S),heading3:p(S),heading4:p(S),heading5:p(S),heading6:p(S),contentSeparator:p(k),list:p(k),quote:p(k),emphasis:p(k),strong:p(k),link:p(k),monospace:p(k),strikethrough:p(k),inserted:p(),deleted:p(),changed:p(),invalid:p(),meta:T,documentMeta:p(T),annotation:p(T),processingInstruction:p(T),definition:r.defineModifier(),constant:r.defineModifier(),function:r.defineModifier(),standard:r.defineModifier(),local:r.defineModifier(),special:r.defineModifier()};u([{tag:_.link,class:"tok-link"},{tag:_.heading,class:"tok-heading"},{tag:_.emphasis,class:"tok-emphasis"},{tag:_.strong,class:"tok-strong"},{tag:_.keyword,class:"tok-keyword"},{tag:_.atom,class:"tok-atom"},{tag:_.bool,class:"tok-bool"},{tag:_.url,class:"tok-url"},{tag:_.labelName,class:"tok-labelName"},{tag:_.inserted,class:"tok-inserted"},{tag:_.deleted,class:"tok-deleted"},{tag:_.literal,class:"tok-literal"},{tag:_.string,class:"tok-string"},{tag:_.number,class:"tok-number"},{tag:[_.regexp,_.escape,_.special(_.string)],class:"tok-string2"},{tag:_.variableName,class:"tok-variableName"},{tag:_.local(_.variableName),class:"tok-variableName tok-local"},{tag:_.definition(_.variableName),class:"tok-variableName tok-definition"},{tag:_.special(_.variableName),class:"tok-variableName2"},{tag:_.definition(_.propertyName),class:"tok-propertyName tok-definition"},{tag:_.typeName,class:"tok-typeName"},{tag:_.namespace,class:"tok-namespace"},{tag:_.className,class:"tok-className"},{tag:_.macroName,class:"tok-macroName"},{tag:_.propertyName,class:"tok-propertyName"},{tag:_.operator,class:"tok-operator"},{tag:_.comment,class:"tok-comment"},{tag:_.meta,class:"tok-meta"},{tag:_.invalid,class:"tok-invalid"},{tag:_.punctuation,class:"tok-punctuation"}])},51392:(e,t,n)=>{"use strict";n.d(t,{IK:()=>M,Jq:()=>p,RA:()=>d,WQ:()=>T});var i=n(21649);class s{constructor(e,t,n,i,s,r,o,a,l,h=0,c){this.p=e,this.stack=t,this.state=n,this.reducePos=i,this.pos=s,this.score=r,this.buffer=o,this.bufferBase=a,this.curContext=l,this.lookAhead=h,this.parent=c}toString(){return`[${this.stack.filter(((e,t)=>t%3==0)).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,n=0){let i=e.parser.context;return new s(e,[],t,n,n,0,[],0,i?new r(i,i.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){var t;let n=e>>19,i=65535&e,{parser:s}=this.p,r=s.dynamicPrecedence(i);if(r&&(this.score+=r),0==n)return this.pushState(s.getGoto(this.state,i,!0),this.reducePos),i=2e3&&!(null===(t=this.p.parser.nodeSet.types[i])||void 0===t?void 0:t.isAnonymous)&&(a==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=l):this.p.lastBigReductionSizeo;)this.stack.pop();this.reduceContext(i,a)}storeNode(e,t,n,i=4,s=!1){if(0==e&&(!this.stack.length||this.stack[this.stack.length-1]0&&0==e.buffer[i-4]&&e.buffer[i-1]>-1){if(t==n)return;if(e.buffer[i-2]>=t)return void(e.buffer[i-2]=n)}}if(s&&this.pos!=n){let s=this.buffer.length;if(s>0&&0!=this.buffer[s-4])for(;s>0&&this.buffer[s-2]>n;)this.buffer[s]=this.buffer[s-4],this.buffer[s+1]=this.buffer[s-3],this.buffer[s+2]=this.buffer[s-2],this.buffer[s+3]=this.buffer[s-1],s-=4,i>4&&(i-=4);this.buffer[s]=e,this.buffer[s+1]=t,this.buffer[s+2]=n,this.buffer[s+3]=i}else this.buffer.push(e,t,n,i)}shift(e,t,n,i){if(131072&e)this.pushState(65535&e,this.pos);else if(0==(262144&e)){let s=e,{parser:r}=this.p;(i>this.pos||t<=r.maxNode)&&(this.pos=i,r.stateFlag(s,1)||(this.reducePos=i)),this.pushState(s,n),this.shiftContext(t,n),t<=r.maxNode&&this.buffer.push(t,n,i,4)}else this.pos=i,this.shiftContext(t,n),t<=this.p.parser.maxNode&&this.buffer.push(t,n,i,4)}apply(e,t,n,i){65536&e?this.reduce(e):this.shift(e,t,n,i)}useNode(e,t){let n=this.p.reused.length-1;(n<0||this.p.reused[n]!=e)&&(this.p.reused.push(e),n++);let i=this.pos;this.reducePos=this.pos=i+e.length,this.pushState(t,i),this.buffer.push(n,i,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(;t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let n=e.buffer.slice(t),i=e.bufferBase+t;for(;e&&i==e.bufferBase;)e=e.parent;return new s(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,n,i,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let n=e<=this.p.parser.maxNode;n&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,n?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new o(this);;){let n=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(0==n)return!1;if(0==(65536&n))return!0;t.reduce(n)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let n=[];for(let i,s=0;s1&t&&e==i))||n.push(t[e],i)}t=n}let n=[];for(let e=0;e>19,i=65535&t,s=this.stack.length-3*n;if(s<0||e.getGoto(this.stack[s],i,!1)<0){let e=this.findForcedReduction();if(null==e)return!1;t=e}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(t),!0}findForcedReduction(){let{parser:e}=this.p,t=[],n=(i,s)=>{if(!t.includes(i))return t.push(i),e.allActions(i,(t=>{if(393216&t);else if(65536&t){let n=(t>>19)-s;if(n>1){let i=65535&t,s=this.stack.length-3*n;if(s>=0&&e.getGoto(this.stack[s],i,!1)>=0)return n<<19|65536|i}}else{let e=n(t,s+1);if(null!=e)return e}}))};return n(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(3!=this.stack.length)return!1;let{parser:e}=this.p;return 65535==e.data[e.stateSlot(this.state,1)]&&!e.stateSlot(this.state,4)}restart(){this.storeNode(0,this.pos,this.pos,4,!0),this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;tthis.lookAhead&&(this.emitLookAhead(),this.lookAhead=e)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}}class r{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}class o{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=65535&e,n=e>>19;0==n?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=3*(n-1);let i=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=i}}class a{constructor(e,t,n){this.stack=e,this.pos=t,this.index=n,this.buffer=e.buffer,0==this.index&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new a(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;null!=e&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,0==this.index&&this.maybeNext()}fork(){return new a(this.stack,this.pos,this.index)}}function l(e,t=Uint16Array){if("string"!=typeof e)return e;let n=null;for(let i=0,s=0;i=92&&t--,t>=34&&t--;let s=t-32;if(s>=46&&(s-=46,n=!0),r+=s,n)break;r*=46}n?n[s++]=r:n=new t(r)}return n}class h{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const c=new h;class u{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=c,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let n=this.range,i=this.rangeIndex,s=this.pos+e;for(;sn.to:s>=n.to;){if(i==this.ranges.length-1)return null;let e=this.ranges[++i];s+=e.from-n.to,n=e}return s}clipPos(e){if(e>=this.range.from&&ee)return Math.max(e,t.from);return this.end}peek(e){let t,n,i=this.chunkOff+e;if(i>=0&&i=this.chunk2Pos&&ti.to&&(this.chunk2=this.chunk2.slice(0,i.to-t)),n=this.chunk2.charCodeAt(0)}}return t>=this.token.lookAhead&&(this.token.lookAhead=t+1),n}acceptToken(e,t=0){let n=t?this.resolveOffset(t,-1):this.pos;if(null==n||n=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=c,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let n="";for(let i of this.ranges){if(i.from>=t)break;i.to>e&&(n+=this.input.read(Math.max(i.from,e),Math.min(i.to,t)))}return n}}class f{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:n}=t.p;m(this.data,e,t,this.id,n.data,n.tokenPrecTable)}}f.prototype.contextual=f.prototype.fallback=f.prototype.extend=!1;class d{constructor(e,t,n){this.precTable=t,this.elseToken=n,this.data="string"==typeof e?l(e):e}token(e,t){let n=e.pos,i=0;for(;;){let n=e.next<0,s=e.resolveOffset(1,1);if(m(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(null==this.elseToken)return;if(n||i++,null==s)break;e.reset(s,e.token)}i&&(e.reset(n,e.token),e.acceptToken(this.elseToken,i))}}d.prototype.contextual=f.prototype.fallback=f.prototype.extend=!1;class p{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function m(e,t,n,i,s,r){let o=0,a=1<0){let n=e[i];if(l.allows(n)&&(-1==t.token.value||t.token.value==n||b(n,t.token.value,s,r))){t.acceptToken(n);break}}let i=t.next,h=0,c=e[o+2];if(!(t.next<0&&c>h&&65535==e[n+3*c-3])){for(;h>1,r=n+s+(s<<1),a=e[r],l=e[r+1]||65536;if(i=l)){o=e[r+2],t.advance();continue e}h=s+1}}break}o=e[n+3*c-1]}}function g(e,t,n){for(let i,s=t;65535!=(i=e[s]);s++)if(i==n)return s-t;return-1}function b(e,t,n,i){let s=g(n,i,t);return s<0||g(n,i,e)t)&&!s.type.isError)return n<0?Math.max(0,Math.min(s.to-1,t-25)):Math.min(e.length,Math.max(s.from+1,t+25));if(n<0?s.prevSibling():s.nextSibling())break;if(!s.parent())return n<0?0:e.length}}class w{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?x(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?x(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=o,null;if(r instanceof i.mp){if(o==e){if(o=Math.max(this.safeFrom,e)&&(this.trees.push(r),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+r.length}}}class k{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map((e=>new h))}getActions(e){let t=0,n=null,{parser:i}=e.p,{tokenizers:s}=i,r=i.stateSlot(e.state,3),o=e.curContext?e.curContext.hash:0,a=0;for(let i=0;ih.end+25&&(a=Math.max(h.lookAhead,a)),0!=h.value)){let i=t;if(h.extended>-1&&(t=this.addActions(e,h.extended,h.end,t)),t=this.addActions(e,h.value,h.end,t),!l.extend&&(n=h,t>i))break}}for(;this.actions.length>t;)this.actions.pop();return a&&e.setLookAhead(a),n||e.pos!=this.stream.end||(n=new h,n.value=e.p.parser.eofTerm,n.start=n.end=e.pos,t=this.addActions(e,n.value,n.end,t)),this.mainToken=n,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new h,{pos:n,p:i}=e;return t.start=n,t.end=Math.min(n+1,i.stream.end),t.value=n==i.stream.end?i.parser.eofTerm:0,t}updateCachedToken(e,t,n){let i=this.stream.clipPos(n.pos);if(t.token(this.stream.reset(i,e),n),e.value>-1){let{parser:t}=n.p;for(let i=0;i=0&&n.p.parser.dialect.allows(s>>1)){0==(1&s)?e.value=s>>1:e.extended=s>>1;break}}}else e.value=0,e.end=this.stream.clipPos(i+1)}putAction(e,t,n,i){for(let t=0;t4*e.bufferLength?new w(n,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e,t,n=this.stacks,i=this.minStackPos,s=this.stacks=[];if(this.bigReductionCount>300&&1==n.length){let[e]=n;for(;e.forceReduce()&&e.stack.length&&e.stack[e.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let r=0;ri)s.push(o);else{if(this.advanceStack(o,s,n))continue;{e||(e=[],t=[]),e.push(o);let n=this.tokens.getMainToken(o);t.push(n.value,n.end)}}break}}if(!s.length){let t=e&&function(e){let t=null;for(let n of e){let e=n.p.stoppedAt;(n.pos==n.p.stream.end||null!=e&&n.pos>e)&&n.p.parser.stateFlag(n.state,2)&&(!t||t.scorethis.stoppedAt?e[0]:this.runRecovery(e,t,s);if(n)return y&&console.log("Force-finish "+this.stackID(n)),this.stackToTree(n.forceAll())}if(this.recovering){let e=1==this.recovering?1:3*this.recovering;if(s.length>e)for(s.sort(((e,t)=>t.score-e.score));s.length>e;)s.pop();s.some((e=>e.reducePos>i))&&this.recovering--}else if(s.length>1){e:for(let e=0;e500&&i.buffer.length>500){if(!((t.score-i.score||t.buffer.length-i.buffer.length)>0)){s.splice(e--,1);continue e}s.splice(n--,1)}}}s.length>12&&s.splice(12,s.length-12)}this.minStackPos=s[0].pos;for(let e=1;e ":"";if(null!=this.stoppedAt&&s>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let t=e.curContext&&e.curContext.tracker.strict,n=t?e.curContext.hash:0;for(let a=this.fragments.nodeAt(s);a;){let s=this.parser.nodeSet.types[a.type.id]==a.type?r.getGoto(e.state,a.type.id):-1;if(s>-1&&a.length&&(!t||(a.prop(i.md.contextHash)||0)==n))return e.useNode(a,s),y&&console.log(o+this.stackID(e)+` (via reuse of ${r.getName(a.type.id)})`),!0;if(!(a instanceof i.mp)||0==a.children.length||a.positions[0]>0)break;let l=a.children[0];if(!(l instanceof i.mp&&0==a.positions[0]))break;a=l}}let a=r.stateSlot(e.state,4);if(a>0)return e.reduce(a),y&&console.log(o+this.stackID(e)+` (via always-reduce ${r.getName(65535&a)})`),!0;if(e.stack.length>=8400)for(;e.stack.length>6e3&&e.forceReduce(););let l=this.tokens.getActions(e);for(let i=0;is?t.push(f):n.push(f)}return!1}advanceFully(e,t){let n=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>n)return A(e,t),!0}}runRecovery(e,t,n){let i=null,s=!1;for(let r=0;r ":"";if(o.deadEnd){if(s)continue;if(s=!0,o.restart(),y&&console.log(h+this.stackID(o)+" (restarted)"),this.advanceFully(o,n))continue}let c=o.split(),u=h;for(let e=0;c.forceReduce()&&e<10&&(y&&console.log(u+this.stackID(c)+" (via force-reduce)"),!this.advanceFully(c,n));e++)y&&(u=this.stackID(c)+" -> ");for(let e of o.recoverByInsert(a))y&&console.log(h+this.stackID(e)+" (via recover-insert)"),this.advanceFully(e,n);this.stream.end>o.pos?(l==o.pos&&(l++,a=0),o.recoverByDelete(a,l),y&&console.log(h+this.stackID(o)+` (via recover-delete ${this.parser.getName(a)})`),A(o,n)):(!i||i.scoree;class M{constructor(e){this.start=e.start,this.shift=e.shift||O,this.reduce=e.reduce||O,this.reuse=e.reuse||O,this.hash=e.hash||(()=>0),this.strict=!1!==e.strict}}class T extends i._b{constructor(e){if(super(),this.wrappers=[],14!=e.version)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let n=0;ne.topRules[t][1])),s=[];for(let e=0;e=0)r(i,e,t[n++]);else{let s=t[n+-i];for(let o=-i;o>0;o--)r(t[n++],e,s);n++}}}this.nodeSet=new i.Lj(t.map(((t,r)=>i.Jq.define({name:r>=this.minRepeatTerm?void 0:t,id:r,props:s[r],top:n.indexOf(r)>-1,error:0==r,skipped:e.skippedNodes&&e.skippedNodes.indexOf(r)>-1})))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=i.L3;let o=l(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let e=0;e"number"==typeof e?new f(o,e):e)),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,n){let i=new S(this,e,t,n);for(let s of this.wrappers)i=s(i,e,t,n);return i}getGoto(e,t,n=!1){let i=this.goto;if(t>=i[0])return-1;for(let s=i[t+1];;){let t=i[s++],r=1&t,o=i[s++];if(r&&n)return o;for(let n=s+(t>>1);s0}validAction(e,t){return!!this.allActions(e,(e=>e==t||null))}allActions(e,t){let n=this.stateSlot(e,4),i=n?t(n):void 0;for(let n=this.stateSlot(e,1);null==i;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])break;n=_(this.data,n+2)}i=t(_(this.data,n+1))}return i}nextStates(e){let t=[];for(let n=this.stateSlot(e,1);;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])break;n=_(this.data,n+2)}if(0==(1&this.data[n+2])){let e=this.data[n+1];t.some(((t,n)=>1&n&&t==e))||t.push(this.data[n],e)}}return t}configure(e){let t=Object.assign(Object.create(T.prototype),this);if(e.props&&(t.nodeSet=this.nodeSet.extend(...e.props)),e.top){let n=this.topRules[e.top];if(!n)throw new RangeError(`Invalid top rule name ${e.top}`);t.top=n}return e.tokenizers&&(t.tokenizers=this.tokenizers.map((t=>{let n=e.tokenizers.find((e=>e.from==t));return n?n.to:t}))),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map(((n,i)=>{let s=e.specializers.find((e=>e.from==n.external));if(!s)return n;let r=Object.assign(Object.assign({},n),{external:s.to});return t.specializers[i]=N(r),r}))),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),null!=e.strict&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),null!=e.bufferLength&&(t.bufferLength=e.bufferLength),t}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return null==t?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),n=t.map((()=>!1));if(e)for(let i of e.split(" ")){let e=t.indexOf(i);e>=0&&(n[e]=!0)}let i=null;for(let e=0;ee.external(n,i)<<1|t}return e.get}},37207:(e,t,n)=>{"use strict";n.d(t,{V:()=>o});const i="undefined"==typeof Symbol?"__ͼ":Symbol.for("ͼ"),s="undefined"==typeof Symbol?"__styleSet"+Math.floor(1e8*Math.random()):Symbol("styleSet"),r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{};class o{constructor(e,t){this.rules=[];let{finish:n}=t||{};function i(e){return/^@/.test(e)?[e]:e.split(/,\s*/)}function s(e,t,r,o){let a=[],l=/^@(\w+)\b/.exec(e[0]),h=l&&"keyframes"==l[1];if(l&&null==t)return r.push(e[0]+";");for(let n in t){let o=t[n];if(/&/.test(n))s(n.split(/,\s*/).map((t=>e.map((e=>t.replace(/&/,e))))).reduce(((e,t)=>e.concat(t))),o,r);else if(o&&"object"==typeof o){if(!l)throw new RangeError("The value of a property ("+n+") should be a primitive value.");s(i(n),o,a,h)}else null!=o&&a.push(n.replace(/_.*/,"").replace(/[A-Z]/g,(e=>"-"+e.toLowerCase()))+": "+o+";")}(a.length||h)&&r.push((!n||l||o?e:e.map(n)).join(", ")+" {"+a.join(" ")+"}")}for(let t in e)s(i(t),e[t],this.rules)}getRules(){return this.rules.join("\n")}static newName(){let e=r[i]||1;return r[i]=e+1,"ͼ"+e.toString(36)}static mount(e,t,n){let i=e[s],r=n&&n.nonce;i?r&&i.setNonce(r):i=new l(e,r),i.mount(Array.isArray(t)?t:[t])}}let a=new Map;class l{constructor(e,t){let n=e.ownerDocument||e,i=n.defaultView;if(!e.head&&e.adoptedStyleSheets&&i.CSSStyleSheet){let t=a.get(n);if(t)return e.adoptedStyleSheets=[t.sheet,...e.adoptedStyleSheets],e[s]=t;this.sheet=new i.CSSStyleSheet,e.adoptedStyleSheets=[this.sheet,...e.adoptedStyleSheets],a.set(n,this)}else{this.styleTag=n.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);let i=e.head||e;i.insertBefore(this.styleTag,i.firstChild)}this.modules=[],e[s]=this}mount(e){let t=this.sheet,n=0,i=0;for(let s=0;s-1&&(this.modules.splice(o,1),i--,o=-1),-1==o){if(this.modules.splice(i++,0,r),t)for(let e=0;e 1) {\n\t\t\th -= 1;\n\t\t}\n\t}\n\n\treturn [\n\t\th * 360,\n\t\ts * 100,\n\t\tv * 100\n\t];\n};\n\nconvert.rgb.hwb = function (rgb) {\n\tvar r = rgb[0];\n\tvar g = rgb[1];\n\tvar b = rgb[2];\n\tvar h = convert.rgb.hsl(rgb)[0];\n\tvar w = 1 / 255 * Math.min(r, Math.min(g, b));\n\n\tb = 1 - 1 / 255 * Math.max(r, Math.max(g, b));\n\n\treturn [h, w * 100, b * 100];\n};\n\nconvert.rgb.cmyk = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar c;\n\tvar m;\n\tvar y;\n\tvar k;\n\n\tk = Math.min(1 - r, 1 - g, 1 - b);\n\tc = (1 - r - k) / (1 - k) || 0;\n\tm = (1 - g - k) / (1 - k) || 0;\n\ty = (1 - b - k) / (1 - k) || 0;\n\n\treturn [c * 100, m * 100, y * 100, k * 100];\n};\n\n/**\n * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance\n * */\nfunction comparativeDistance(x, y) {\n\treturn (\n\t\tMath.pow(x[0] - y[0], 2) +\n\t\tMath.pow(x[1] - y[1], 2) +\n\t\tMath.pow(x[2] - y[2], 2)\n\t);\n}\n\nconvert.rgb.keyword = function (rgb) {\n\tvar reversed = reverseKeywords[rgb];\n\tif (reversed) {\n\t\treturn reversed;\n\t}\n\n\tvar currentClosestDistance = Infinity;\n\tvar currentClosestKeyword;\n\n\tfor (var keyword in cssKeywords) {\n\t\tif (cssKeywords.hasOwnProperty(keyword)) {\n\t\t\tvar value = cssKeywords[keyword];\n\n\t\t\t// Compute comparative distance\n\t\t\tvar distance = comparativeDistance(rgb, value);\n\n\t\t\t// Check if its less, if so set as closest\n\t\t\tif (distance < currentClosestDistance) {\n\t\t\t\tcurrentClosestDistance = distance;\n\t\t\t\tcurrentClosestKeyword = keyword;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn currentClosestKeyword;\n};\n\nconvert.keyword.rgb = function (keyword) {\n\treturn cssKeywords[keyword];\n};\n\nconvert.rgb.xyz = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\n\t// assume sRGB\n\tr = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);\n\tg = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);\n\tb = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);\n\n\tvar x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);\n\tvar y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);\n\tvar z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);\n\n\treturn [x * 100, y * 100, z * 100];\n};\n\nconvert.rgb.lab = function (rgb) {\n\tvar xyz = convert.rgb.xyz(rgb);\n\tvar x = xyz[0];\n\tvar y = xyz[1];\n\tvar z = xyz[2];\n\tvar l;\n\tvar a;\n\tvar b;\n\n\tx /= 95.047;\n\ty /= 100;\n\tz /= 108.883;\n\n\tx = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);\n\ty = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);\n\tz = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);\n\n\tl = (116 * y) - 16;\n\ta = 500 * (x - y);\n\tb = 200 * (y - z);\n\n\treturn [l, a, b];\n};\n\nconvert.hsl.rgb = function (hsl) {\n\tvar h = hsl[0] / 360;\n\tvar s = hsl[1] / 100;\n\tvar l = hsl[2] / 100;\n\tvar t1;\n\tvar t2;\n\tvar t3;\n\tvar rgb;\n\tvar val;\n\n\tif (s === 0) {\n\t\tval = l * 255;\n\t\treturn [val, val, val];\n\t}\n\n\tif (l < 0.5) {\n\t\tt2 = l * (1 + s);\n\t} else {\n\t\tt2 = l + s - l * s;\n\t}\n\n\tt1 = 2 * l - t2;\n\n\trgb = [0, 0, 0];\n\tfor (var i = 0; i < 3; i++) {\n\t\tt3 = h + 1 / 3 * -(i - 1);\n\t\tif (t3 < 0) {\n\t\t\tt3++;\n\t\t}\n\t\tif (t3 > 1) {\n\t\t\tt3--;\n\t\t}\n\n\t\tif (6 * t3 < 1) {\n\t\t\tval = t1 + (t2 - t1) * 6 * t3;\n\t\t} else if (2 * t3 < 1) {\n\t\t\tval = t2;\n\t\t} else if (3 * t3 < 2) {\n\t\t\tval = t1 + (t2 - t1) * (2 / 3 - t3) * 6;\n\t\t} else {\n\t\t\tval = t1;\n\t\t}\n\n\t\trgb[i] = val * 255;\n\t}\n\n\treturn rgb;\n};\n\nconvert.hsl.hsv = function (hsl) {\n\tvar h = hsl[0];\n\tvar s = hsl[1] / 100;\n\tvar l = hsl[2] / 100;\n\tvar smin = s;\n\tvar lmin = Math.max(l, 0.01);\n\tvar sv;\n\tvar v;\n\n\tl *= 2;\n\ts *= (l <= 1) ? l : 2 - l;\n\tsmin *= lmin <= 1 ? lmin : 2 - lmin;\n\tv = (l + s) / 2;\n\tsv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);\n\n\treturn [h, sv * 100, v * 100];\n};\n\nconvert.hsv.rgb = function (hsv) {\n\tvar h = hsv[0] / 60;\n\tvar s = hsv[1] / 100;\n\tvar v = hsv[2] / 100;\n\tvar hi = Math.floor(h) % 6;\n\n\tvar f = h - Math.floor(h);\n\tvar p = 255 * v * (1 - s);\n\tvar q = 255 * v * (1 - (s * f));\n\tvar t = 255 * v * (1 - (s * (1 - f)));\n\tv *= 255;\n\n\tswitch (hi) {\n\t\tcase 0:\n\t\t\treturn [v, t, p];\n\t\tcase 1:\n\t\t\treturn [q, v, p];\n\t\tcase 2:\n\t\t\treturn [p, v, t];\n\t\tcase 3:\n\t\t\treturn [p, q, v];\n\t\tcase 4:\n\t\t\treturn [t, p, v];\n\t\tcase 5:\n\t\t\treturn [v, p, q];\n\t}\n};\n\nconvert.hsv.hsl = function (hsv) {\n\tvar h = hsv[0];\n\tvar s = hsv[1] / 100;\n\tvar v = hsv[2] / 100;\n\tvar vmin = Math.max(v, 0.01);\n\tvar lmin;\n\tvar sl;\n\tvar l;\n\n\tl = (2 - s) * v;\n\tlmin = (2 - s) * vmin;\n\tsl = s * vmin;\n\tsl /= (lmin <= 1) ? lmin : 2 - lmin;\n\tsl = sl || 0;\n\tl /= 2;\n\n\treturn [h, sl * 100, l * 100];\n};\n\n// http://dev.w3.org/csswg/css-color/#hwb-to-rgb\nconvert.hwb.rgb = function (hwb) {\n\tvar h = hwb[0] / 360;\n\tvar wh = hwb[1] / 100;\n\tvar bl = hwb[2] / 100;\n\tvar ratio = wh + bl;\n\tvar i;\n\tvar v;\n\tvar f;\n\tvar n;\n\n\t// wh + bl cant be > 1\n\tif (ratio > 1) {\n\t\twh /= ratio;\n\t\tbl /= ratio;\n\t}\n\n\ti = Math.floor(6 * h);\n\tv = 1 - bl;\n\tf = 6 * h - i;\n\n\tif ((i & 0x01) !== 0) {\n\t\tf = 1 - f;\n\t}\n\n\tn = wh + f * (v - wh); // linear interpolation\n\n\tvar r;\n\tvar g;\n\tvar b;\n\tswitch (i) {\n\t\tdefault:\n\t\tcase 6:\n\t\tcase 0: r = v; g = n; b = wh; break;\n\t\tcase 1: r = n; g = v; b = wh; break;\n\t\tcase 2: r = wh; g = v; b = n; break;\n\t\tcase 3: r = wh; g = n; b = v; break;\n\t\tcase 4: r = n; g = wh; b = v; break;\n\t\tcase 5: r = v; g = wh; b = n; break;\n\t}\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.cmyk.rgb = function (cmyk) {\n\tvar c = cmyk[0] / 100;\n\tvar m = cmyk[1] / 100;\n\tvar y = cmyk[2] / 100;\n\tvar k = cmyk[3] / 100;\n\tvar r;\n\tvar g;\n\tvar b;\n\n\tr = 1 - Math.min(1, c * (1 - k) + k);\n\tg = 1 - Math.min(1, m * (1 - k) + k);\n\tb = 1 - Math.min(1, y * (1 - k) + k);\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.xyz.rgb = function (xyz) {\n\tvar x = xyz[0] / 100;\n\tvar y = xyz[1] / 100;\n\tvar z = xyz[2] / 100;\n\tvar r;\n\tvar g;\n\tvar b;\n\n\tr = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);\n\tg = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);\n\tb = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);\n\n\t// assume sRGB\n\tr = r > 0.0031308\n\t\t? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)\n\t\t: r * 12.92;\n\n\tg = g > 0.0031308\n\t\t? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)\n\t\t: g * 12.92;\n\n\tb = b > 0.0031308\n\t\t? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)\n\t\t: b * 12.92;\n\n\tr = Math.min(Math.max(0, r), 1);\n\tg = Math.min(Math.max(0, g), 1);\n\tb = Math.min(Math.max(0, b), 1);\n\n\treturn [r * 255, g * 255, b * 255];\n};\n\nconvert.xyz.lab = function (xyz) {\n\tvar x = xyz[0];\n\tvar y = xyz[1];\n\tvar z = xyz[2];\n\tvar l;\n\tvar a;\n\tvar b;\n\n\tx /= 95.047;\n\ty /= 100;\n\tz /= 108.883;\n\n\tx = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);\n\ty = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);\n\tz = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);\n\n\tl = (116 * y) - 16;\n\ta = 500 * (x - y);\n\tb = 200 * (y - z);\n\n\treturn [l, a, b];\n};\n\nconvert.lab.xyz = function (lab) {\n\tvar l = lab[0];\n\tvar a = lab[1];\n\tvar b = lab[2];\n\tvar x;\n\tvar y;\n\tvar z;\n\n\ty = (l + 16) / 116;\n\tx = a / 500 + y;\n\tz = y - b / 200;\n\n\tvar y2 = Math.pow(y, 3);\n\tvar x2 = Math.pow(x, 3);\n\tvar z2 = Math.pow(z, 3);\n\ty = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;\n\tx = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;\n\tz = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;\n\n\tx *= 95.047;\n\ty *= 100;\n\tz *= 108.883;\n\n\treturn [x, y, z];\n};\n\nconvert.lab.lch = function (lab) {\n\tvar l = lab[0];\n\tvar a = lab[1];\n\tvar b = lab[2];\n\tvar hr;\n\tvar h;\n\tvar c;\n\n\thr = Math.atan2(b, a);\n\th = hr * 360 / 2 / Math.PI;\n\n\tif (h < 0) {\n\t\th += 360;\n\t}\n\n\tc = Math.sqrt(a * a + b * b);\n\n\treturn [l, c, h];\n};\n\nconvert.lch.lab = function (lch) {\n\tvar l = lch[0];\n\tvar c = lch[1];\n\tvar h = lch[2];\n\tvar a;\n\tvar b;\n\tvar hr;\n\n\thr = h / 360 * 2 * Math.PI;\n\ta = c * Math.cos(hr);\n\tb = c * Math.sin(hr);\n\n\treturn [l, a, b];\n};\n\nconvert.rgb.ansi16 = function (args) {\n\tvar r = args[0];\n\tvar g = args[1];\n\tvar b = args[2];\n\tvar value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization\n\n\tvalue = Math.round(value / 50);\n\n\tif (value === 0) {\n\t\treturn 30;\n\t}\n\n\tvar ansi = 30\n\t\t+ ((Math.round(b / 255) << 2)\n\t\t| (Math.round(g / 255) << 1)\n\t\t| Math.round(r / 255));\n\n\tif (value === 2) {\n\t\tansi += 60;\n\t}\n\n\treturn ansi;\n};\n\nconvert.hsv.ansi16 = function (args) {\n\t// optimization here; we already know the value and don't need to get\n\t// it converted for us.\n\treturn convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);\n};\n\nconvert.rgb.ansi256 = function (args) {\n\tvar r = args[0];\n\tvar g = args[1];\n\tvar b = args[2];\n\n\t// we use the extended greyscale palette here, with the exception of\n\t// black and white. normal palette only has 4 greyscale shades.\n\tif (r === g && g === b) {\n\t\tif (r < 8) {\n\t\t\treturn 16;\n\t\t}\n\n\t\tif (r > 248) {\n\t\t\treturn 231;\n\t\t}\n\n\t\treturn Math.round(((r - 8) / 247) * 24) + 232;\n\t}\n\n\tvar ansi = 16\n\t\t+ (36 * Math.round(r / 255 * 5))\n\t\t+ (6 * Math.round(g / 255 * 5))\n\t\t+ Math.round(b / 255 * 5);\n\n\treturn ansi;\n};\n\nconvert.ansi16.rgb = function (args) {\n\tvar color = args % 10;\n\n\t// handle greyscale\n\tif (color === 0 || color === 7) {\n\t\tif (args > 50) {\n\t\t\tcolor += 3.5;\n\t\t}\n\n\t\tcolor = color / 10.5 * 255;\n\n\t\treturn [color, color, color];\n\t}\n\n\tvar mult = (~~(args > 50) + 1) * 0.5;\n\tvar r = ((color & 1) * mult) * 255;\n\tvar g = (((color >> 1) & 1) * mult) * 255;\n\tvar b = (((color >> 2) & 1) * mult) * 255;\n\n\treturn [r, g, b];\n};\n\nconvert.ansi256.rgb = function (args) {\n\t// handle greyscale\n\tif (args >= 232) {\n\t\tvar c = (args - 232) * 10 + 8;\n\t\treturn [c, c, c];\n\t}\n\n\targs -= 16;\n\n\tvar rem;\n\tvar r = Math.floor(args / 36) / 5 * 255;\n\tvar g = Math.floor((rem = args % 36) / 6) / 5 * 255;\n\tvar b = (rem % 6) / 5 * 255;\n\n\treturn [r, g, b];\n};\n\nconvert.rgb.hex = function (args) {\n\tvar integer = ((Math.round(args[0]) & 0xFF) << 16)\n\t\t+ ((Math.round(args[1]) & 0xFF) << 8)\n\t\t+ (Math.round(args[2]) & 0xFF);\n\n\tvar string = integer.toString(16).toUpperCase();\n\treturn '000000'.substring(string.length) + string;\n};\n\nconvert.hex.rgb = function (args) {\n\tvar match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);\n\tif (!match) {\n\t\treturn [0, 0, 0];\n\t}\n\n\tvar colorString = match[0];\n\n\tif (match[0].length === 3) {\n\t\tcolorString = colorString.split('').map(function (char) {\n\t\t\treturn char + char;\n\t\t}).join('');\n\t}\n\n\tvar integer = parseInt(colorString, 16);\n\tvar r = (integer >> 16) & 0xFF;\n\tvar g = (integer >> 8) & 0xFF;\n\tvar b = integer & 0xFF;\n\n\treturn [r, g, b];\n};\n\nconvert.rgb.hcg = function (rgb) {\n\tvar r = rgb[0] / 255;\n\tvar g = rgb[1] / 255;\n\tvar b = rgb[2] / 255;\n\tvar max = Math.max(Math.max(r, g), b);\n\tvar min = Math.min(Math.min(r, g), b);\n\tvar chroma = (max - min);\n\tvar grayscale;\n\tvar hue;\n\n\tif (chroma < 1) {\n\t\tgrayscale = min / (1 - chroma);\n\t} else {\n\t\tgrayscale = 0;\n\t}\n\n\tif (chroma <= 0) {\n\t\thue = 0;\n\t} else\n\tif (max === r) {\n\t\thue = ((g - b) / chroma) % 6;\n\t} else\n\tif (max === g) {\n\t\thue = 2 + (b - r) / chroma;\n\t} else {\n\t\thue = 4 + (r - g) / chroma + 4;\n\t}\n\n\thue /= 6;\n\thue %= 1;\n\n\treturn [hue * 360, chroma * 100, grayscale * 100];\n};\n\nconvert.hsl.hcg = function (hsl) {\n\tvar s = hsl[1] / 100;\n\tvar l = hsl[2] / 100;\n\tvar c = 1;\n\tvar f = 0;\n\n\tif (l < 0.5) {\n\t\tc = 2.0 * s * l;\n\t} else {\n\t\tc = 2.0 * s * (1.0 - l);\n\t}\n\n\tif (c < 1.0) {\n\t\tf = (l - 0.5 * c) / (1.0 - c);\n\t}\n\n\treturn [hsl[0], c * 100, f * 100];\n};\n\nconvert.hsv.hcg = function (hsv) {\n\tvar s = hsv[1] / 100;\n\tvar v = hsv[2] / 100;\n\n\tvar c = s * v;\n\tvar f = 0;\n\n\tif (c < 1.0) {\n\t\tf = (v - c) / (1 - c);\n\t}\n\n\treturn [hsv[0], c * 100, f * 100];\n};\n\nconvert.hcg.rgb = function (hcg) {\n\tvar h = hcg[0] / 360;\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\n\tif (c === 0.0) {\n\t\treturn [g * 255, g * 255, g * 255];\n\t}\n\n\tvar pure = [0, 0, 0];\n\tvar hi = (h % 1) * 6;\n\tvar v = hi % 1;\n\tvar w = 1 - v;\n\tvar mg = 0;\n\n\tswitch (Math.floor(hi)) {\n\t\tcase 0:\n\t\t\tpure[0] = 1; pure[1] = v; pure[2] = 0; break;\n\t\tcase 1:\n\t\t\tpure[0] = w; pure[1] = 1; pure[2] = 0; break;\n\t\tcase 2:\n\t\t\tpure[0] = 0; pure[1] = 1; pure[2] = v; break;\n\t\tcase 3:\n\t\t\tpure[0] = 0; pure[1] = w; pure[2] = 1; break;\n\t\tcase 4:\n\t\t\tpure[0] = v; pure[1] = 0; pure[2] = 1; break;\n\t\tdefault:\n\t\t\tpure[0] = 1; pure[1] = 0; pure[2] = w;\n\t}\n\n\tmg = (1.0 - c) * g;\n\n\treturn [\n\t\t(c * pure[0] + mg) * 255,\n\t\t(c * pure[1] + mg) * 255,\n\t\t(c * pure[2] + mg) * 255\n\t];\n};\n\nconvert.hcg.hsv = function (hcg) {\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\n\tvar v = c + g * (1.0 - c);\n\tvar f = 0;\n\n\tif (v > 0.0) {\n\t\tf = c / v;\n\t}\n\n\treturn [hcg[0], f * 100, v * 100];\n};\n\nconvert.hcg.hsl = function (hcg) {\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\n\tvar l = g * (1.0 - c) + 0.5 * c;\n\tvar s = 0;\n\n\tif (l > 0.0 && l < 0.5) {\n\t\ts = c / (2 * l);\n\t} else\n\tif (l >= 0.5 && l < 1.0) {\n\t\ts = c / (2 * (1 - l));\n\t}\n\n\treturn [hcg[0], s * 100, l * 100];\n};\n\nconvert.hcg.hwb = function (hcg) {\n\tvar c = hcg[1] / 100;\n\tvar g = hcg[2] / 100;\n\tvar v = c + g * (1.0 - c);\n\treturn [hcg[0], (v - c) * 100, (1 - v) * 100];\n};\n\nconvert.hwb.hcg = function (hwb) {\n\tvar w = hwb[1] / 100;\n\tvar b = hwb[2] / 100;\n\tvar v = 1 - b;\n\tvar c = v - w;\n\tvar g = 0;\n\n\tif (c < 1) {\n\t\tg = (v - c) / (1 - c);\n\t}\n\n\treturn [hwb[0], c * 100, g * 100];\n};\n\nconvert.apple.rgb = function (apple) {\n\treturn [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];\n};\n\nconvert.rgb.apple = function (rgb) {\n\treturn [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];\n};\n\nconvert.gray.rgb = function (args) {\n\treturn [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];\n};\n\nconvert.gray.hsl = convert.gray.hsv = function (args) {\n\treturn [0, 0, args[0]];\n};\n\nconvert.gray.hwb = function (gray) {\n\treturn [0, 100, gray[0]];\n};\n\nconvert.gray.cmyk = function (gray) {\n\treturn [0, 0, 0, gray[0]];\n};\n\nconvert.gray.lab = function (gray) {\n\treturn [gray[0], 0, 0];\n};\n\nconvert.gray.hex = function (gray) {\n\tvar val = Math.round(gray[0] / 100 * 255) & 0xFF;\n\tvar integer = (val << 16) + (val << 8) + val;\n\n\tvar string = integer.toString(16).toUpperCase();\n\treturn '000000'.substring(string.length) + string;\n};\n\nconvert.rgb.gray = function (rgb) {\n\tvar val = (rgb[0] + rgb[1] + rgb[2]) / 3;\n\treturn [val / 255 * 100];\n};\n","var conversions = require('./conversions');\nvar route = require('./route');\n\nvar convert = {};\n\nvar models = Object.keys(conversions);\n\nfunction wrapRaw(fn) {\n\tvar wrappedFn = function (args) {\n\t\tif (args === undefined || args === null) {\n\t\t\treturn args;\n\t\t}\n\n\t\tif (arguments.length > 1) {\n\t\t\targs = Array.prototype.slice.call(arguments);\n\t\t}\n\n\t\treturn fn(args);\n\t};\n\n\t// preserve .conversion property if there is one\n\tif ('conversion' in fn) {\n\t\twrappedFn.conversion = fn.conversion;\n\t}\n\n\treturn wrappedFn;\n}\n\nfunction wrapRounded(fn) {\n\tvar wrappedFn = function (args) {\n\t\tif (args === undefined || args === null) {\n\t\t\treturn args;\n\t\t}\n\n\t\tif (arguments.length > 1) {\n\t\t\targs = Array.prototype.slice.call(arguments);\n\t\t}\n\n\t\tvar result = fn(args);\n\n\t\t// we're assuming the result is an array here.\n\t\t// see notice in conversions.js; don't use box types\n\t\t// in conversion functions.\n\t\tif (typeof result === 'object') {\n\t\t\tfor (var len = result.length, i = 0; i < len; i++) {\n\t\t\t\tresult[i] = Math.round(result[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t};\n\n\t// preserve .conversion property if there is one\n\tif ('conversion' in fn) {\n\t\twrappedFn.conversion = fn.conversion;\n\t}\n\n\treturn wrappedFn;\n}\n\nmodels.forEach(function (fromModel) {\n\tconvert[fromModel] = {};\n\n\tObject.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});\n\tObject.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});\n\n\tvar routes = route(fromModel);\n\tvar routeModels = Object.keys(routes);\n\n\trouteModels.forEach(function (toModel) {\n\t\tvar fn = routes[toModel];\n\n\t\tconvert[fromModel][toModel] = wrapRounded(fn);\n\t\tconvert[fromModel][toModel].raw = wrapRaw(fn);\n\t});\n});\n\nmodule.exports = convert;\n","var conversions = require('./conversions');\n\n/*\n\tthis function routes a model to all other models.\n\n\tall functions that are routed have a property `.conversion` attached\n\tto the returned synthetic function. This property is an array\n\tof strings, each with the steps in between the 'from' and 'to'\n\tcolor models (inclusive).\n\n\tconversions that are not possible simply are not included.\n*/\n\nfunction buildGraph() {\n\tvar graph = {};\n\t// https://jsperf.com/object-keys-vs-for-in-with-closure/3\n\tvar models = Object.keys(conversions);\n\n\tfor (var len = models.length, i = 0; i < len; i++) {\n\t\tgraph[models[i]] = {\n\t\t\t// http://jsperf.com/1-vs-infinity\n\t\t\t// micro-opt, but this is simple.\n\t\t\tdistance: -1,\n\t\t\tparent: null\n\t\t};\n\t}\n\n\treturn graph;\n}\n\n// https://en.wikipedia.org/wiki/Breadth-first_search\nfunction deriveBFS(fromModel) {\n\tvar graph = buildGraph();\n\tvar queue = [fromModel]; // unshift -> queue -> pop\n\n\tgraph[fromModel].distance = 0;\n\n\twhile (queue.length) {\n\t\tvar current = queue.pop();\n\t\tvar adjacents = Object.keys(conversions[current]);\n\n\t\tfor (var len = adjacents.length, i = 0; i < len; i++) {\n\t\t\tvar adjacent = adjacents[i];\n\t\t\tvar node = graph[adjacent];\n\n\t\t\tif (node.distance === -1) {\n\t\t\t\tnode.distance = graph[current].distance + 1;\n\t\t\t\tnode.parent = current;\n\t\t\t\tqueue.unshift(adjacent);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn graph;\n}\n\nfunction link(from, to) {\n\treturn function (args) {\n\t\treturn to(from(args));\n\t};\n}\n\nfunction wrapConversion(toModel, graph) {\n\tvar path = [graph[toModel].parent, toModel];\n\tvar fn = conversions[graph[toModel].parent][toModel];\n\n\tvar cur = graph[toModel].parent;\n\twhile (graph[cur].parent) {\n\t\tpath.unshift(graph[cur].parent);\n\t\tfn = link(conversions[graph[cur].parent][cur], fn);\n\t\tcur = graph[cur].parent;\n\t}\n\n\tfn.conversion = path;\n\treturn fn;\n}\n\nmodule.exports = function (fromModel) {\n\tvar graph = deriveBFS(fromModel);\n\tvar conversion = {};\n\n\tvar models = Object.keys(graph);\n\tfor (var len = models.length, i = 0; i < len; i++) {\n\t\tvar toModel = models[i];\n\t\tvar node = graph[toModel];\n\n\t\tif (node.parent === null) {\n\t\t\t// no possible conversion, or this node is the source model.\n\t\t\tcontinue;\n\t\t}\n\n\t\tconversion[toModel] = wrapConversion(toModel, graph);\n\t}\n\n\treturn conversion;\n};\n\n","'use strict'\r\n\r\nmodule.exports = {\r\n\t\"aliceblue\": [240, 248, 255],\r\n\t\"antiquewhite\": [250, 235, 215],\r\n\t\"aqua\": [0, 255, 255],\r\n\t\"aquamarine\": [127, 255, 212],\r\n\t\"azure\": [240, 255, 255],\r\n\t\"beige\": [245, 245, 220],\r\n\t\"bisque\": [255, 228, 196],\r\n\t\"black\": [0, 0, 0],\r\n\t\"blanchedalmond\": [255, 235, 205],\r\n\t\"blue\": [0, 0, 255],\r\n\t\"blueviolet\": [138, 43, 226],\r\n\t\"brown\": [165, 42, 42],\r\n\t\"burlywood\": [222, 184, 135],\r\n\t\"cadetblue\": [95, 158, 160],\r\n\t\"chartreuse\": [127, 255, 0],\r\n\t\"chocolate\": [210, 105, 30],\r\n\t\"coral\": [255, 127, 80],\r\n\t\"cornflowerblue\": [100, 149, 237],\r\n\t\"cornsilk\": [255, 248, 220],\r\n\t\"crimson\": [220, 20, 60],\r\n\t\"cyan\": [0, 255, 255],\r\n\t\"darkblue\": [0, 0, 139],\r\n\t\"darkcyan\": [0, 139, 139],\r\n\t\"darkgoldenrod\": [184, 134, 11],\r\n\t\"darkgray\": [169, 169, 169],\r\n\t\"darkgreen\": [0, 100, 0],\r\n\t\"darkgrey\": [169, 169, 169],\r\n\t\"darkkhaki\": [189, 183, 107],\r\n\t\"darkmagenta\": [139, 0, 139],\r\n\t\"darkolivegreen\": [85, 107, 47],\r\n\t\"darkorange\": [255, 140, 0],\r\n\t\"darkorchid\": [153, 50, 204],\r\n\t\"darkred\": [139, 0, 0],\r\n\t\"darksalmon\": [233, 150, 122],\r\n\t\"darkseagreen\": [143, 188, 143],\r\n\t\"darkslateblue\": [72, 61, 139],\r\n\t\"darkslategray\": [47, 79, 79],\r\n\t\"darkslategrey\": [47, 79, 79],\r\n\t\"darkturquoise\": [0, 206, 209],\r\n\t\"darkviolet\": [148, 0, 211],\r\n\t\"deeppink\": [255, 20, 147],\r\n\t\"deepskyblue\": [0, 191, 255],\r\n\t\"dimgray\": [105, 105, 105],\r\n\t\"dimgrey\": [105, 105, 105],\r\n\t\"dodgerblue\": [30, 144, 255],\r\n\t\"firebrick\": [178, 34, 34],\r\n\t\"floralwhite\": [255, 250, 240],\r\n\t\"forestgreen\": [34, 139, 34],\r\n\t\"fuchsia\": [255, 0, 255],\r\n\t\"gainsboro\": [220, 220, 220],\r\n\t\"ghostwhite\": [248, 248, 255],\r\n\t\"gold\": [255, 215, 0],\r\n\t\"goldenrod\": [218, 165, 32],\r\n\t\"gray\": [128, 128, 128],\r\n\t\"green\": [0, 128, 0],\r\n\t\"greenyellow\": [173, 255, 47],\r\n\t\"grey\": [128, 128, 128],\r\n\t\"honeydew\": [240, 255, 240],\r\n\t\"hotpink\": [255, 105, 180],\r\n\t\"indianred\": [205, 92, 92],\r\n\t\"indigo\": [75, 0, 130],\r\n\t\"ivory\": [255, 255, 240],\r\n\t\"khaki\": [240, 230, 140],\r\n\t\"lavender\": [230, 230, 250],\r\n\t\"lavenderblush\": [255, 240, 245],\r\n\t\"lawngreen\": [124, 252, 0],\r\n\t\"lemonchiffon\": [255, 250, 205],\r\n\t\"lightblue\": [173, 216, 230],\r\n\t\"lightcoral\": [240, 128, 128],\r\n\t\"lightcyan\": [224, 255, 255],\r\n\t\"lightgoldenrodyellow\": [250, 250, 210],\r\n\t\"lightgray\": [211, 211, 211],\r\n\t\"lightgreen\": [144, 238, 144],\r\n\t\"lightgrey\": [211, 211, 211],\r\n\t\"lightpink\": [255, 182, 193],\r\n\t\"lightsalmon\": [255, 160, 122],\r\n\t\"lightseagreen\": [32, 178, 170],\r\n\t\"lightskyblue\": [135, 206, 250],\r\n\t\"lightslategray\": [119, 136, 153],\r\n\t\"lightslategrey\": [119, 136, 153],\r\n\t\"lightsteelblue\": [176, 196, 222],\r\n\t\"lightyellow\": [255, 255, 224],\r\n\t\"lime\": [0, 255, 0],\r\n\t\"limegreen\": [50, 205, 50],\r\n\t\"linen\": [250, 240, 230],\r\n\t\"magenta\": [255, 0, 255],\r\n\t\"maroon\": [128, 0, 0],\r\n\t\"mediumaquamarine\": [102, 205, 170],\r\n\t\"mediumblue\": [0, 0, 205],\r\n\t\"mediumorchid\": [186, 85, 211],\r\n\t\"mediumpurple\": [147, 112, 219],\r\n\t\"mediumseagreen\": [60, 179, 113],\r\n\t\"mediumslateblue\": [123, 104, 238],\r\n\t\"mediumspringgreen\": [0, 250, 154],\r\n\t\"mediumturquoise\": [72, 209, 204],\r\n\t\"mediumvioletred\": [199, 21, 133],\r\n\t\"midnightblue\": [25, 25, 112],\r\n\t\"mintcream\": [245, 255, 250],\r\n\t\"mistyrose\": [255, 228, 225],\r\n\t\"moccasin\": [255, 228, 181],\r\n\t\"navajowhite\": [255, 222, 173],\r\n\t\"navy\": [0, 0, 128],\r\n\t\"oldlace\": [253, 245, 230],\r\n\t\"olive\": [128, 128, 0],\r\n\t\"olivedrab\": [107, 142, 35],\r\n\t\"orange\": [255, 165, 0],\r\n\t\"orangered\": [255, 69, 0],\r\n\t\"orchid\": [218, 112, 214],\r\n\t\"palegoldenrod\": [238, 232, 170],\r\n\t\"palegreen\": [152, 251, 152],\r\n\t\"paleturquoise\": [175, 238, 238],\r\n\t\"palevioletred\": [219, 112, 147],\r\n\t\"papayawhip\": [255, 239, 213],\r\n\t\"peachpuff\": [255, 218, 185],\r\n\t\"peru\": [205, 133, 63],\r\n\t\"pink\": [255, 192, 203],\r\n\t\"plum\": [221, 160, 221],\r\n\t\"powderblue\": [176, 224, 230],\r\n\t\"purple\": [128, 0, 128],\r\n\t\"rebeccapurple\": [102, 51, 153],\r\n\t\"red\": [255, 0, 0],\r\n\t\"rosybrown\": [188, 143, 143],\r\n\t\"royalblue\": [65, 105, 225],\r\n\t\"saddlebrown\": [139, 69, 19],\r\n\t\"salmon\": [250, 128, 114],\r\n\t\"sandybrown\": [244, 164, 96],\r\n\t\"seagreen\": [46, 139, 87],\r\n\t\"seashell\": [255, 245, 238],\r\n\t\"sienna\": [160, 82, 45],\r\n\t\"silver\": [192, 192, 192],\r\n\t\"skyblue\": [135, 206, 235],\r\n\t\"slateblue\": [106, 90, 205],\r\n\t\"slategray\": [112, 128, 144],\r\n\t\"slategrey\": [112, 128, 144],\r\n\t\"snow\": [255, 250, 250],\r\n\t\"springgreen\": [0, 255, 127],\r\n\t\"steelblue\": [70, 130, 180],\r\n\t\"tan\": [210, 180, 140],\r\n\t\"teal\": [0, 128, 128],\r\n\t\"thistle\": [216, 191, 216],\r\n\t\"tomato\": [255, 99, 71],\r\n\t\"turquoise\": [64, 224, 208],\r\n\t\"violet\": [238, 130, 238],\r\n\t\"wheat\": [245, 222, 179],\r\n\t\"white\": [255, 255, 255],\r\n\t\"whitesmoke\": [245, 245, 245],\r\n\t\"yellow\": [255, 255, 0],\r\n\t\"yellowgreen\": [154, 205, 50]\r\n};\r\n","/* MIT license */\nvar colorNames = require('color-name');\nvar swizzle = require('simple-swizzle');\nvar hasOwnProperty = Object.hasOwnProperty;\n\nvar reverseNames = Object.create(null);\n\n// create a list of reverse color names\nfor (var name in colorNames) {\n\tif (hasOwnProperty.call(colorNames, name)) {\n\t\treverseNames[colorNames[name]] = name;\n\t}\n}\n\nvar cs = module.exports = {\n\tto: {},\n\tget: {}\n};\n\ncs.get = function (string) {\n\tvar prefix = string.substring(0, 3).toLowerCase();\n\tvar val;\n\tvar model;\n\tswitch (prefix) {\n\t\tcase 'hsl':\n\t\t\tval = cs.get.hsl(string);\n\t\t\tmodel = 'hsl';\n\t\t\tbreak;\n\t\tcase 'hwb':\n\t\t\tval = cs.get.hwb(string);\n\t\t\tmodel = 'hwb';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tval = cs.get.rgb(string);\n\t\t\tmodel = 'rgb';\n\t\t\tbreak;\n\t}\n\n\tif (!val) {\n\t\treturn null;\n\t}\n\n\treturn {model: model, value: val};\n};\n\ncs.get.rgb = function (string) {\n\tif (!string) {\n\t\treturn null;\n\t}\n\n\tvar abbr = /^#([a-f0-9]{3,4})$/i;\n\tvar hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i;\n\tvar rgba = /^rgba?\\(\\s*([+-]?\\d+)(?=[\\s,])\\s*(?:,\\s*)?([+-]?\\d+)(?=[\\s,])\\s*(?:,\\s*)?([+-]?\\d+)\\s*(?:[,|\\/]\\s*([+-]?[\\d\\.]+)(%?)\\s*)?\\)$/;\n\tvar per = /^rgba?\\(\\s*([+-]?[\\d\\.]+)\\%\\s*,?\\s*([+-]?[\\d\\.]+)\\%\\s*,?\\s*([+-]?[\\d\\.]+)\\%\\s*(?:[,|\\/]\\s*([+-]?[\\d\\.]+)(%?)\\s*)?\\)$/;\n\tvar keyword = /^(\\w+)$/;\n\n\tvar rgb = [0, 0, 0, 1];\n\tvar match;\n\tvar i;\n\tvar hexAlpha;\n\n\tif (match = string.match(hex)) {\n\t\thexAlpha = match[2];\n\t\tmatch = match[1];\n\n\t\tfor (i = 0; i < 3; i++) {\n\t\t\t// https://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/19\n\t\t\tvar i2 = i * 2;\n\t\t\trgb[i] = parseInt(match.slice(i2, i2 + 2), 16);\n\t\t}\n\n\t\tif (hexAlpha) {\n\t\t\trgb[3] = parseInt(hexAlpha, 16) / 255;\n\t\t}\n\t} else if (match = string.match(abbr)) {\n\t\tmatch = match[1];\n\t\thexAlpha = match[3];\n\n\t\tfor (i = 0; i < 3; i++) {\n\t\t\trgb[i] = parseInt(match[i] + match[i], 16);\n\t\t}\n\n\t\tif (hexAlpha) {\n\t\t\trgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255;\n\t\t}\n\t} else if (match = string.match(rgba)) {\n\t\tfor (i = 0; i < 3; i++) {\n\t\t\trgb[i] = parseInt(match[i + 1], 0);\n\t\t}\n\n\t\tif (match[4]) {\n\t\t\tif (match[5]) {\n\t\t\t\trgb[3] = parseFloat(match[4]) * 0.01;\n\t\t\t} else {\n\t\t\t\trgb[3] = parseFloat(match[4]);\n\t\t\t}\n\t\t}\n\t} else if (match = string.match(per)) {\n\t\tfor (i = 0; i < 3; i++) {\n\t\t\trgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);\n\t\t}\n\n\t\tif (match[4]) {\n\t\t\tif (match[5]) {\n\t\t\t\trgb[3] = parseFloat(match[4]) * 0.01;\n\t\t\t} else {\n\t\t\t\trgb[3] = parseFloat(match[4]);\n\t\t\t}\n\t\t}\n\t} else if (match = string.match(keyword)) {\n\t\tif (match[1] === 'transparent') {\n\t\t\treturn [0, 0, 0, 0];\n\t\t}\n\n\t\tif (!hasOwnProperty.call(colorNames, match[1])) {\n\t\t\treturn null;\n\t\t}\n\n\t\trgb = colorNames[match[1]];\n\t\trgb[3] = 1;\n\n\t\treturn rgb;\n\t} else {\n\t\treturn null;\n\t}\n\n\tfor (i = 0; i < 3; i++) {\n\t\trgb[i] = clamp(rgb[i], 0, 255);\n\t}\n\trgb[3] = clamp(rgb[3], 0, 1);\n\n\treturn rgb;\n};\n\ncs.get.hsl = function (string) {\n\tif (!string) {\n\t\treturn null;\n\t}\n\n\tvar hsl = /^hsla?\\(\\s*([+-]?(?:\\d{0,3}\\.)?\\d+)(?:deg)?\\s*,?\\s*([+-]?[\\d\\.]+)%\\s*,?\\s*([+-]?[\\d\\.]+)%\\s*(?:[,|\\/]\\s*([+-]?(?=\\.\\d|\\d)(?:0|[1-9]\\d*)?(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)\\s*)?\\)$/;\n\tvar match = string.match(hsl);\n\n\tif (match) {\n\t\tvar alpha = parseFloat(match[4]);\n\t\tvar h = ((parseFloat(match[1]) % 360) + 360) % 360;\n\t\tvar s = clamp(parseFloat(match[2]), 0, 100);\n\t\tvar l = clamp(parseFloat(match[3]), 0, 100);\n\t\tvar a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1);\n\n\t\treturn [h, s, l, a];\n\t}\n\n\treturn null;\n};\n\ncs.get.hwb = function (string) {\n\tif (!string) {\n\t\treturn null;\n\t}\n\n\tvar hwb = /^hwb\\(\\s*([+-]?\\d{0,3}(?:\\.\\d+)?)(?:deg)?\\s*,\\s*([+-]?[\\d\\.]+)%\\s*,\\s*([+-]?[\\d\\.]+)%\\s*(?:,\\s*([+-]?(?=\\.\\d|\\d)(?:0|[1-9]\\d*)?(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)\\s*)?\\)$/;\n\tvar match = string.match(hwb);\n\n\tif (match) {\n\t\tvar alpha = parseFloat(match[4]);\n\t\tvar h = ((parseFloat(match[1]) % 360) + 360) % 360;\n\t\tvar w = clamp(parseFloat(match[2]), 0, 100);\n\t\tvar b = clamp(parseFloat(match[3]), 0, 100);\n\t\tvar a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1);\n\t\treturn [h, w, b, a];\n\t}\n\n\treturn null;\n};\n\ncs.to.hex = function () {\n\tvar rgba = swizzle(arguments);\n\n\treturn (\n\t\t'#' +\n\t\thexDouble(rgba[0]) +\n\t\thexDouble(rgba[1]) +\n\t\thexDouble(rgba[2]) +\n\t\t(rgba[3] < 1\n\t\t\t? (hexDouble(Math.round(rgba[3] * 255)))\n\t\t\t: '')\n\t);\n};\n\ncs.to.rgb = function () {\n\tvar rgba = swizzle(arguments);\n\n\treturn rgba.length < 4 || rgba[3] === 1\n\t\t? 'rgb(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ')'\n\t\t: 'rgba(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ', ' + rgba[3] + ')';\n};\n\ncs.to.rgb.percent = function () {\n\tvar rgba = swizzle(arguments);\n\n\tvar r = Math.round(rgba[0] / 255 * 100);\n\tvar g = Math.round(rgba[1] / 255 * 100);\n\tvar b = Math.round(rgba[2] / 255 * 100);\n\n\treturn rgba.length < 4 || rgba[3] === 1\n\t\t? 'rgb(' + r + '%, ' + g + '%, ' + b + '%)'\n\t\t: 'rgba(' + r + '%, ' + g + '%, ' + b + '%, ' + rgba[3] + ')';\n};\n\ncs.to.hsl = function () {\n\tvar hsla = swizzle(arguments);\n\treturn hsla.length < 4 || hsla[3] === 1\n\t\t? 'hsl(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%)'\n\t\t: 'hsla(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%, ' + hsla[3] + ')';\n};\n\n// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax\n// (hwb have alpha optional & 1 is default value)\ncs.to.hwb = function () {\n\tvar hwba = swizzle(arguments);\n\n\tvar a = '';\n\tif (hwba.length >= 4 && hwba[3] !== 1) {\n\t\ta = ', ' + hwba[3];\n\t}\n\n\treturn 'hwb(' + hwba[0] + ', ' + hwba[1] + '%, ' + hwba[2] + '%' + a + ')';\n};\n\ncs.to.keyword = function (rgb) {\n\treturn reverseNames[rgb.slice(0, 3)];\n};\n\n// helpers\nfunction clamp(num, min, max) {\n\treturn Math.min(Math.max(min, num), max);\n}\n\nfunction hexDouble(num) {\n\tvar str = Math.round(num).toString(16).toUpperCase();\n\treturn (str.length < 2) ? '0' + str : str;\n}\n","'use strict';\n\nvar colorString = require('color-string');\nvar convert = require('color-convert');\n\nvar _slice = [].slice;\n\nvar skippedModels = [\n\t// to be honest, I don't really feel like keyword belongs in color convert, but eh.\n\t'keyword',\n\n\t// gray conflicts with some method names, and has its own method defined.\n\t'gray',\n\n\t// shouldn't really be in color-convert either...\n\t'hex'\n];\n\nvar hashedModelKeys = {};\nObject.keys(convert).forEach(function (model) {\n\thashedModelKeys[_slice.call(convert[model].labels).sort().join('')] = model;\n});\n\nvar limiters = {};\n\nfunction Color(obj, model) {\n\tif (!(this instanceof Color)) {\n\t\treturn new Color(obj, model);\n\t}\n\n\tif (model && model in skippedModels) {\n\t\tmodel = null;\n\t}\n\n\tif (model && !(model in convert)) {\n\t\tthrow new Error('Unknown model: ' + model);\n\t}\n\n\tvar i;\n\tvar channels;\n\n\tif (obj == null) { // eslint-disable-line no-eq-null,eqeqeq\n\t\tthis.model = 'rgb';\n\t\tthis.color = [0, 0, 0];\n\t\tthis.valpha = 1;\n\t} else if (obj instanceof Color) {\n\t\tthis.model = obj.model;\n\t\tthis.color = obj.color.slice();\n\t\tthis.valpha = obj.valpha;\n\t} else if (typeof obj === 'string') {\n\t\tvar result = colorString.get(obj);\n\t\tif (result === null) {\n\t\t\tthrow new Error('Unable to parse color from string: ' + obj);\n\t\t}\n\n\t\tthis.model = result.model;\n\t\tchannels = convert[this.model].channels;\n\t\tthis.color = result.value.slice(0, channels);\n\t\tthis.valpha = typeof result.value[channels] === 'number' ? result.value[channels] : 1;\n\t} else if (obj.length) {\n\t\tthis.model = model || 'rgb';\n\t\tchannels = convert[this.model].channels;\n\t\tvar newArr = _slice.call(obj, 0, channels);\n\t\tthis.color = zeroArray(newArr, channels);\n\t\tthis.valpha = typeof obj[channels] === 'number' ? obj[channels] : 1;\n\t} else if (typeof obj === 'number') {\n\t\t// this is always RGB - can be converted later on.\n\t\tobj &= 0xFFFFFF;\n\t\tthis.model = 'rgb';\n\t\tthis.color = [\n\t\t\t(obj >> 16) & 0xFF,\n\t\t\t(obj >> 8) & 0xFF,\n\t\t\tobj & 0xFF\n\t\t];\n\t\tthis.valpha = 1;\n\t} else {\n\t\tthis.valpha = 1;\n\n\t\tvar keys = Object.keys(obj);\n\t\tif ('alpha' in obj) {\n\t\t\tkeys.splice(keys.indexOf('alpha'), 1);\n\t\t\tthis.valpha = typeof obj.alpha === 'number' ? obj.alpha : 0;\n\t\t}\n\n\t\tvar hashedKeys = keys.sort().join('');\n\t\tif (!(hashedKeys in hashedModelKeys)) {\n\t\t\tthrow new Error('Unable to parse color from object: ' + JSON.stringify(obj));\n\t\t}\n\n\t\tthis.model = hashedModelKeys[hashedKeys];\n\n\t\tvar labels = convert[this.model].labels;\n\t\tvar color = [];\n\t\tfor (i = 0; i < labels.length; i++) {\n\t\t\tcolor.push(obj[labels[i]]);\n\t\t}\n\n\t\tthis.color = zeroArray(color);\n\t}\n\n\t// perform limitations (clamping, etc.)\n\tif (limiters[this.model]) {\n\t\tchannels = convert[this.model].channels;\n\t\tfor (i = 0; i < channels; i++) {\n\t\t\tvar limit = limiters[this.model][i];\n\t\t\tif (limit) {\n\t\t\t\tthis.color[i] = limit(this.color[i]);\n\t\t\t}\n\t\t}\n\t}\n\n\tthis.valpha = Math.max(0, Math.min(1, this.valpha));\n\n\tif (Object.freeze) {\n\t\tObject.freeze(this);\n\t}\n}\n\nColor.prototype = {\n\ttoString: function () {\n\t\treturn this.string();\n\t},\n\n\ttoJSON: function () {\n\t\treturn this[this.model]();\n\t},\n\n\tstring: function (places) {\n\t\tvar self = this.model in colorString.to ? this : this.rgb();\n\t\tself = self.round(typeof places === 'number' ? places : 1);\n\t\tvar args = self.valpha === 1 ? self.color : self.color.concat(this.valpha);\n\t\treturn colorString.to[self.model](args);\n\t},\n\n\tpercentString: function (places) {\n\t\tvar self = this.rgb().round(typeof places === 'number' ? places : 1);\n\t\tvar args = self.valpha === 1 ? self.color : self.color.concat(this.valpha);\n\t\treturn colorString.to.rgb.percent(args);\n\t},\n\n\tarray: function () {\n\t\treturn this.valpha === 1 ? this.color.slice() : this.color.concat(this.valpha);\n\t},\n\n\tobject: function () {\n\t\tvar result = {};\n\t\tvar channels = convert[this.model].channels;\n\t\tvar labels = convert[this.model].labels;\n\n\t\tfor (var i = 0; i < channels; i++) {\n\t\t\tresult[labels[i]] = this.color[i];\n\t\t}\n\n\t\tif (this.valpha !== 1) {\n\t\t\tresult.alpha = this.valpha;\n\t\t}\n\n\t\treturn result;\n\t},\n\n\tunitArray: function () {\n\t\tvar rgb = this.rgb().color;\n\t\trgb[0] /= 255;\n\t\trgb[1] /= 255;\n\t\trgb[2] /= 255;\n\n\t\tif (this.valpha !== 1) {\n\t\t\trgb.push(this.valpha);\n\t\t}\n\n\t\treturn rgb;\n\t},\n\n\tunitObject: function () {\n\t\tvar rgb = this.rgb().object();\n\t\trgb.r /= 255;\n\t\trgb.g /= 255;\n\t\trgb.b /= 255;\n\n\t\tif (this.valpha !== 1) {\n\t\t\trgb.alpha = this.valpha;\n\t\t}\n\n\t\treturn rgb;\n\t},\n\n\tround: function (places) {\n\t\tplaces = Math.max(places || 0, 0);\n\t\treturn new Color(this.color.map(roundToPlace(places)).concat(this.valpha), this.model);\n\t},\n\n\talpha: function (val) {\n\t\tif (arguments.length) {\n\t\t\treturn new Color(this.color.concat(Math.max(0, Math.min(1, val))), this.model);\n\t\t}\n\n\t\treturn this.valpha;\n\t},\n\n\t// rgb\n\tred: getset('rgb', 0, maxfn(255)),\n\tgreen: getset('rgb', 1, maxfn(255)),\n\tblue: getset('rgb', 2, maxfn(255)),\n\n\thue: getset(['hsl', 'hsv', 'hsl', 'hwb', 'hcg'], 0, function (val) { return ((val % 360) + 360) % 360; }), // eslint-disable-line brace-style\n\n\tsaturationl: getset('hsl', 1, maxfn(100)),\n\tlightness: getset('hsl', 2, maxfn(100)),\n\n\tsaturationv: getset('hsv', 1, maxfn(100)),\n\tvalue: getset('hsv', 2, maxfn(100)),\n\n\tchroma: getset('hcg', 1, maxfn(100)),\n\tgray: getset('hcg', 2, maxfn(100)),\n\n\twhite: getset('hwb', 1, maxfn(100)),\n\twblack: getset('hwb', 2, maxfn(100)),\n\n\tcyan: getset('cmyk', 0, maxfn(100)),\n\tmagenta: getset('cmyk', 1, maxfn(100)),\n\tyellow: getset('cmyk', 2, maxfn(100)),\n\tblack: getset('cmyk', 3, maxfn(100)),\n\n\tx: getset('xyz', 0, maxfn(100)),\n\ty: getset('xyz', 1, maxfn(100)),\n\tz: getset('xyz', 2, maxfn(100)),\n\n\tl: getset('lab', 0, maxfn(100)),\n\ta: getset('lab', 1),\n\tb: getset('lab', 2),\n\n\tkeyword: function (val) {\n\t\tif (arguments.length) {\n\t\t\treturn new Color(val);\n\t\t}\n\n\t\treturn convert[this.model].keyword(this.color);\n\t},\n\n\thex: function (val) {\n\t\tif (arguments.length) {\n\t\t\treturn new Color(val);\n\t\t}\n\n\t\treturn colorString.to.hex(this.rgb().round().color);\n\t},\n\n\trgbNumber: function () {\n\t\tvar rgb = this.rgb().color;\n\t\treturn ((rgb[0] & 0xFF) << 16) | ((rgb[1] & 0xFF) << 8) | (rgb[2] & 0xFF);\n\t},\n\n\tluminosity: function () {\n\t\t// http://www.w3.org/TR/WCAG20/#relativeluminancedef\n\t\tvar rgb = this.rgb().color;\n\n\t\tvar lum = [];\n\t\tfor (var i = 0; i < rgb.length; i++) {\n\t\t\tvar chan = rgb[i] / 255;\n\t\t\tlum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);\n\t\t}\n\n\t\treturn 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];\n\t},\n\n\tcontrast: function (color2) {\n\t\t// http://www.w3.org/TR/WCAG20/#contrast-ratiodef\n\t\tvar lum1 = this.luminosity();\n\t\tvar lum2 = color2.luminosity();\n\n\t\tif (lum1 > lum2) {\n\t\t\treturn (lum1 + 0.05) / (lum2 + 0.05);\n\t\t}\n\n\t\treturn (lum2 + 0.05) / (lum1 + 0.05);\n\t},\n\n\tlevel: function (color2) {\n\t\tvar contrastRatio = this.contrast(color2);\n\t\tif (contrastRatio >= 7.1) {\n\t\t\treturn 'AAA';\n\t\t}\n\n\t\treturn (contrastRatio >= 4.5) ? 'AA' : '';\n\t},\n\n\tisDark: function () {\n\t\t// YIQ equation from http://24ways.org/2010/calculating-color-contrast\n\t\tvar rgb = this.rgb().color;\n\t\tvar yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;\n\t\treturn yiq < 128;\n\t},\n\n\tisLight: function () {\n\t\treturn !this.isDark();\n\t},\n\n\tnegate: function () {\n\t\tvar rgb = this.rgb();\n\t\tfor (var i = 0; i < 3; i++) {\n\t\t\trgb.color[i] = 255 - rgb.color[i];\n\t\t}\n\t\treturn rgb;\n\t},\n\n\tlighten: function (ratio) {\n\t\tvar hsl = this.hsl();\n\t\thsl.color[2] += hsl.color[2] * ratio;\n\t\treturn hsl;\n\t},\n\n\tdarken: function (ratio) {\n\t\tvar hsl = this.hsl();\n\t\thsl.color[2] -= hsl.color[2] * ratio;\n\t\treturn hsl;\n\t},\n\n\tsaturate: function (ratio) {\n\t\tvar hsl = this.hsl();\n\t\thsl.color[1] += hsl.color[1] * ratio;\n\t\treturn hsl;\n\t},\n\n\tdesaturate: function (ratio) {\n\t\tvar hsl = this.hsl();\n\t\thsl.color[1] -= hsl.color[1] * ratio;\n\t\treturn hsl;\n\t},\n\n\twhiten: function (ratio) {\n\t\tvar hwb = this.hwb();\n\t\thwb.color[1] += hwb.color[1] * ratio;\n\t\treturn hwb;\n\t},\n\n\tblacken: function (ratio) {\n\t\tvar hwb = this.hwb();\n\t\thwb.color[2] += hwb.color[2] * ratio;\n\t\treturn hwb;\n\t},\n\n\tgrayscale: function () {\n\t\t// http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale\n\t\tvar rgb = this.rgb().color;\n\t\tvar val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;\n\t\treturn Color.rgb(val, val, val);\n\t},\n\n\tfade: function (ratio) {\n\t\treturn this.alpha(this.valpha - (this.valpha * ratio));\n\t},\n\n\topaquer: function (ratio) {\n\t\treturn this.alpha(this.valpha + (this.valpha * ratio));\n\t},\n\n\trotate: function (degrees) {\n\t\tvar hsl = this.hsl();\n\t\tvar hue = hsl.color[0];\n\t\thue = (hue + degrees) % 360;\n\t\thue = hue < 0 ? 360 + hue : hue;\n\t\thsl.color[0] = hue;\n\t\treturn hsl;\n\t},\n\n\tmix: function (mixinColor, weight) {\n\t\t// ported from sass implementation in C\n\t\t// https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209\n\t\tif (!mixinColor || !mixinColor.rgb) {\n\t\t\tthrow new Error('Argument to \"mix\" was not a Color instance, but rather an instance of ' + typeof mixinColor);\n\t\t}\n\t\tvar color1 = mixinColor.rgb();\n\t\tvar color2 = this.rgb();\n\t\tvar p = weight === undefined ? 0.5 : weight;\n\n\t\tvar w = 2 * p - 1;\n\t\tvar a = color1.alpha() - color2.alpha();\n\n\t\tvar w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;\n\t\tvar w2 = 1 - w1;\n\n\t\treturn Color.rgb(\n\t\t\t\tw1 * color1.red() + w2 * color2.red(),\n\t\t\t\tw1 * color1.green() + w2 * color2.green(),\n\t\t\t\tw1 * color1.blue() + w2 * color2.blue(),\n\t\t\t\tcolor1.alpha() * p + color2.alpha() * (1 - p));\n\t}\n};\n\n// model conversion methods and static constructors\nObject.keys(convert).forEach(function (model) {\n\tif (skippedModels.indexOf(model) !== -1) {\n\t\treturn;\n\t}\n\n\tvar channels = convert[model].channels;\n\n\t// conversion methods\n\tColor.prototype[model] = function () {\n\t\tif (this.model === model) {\n\t\t\treturn new Color(this);\n\t\t}\n\n\t\tif (arguments.length) {\n\t\t\treturn new Color(arguments, model);\n\t\t}\n\n\t\tvar newAlpha = typeof arguments[channels] === 'number' ? channels : this.valpha;\n\t\treturn new Color(assertArray(convert[this.model][model].raw(this.color)).concat(newAlpha), model);\n\t};\n\n\t// 'static' construction methods\n\tColor[model] = function (color) {\n\t\tif (typeof color === 'number') {\n\t\t\tcolor = zeroArray(_slice.call(arguments), channels);\n\t\t}\n\t\treturn new Color(color, model);\n\t};\n});\n\nfunction roundTo(num, places) {\n\treturn Number(num.toFixed(places));\n}\n\nfunction roundToPlace(places) {\n\treturn function (num) {\n\t\treturn roundTo(num, places);\n\t};\n}\n\nfunction getset(model, channel, modifier) {\n\tmodel = Array.isArray(model) ? model : [model];\n\n\tmodel.forEach(function (m) {\n\t\t(limiters[m] || (limiters[m] = []))[channel] = modifier;\n\t});\n\n\tmodel = model[0];\n\n\treturn function (val) {\n\t\tvar result;\n\n\t\tif (arguments.length) {\n\t\t\tif (modifier) {\n\t\t\t\tval = modifier(val);\n\t\t\t}\n\n\t\t\tresult = this[model]();\n\t\t\tresult.color[channel] = val;\n\t\t\treturn result;\n\t\t}\n\n\t\tresult = this[model]().color[channel];\n\t\tif (modifier) {\n\t\t\tresult = modifier(result);\n\t\t}\n\n\t\treturn result;\n\t};\n}\n\nfunction maxfn(max) {\n\treturn function (v) {\n\t\treturn Math.max(0, Math.min(max, v));\n\t};\n}\n\nfunction assertArray(val) {\n\treturn Array.isArray(val) ? val : [val];\n}\n\nfunction zeroArray(arr, length) {\n\tfor (var i = 0; i < length; i++) {\n\t\tif (typeof arr[i] !== 'number') {\n\t\t\tarr[i] = 0;\n\t\t}\n\t}\n\n\treturn arr;\n}\n\nmodule.exports = Color;\n","/**\n * The unique id is used for unique hashes.\n */\nlet uniqueId = 0;\n/**\n * Quick dictionary lookup for unit-less numbers.\n */\nconst CSS_NUMBER = Object.create(null);\n/**\n * CSS properties that are valid unit-less numbers.\n *\n * Ref: https://github.com/facebook/react/blob/master/packages/react-dom/src/shared/CSSProperty.js\n */\nconst CSS_NUMBER_KEYS = [\n \"animation-iteration-count\",\n \"border-image-outset\",\n \"border-image-slice\",\n \"border-image-width\",\n \"box-flex\",\n \"box-flex-group\",\n \"box-ordinal-group\",\n \"column-count\",\n \"columns\",\n \"counter-increment\",\n \"counter-reset\",\n \"flex\",\n \"flex-grow\",\n \"flex-positive\",\n \"flex-shrink\",\n \"flex-negative\",\n \"flex-order\",\n \"font-weight\",\n \"grid-area\",\n \"grid-column\",\n \"grid-column-end\",\n \"grid-column-span\",\n \"grid-column-start\",\n \"grid-row\",\n \"grid-row-end\",\n \"grid-row-span\",\n \"grid-row-start\",\n \"line-clamp\",\n \"line-height\",\n \"opacity\",\n \"order\",\n \"orphans\",\n \"tab-size\",\n \"widows\",\n \"z-index\",\n \"zoom\",\n // SVG properties.\n \"fill-opacity\",\n \"flood-opacity\",\n \"stop-opacity\",\n \"stroke-dasharray\",\n \"stroke-dashoffset\",\n \"stroke-miterlimit\",\n \"stroke-opacity\",\n \"stroke-width\"\n];\n// Add vendor prefixes to all unit-less properties.\nfor (const property of CSS_NUMBER_KEYS) {\n for (const prefix of [\"-webkit-\", \"-ms-\", \"-moz-\", \"-o-\", \"\"]) {\n CSS_NUMBER[prefix + property] = true;\n }\n}\n/**\n * Escape a CSS class name.\n */\nfunction escape(str) {\n return str.replace(/[ !#$%&()*+,./;<=>?@[\\]^`{|}~\"'\\\\]/g, \"\\\\$&\");\n}\n/**\n * Transform a JavaScript property into a CSS property.\n */\nfunction hyphenate(propertyName) {\n return propertyName\n .replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`)\n .replace(/^ms-/, \"-ms-\"); // Internet Explorer vendor prefix.\n}\n/**\n * Generate a hash value from a string.\n */\nfunction stringHash(str) {\n let value = 5381;\n let len = str.length;\n while (len--)\n value = (value * 33) ^ str.charCodeAt(len);\n return (value >>> 0).toString(36);\n}\n/**\n * Transform a style string to a CSS string.\n */\nfunction styleToString(key, value) {\n if (value && typeof value === \"number\" && !CSS_NUMBER[key]) {\n return `${key}:${value}px`;\n }\n return `${key}:${value}`;\n}\n/**\n * Sort an array of tuples by first value.\n */\nfunction sortTuples(value) {\n return value.sort((a, b) => (a[0] > b[0] ? 1 : -1));\n}\n/**\n * Categorize user styles.\n */\nfunction parseStyles(styles, hasNestedStyles) {\n const properties = [];\n const nestedStyles = [];\n // Sort keys before adding to styles.\n for (const key of Object.keys(styles)) {\n const name = key.trim();\n const value = styles[key];\n if (name.charCodeAt(0) !== 36 /* $ */ && value != null) {\n if (typeof value === \"object\" && !Array.isArray(value)) {\n nestedStyles.push([name, value]);\n }\n else {\n properties.push([hyphenate(name), value]);\n }\n }\n }\n return {\n style: stringifyProperties(sortTuples(properties)),\n nested: hasNestedStyles ? nestedStyles : sortTuples(nestedStyles),\n isUnique: !!styles.$unique\n };\n}\n/**\n * Stringify an array of property tuples.\n */\nfunction stringifyProperties(properties) {\n return properties\n .map(([name, value]) => {\n if (!Array.isArray(value))\n return styleToString(name, value);\n return value.map(x => styleToString(name, x)).join(\";\");\n })\n .join(\";\");\n}\n/**\n * Interpolate CSS selectors.\n */\nfunction interpolate(selector, parent) {\n if (selector.indexOf(\"&\") === -1)\n return `${parent} ${selector}`;\n return selector.replace(/&/g, parent);\n}\n/**\n * Recursive loop building styles with deferred selectors.\n */\nfunction stylize(selector, styles, rulesList, stylesList, parent) {\n const { style, nested, isUnique } = parseStyles(styles, selector !== \"\");\n let pid = style;\n if (selector.charCodeAt(0) === 64 /* @ */) {\n const child = {\n selector,\n styles: [],\n rules: [],\n style: parent ? \"\" : style\n };\n rulesList.push(child);\n // Nested styles support (e.g. `.foo > @media > .bar`).\n if (style && parent) {\n child.styles.push({ selector: parent, style, isUnique });\n }\n for (const [name, value] of nested) {\n pid += name + stylize(name, value, child.rules, child.styles, parent);\n }\n }\n else {\n const key = parent ? interpolate(selector, parent) : selector;\n if (style)\n stylesList.push({ selector: key, style, isUnique });\n for (const [name, value] of nested) {\n pid += name + stylize(name, value, rulesList, stylesList, key);\n }\n }\n return pid;\n}\n/**\n * Transform `stylize` tree into style objects.\n */\nfunction composeStylize(cache, pid, rulesList, stylesList, className, isStyle) {\n for (const { selector, style, isUnique } of stylesList) {\n const key = isStyle ? interpolate(selector, className) : selector;\n const id = isUnique\n ? `u\\0${(++uniqueId).toString(36)}`\n : `s\\0${pid}\\0${style}`;\n const item = new Style(style, id);\n item.add(new Selector(key, `k\\0${pid}\\0${key}`));\n cache.add(item);\n }\n for (const { selector, style, rules, styles } of rulesList) {\n const item = new Rule(selector, style, `r\\0${pid}\\0${selector}\\0${style}`);\n composeStylize(item, pid, rules, styles, className, isStyle);\n cache.add(item);\n }\n}\n/**\n * Cache to list to styles.\n */\nfunction join(arr) {\n let res = \"\";\n for (let i = 0; i < arr.length; i++)\n res += arr[i];\n return res;\n}\n/**\n * Noop changes.\n */\nconst noopChanges = {\n add: () => undefined,\n change: () => undefined,\n remove: () => undefined\n};\n/**\n * Implement a cache/event emitter.\n */\nexport class Cache {\n constructor(changes = noopChanges) {\n this.changes = changes;\n this.sheet = [];\n this.changeId = 0;\n this._keys = [];\n this._children = Object.create(null);\n this._counters = Object.create(null);\n }\n add(style) {\n const count = this._counters[style.id] || 0;\n const item = this._children[style.id] || style.clone();\n this._counters[style.id] = count + 1;\n if (count === 0) {\n this._children[item.id] = item;\n this._keys.push(item.id);\n this.sheet.push(item.getStyles());\n this.changeId++;\n this.changes.add(item, this._keys.length - 1);\n }\n else if (item instanceof Cache && style instanceof Cache) {\n const curIndex = this._keys.indexOf(style.id);\n const prevItemChangeId = item.changeId;\n item.merge(style);\n if (item.changeId !== prevItemChangeId) {\n this.sheet.splice(curIndex, 1, item.getStyles());\n this.changeId++;\n this.changes.change(item, curIndex, curIndex);\n }\n }\n }\n remove(style) {\n const count = this._counters[style.id];\n if (count) {\n this._counters[style.id] = count - 1;\n const item = this._children[style.id];\n const index = this._keys.indexOf(item.id);\n if (count === 1) {\n delete this._counters[style.id];\n delete this._children[style.id];\n this._keys.splice(index, 1);\n this.sheet.splice(index, 1);\n this.changeId++;\n this.changes.remove(item, index);\n }\n else if (item instanceof Cache && style instanceof Cache) {\n const prevChangeId = item.changeId;\n item.unmerge(style);\n if (item.changeId !== prevChangeId) {\n this.sheet.splice(index, 1, item.getStyles());\n this.changeId++;\n this.changes.change(item, index, index);\n }\n }\n }\n }\n values() {\n return this._keys.map(key => this._children[key]);\n }\n merge(cache) {\n for (const item of cache.values())\n this.add(item);\n return this;\n }\n unmerge(cache) {\n for (const item of cache.values())\n this.remove(item);\n return this;\n }\n clone() {\n return new Cache().merge(this);\n }\n}\n/**\n * Selector is a dumb class made to represent nested CSS selectors.\n */\nexport class Selector {\n constructor(selector, id) {\n this.selector = selector;\n this.id = id;\n }\n getStyles() {\n return this.selector;\n }\n clone() {\n return this;\n }\n}\n/**\n * The style container registers a style string with selectors.\n */\nexport class Style extends Cache {\n constructor(style, id) {\n super();\n this.style = style;\n this.id = id;\n }\n getStyles() {\n return `${this.sheet.join(\",\")}{${this.style}}`;\n }\n clone() {\n return new Style(this.style, this.id).merge(this);\n }\n}\n/**\n * Implement rule logic for style output.\n */\nexport class Rule extends Cache {\n constructor(rule, style, id) {\n super();\n this.rule = rule;\n this.style = style;\n this.id = id;\n }\n getStyles() {\n return `${this.rule}{${this.style}${join(this.sheet)}}`;\n }\n clone() {\n return new Rule(this.rule, this.style, this.id).merge(this);\n }\n}\nfunction key(pid, styles) {\n const key = `f${stringHash(pid)}`;\n if (process.env.NODE_ENV === \"production\" || !styles.$displayName)\n return key;\n return `${styles.$displayName}_${key}`;\n}\n/**\n * The FreeStyle class implements the API for everything else.\n */\nexport class FreeStyle extends Cache {\n constructor(id, changes) {\n super(changes);\n this.id = id;\n }\n registerStyle(styles) {\n const rulesList = [];\n const stylesList = [];\n const pid = stylize(\"&\", styles, rulesList, stylesList);\n const id = key(pid, styles);\n const selector = `.${process.env.NODE_ENV === \"production\" ? id : escape(id)}`;\n composeStylize(this, pid, rulesList, stylesList, selector, true);\n return id;\n }\n registerKeyframes(keyframes) {\n return this.registerHashRule(\"@keyframes\", keyframes);\n }\n registerHashRule(prefix, styles) {\n const rulesList = [];\n const stylesList = [];\n const pid = stylize(\"\", styles, rulesList, stylesList);\n const id = key(pid, styles);\n const selector = `${prefix} ${process.env.NODE_ENV === \"production\" ? id : escape(id)}`;\n const rule = new Rule(selector, \"\", `h\\0${pid}\\0${prefix}`);\n composeStylize(rule, pid, rulesList, stylesList, \"\", false);\n this.add(rule);\n return id;\n }\n registerRule(rule, styles) {\n const rulesList = [];\n const stylesList = [];\n const pid = stylize(rule, styles, rulesList, stylesList);\n composeStylize(this, pid, rulesList, stylesList, \"\", false);\n }\n registerCss(styles) {\n return this.registerRule(\"\", styles);\n }\n getStyles() {\n return join(this.sheet);\n }\n clone() {\n return new FreeStyle(this.id, this.changes).merge(this);\n }\n}\n/**\n * Exports a simple function to create a new instance.\n */\nexport function create(changes) {\n return new FreeStyle(`f${(++uniqueId).toString(36)}`, changes);\n}\n//# sourceMappingURL=index.js.map","/**\n * lodash (Custom Build) \n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the `TypeError` message for \"Functions\" methods. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/** Used as the internal argument placeholder. */\nvar PLACEHOLDER = '__lodash_placeholder__';\n\n/** Used to compose bitmasks for function metadata. */\nvar BIND_FLAG = 1,\n BIND_KEY_FLAG = 2,\n CURRY_BOUND_FLAG = 4,\n CURRY_FLAG = 8,\n CURRY_RIGHT_FLAG = 16,\n PARTIAL_FLAG = 32,\n PARTIAL_RIGHT_FLAG = 64,\n ARY_FLAG = 128,\n REARG_FLAG = 256,\n FLIP_FLAG = 512;\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0,\n MAX_SAFE_INTEGER = 9007199254740991,\n MAX_INTEGER = 1.7976931348623157e+308,\n NAN = 0 / 0;\n\n/** Used to associate wrap methods with their bit flags. */\nvar wrapFlags = [\n ['ary', ARY_FLAG],\n ['bind', BIND_FLAG],\n ['bindKey', BIND_KEY_FLAG],\n ['curry', CURRY_FLAG],\n ['curryRight', CURRY_RIGHT_FLAG],\n ['flip', FLIP_FLAG],\n ['partial', PARTIAL_FLAG],\n ['partialRight', PARTIAL_RIGHT_FLAG],\n ['rearg', REARG_FLAG]\n];\n\n/** `Object#toString` result references. */\nvar funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n symbolTag = '[object Symbol]';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to match leading and trailing whitespace. */\nvar reTrim = /^\\s+|\\s+$/g;\n\n/** Used to match wrap detail comments. */\nvar reWrapComment = /\\{(?:\\n\\/\\* \\[wrapped with .+\\] \\*\\/)?\\n?/,\n reWrapDetails = /\\{\\n\\/\\* \\[wrapped with (.+)\\] \\*/,\n reSplitDetails = /,? & /;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\n/**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\nfunction arrayEach(array, iteratee) {\n var index = -1,\n length = array ? array.length : 0;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n}\n\n/**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludes(array, value) {\n var length = array ? array.length : 0;\n return !!length && baseIndexOf(array, value, 0) > -1;\n}\n\n/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\n/**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseIndexOf(array, value, fromIndex) {\n if (value !== value) {\n return baseFindIndex(array, baseIsNaN, fromIndex);\n }\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\n/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\n/**\n * Gets the number of `placeholder` occurrences in `array`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} placeholder The placeholder to search for.\n * @returns {number} Returns the placeholder count.\n */\nfunction countHolders(array, placeholder) {\n var length = array.length,\n result = 0;\n\n while (length--) {\n if (array[length] === placeholder) {\n result++;\n }\n }\n return result;\n}\n\n/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\n/**\n * Checks if `value` is a host object in IE < 9.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a host object, else `false`.\n */\nfunction isHostObject(value) {\n // Many host objects are `Object` objects that can coerce to strings\n // despite having improperly defined `toString` methods.\n var result = false;\n if (value != null && typeof value.toString != 'function') {\n try {\n result = !!(value + '');\n } catch (e) {}\n }\n return result;\n}\n\n/**\n * Replaces all `placeholder` elements in `array` with an internal placeholder\n * and returns an array of their indexes.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {*} placeholder The placeholder to replace.\n * @returns {Array} Returns the new array of placeholder indexes.\n */\nfunction replaceHolders(array, placeholder) {\n var index = -1,\n length = array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (value === placeholder || value === PLACEHOLDER) {\n array[index] = PLACEHOLDER;\n result[resIndex++] = index;\n }\n }\n return result;\n}\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/** Built-in value references. */\nvar objectCreate = Object.create;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n nativeMin = Math.min;\n\n/* Used to set `toString` methods. */\nvar defineProperty = (function() {\n var func = getNative(Object, 'defineProperty'),\n name = getNative.name;\n\n return (name && name.length > 2) ? func : undefined;\n}());\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} prototype The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nfunction baseCreate(proto) {\n return isObject(proto) ? objectCreate(proto) : {};\n}\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\n/**\n * Creates an array that is the composition of partially applied arguments,\n * placeholders, and provided arguments into a single array of arguments.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to prepend to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\nfunction composeArgs(args, partials, holders, isCurried) {\n var argsIndex = -1,\n argsLength = args.length,\n holdersLength = holders.length,\n leftIndex = -1,\n leftLength = partials.length,\n rangeLength = nativeMax(argsLength - holdersLength, 0),\n result = Array(leftLength + rangeLength),\n isUncurried = !isCurried;\n\n while (++leftIndex < leftLength) {\n result[leftIndex] = partials[leftIndex];\n }\n while (++argsIndex < holdersLength) {\n if (isUncurried || argsIndex < argsLength) {\n result[holders[argsIndex]] = args[argsIndex];\n }\n }\n while (rangeLength--) {\n result[leftIndex++] = args[argsIndex++];\n }\n return result;\n}\n\n/**\n * This function is like `composeArgs` except that the arguments composition\n * is tailored for `_.partialRight`.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to append to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\nfunction composeArgsRight(args, partials, holders, isCurried) {\n var argsIndex = -1,\n argsLength = args.length,\n holdersIndex = -1,\n holdersLength = holders.length,\n rightIndex = -1,\n rightLength = partials.length,\n rangeLength = nativeMax(argsLength - holdersLength, 0),\n result = Array(rangeLength + rightLength),\n isUncurried = !isCurried;\n\n while (++argsIndex < rangeLength) {\n result[argsIndex] = args[argsIndex];\n }\n var offset = argsIndex;\n while (++rightIndex < rightLength) {\n result[offset + rightIndex] = partials[rightIndex];\n }\n while (++holdersIndex < holdersLength) {\n if (isUncurried || argsIndex < argsLength) {\n result[offset + holders[holdersIndex]] = args[argsIndex++];\n }\n }\n return result;\n}\n\n/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\n/**\n * Creates a function that wraps `func` to invoke it with the optional `this`\n * binding of `thisArg`.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\nfunction createBind(func, bitmask, thisArg) {\n var isBind = bitmask & BIND_FLAG,\n Ctor = createCtor(func);\n\n function wrapper() {\n var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n return fn.apply(isBind ? thisArg : this, arguments);\n }\n return wrapper;\n}\n\n/**\n * Creates a function that produces an instance of `Ctor` regardless of\n * whether it was invoked as part of a `new` expression or by `call` or `apply`.\n *\n * @private\n * @param {Function} Ctor The constructor to wrap.\n * @returns {Function} Returns the new wrapped function.\n */\nfunction createCtor(Ctor) {\n return function() {\n // Use a `switch` statement to work with class constructors. See\n // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist\n // for more details.\n var args = arguments;\n switch (args.length) {\n case 0: return new Ctor;\n case 1: return new Ctor(args[0]);\n case 2: return new Ctor(args[0], args[1]);\n case 3: return new Ctor(args[0], args[1], args[2]);\n case 4: return new Ctor(args[0], args[1], args[2], args[3]);\n case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);\n case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);\n case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);\n }\n var thisBinding = baseCreate(Ctor.prototype),\n result = Ctor.apply(thisBinding, args);\n\n // Mimic the constructor's `return` behavior.\n // See https://es5.github.io/#x13.2.2 for more details.\n return isObject(result) ? result : thisBinding;\n };\n}\n\n/**\n * Creates a function that wraps `func` to enable currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {number} arity The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\nfunction createCurry(func, bitmask, arity) {\n var Ctor = createCtor(func);\n\n function wrapper() {\n var length = arguments.length,\n args = Array(length),\n index = length,\n placeholder = getHolder(wrapper);\n\n while (index--) {\n args[index] = arguments[index];\n }\n var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)\n ? []\n : replaceHolders(args, placeholder);\n\n length -= holders.length;\n if (length < arity) {\n return createRecurry(\n func, bitmask, createHybrid, wrapper.placeholder, undefined,\n args, holders, undefined, undefined, arity - length);\n }\n var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n return apply(fn, this, args);\n }\n return wrapper;\n}\n\n/**\n * Creates a function that wraps `func` to invoke it with optional `this`\n * binding of `thisArg`, partial application, and currying.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n * the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [partialsRight] The arguments to append to those provided\n * to the new function.\n * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\nfunction createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {\n var isAry = bitmask & ARY_FLAG,\n isBind = bitmask & BIND_FLAG,\n isBindKey = bitmask & BIND_KEY_FLAG,\n isCurried = bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG),\n isFlip = bitmask & FLIP_FLAG,\n Ctor = isBindKey ? undefined : createCtor(func);\n\n function wrapper() {\n var length = arguments.length,\n args = Array(length),\n index = length;\n\n while (index--) {\n args[index] = arguments[index];\n }\n if (isCurried) {\n var placeholder = getHolder(wrapper),\n holdersCount = countHolders(args, placeholder);\n }\n if (partials) {\n args = composeArgs(args, partials, holders, isCurried);\n }\n if (partialsRight) {\n args = composeArgsRight(args, partialsRight, holdersRight, isCurried);\n }\n length -= holdersCount;\n if (isCurried && length < arity) {\n var newHolders = replaceHolders(args, placeholder);\n return createRecurry(\n func, bitmask, createHybrid, wrapper.placeholder, thisArg,\n args, newHolders, argPos, ary, arity - length\n );\n }\n var thisBinding = isBind ? thisArg : this,\n fn = isBindKey ? thisBinding[func] : func;\n\n length = args.length;\n if (argPos) {\n args = reorder(args, argPos);\n } else if (isFlip && length > 1) {\n args.reverse();\n }\n if (isAry && ary < length) {\n args.length = ary;\n }\n if (this && this !== root && this instanceof wrapper) {\n fn = Ctor || createCtor(fn);\n }\n return fn.apply(thisBinding, args);\n }\n return wrapper;\n}\n\n/**\n * Creates a function that wraps `func` to invoke it with the `this` binding\n * of `thisArg` and `partials` prepended to the arguments it receives.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} partials The arguments to prepend to those provided to\n * the new function.\n * @returns {Function} Returns the new wrapped function.\n */\nfunction createPartial(func, bitmask, thisArg, partials) {\n var isBind = bitmask & BIND_FLAG,\n Ctor = createCtor(func);\n\n function wrapper() {\n var argsIndex = -1,\n argsLength = arguments.length,\n leftIndex = -1,\n leftLength = partials.length,\n args = Array(leftLength + argsLength),\n fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n\n while (++leftIndex < leftLength) {\n args[leftIndex] = partials[leftIndex];\n }\n while (argsLength--) {\n args[leftIndex++] = arguments[++argsIndex];\n }\n return apply(fn, isBind ? thisArg : this, args);\n }\n return wrapper;\n}\n\n/**\n * Creates a function that wraps `func` to continue currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {Function} wrapFunc The function to create the `func` wrapper.\n * @param {*} placeholder The placeholder value.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n * the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\nfunction createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {\n var isCurry = bitmask & CURRY_FLAG,\n newHolders = isCurry ? holders : undefined,\n newHoldersRight = isCurry ? undefined : holders,\n newPartials = isCurry ? partials : undefined,\n newPartialsRight = isCurry ? undefined : partials;\n\n bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);\n bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);\n\n if (!(bitmask & CURRY_BOUND_FLAG)) {\n bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);\n }\n\n var result = wrapFunc(func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity);\n result.placeholder = placeholder;\n return setWrapToString(result, func, bitmask);\n}\n\n/**\n * Creates a function that either curries or invokes `func` with optional\n * `this` binding and partially applied arguments.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags.\n * The bitmask may be composed of the following flags:\n * 1 - `_.bind`\n * 2 - `_.bindKey`\n * 4 - `_.curry` or `_.curryRight` of a bound function\n * 8 - `_.curry`\n * 16 - `_.curryRight`\n * 32 - `_.partial`\n * 64 - `_.partialRight`\n * 128 - `_.rearg`\n * 256 - `_.ary`\n * 512 - `_.flip`\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to be partially applied.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\nfunction createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {\n var isBindKey = bitmask & BIND_KEY_FLAG;\n if (!isBindKey && typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var length = partials ? partials.length : 0;\n if (!length) {\n bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);\n partials = holders = undefined;\n }\n ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);\n arity = arity === undefined ? arity : toInteger(arity);\n length -= holders ? holders.length : 0;\n\n if (bitmask & PARTIAL_RIGHT_FLAG) {\n var partialsRight = partials,\n holdersRight = holders;\n\n partials = holders = undefined;\n }\n\n var newData = [\n func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,\n argPos, ary, arity\n ];\n\n func = newData[0];\n bitmask = newData[1];\n thisArg = newData[2];\n partials = newData[3];\n holders = newData[4];\n arity = newData[9] = newData[9] == null\n ? (isBindKey ? 0 : func.length)\n : nativeMax(newData[9] - length, 0);\n\n if (!arity && bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG)) {\n bitmask &= ~(CURRY_FLAG | CURRY_RIGHT_FLAG);\n }\n if (!bitmask || bitmask == BIND_FLAG) {\n var result = createBind(func, bitmask, thisArg);\n } else if (bitmask == CURRY_FLAG || bitmask == CURRY_RIGHT_FLAG) {\n result = createCurry(func, bitmask, arity);\n } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !holders.length) {\n result = createPartial(func, bitmask, thisArg, partials);\n } else {\n result = createHybrid.apply(undefined, newData);\n }\n return setWrapToString(result, func, bitmask);\n}\n\n/**\n * Gets the argument placeholder value for `func`.\n *\n * @private\n * @param {Function} func The function to inspect.\n * @returns {*} Returns the placeholder value.\n */\nfunction getHolder(func) {\n var object = func;\n return object.placeholder;\n}\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\n/**\n * Extracts wrapper details from the `source` body comment.\n *\n * @private\n * @param {string} source The source to inspect.\n * @returns {Array} Returns the wrapper details.\n */\nfunction getWrapDetails(source) {\n var match = source.match(reWrapDetails);\n return match ? match[1].split(reSplitDetails) : [];\n}\n\n/**\n * Inserts wrapper `details` in a comment at the top of the `source` body.\n *\n * @private\n * @param {string} source The source to modify.\n * @returns {Array} details The details to insert.\n * @returns {string} Returns the modified source.\n */\nfunction insertWrapDetails(source, details) {\n var length = details.length,\n lastIndex = length - 1;\n\n details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];\n details = details.join(length > 2 ? ', ' : ' ');\n return source.replace(reWrapComment, '{\\n/* [wrapped with ' + details + '] */\\n');\n}\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n length = length == null ? MAX_SAFE_INTEGER : length;\n return !!length &&\n (typeof value == 'number' || reIsUint.test(value)) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\n/**\n * Reorder `array` according to the specified indexes where the element at\n * the first index is assigned as the first element, the element at\n * the second index is assigned as the second element, and so on.\n *\n * @private\n * @param {Array} array The array to reorder.\n * @param {Array} indexes The arranged array indexes.\n * @returns {Array} Returns `array`.\n */\nfunction reorder(array, indexes) {\n var arrLength = array.length,\n length = nativeMin(indexes.length, arrLength),\n oldArray = copyArray(array);\n\n while (length--) {\n var index = indexes[length];\n array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;\n }\n return array;\n}\n\n/**\n * Sets the `toString` method of `wrapper` to mimic the source of `reference`\n * with wrapper details in a comment at the top of the source body.\n *\n * @private\n * @param {Function} wrapper The function to modify.\n * @param {Function} reference The reference function.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Function} Returns `wrapper`.\n */\nvar setWrapToString = !defineProperty ? identity : function(wrapper, reference, bitmask) {\n var source = (reference + '');\n return defineProperty(wrapper, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)))\n });\n};\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to process.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\n/**\n * Updates wrapper `details` based on `bitmask` flags.\n *\n * @private\n * @returns {Array} details The details to modify.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Array} Returns `details`.\n */\nfunction updateWrapDetails(details, bitmask) {\n arrayEach(wrapFlags, function(pair) {\n var value = '_.' + pair[0];\n if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {\n details.push(value);\n }\n });\n return details.sort();\n}\n\n/**\n * Creates a function that accepts arguments of `func` and either invokes\n * `func` returning its result, if at least `arity` number of arguments have\n * been provided, or returns a function that accepts the remaining `func`\n * arguments, and so on. The arity of `func` may be specified if `func.length`\n * is not sufficient.\n *\n * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for provided arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of curried functions.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n * return [a, b, c];\n * };\n *\n * var curried = _.curry(abc);\n *\n * curried(1)(2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // Curried with placeholders.\n * curried(1)(_, 3)(2);\n * // => [1, 2, 3]\n */\nfunction curry(func, arity, guard) {\n arity = guard ? undefined : arity;\n var result = createWrap(func, CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n result.placeholder = curry.placeholder;\n return result;\n}\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 8-9 which returns 'object' for typed array and other constructors.\n var tag = isObject(value) ? objectToString.call(value) : '';\n return tag == funcTag || tag == genTag;\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return !!value && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && objectToString.call(value) == symbolTag);\n}\n\n/**\n * Converts `value` to a finite number.\n *\n * @static\n * @memberOf _\n * @since 4.12.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted number.\n * @example\n *\n * _.toFinite(3.2);\n * // => 3.2\n *\n * _.toFinite(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toFinite(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toFinite('3.2');\n * // => 3.2\n */\nfunction toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n var sign = (value < 0 ? -1 : 1);\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\n}\n\n/**\n * Converts `value` to an integer.\n *\n * **Note:** This method is loosely based on\n * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toInteger(3.2);\n * // => 3\n *\n * _.toInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toInteger(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toInteger('3.2');\n * // => 3\n */\nfunction toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n}\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = value.replace(reTrim, '');\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\n/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\n/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\n// Assign default placeholders.\ncurry.placeholder = {};\n\nmodule.exports = curry;\n","module.exports =\n/******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n/******/\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId])\n/******/ \t\t\treturn installedModules[moduleId].exports;\n/******/\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\texports: {},\n/******/ \t\t\tid: moduleId,\n/******/ \t\t\tloaded: false\n/******/ \t\t};\n/******/\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.loaded = true;\n/******/\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/\n/******/\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n/******/\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n/******/\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"\";\n/******/\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(0);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\tmodule.exports = __webpack_require__(1);\n\n\n/***/ }),\n/* 1 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t'use strict';\n\t\n\tObject.defineProperty(exports, '__esModule', {\n\t value: true\n\t});\n\t\n\tfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\t\n\tvar _Highlighter = __webpack_require__(2);\n\t\n\tvar _Highlighter2 = _interopRequireDefault(_Highlighter);\n\n\texports['default'] = _Highlighter2['default'];\n\tmodule.exports = exports['default'];\n\n/***/ }),\n/* 2 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t'use strict';\n\t\n\tObject.defineProperty(exports, '__esModule', {\n\t value: true\n\t});\n\t\n\tvar _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };\n\t\n\texports['default'] = Highlighter;\n\t\n\tfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\t\n\tfunction _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }\n\t\n\tvar _highlightWordsCore = __webpack_require__(3);\n\t\n\tvar _propTypes = __webpack_require__(4);\n\t\n\tvar _propTypes2 = _interopRequireDefault(_propTypes);\n\t\n\tvar _react = __webpack_require__(14);\n\t\n\tvar _memoizeOne = __webpack_require__(15);\n\t\n\tvar _memoizeOne2 = _interopRequireDefault(_memoizeOne);\n\t\n\tHighlighter.propTypes = {\n\t activeClassName: _propTypes2['default'].string,\n\t activeIndex: _propTypes2['default'].number,\n\t activeStyle: _propTypes2['default'].object,\n\t autoEscape: _propTypes2['default'].bool,\n\t className: _propTypes2['default'].string,\n\t findChunks: _propTypes2['default'].func,\n\t highlightClassName: _propTypes2['default'].oneOfType([_propTypes2['default'].object, _propTypes2['default'].string]),\n\t highlightStyle: _propTypes2['default'].object,\n\t highlightTag: _propTypes2['default'].oneOfType([_propTypes2['default'].node, _propTypes2['default'].func, _propTypes2['default'].string]),\n\t sanitize: _propTypes2['default'].func,\n\t searchWords: _propTypes2['default'].arrayOf(_propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].instanceOf(RegExp)])).isRequired,\n\t textToHighlight: _propTypes2['default'].string.isRequired,\n\t unhighlightTag: _propTypes2['default'].oneOfType([_propTypes2['default'].node, _propTypes2['default'].func, _propTypes2['default'].string]),\n\t unhighlightClassName: _propTypes2['default'].string,\n\t unhighlightStyle: _propTypes2['default'].object\n\t};\n\t\n\t/**\r\n\t * Highlights all occurrences of search terms (searchText) within a string (textToHighlight).\r\n\t * This function returns an array of strings and s (wrapping highlighted words).\r\n\t */\n\t\n\tfunction Highlighter(_ref) {\n\t var _ref$activeClassName = _ref.activeClassName;\n\t var activeClassName = _ref$activeClassName === undefined ? '' : _ref$activeClassName;\n\t var _ref$activeIndex = _ref.activeIndex;\n\t var activeIndex = _ref$activeIndex === undefined ? -1 : _ref$activeIndex;\n\t var activeStyle = _ref.activeStyle;\n\t var autoEscape = _ref.autoEscape;\n\t var _ref$caseSensitive = _ref.caseSensitive;\n\t var caseSensitive = _ref$caseSensitive === undefined ? false : _ref$caseSensitive;\n\t var className = _ref.className;\n\t var findChunks = _ref.findChunks;\n\t var _ref$highlightClassName = _ref.highlightClassName;\n\t var highlightClassName = _ref$highlightClassName === undefined ? '' : _ref$highlightClassName;\n\t var _ref$highlightStyle = _ref.highlightStyle;\n\t var highlightStyle = _ref$highlightStyle === undefined ? {} : _ref$highlightStyle;\n\t var _ref$highlightTag = _ref.highlightTag;\n\t var highlightTag = _ref$highlightTag === undefined ? 'mark' : _ref$highlightTag;\n\t var sanitize = _ref.sanitize;\n\t var searchWords = _ref.searchWords;\n\t var textToHighlight = _ref.textToHighlight;\n\t var _ref$unhighlightTag = _ref.unhighlightTag;\n\t var unhighlightTag = _ref$unhighlightTag === undefined ? 'span' : _ref$unhighlightTag;\n\t var _ref$unhighlightClassName = _ref.unhighlightClassName;\n\t var unhighlightClassName = _ref$unhighlightClassName === undefined ? '' : _ref$unhighlightClassName;\n\t var unhighlightStyle = _ref.unhighlightStyle;\n\t\n\t var rest = _objectWithoutProperties(_ref, ['activeClassName', 'activeIndex', 'activeStyle', 'autoEscape', 'caseSensitive', 'className', 'findChunks', 'highlightClassName', 'highlightStyle', 'highlightTag', 'sanitize', 'searchWords', 'textToHighlight', 'unhighlightTag', 'unhighlightClassName', 'unhighlightStyle']);\n\t\n\t var chunks = (0, _highlightWordsCore.findAll)({\n\t autoEscape: autoEscape,\n\t caseSensitive: caseSensitive,\n\t findChunks: findChunks,\n\t sanitize: sanitize,\n\t searchWords: searchWords,\n\t textToHighlight: textToHighlight\n\t });\n\t var HighlightTag = highlightTag;\n\t var highlightIndex = -1;\n\t var highlightClassNames = '';\n\t var highlightStyles = undefined;\n\t\n\t var lowercaseProps = function lowercaseProps(object) {\n\t var mapped = {};\n\t for (var key in object) {\n\t mapped[key.toLowerCase()] = object[key];\n\t }\n\t return mapped;\n\t };\n\t var memoizedLowercaseProps = (0, _memoizeOne2['default'])(lowercaseProps);\n\t\n\t return (0, _react.createElement)('span', _extends({\n\t className: className\n\t }, rest, {\n\t children: chunks.map(function (chunk, index) {\n\t var text = textToHighlight.substr(chunk.start, chunk.end - chunk.start);\n\t\n\t if (chunk.highlight) {\n\t highlightIndex++;\n\t\n\t var highlightClass = undefined;\n\t if (typeof highlightClassName === 'object') {\n\t if (!caseSensitive) {\n\t highlightClassName = memoizedLowercaseProps(highlightClassName);\n\t highlightClass = highlightClassName[text.toLowerCase()];\n\t } else {\n\t highlightClass = highlightClassName[text];\n\t }\n\t } else {\n\t highlightClass = highlightClassName;\n\t }\n\t\n\t var isActive = highlightIndex === +activeIndex;\n\t\n\t highlightClassNames = highlightClass + ' ' + (isActive ? activeClassName : '');\n\t highlightStyles = isActive === true && activeStyle != null ? Object.assign({}, highlightStyle, activeStyle) : highlightStyle;\n\t\n\t var props = {\n\t children: text,\n\t className: highlightClassNames,\n\t key: index,\n\t style: highlightStyles\n\t };\n\t\n\t // Don't attach arbitrary props to DOM elements; this triggers React DEV warnings (https://fb.me/react-unknown-prop)\n\t // Only pass through the highlightIndex attribute for custom components.\n\t if (typeof HighlightTag !== 'string') {\n\t props.highlightIndex = highlightIndex;\n\t }\n\t\n\t return (0, _react.createElement)(HighlightTag, props);\n\t } else {\n\t return (0, _react.createElement)(unhighlightTag, {\n\t children: text,\n\t className: unhighlightClassName,\n\t key: index,\n\t style: unhighlightStyle\n\t });\n\t }\n\t })\n\t }));\n\t}\n\t\n\tmodule.exports = exports['default'];\n\n/***/ }),\n/* 3 */\n/***/ (function(module, exports) {\n\n\tmodule.exports =\n\t/******/ (function(modules) { // webpackBootstrap\n\t/******/ \t// The module cache\n\t/******/ \tvar installedModules = {};\n\t/******/\n\t/******/ \t// The require function\n\t/******/ \tfunction __webpack_require__(moduleId) {\n\t/******/\n\t/******/ \t\t// Check if module is in cache\n\t/******/ \t\tif(installedModules[moduleId])\n\t/******/ \t\t\treturn installedModules[moduleId].exports;\n\t/******/\n\t/******/ \t\t// Create a new module (and put it into the cache)\n\t/******/ \t\tvar module = installedModules[moduleId] = {\n\t/******/ \t\t\texports: {},\n\t/******/ \t\t\tid: moduleId,\n\t/******/ \t\t\tloaded: false\n\t/******/ \t\t};\n\t/******/\n\t/******/ \t\t// Execute the module function\n\t/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\t/******/\n\t/******/ \t\t// Flag the module as loaded\n\t/******/ \t\tmodule.loaded = true;\n\t/******/\n\t/******/ \t\t// Return the exports of the module\n\t/******/ \t\treturn module.exports;\n\t/******/ \t}\n\t/******/\n\t/******/\n\t/******/ \t// expose the modules object (__webpack_modules__)\n\t/******/ \t__webpack_require__.m = modules;\n\t/******/\n\t/******/ \t// expose the module cache\n\t/******/ \t__webpack_require__.c = installedModules;\n\t/******/\n\t/******/ \t// __webpack_public_path__\n\t/******/ \t__webpack_require__.p = \"\";\n\t/******/\n\t/******/ \t// Load entry module and return exports\n\t/******/ \treturn __webpack_require__(0);\n\t/******/ })\n\t/************************************************************************/\n\t/******/ ([\n\t/* 0 */\n\t/***/ (function(module, exports, __webpack_require__) {\n\t\n\t\tmodule.exports = __webpack_require__(1);\n\t\n\t\n\t/***/ }),\n\t/* 1 */\n\t/***/ (function(module, exports, __webpack_require__) {\n\t\n\t\t'use strict';\n\t\t\n\t\tObject.defineProperty(exports, \"__esModule\", {\n\t\t value: true\n\t\t});\n\t\t\n\t\tvar _utils = __webpack_require__(2);\n\t\t\n\t\tObject.defineProperty(exports, 'combineChunks', {\n\t\t enumerable: true,\n\t\t get: function get() {\n\t\t return _utils.combineChunks;\n\t\t }\n\t\t});\n\t\tObject.defineProperty(exports, 'fillInChunks', {\n\t\t enumerable: true,\n\t\t get: function get() {\n\t\t return _utils.fillInChunks;\n\t\t }\n\t\t});\n\t\tObject.defineProperty(exports, 'findAll', {\n\t\t enumerable: true,\n\t\t get: function get() {\n\t\t return _utils.findAll;\n\t\t }\n\t\t});\n\t\tObject.defineProperty(exports, 'findChunks', {\n\t\t enumerable: true,\n\t\t get: function get() {\n\t\t return _utils.findChunks;\n\t\t }\n\t\t});\n\t\n\t/***/ }),\n\t/* 2 */\n\t/***/ (function(module, exports) {\n\t\n\t\t'use strict';\n\t\t\n\t\tObject.defineProperty(exports, \"__esModule\", {\n\t\t value: true\n\t\t});\n\t\t/**\n\t\t * Creates an array of chunk objects representing both higlightable and non highlightable pieces of text that match each search word.\n\t\t * @return Array of \"chunks\" (where a Chunk is { start:number, end:number, highlight:boolean })\n\t\t */\n\t\tvar findAll = exports.findAll = function findAll(_ref) {\n\t\t var autoEscape = _ref.autoEscape,\n\t\t _ref$caseSensitive = _ref.caseSensitive,\n\t\t caseSensitive = _ref$caseSensitive === undefined ? false : _ref$caseSensitive,\n\t\t _ref$findChunks = _ref.findChunks,\n\t\t findChunks = _ref$findChunks === undefined ? defaultFindChunks : _ref$findChunks,\n\t\t sanitize = _ref.sanitize,\n\t\t searchWords = _ref.searchWords,\n\t\t textToHighlight = _ref.textToHighlight;\n\t\t return fillInChunks({\n\t\t chunksToHighlight: combineChunks({\n\t\t chunks: findChunks({\n\t\t autoEscape: autoEscape,\n\t\t caseSensitive: caseSensitive,\n\t\t sanitize: sanitize,\n\t\t searchWords: searchWords,\n\t\t textToHighlight: textToHighlight\n\t\t })\n\t\t }),\n\t\t totalLength: textToHighlight ? textToHighlight.length : 0\n\t\t });\n\t\t};\n\t\t\n\t\t/**\n\t\t * Takes an array of {start:number, end:number} objects and combines chunks that overlap into single chunks.\n\t\t * @return {start:number, end:number}[]\n\t\t */\n\t\tvar combineChunks = exports.combineChunks = function combineChunks(_ref2) {\n\t\t var chunks = _ref2.chunks;\n\t\t\n\t\t chunks = chunks.sort(function (first, second) {\n\t\t return first.start - second.start;\n\t\t }).reduce(function (processedChunks, nextChunk) {\n\t\t // First chunk just goes straight in the array...\n\t\t if (processedChunks.length === 0) {\n\t\t return [nextChunk];\n\t\t } else {\n\t\t // ... subsequent chunks get checked to see if they overlap...\n\t\t var prevChunk = processedChunks.pop();\n\t\t if (nextChunk.start <= prevChunk.end) {\n\t\t // It may be the case that prevChunk completely surrounds nextChunk, so take the\n\t\t // largest of the end indeces.\n\t\t var endIndex = Math.max(prevChunk.end, nextChunk.end);\n\t\t processedChunks.push({ start: prevChunk.start, end: endIndex });\n\t\t } else {\n\t\t processedChunks.push(prevChunk, nextChunk);\n\t\t }\n\t\t return processedChunks;\n\t\t }\n\t\t }, []);\n\t\t\n\t\t return chunks;\n\t\t};\n\t\t\n\t\t/**\n\t\t * Examine text for any matches.\n\t\t * If we find matches, add them to the returned array as a \"chunk\" object ({start:number, end:number}).\n\t\t * @return {start:number, end:number}[]\n\t\t */\n\t\tvar defaultFindChunks = function defaultFindChunks(_ref3) {\n\t\t var autoEscape = _ref3.autoEscape,\n\t\t caseSensitive = _ref3.caseSensitive,\n\t\t _ref3$sanitize = _ref3.sanitize,\n\t\t sanitize = _ref3$sanitize === undefined ? identity : _ref3$sanitize,\n\t\t searchWords = _ref3.searchWords,\n\t\t textToHighlight = _ref3.textToHighlight;\n\t\t\n\t\t textToHighlight = sanitize(textToHighlight);\n\t\t\n\t\t return searchWords.filter(function (searchWord) {\n\t\t return searchWord;\n\t\t }) // Remove empty words\n\t\t .reduce(function (chunks, searchWord) {\n\t\t searchWord = sanitize(searchWord);\n\t\t\n\t\t if (autoEscape) {\n\t\t searchWord = escapeRegExpFn(searchWord);\n\t\t }\n\t\t\n\t\t var regex = new RegExp(searchWord, caseSensitive ? 'g' : 'gi');\n\t\t\n\t\t var match = void 0;\n\t\t while (match = regex.exec(textToHighlight)) {\n\t\t var start = match.index;\n\t\t var end = regex.lastIndex;\n\t\t // We do not return zero-length matches\n\t\t if (end > start) {\n\t\t chunks.push({ start: start, end: end });\n\t\t }\n\t\t\n\t\t // Prevent browsers like Firefox from getting stuck in an infinite loop\n\t\t // See http://www.regexguru.com/2008/04/watch-out-for-zero-length-matches/\n\t\t if (match.index == regex.lastIndex) {\n\t\t regex.lastIndex++;\n\t\t }\n\t\t }\n\t\t\n\t\t return chunks;\n\t\t }, []);\n\t\t};\n\t\t// Allow the findChunks to be overridden in findAll,\n\t\t// but for backwards compatibility we export as the old name\n\t\texports.findChunks = defaultFindChunks;\n\t\t\n\t\t/**\n\t\t * Given a set of chunks to highlight, create an additional set of chunks\n\t\t * to represent the bits of text between the highlighted text.\n\t\t * @param chunksToHighlight {start:number, end:number}[]\n\t\t * @param totalLength number\n\t\t * @return {start:number, end:number, highlight:boolean}[]\n\t\t */\n\t\t\n\t\tvar fillInChunks = exports.fillInChunks = function fillInChunks(_ref4) {\n\t\t var chunksToHighlight = _ref4.chunksToHighlight,\n\t\t totalLength = _ref4.totalLength;\n\t\t\n\t\t var allChunks = [];\n\t\t var append = function append(start, end, highlight) {\n\t\t if (end - start > 0) {\n\t\t allChunks.push({\n\t\t start: start,\n\t\t end: end,\n\t\t highlight: highlight\n\t\t });\n\t\t }\n\t\t };\n\t\t\n\t\t if (chunksToHighlight.length === 0) {\n\t\t append(0, totalLength, false);\n\t\t } else {\n\t\t var lastIndex = 0;\n\t\t chunksToHighlight.forEach(function (chunk) {\n\t\t append(lastIndex, chunk.start, false);\n\t\t append(chunk.start, chunk.end, true);\n\t\t lastIndex = chunk.end;\n\t\t });\n\t\t append(lastIndex, totalLength, false);\n\t\t }\n\t\t return allChunks;\n\t\t};\n\t\t\n\t\tfunction identity(value) {\n\t\t return value;\n\t\t}\n\t\t\n\t\tfunction escapeRegExpFn(str) {\n\t\t return str.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g, '\\\\$&');\n\t\t}\n\t\n\t/***/ })\n\t/******/ ]);\n\t//# sourceMappingURL=index.js.map\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(process) {/**\n\t * Copyright (c) 2013-present, Facebook, Inc.\n\t *\n\t * This source code is licensed under the MIT license found in the\n\t * LICENSE file in the root directory of this source tree.\n\t */\n\t\n\tif (process.env.NODE_ENV !== 'production') {\n\t var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' &&\n\t Symbol.for &&\n\t Symbol.for('react.element')) ||\n\t 0xeac7;\n\t\n\t var isValidElement = function(object) {\n\t return typeof object === 'object' &&\n\t object !== null &&\n\t object.$$typeof === REACT_ELEMENT_TYPE;\n\t };\n\t\n\t // By explicitly using `prop-types` you are opting into new development behavior.\n\t // http://fb.me/prop-types-in-prod\n\t var throwOnDirectAccess = true;\n\t module.exports = __webpack_require__(6)(isValidElement, throwOnDirectAccess);\n\t} else {\n\t // By explicitly using `prop-types` you are opting into new production behavior.\n\t // http://fb.me/prop-types-in-prod\n\t module.exports = __webpack_require__(13)();\n\t}\n\t\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5)))\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports) {\n\n\t// shim for using process in browser\n\tvar process = module.exports = {};\n\t\n\t// cached from whatever global is present so that test runners that stub it\n\t// don't break things. But we need to wrap it in a try catch in case it is\n\t// wrapped in strict mode code which doesn't define any globals. It's inside a\n\t// function because try/catches deoptimize in certain engines.\n\t\n\tvar cachedSetTimeout;\n\tvar cachedClearTimeout;\n\t\n\tfunction defaultSetTimout() {\n\t throw new Error('setTimeout has not been defined');\n\t}\n\tfunction defaultClearTimeout () {\n\t throw new Error('clearTimeout has not been defined');\n\t}\n\t(function () {\n\t try {\n\t if (typeof setTimeout === 'function') {\n\t cachedSetTimeout = setTimeout;\n\t } else {\n\t cachedSetTimeout = defaultSetTimout;\n\t }\n\t } catch (e) {\n\t cachedSetTimeout = defaultSetTimout;\n\t }\n\t try {\n\t if (typeof clearTimeout === 'function') {\n\t cachedClearTimeout = clearTimeout;\n\t } else {\n\t cachedClearTimeout = defaultClearTimeout;\n\t }\n\t } catch (e) {\n\t cachedClearTimeout = defaultClearTimeout;\n\t }\n\t} ())\n\tfunction runTimeout(fun) {\n\t if (cachedSetTimeout === setTimeout) {\n\t //normal enviroments in sane situations\n\t return setTimeout(fun, 0);\n\t }\n\t // if setTimeout wasn't available but was latter defined\n\t if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n\t cachedSetTimeout = setTimeout;\n\t return setTimeout(fun, 0);\n\t }\n\t try {\n\t // when when somebody has screwed with setTimeout but no I.E. maddness\n\t return cachedSetTimeout(fun, 0);\n\t } catch(e){\n\t try {\n\t // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n\t return cachedSetTimeout.call(null, fun, 0);\n\t } catch(e){\n\t // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n\t return cachedSetTimeout.call(this, fun, 0);\n\t }\n\t }\n\t\n\t\n\t}\n\tfunction runClearTimeout(marker) {\n\t if (cachedClearTimeout === clearTimeout) {\n\t //normal enviroments in sane situations\n\t return clearTimeout(marker);\n\t }\n\t // if clearTimeout wasn't available but was latter defined\n\t if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n\t cachedClearTimeout = clearTimeout;\n\t return clearTimeout(marker);\n\t }\n\t try {\n\t // when when somebody has screwed with setTimeout but no I.E. maddness\n\t return cachedClearTimeout(marker);\n\t } catch (e){\n\t try {\n\t // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n\t return cachedClearTimeout.call(null, marker);\n\t } catch (e){\n\t // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n\t // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n\t return cachedClearTimeout.call(this, marker);\n\t }\n\t }\n\t\n\t\n\t\n\t}\n\tvar queue = [];\n\tvar draining = false;\n\tvar currentQueue;\n\tvar queueIndex = -1;\n\t\n\tfunction cleanUpNextTick() {\n\t if (!draining || !currentQueue) {\n\t return;\n\t }\n\t draining = false;\n\t if (currentQueue.length) {\n\t queue = currentQueue.concat(queue);\n\t } else {\n\t queueIndex = -1;\n\t }\n\t if (queue.length) {\n\t drainQueue();\n\t }\n\t}\n\t\n\tfunction drainQueue() {\n\t if (draining) {\n\t return;\n\t }\n\t var timeout = runTimeout(cleanUpNextTick);\n\t draining = true;\n\t\n\t var len = queue.length;\n\t while(len) {\n\t currentQueue = queue;\n\t queue = [];\n\t while (++queueIndex < len) {\n\t if (currentQueue) {\n\t currentQueue[queueIndex].run();\n\t }\n\t }\n\t queueIndex = -1;\n\t len = queue.length;\n\t }\n\t currentQueue = null;\n\t draining = false;\n\t runClearTimeout(timeout);\n\t}\n\t\n\tprocess.nextTick = function (fun) {\n\t var args = new Array(arguments.length - 1);\n\t if (arguments.length > 1) {\n\t for (var i = 1; i < arguments.length; i++) {\n\t args[i - 1] = arguments[i];\n\t }\n\t }\n\t queue.push(new Item(fun, args));\n\t if (queue.length === 1 && !draining) {\n\t runTimeout(drainQueue);\n\t }\n\t};\n\t\n\t// v8 likes predictible objects\n\tfunction Item(fun, array) {\n\t this.fun = fun;\n\t this.array = array;\n\t}\n\tItem.prototype.run = function () {\n\t this.fun.apply(null, this.array);\n\t};\n\tprocess.title = 'browser';\n\tprocess.browser = true;\n\tprocess.env = {};\n\tprocess.argv = [];\n\tprocess.version = ''; // empty string to avoid regexp issues\n\tprocess.versions = {};\n\t\n\tfunction noop() {}\n\t\n\tprocess.on = noop;\n\tprocess.addListener = noop;\n\tprocess.once = noop;\n\tprocess.off = noop;\n\tprocess.removeListener = noop;\n\tprocess.removeAllListeners = noop;\n\tprocess.emit = noop;\n\tprocess.prependListener = noop;\n\tprocess.prependOnceListener = noop;\n\t\n\tprocess.listeners = function (name) { return [] }\n\t\n\tprocess.binding = function (name) {\n\t throw new Error('process.binding is not supported');\n\t};\n\t\n\tprocess.cwd = function () { return '/' };\n\tprocess.chdir = function (dir) {\n\t throw new Error('process.chdir is not supported');\n\t};\n\tprocess.umask = function() { return 0; };\n\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(process) {/**\n\t * Copyright (c) 2013-present, Facebook, Inc.\n\t *\n\t * This source code is licensed under the MIT license found in the\n\t * LICENSE file in the root directory of this source tree.\n\t */\n\t\n\t'use strict';\n\t\n\tvar emptyFunction = __webpack_require__(7);\n\tvar invariant = __webpack_require__(8);\n\tvar warning = __webpack_require__(9);\n\tvar assign = __webpack_require__(10);\n\t\n\tvar ReactPropTypesSecret = __webpack_require__(11);\n\tvar checkPropTypes = __webpack_require__(12);\n\t\n\tmodule.exports = function(isValidElement, throwOnDirectAccess) {\n\t /* global Symbol */\n\t var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;\n\t var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.\n\t\n\t /**\n\t * Returns the iterator method function contained on the iterable object.\n\t *\n\t * Be sure to invoke the function with the iterable as context:\n\t *\n\t * var iteratorFn = getIteratorFn(myIterable);\n\t * if (iteratorFn) {\n\t * var iterator = iteratorFn.call(myIterable);\n\t * ...\n\t * }\n\t *\n\t * @param {?object} maybeIterable\n\t * @return {?function}\n\t */\n\t function getIteratorFn(maybeIterable) {\n\t var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);\n\t if (typeof iteratorFn === 'function') {\n\t return iteratorFn;\n\t }\n\t }\n\t\n\t /**\n\t * Collection of methods that allow declaration and validation of props that are\n\t * supplied to React components. Example usage:\n\t *\n\t * var Props = require('ReactPropTypes');\n\t * var MyArticle = React.createClass({\n\t * propTypes: {\n\t * // An optional string prop named \"description\".\n\t * description: Props.string,\n\t *\n\t * // A required enum prop named \"category\".\n\t * category: Props.oneOf(['News','Photos']).isRequired,\n\t *\n\t * // A prop named \"dialog\" that requires an instance of Dialog.\n\t * dialog: Props.instanceOf(Dialog).isRequired\n\t * },\n\t * render: function() { ... }\n\t * });\n\t *\n\t * A more formal specification of how these methods are used:\n\t *\n\t * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)\n\t * decl := ReactPropTypes.{type}(.isRequired)?\n\t *\n\t * Each and every declaration produces a function with the same signature. This\n\t * allows the creation of custom validation functions. For example:\n\t *\n\t * var MyLink = React.createClass({\n\t * propTypes: {\n\t * // An optional string or URI prop named \"href\".\n\t * href: function(props, propName, componentName) {\n\t * var propValue = props[propName];\n\t * if (propValue != null && typeof propValue !== 'string' &&\n\t * !(propValue instanceof URI)) {\n\t * return new Error(\n\t * 'Expected a string or an URI for ' + propName + ' in ' +\n\t * componentName\n\t * );\n\t * }\n\t * }\n\t * },\n\t * render: function() {...}\n\t * });\n\t *\n\t * @internal\n\t */\n\t\n\t var ANONYMOUS = '<>';\n\t\n\t // Important!\n\t // Keep this list in sync with production version in `./factoryWithThrowingShims.js`.\n\t var ReactPropTypes = {\n\t array: createPrimitiveTypeChecker('array'),\n\t bool: createPrimitiveTypeChecker('boolean'),\n\t func: createPrimitiveTypeChecker('function'),\n\t number: createPrimitiveTypeChecker('number'),\n\t object: createPrimitiveTypeChecker('object'),\n\t string: createPrimitiveTypeChecker('string'),\n\t symbol: createPrimitiveTypeChecker('symbol'),\n\t\n\t any: createAnyTypeChecker(),\n\t arrayOf: createArrayOfTypeChecker,\n\t element: createElementTypeChecker(),\n\t instanceOf: createInstanceTypeChecker,\n\t node: createNodeChecker(),\n\t objectOf: createObjectOfTypeChecker,\n\t oneOf: createEnumTypeChecker,\n\t oneOfType: createUnionTypeChecker,\n\t shape: createShapeTypeChecker,\n\t exact: createStrictShapeTypeChecker,\n\t };\n\t\n\t /**\n\t * inlined Object.is polyfill to avoid requiring consumers ship their own\n\t * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n\t */\n\t /*eslint-disable no-self-compare*/\n\t function is(x, y) {\n\t // SameValue algorithm\n\t if (x === y) {\n\t // Steps 1-5, 7-10\n\t // Steps 6.b-6.e: +0 != -0\n\t return x !== 0 || 1 / x === 1 / y;\n\t } else {\n\t // Step 6.a: NaN == NaN\n\t return x !== x && y !== y;\n\t }\n\t }\n\t /*eslint-enable no-self-compare*/\n\t\n\t /**\n\t * We use an Error-like object for backward compatibility as people may call\n\t * PropTypes directly and inspect their output. However, we don't use real\n\t * Errors anymore. We don't inspect their stack anyway, and creating them\n\t * is prohibitively expensive if they are created too often, such as what\n\t * happens in oneOfType() for any type before the one that matched.\n\t */\n\t function PropTypeError(message) {\n\t this.message = message;\n\t this.stack = '';\n\t }\n\t // Make `instanceof Error` still work for returned errors.\n\t PropTypeError.prototype = Error.prototype;\n\t\n\t function createChainableTypeChecker(validate) {\n\t if (process.env.NODE_ENV !== 'production') {\n\t var manualPropTypeCallCache = {};\n\t var manualPropTypeWarningCount = 0;\n\t }\n\t function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {\n\t componentName = componentName || ANONYMOUS;\n\t propFullName = propFullName || propName;\n\t\n\t if (secret !== ReactPropTypesSecret) {\n\t if (throwOnDirectAccess) {\n\t // New behavior only for users of `prop-types` package\n\t invariant(\n\t false,\n\t 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n\t 'Use `PropTypes.checkPropTypes()` to call them. ' +\n\t 'Read more at http://fb.me/use-check-prop-types'\n\t );\n\t } else if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined') {\n\t // Old behavior for people using React.PropTypes\n\t var cacheKey = componentName + ':' + propName;\n\t if (\n\t !manualPropTypeCallCache[cacheKey] &&\n\t // Avoid spamming the console because they are often not actionable except for lib authors\n\t manualPropTypeWarningCount < 3\n\t ) {\n\t warning(\n\t false,\n\t 'You are manually calling a React.PropTypes validation ' +\n\t 'function for the `%s` prop on `%s`. This is deprecated ' +\n\t 'and will throw in the standalone `prop-types` package. ' +\n\t 'You may be seeing this warning due to a third-party PropTypes ' +\n\t 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.',\n\t propFullName,\n\t componentName\n\t );\n\t manualPropTypeCallCache[cacheKey] = true;\n\t manualPropTypeWarningCount++;\n\t }\n\t }\n\t }\n\t if (props[propName] == null) {\n\t if (isRequired) {\n\t if (props[propName] === null) {\n\t return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));\n\t }\n\t return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));\n\t }\n\t return null;\n\t } else {\n\t return validate(props, propName, componentName, location, propFullName);\n\t }\n\t }\n\t\n\t var chainedCheckType = checkType.bind(null, false);\n\t chainedCheckType.isRequired = checkType.bind(null, true);\n\t\n\t return chainedCheckType;\n\t }\n\t\n\t function createPrimitiveTypeChecker(expectedType) {\n\t function validate(props, propName, componentName, location, propFullName, secret) {\n\t var propValue = props[propName];\n\t var propType = getPropType(propValue);\n\t if (propType !== expectedType) {\n\t // `propValue` being instance of, say, date/regexp, pass the 'object'\n\t // check, but we can offer a more precise error message here rather than\n\t // 'of type `object`'.\n\t var preciseType = getPreciseType(propValue);\n\t\n\t return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));\n\t }\n\t return null;\n\t }\n\t return createChainableTypeChecker(validate);\n\t }\n\t\n\t function createAnyTypeChecker() {\n\t return createChainableTypeChecker(emptyFunction.thatReturnsNull);\n\t }\n\t\n\t function createArrayOfTypeChecker(typeChecker) {\n\t function validate(props, propName, componentName, location, propFullName) {\n\t if (typeof typeChecker !== 'function') {\n\t return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');\n\t }\n\t var propValue = props[propName];\n\t if (!Array.isArray(propValue)) {\n\t var propType = getPropType(propValue);\n\t return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));\n\t }\n\t for (var i = 0; i < propValue.length; i++) {\n\t var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);\n\t if (error instanceof Error) {\n\t return error;\n\t }\n\t }\n\t return null;\n\t }\n\t return createChainableTypeChecker(validate);\n\t }\n\t\n\t function createElementTypeChecker() {\n\t function validate(props, propName, componentName, location, propFullName) {\n\t var propValue = props[propName];\n\t if (!isValidElement(propValue)) {\n\t var propType = getPropType(propValue);\n\t return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));\n\t }\n\t return null;\n\t }\n\t return createChainableTypeChecker(validate);\n\t }\n\t\n\t function createInstanceTypeChecker(expectedClass) {\n\t function validate(props, propName, componentName, location, propFullName) {\n\t if (!(props[propName] instanceof expectedClass)) {\n\t var expectedClassName = expectedClass.name || ANONYMOUS;\n\t var actualClassName = getClassName(props[propName]);\n\t return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));\n\t }\n\t return null;\n\t }\n\t return createChainableTypeChecker(validate);\n\t }\n\t\n\t function createEnumTypeChecker(expectedValues) {\n\t if (!Array.isArray(expectedValues)) {\n\t process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0;\n\t return emptyFunction.thatReturnsNull;\n\t }\n\t\n\t function validate(props, propName, componentName, location, propFullName) {\n\t var propValue = props[propName];\n\t for (var i = 0; i < expectedValues.length; i++) {\n\t if (is(propValue, expectedValues[i])) {\n\t return null;\n\t }\n\t }\n\t\n\t var valuesString = JSON.stringify(expectedValues);\n\t return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));\n\t }\n\t return createChainableTypeChecker(validate);\n\t }\n\t\n\t function createObjectOfTypeChecker(typeChecker) {\n\t function validate(props, propName, componentName, location, propFullName) {\n\t if (typeof typeChecker !== 'function') {\n\t return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');\n\t }\n\t var propValue = props[propName];\n\t var propType = getPropType(propValue);\n\t if (propType !== 'object') {\n\t return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));\n\t }\n\t for (var key in propValue) {\n\t if (propValue.hasOwnProperty(key)) {\n\t var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);\n\t if (error instanceof Error) {\n\t return error;\n\t }\n\t }\n\t }\n\t return null;\n\t }\n\t return createChainableTypeChecker(validate);\n\t }\n\t\n\t function createUnionTypeChecker(arrayOfTypeCheckers) {\n\t if (!Array.isArray(arrayOfTypeCheckers)) {\n\t process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0;\n\t return emptyFunction.thatReturnsNull;\n\t }\n\t\n\t for (var i = 0; i < arrayOfTypeCheckers.length; i++) {\n\t var checker = arrayOfTypeCheckers[i];\n\t if (typeof checker !== 'function') {\n\t warning(\n\t false,\n\t 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +\n\t 'received %s at index %s.',\n\t getPostfixForTypeWarning(checker),\n\t i\n\t );\n\t return emptyFunction.thatReturnsNull;\n\t }\n\t }\n\t\n\t function validate(props, propName, componentName, location, propFullName) {\n\t for (var i = 0; i < arrayOfTypeCheckers.length; i++) {\n\t var checker = arrayOfTypeCheckers[i];\n\t if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) {\n\t return null;\n\t }\n\t }\n\t\n\t return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));\n\t }\n\t return createChainableTypeChecker(validate);\n\t }\n\t\n\t function createNodeChecker() {\n\t function validate(props, propName, componentName, location, propFullName) {\n\t if (!isNode(props[propName])) {\n\t return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));\n\t }\n\t return null;\n\t }\n\t return createChainableTypeChecker(validate);\n\t }\n\t\n\t function createShapeTypeChecker(shapeTypes) {\n\t function validate(props, propName, componentName, location, propFullName) {\n\t var propValue = props[propName];\n\t var propType = getPropType(propValue);\n\t if (propType !== 'object') {\n\t return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));\n\t }\n\t for (var key in shapeTypes) {\n\t var checker = shapeTypes[key];\n\t if (!checker) {\n\t continue;\n\t }\n\t var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);\n\t if (error) {\n\t return error;\n\t }\n\t }\n\t return null;\n\t }\n\t return createChainableTypeChecker(validate);\n\t }\n\t\n\t function createStrictShapeTypeChecker(shapeTypes) {\n\t function validate(props, propName, componentName, location, propFullName) {\n\t var propValue = props[propName];\n\t var propType = getPropType(propValue);\n\t if (propType !== 'object') {\n\t return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));\n\t }\n\t // We need to check all keys in case some are required but missing from\n\t // props.\n\t var allKeys = assign({}, props[propName], shapeTypes);\n\t for (var key in allKeys) {\n\t var checker = shapeTypes[key];\n\t if (!checker) {\n\t return new PropTypeError(\n\t 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +\n\t '\\nBad object: ' + JSON.stringify(props[propName], null, ' ') +\n\t '\\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')\n\t );\n\t }\n\t var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);\n\t if (error) {\n\t return error;\n\t }\n\t }\n\t return null;\n\t }\n\t\n\t return createChainableTypeChecker(validate);\n\t }\n\t\n\t function isNode(propValue) {\n\t switch (typeof propValue) {\n\t case 'number':\n\t case 'string':\n\t case 'undefined':\n\t return true;\n\t case 'boolean':\n\t return !propValue;\n\t case 'object':\n\t if (Array.isArray(propValue)) {\n\t return propValue.every(isNode);\n\t }\n\t if (propValue === null || isValidElement(propValue)) {\n\t return true;\n\t }\n\t\n\t var iteratorFn = getIteratorFn(propValue);\n\t if (iteratorFn) {\n\t var iterator = iteratorFn.call(propValue);\n\t var step;\n\t if (iteratorFn !== propValue.entries) {\n\t while (!(step = iterator.next()).done) {\n\t if (!isNode(step.value)) {\n\t return false;\n\t }\n\t }\n\t } else {\n\t // Iterator will provide entry [k,v] tuples rather than values.\n\t while (!(step = iterator.next()).done) {\n\t var entry = step.value;\n\t if (entry) {\n\t if (!isNode(entry[1])) {\n\t return false;\n\t }\n\t }\n\t }\n\t }\n\t } else {\n\t return false;\n\t }\n\t\n\t return true;\n\t default:\n\t return false;\n\t }\n\t }\n\t\n\t function isSymbol(propType, propValue) {\n\t // Native Symbol.\n\t if (propType === 'symbol') {\n\t return true;\n\t }\n\t\n\t // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'\n\t if (propValue['@@toStringTag'] === 'Symbol') {\n\t return true;\n\t }\n\t\n\t // Fallback for non-spec compliant Symbols which are polyfilled.\n\t if (typeof Symbol === 'function' && propValue instanceof Symbol) {\n\t return true;\n\t }\n\t\n\t return false;\n\t }\n\t\n\t // Equivalent of `typeof` but with special handling for array and regexp.\n\t function getPropType(propValue) {\n\t var propType = typeof propValue;\n\t if (Array.isArray(propValue)) {\n\t return 'array';\n\t }\n\t if (propValue instanceof RegExp) {\n\t // Old webkits (at least until Android 4.0) return 'function' rather than\n\t // 'object' for typeof a RegExp. We'll normalize this here so that /bla/\n\t // passes PropTypes.object.\n\t return 'object';\n\t }\n\t if (isSymbol(propType, propValue)) {\n\t return 'symbol';\n\t }\n\t return propType;\n\t }\n\t\n\t // This handles more types than `getPropType`. Only used for error messages.\n\t // See `createPrimitiveTypeChecker`.\n\t function getPreciseType(propValue) {\n\t if (typeof propValue === 'undefined' || propValue === null) {\n\t return '' + propValue;\n\t }\n\t var propType = getPropType(propValue);\n\t if (propType === 'object') {\n\t if (propValue instanceof Date) {\n\t return 'date';\n\t } else if (propValue instanceof RegExp) {\n\t return 'regexp';\n\t }\n\t }\n\t return propType;\n\t }\n\t\n\t // Returns a string that is postfixed to a warning about an invalid type.\n\t // For example, \"undefined\" or \"of type array\"\n\t function getPostfixForTypeWarning(value) {\n\t var type = getPreciseType(value);\n\t switch (type) {\n\t case 'array':\n\t case 'object':\n\t return 'an ' + type;\n\t case 'boolean':\n\t case 'date':\n\t case 'regexp':\n\t return 'a ' + type;\n\t default:\n\t return type;\n\t }\n\t }\n\t\n\t // Returns class name of the object, if any.\n\t function getClassName(propValue) {\n\t if (!propValue.constructor || !propValue.constructor.name) {\n\t return ANONYMOUS;\n\t }\n\t return propValue.constructor.name;\n\t }\n\t\n\t ReactPropTypes.checkPropTypes = checkPropTypes;\n\t ReactPropTypes.PropTypes = ReactPropTypes;\n\t\n\t return ReactPropTypes;\n\t};\n\t\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5)))\n\n/***/ }),\n/* 7 */\n/***/ (function(module, exports) {\n\n\t\"use strict\";\n\t\n\t/**\n\t * Copyright (c) 2013-present, Facebook, Inc.\n\t *\n\t * This source code is licensed under the MIT license found in the\n\t * LICENSE file in the root directory of this source tree.\n\t *\n\t * \n\t */\n\t\n\tfunction makeEmptyFunction(arg) {\n\t return function () {\n\t return arg;\n\t };\n\t}\n\t\n\t/**\n\t * This function accepts and discards inputs; it has no side effects. This is\n\t * primarily useful idiomatically for overridable function endpoints which\n\t * always need to be callable, since JS lacks a null-call idiom ala Cocoa.\n\t */\n\tvar emptyFunction = function emptyFunction() {};\n\t\n\temptyFunction.thatReturns = makeEmptyFunction;\n\temptyFunction.thatReturnsFalse = makeEmptyFunction(false);\n\temptyFunction.thatReturnsTrue = makeEmptyFunction(true);\n\temptyFunction.thatReturnsNull = makeEmptyFunction(null);\n\temptyFunction.thatReturnsThis = function () {\n\t return this;\n\t};\n\temptyFunction.thatReturnsArgument = function (arg) {\n\t return arg;\n\t};\n\t\n\tmodule.exports = emptyFunction;\n\n/***/ }),\n/* 8 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(process) {/**\n\t * Copyright (c) 2013-present, Facebook, Inc.\n\t *\n\t * This source code is licensed under the MIT license found in the\n\t * LICENSE file in the root directory of this source tree.\n\t *\n\t */\n\t\n\t'use strict';\n\t\n\t/**\n\t * Use invariant() to assert state which your program assumes to be true.\n\t *\n\t * Provide sprintf-style format (only %s is supported) and arguments\n\t * to provide information about what broke and what you were\n\t * expecting.\n\t *\n\t * The invariant message will be stripped in production, but the invariant\n\t * will remain to ensure logic does not differ in production.\n\t */\n\t\n\tvar validateFormat = function validateFormat(format) {};\n\t\n\tif (process.env.NODE_ENV !== 'production') {\n\t validateFormat = function validateFormat(format) {\n\t if (format === undefined) {\n\t throw new Error('invariant requires an error message argument');\n\t }\n\t };\n\t}\n\t\n\tfunction invariant(condition, format, a, b, c, d, e, f) {\n\t validateFormat(format);\n\t\n\t if (!condition) {\n\t var error;\n\t if (format === undefined) {\n\t error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');\n\t } else {\n\t var args = [a, b, c, d, e, f];\n\t var argIndex = 0;\n\t error = new Error(format.replace(/%s/g, function () {\n\t return args[argIndex++];\n\t }));\n\t error.name = 'Invariant Violation';\n\t }\n\t\n\t error.framesToPop = 1; // we don't care about invariant's own frame\n\t throw error;\n\t }\n\t}\n\t\n\tmodule.exports = invariant;\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5)))\n\n/***/ }),\n/* 9 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(process) {/**\n\t * Copyright (c) 2014-present, Facebook, Inc.\n\t *\n\t * This source code is licensed under the MIT license found in the\n\t * LICENSE file in the root directory of this source tree.\n\t *\n\t */\n\t\n\t'use strict';\n\t\n\tvar emptyFunction = __webpack_require__(7);\n\t\n\t/**\n\t * Similar to invariant but only logs a warning if the condition is not met.\n\t * This can be used to log issues in development environments in critical\n\t * paths. Removing the logging code for production environments will keep the\n\t * same logic and follow the same code paths.\n\t */\n\t\n\tvar warning = emptyFunction;\n\t\n\tif (process.env.NODE_ENV !== 'production') {\n\t var printWarning = function printWarning(format) {\n\t for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n\t args[_key - 1] = arguments[_key];\n\t }\n\t\n\t var argIndex = 0;\n\t var message = 'Warning: ' + format.replace(/%s/g, function () {\n\t return args[argIndex++];\n\t });\n\t if (typeof console !== 'undefined') {\n\t console.error(message);\n\t }\n\t try {\n\t // --- Welcome to debugging React ---\n\t // This error was thrown as a convenience so that you can use this stack\n\t // to find the callsite that caused this warning to fire.\n\t throw new Error(message);\n\t } catch (x) {}\n\t };\n\t\n\t warning = function warning(condition, format) {\n\t if (format === undefined) {\n\t throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');\n\t }\n\t\n\t if (format.indexOf('Failed Composite propType: ') === 0) {\n\t return; // Ignore CompositeComponent proptype check.\n\t }\n\t\n\t if (!condition) {\n\t for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {\n\t args[_key2 - 2] = arguments[_key2];\n\t }\n\t\n\t printWarning.apply(undefined, [format].concat(args));\n\t }\n\t };\n\t}\n\t\n\tmodule.exports = warning;\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5)))\n\n/***/ }),\n/* 10 */\n/***/ (function(module, exports) {\n\n\t/*\n\tobject-assign\n\t(c) Sindre Sorhus\n\t@license MIT\n\t*/\n\t\n\t'use strict';\n\t/* eslint-disable no-unused-vars */\n\tvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\n\tvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\tvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\t\n\tfunction toObject(val) {\n\t\tif (val === null || val === undefined) {\n\t\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t\t}\n\t\n\t\treturn Object(val);\n\t}\n\t\n\tfunction shouldUseNative() {\n\t\ttry {\n\t\t\tif (!Object.assign) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\n\t\t\t// Detect buggy property enumeration order in older V8 versions.\n\t\n\t\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\t\tvar test1 = new String('abc'); // eslint-disable-line no-new-wrappers\n\t\t\ttest1[5] = 'de';\n\t\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\t\treturn false;\n\t\t\t}\n\t\n\t\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\t\tvar test2 = {};\n\t\t\tfor (var i = 0; i < 10; i++) {\n\t\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t\t}\n\t\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\t\treturn test2[n];\n\t\t\t});\n\t\t\tif (order2.join('') !== '0123456789') {\n\t\t\t\treturn false;\n\t\t\t}\n\t\n\t\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\t\tvar test3 = {};\n\t\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\t\ttest3[letter] = letter;\n\t\t\t});\n\t\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\t\treturn false;\n\t\t\t}\n\t\n\t\t\treturn true;\n\t\t} catch (err) {\n\t\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\t\tvar from;\n\t\tvar to = toObject(target);\n\t\tvar symbols;\n\t\n\t\tfor (var s = 1; s < arguments.length; s++) {\n\t\t\tfrom = Object(arguments[s]);\n\t\n\t\t\tfor (var key in from) {\n\t\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\t\tto[key] = from[key];\n\t\t\t\t}\n\t\t\t}\n\t\n\t\t\tif (getOwnPropertySymbols) {\n\t\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\t\treturn to;\n\t};\n\n\n/***/ }),\n/* 11 */\n/***/ (function(module, exports) {\n\n\t/**\n\t * Copyright (c) 2013-present, Facebook, Inc.\n\t *\n\t * This source code is licensed under the MIT license found in the\n\t * LICENSE file in the root directory of this source tree.\n\t */\n\t\n\t'use strict';\n\t\n\tvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\t\n\tmodule.exports = ReactPropTypesSecret;\n\n\n/***/ }),\n/* 12 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(process) {/**\n\t * Copyright (c) 2013-present, Facebook, Inc.\n\t *\n\t * This source code is licensed under the MIT license found in the\n\t * LICENSE file in the root directory of this source tree.\n\t */\n\t\n\t'use strict';\n\t\n\tif (process.env.NODE_ENV !== 'production') {\n\t var invariant = __webpack_require__(8);\n\t var warning = __webpack_require__(9);\n\t var ReactPropTypesSecret = __webpack_require__(11);\n\t var loggedTypeFailures = {};\n\t}\n\t\n\t/**\n\t * Assert that the values match with the type specs.\n\t * Error messages are memorized and will only be shown once.\n\t *\n\t * @param {object} typeSpecs Map of name to a ReactPropType\n\t * @param {object} values Runtime values that need to be type-checked\n\t * @param {string} location e.g. \"prop\", \"context\", \"child context\"\n\t * @param {string} componentName Name of the component for error messages.\n\t * @param {?Function} getStack Returns the component stack.\n\t * @private\n\t */\n\tfunction checkPropTypes(typeSpecs, values, location, componentName, getStack) {\n\t if (process.env.NODE_ENV !== 'production') {\n\t for (var typeSpecName in typeSpecs) {\n\t if (typeSpecs.hasOwnProperty(typeSpecName)) {\n\t var error;\n\t // Prop type validation may throw. In case they do, we don't want to\n\t // fail the render phase where it didn't fail before. So we log it.\n\t // After these have been cleaned up, we'll let them throw.\n\t try {\n\t // This is intentionally an invariant that gets caught. It's the same\n\t // behavior as without this statement except with a better message.\n\t invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'the `prop-types` package, but received `%s`.', componentName || 'React class', location, typeSpecName, typeof typeSpecs[typeSpecName]);\n\t error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);\n\t } catch (ex) {\n\t error = ex;\n\t }\n\t warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error);\n\t if (error instanceof Error && !(error.message in loggedTypeFailures)) {\n\t // Only monitor this failure once because there tends to be a lot of the\n\t // same error.\n\t loggedTypeFailures[error.message] = true;\n\t\n\t var stack = getStack ? getStack() : '';\n\t\n\t warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : '');\n\t }\n\t }\n\t }\n\t }\n\t}\n\t\n\tmodule.exports = checkPropTypes;\n\t\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5)))\n\n/***/ }),\n/* 13 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/**\n\t * Copyright (c) 2013-present, Facebook, Inc.\n\t *\n\t * This source code is licensed under the MIT license found in the\n\t * LICENSE file in the root directory of this source tree.\n\t */\n\t\n\t'use strict';\n\t\n\tvar emptyFunction = __webpack_require__(7);\n\tvar invariant = __webpack_require__(8);\n\tvar ReactPropTypesSecret = __webpack_require__(11);\n\t\n\tmodule.exports = function() {\n\t function shim(props, propName, componentName, location, propFullName, secret) {\n\t if (secret === ReactPropTypesSecret) {\n\t // It is still safe when called from React.\n\t return;\n\t }\n\t invariant(\n\t false,\n\t 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n\t 'Use PropTypes.checkPropTypes() to call them. ' +\n\t 'Read more at http://fb.me/use-check-prop-types'\n\t );\n\t };\n\t shim.isRequired = shim;\n\t function getShim() {\n\t return shim;\n\t };\n\t // Important!\n\t // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.\n\t var ReactPropTypes = {\n\t array: shim,\n\t bool: shim,\n\t func: shim,\n\t number: shim,\n\t object: shim,\n\t string: shim,\n\t symbol: shim,\n\t\n\t any: shim,\n\t arrayOf: getShim,\n\t element: shim,\n\t instanceOf: getShim,\n\t node: shim,\n\t objectOf: getShim,\n\t oneOf: getShim,\n\t oneOfType: getShim,\n\t shape: getShim,\n\t exact: getShim\n\t };\n\t\n\t ReactPropTypes.checkPropTypes = emptyFunction;\n\t ReactPropTypes.PropTypes = ReactPropTypes;\n\t\n\t return ReactPropTypes;\n\t};\n\n\n/***/ }),\n/* 14 */\n/***/ (function(module, exports) {\n\n\tmodule.exports = require(\"react\");\n\n/***/ }),\n/* 15 */\n/***/ (function(module, exports) {\n\n\t'use strict';\n\t\n\tvar simpleIsEqual = function simpleIsEqual(a, b) {\n\t return a === b;\n\t};\n\t\n\tfunction index (resultFn) {\n\t var isEqual = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : simpleIsEqual;\n\t\n\t var lastThis = void 0;\n\t var lastArgs = [];\n\t var lastResult = void 0;\n\t var calledOnce = false;\n\t\n\t var isNewArgEqualToLast = function isNewArgEqualToLast(newArg, index) {\n\t return isEqual(newArg, lastArgs[index]);\n\t };\n\t\n\t var result = function result() {\n\t for (var _len = arguments.length, newArgs = Array(_len), _key = 0; _key < _len; _key++) {\n\t newArgs[_key] = arguments[_key];\n\t }\n\t\n\t if (calledOnce && lastThis === this && newArgs.length === lastArgs.length && newArgs.every(isNewArgEqualToLast)) {\n\t return lastResult;\n\t }\n\t\n\t calledOnce = true;\n\t lastThis = this;\n\t lastArgs = newArgs;\n\t lastResult = resultFn.apply(this, newArgs);\n\t return lastResult;\n\t };\n\t\n\t return result;\n\t}\n\t\n\tmodule.exports = index;\n\n\n/***/ })\n/******/ ]);\n//# sourceMappingURL=main.js.map","'use strict';\n\nvar isArrayish = require('is-arrayish');\n\nvar concat = Array.prototype.concat;\nvar slice = Array.prototype.slice;\n\nvar swizzle = module.exports = function swizzle(args) {\n\tvar results = [];\n\n\tfor (var i = 0, len = args.length; i < len; i++) {\n\t\tvar arg = args[i];\n\n\t\tif (isArrayish(arg)) {\n\t\t\t// http://jsperf.com/javascript-array-concat-vs-push/98\n\t\t\tresults = concat.call(results, slice.call(arg));\n\t\t} else {\n\t\t\tresults.push(arg);\n\t\t}\n\t}\n\n\treturn results;\n};\n\nswizzle.wrap = function (fn) {\n\treturn function () {\n\t\treturn fn(swizzle(arguments));\n\t};\n};\n","module.exports = function isArrayish(obj) {\n\tif (!obj || typeof obj === 'string') {\n\t\treturn false;\n\t}\n\n\treturn obj instanceof Array || Array.isArray(obj) ||\n\t\t(obj.length >= 0 && (obj.splice instanceof Function ||\n\t\t\t(Object.getOwnPropertyDescriptor(obj, (obj.length - 1)) && obj.constructor.name !== 'String')));\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar typestyle_1 = require(\"./internal/typestyle\");\nexports.TypeStyle = typestyle_1.TypeStyle;\n/**\n * All the CSS types in the 'types' namespace\n */\nvar types = require(\"./types\");\nexports.types = types;\n/**\n * Export certain utilities\n */\nvar utilities_1 = require(\"./internal/utilities\");\nexports.extend = utilities_1.extend;\nexports.classes = utilities_1.classes;\nexports.media = utilities_1.media;\n/** Zero configuration, default instance of TypeStyle */\nvar ts = new typestyle_1.TypeStyle({ autoGenerateTag: true });\n/** Sets the target tag where we write the css on style updates */\nexports.setStylesTarget = ts.setStylesTarget;\n/**\n * Insert `raw` CSS as a string. This is useful for e.g.\n * - third party CSS that you are customizing with template strings\n * - generating raw CSS in JavaScript\n * - reset libraries like normalize.css that you can use without loaders\n */\nexports.cssRaw = ts.cssRaw;\n/**\n * Takes CSSProperties and registers it to a global selector (body, html, etc.)\n */\nexports.cssRule = ts.cssRule;\n/**\n * Renders styles to the singleton tag imediately\n * NOTE: You should only call it on initial render to prevent any non CSS flash.\n * After that it is kept sync using `requestAnimationFrame` and we haven't noticed any bad flashes.\n **/\nexports.forceRenderStyles = ts.forceRenderStyles;\n/**\n * Utility function to register an @font-face\n */\nexports.fontFace = ts.fontFace;\n/**\n * Allows use to use the stylesheet in a node.js environment\n */\nexports.getStyles = ts.getStyles;\n/**\n * Takes keyframes and returns a generated animationName\n */\nexports.keyframes = ts.keyframes;\n/**\n * Helps with testing. Reinitializes FreeStyle + raw\n */\nexports.reinit = ts.reinit;\n/**\n * Takes CSSProperties and return a generated className you can use on your component\n */\nexports.style = ts.style;\n/**\n * Takes an object where property names are ideal class names and property values are CSSProperties, and\n * returns an object where property names are the same ideal class names and the property values are\n * the actual generated class names using the ideal class name as the $debugName\n */\nexports.stylesheet = ts.stylesheet;\n/**\n * Creates a new instance of TypeStyle separate from the default instance.\n *\n * - Use this for creating a different typestyle instance for a shadow dom component.\n * - Use this if you don't want an auto tag generated and you just want to collect the CSS.\n *\n * NOTE: styles aren't shared between different instances.\n */\nfunction createTypeStyle(target) {\n var instance = new typestyle_1.TypeStyle({ autoGenerateTag: false });\n if (target) {\n instance.setStylesTarget(target);\n }\n return instance;\n}\nexports.createTypeStyle = createTypeStyle;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * We need to do the following to *our* objects before passing to freestyle:\n * - For any `$nest` directive move up to FreeStyle style nesting\n * - For any `$unique` directive map to FreeStyle Unique\n * - For any `$debugName` directive return the debug name\n */\nfunction convertToStyles(object) {\n /** The final result we will return */\n var styles = {};\n for (var key in object) {\n /** Grab the value upfront */\n var val = object[key];\n /** TypeStyle configuration options */\n if (key === '$nest') {\n var nested = val;\n for (var selector in nested) {\n var subproperties = nested[selector];\n styles[selector] = convertToStyles(subproperties);\n }\n }\n else if (key === '$debugName') {\n styles.$displayName = val;\n }\n else {\n styles[key] = val;\n }\n }\n return styles;\n}\nexports.convertToStyles = convertToStyles;\n// todo: better name here\nfunction convertToKeyframes(frames) {\n var result = {};\n for (var offset in frames) {\n if (offset !== '$debugName') {\n result[offset] = frames[offset];\n }\n }\n if (frames.$debugName) {\n result.$displayName = frames.$debugName;\n }\n return result;\n}\nexports.convertToKeyframes = convertToKeyframes;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar FreeStyle = require(\"free-style\");\nvar formatting_1 = require(\"./formatting\");\nvar utilities_1 = require(\"./utilities\");\n/**\n * Creates an instance of free style with our options\n */\nvar createFreeStyle = function () { return FreeStyle.create(); };\n/**\n * Maintains a single stylesheet and keeps it in sync with requested styles\n */\nvar TypeStyle = /** @class */ (function () {\n function TypeStyle(_a) {\n var _this = this;\n var autoGenerateTag = _a.autoGenerateTag;\n /**\n * Insert `raw` CSS as a string. This is useful for e.g.\n * - third party CSS that you are customizing with template strings\n * - generating raw CSS in JavaScript\n * - reset libraries like normalize.css that you can use without loaders\n */\n this.cssRaw = function (mustBeValidCSS) {\n if (!mustBeValidCSS) {\n return;\n }\n _this._raw += mustBeValidCSS || '';\n _this._pendingRawChange = true;\n _this._styleUpdated();\n };\n /**\n * Takes CSSProperties and registers it to a global selector (body, html, etc.)\n */\n this.cssRule = function (selector) {\n var objects = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n objects[_i - 1] = arguments[_i];\n }\n var styles = formatting_1.convertToStyles(utilities_1.extend.apply(void 0, objects));\n _this._freeStyle.registerRule(selector, styles);\n _this._styleUpdated();\n return;\n };\n /**\n * Renders styles to the singleton tag imediately\n * NOTE: You should only call it on initial render to prevent any non CSS flash.\n * After that it is kept sync using `requestAnimationFrame` and we haven't noticed any bad flashes.\n **/\n this.forceRenderStyles = function () {\n var target = _this._getTag();\n if (!target) {\n return;\n }\n target.textContent = _this.getStyles();\n };\n /**\n * Utility function to register an @font-face\n */\n this.fontFace = function () {\n var fontFace = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n fontFace[_i] = arguments[_i];\n }\n var freeStyle = _this._freeStyle;\n for (var _a = 0, _b = fontFace; _a < _b.length; _a++) {\n var face = _b[_a];\n freeStyle.registerRule('@font-face', face);\n }\n _this._styleUpdated();\n return;\n };\n /**\n * Allows use to use the stylesheet in a node.js environment\n */\n this.getStyles = function () {\n return (_this._raw || '') + _this._freeStyle.getStyles();\n };\n /**\n * Takes keyframes and returns a generated animationName\n */\n this.keyframes = function (frames) {\n var keyframes = formatting_1.convertToKeyframes(frames);\n // TODO: replace $debugName with display name\n var animationName = _this._freeStyle.registerKeyframes(keyframes);\n _this._styleUpdated();\n return animationName;\n };\n /**\n * Helps with testing. Reinitializes FreeStyle + raw\n */\n this.reinit = function () {\n /** reinit freestyle */\n var freeStyle = createFreeStyle();\n _this._freeStyle = freeStyle;\n _this._lastFreeStyleChangeId = freeStyle.changeId;\n /** reinit raw */\n _this._raw = '';\n _this._pendingRawChange = false;\n /** Clear any styles that were flushed */\n var target = _this._getTag();\n if (target) {\n target.textContent = '';\n }\n };\n /** Sets the target tag where we write the css on style updates */\n this.setStylesTarget = function (tag) {\n /** Clear any data in any previous tag */\n if (_this._tag) {\n _this._tag.textContent = '';\n }\n _this._tag = tag;\n /** This special time buffer immediately */\n _this.forceRenderStyles();\n };\n /**\n * Takes an object where property names are ideal class names and property values are CSSProperties, and\n * returns an object where property names are the same ideal class names and the property values are\n * the actual generated class names using the ideal class name as the $debugName\n */\n this.stylesheet = function (classes) {\n var classNames = Object.getOwnPropertyNames(classes);\n var result = {};\n for (var _i = 0, classNames_1 = classNames; _i < classNames_1.length; _i++) {\n var className = classNames_1[_i];\n var classDef = classes[className];\n if (classDef) {\n classDef.$debugName = className;\n result[className] = _this.style(classDef);\n }\n }\n return result;\n };\n var freeStyle = createFreeStyle();\n this._autoGenerateTag = autoGenerateTag;\n this._freeStyle = freeStyle;\n this._lastFreeStyleChangeId = freeStyle.changeId;\n this._pending = 0;\n this._pendingRawChange = false;\n this._raw = '';\n this._tag = undefined;\n // rebind prototype to TypeStyle. It might be better to do a function() { return this.style.apply(this, arguments)}\n this.style = this.style.bind(this);\n }\n /**\n * Only calls cb all sync operations settle\n */\n TypeStyle.prototype._afterAllSync = function (cb) {\n var _this = this;\n this._pending++;\n var pending = this._pending;\n utilities_1.raf(function () {\n if (pending !== _this._pending) {\n return;\n }\n cb();\n });\n };\n TypeStyle.prototype._getTag = function () {\n if (this._tag) {\n return this._tag;\n }\n if (this._autoGenerateTag) {\n var tag = typeof window === 'undefined'\n ? { textContent: '' }\n : document.createElement('style');\n if (typeof document !== 'undefined') {\n document.head.appendChild(tag);\n }\n this._tag = tag;\n return tag;\n }\n return undefined;\n };\n /** Checks if the style tag needs updating and if so queues up the change */\n TypeStyle.prototype._styleUpdated = function () {\n var _this = this;\n var changeId = this._freeStyle.changeId;\n var lastChangeId = this._lastFreeStyleChangeId;\n if (!this._pendingRawChange && changeId === lastChangeId) {\n return;\n }\n this._lastFreeStyleChangeId = changeId;\n this._pendingRawChange = false;\n this._afterAllSync(function () { return _this.forceRenderStyles(); });\n };\n TypeStyle.prototype.style = function () {\n var className = this._freeStyle.registerStyle(formatting_1.convertToStyles(utilities_1.extend.apply(undefined, arguments)));\n this._styleUpdated();\n return className;\n };\n return TypeStyle;\n}());\nexports.TypeStyle = TypeStyle;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/** Raf for node + browser */\nexports.raf = typeof requestAnimationFrame === 'undefined'\n /**\n * Make sure setTimeout is always invoked with\n * `this` set to `window` or `global` automatically\n **/\n ? function (cb) { return setTimeout(cb); }\n /**\n * Make sure window.requestAnimationFrame is always invoked with `this` window\n * We might have raf without window in case of `raf/polyfill` (recommended by React)\n **/\n : typeof window === 'undefined'\n ? requestAnimationFrame\n : requestAnimationFrame.bind(window);\n/**\n * Utility to join classes conditionally\n */\nfunction classes() {\n var classes = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n classes[_i] = arguments[_i];\n }\n return classes\n .map(function (c) { return c && typeof c === 'object' ? Object.keys(c).map(function (key) { return !!c[key] && key; }) : [c]; })\n .reduce(function (flattened, c) { return flattened.concat(c); }, [])\n .filter(function (c) { return !!c; })\n .join(' ');\n}\nexports.classes = classes;\n/**\n * Merges various styles into a single style object.\n * Note: if two objects have the same property the last one wins\n */\nfunction extend() {\n var objects = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n objects[_i] = arguments[_i];\n }\n /** The final result we will return */\n var result = {};\n for (var _a = 0, objects_1 = objects; _a < objects_1.length; _a++) {\n var object = objects_1[_a];\n if (object == null || object === false) {\n continue;\n }\n for (var key in object) {\n /** Falsy values except a explicit 0 is ignored */\n var val = object[key];\n if (!val && val !== 0) {\n continue;\n }\n /** if nested media or pseudo selector */\n if (key === '$nest' && val) {\n result[key] = result['$nest'] ? extend(result['$nest'], val) : val;\n }\n /** if freestyle sub key that needs merging. We come here due to our recursive calls */\n else if ((key.indexOf('&') !== -1 || key.indexOf('@media') === 0)) {\n result[key] = result[key] ? extend(result[key], val) : val;\n }\n else {\n result[key] = val;\n }\n }\n }\n return result;\n}\nexports.extend = extend;\n/**\n * Utility to help customize styles with media queries. e.g.\n * ```\n * style(\n * media({maxWidth:500}, {color:'red'})\n * )\n * ```\n */\nexports.media = function (mediaQuery) {\n var _a;\n var objects = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n objects[_i - 1] = arguments[_i];\n }\n var mediaQuerySections = [];\n if (mediaQuery.type)\n mediaQuerySections.push(mediaQuery.type);\n if (mediaQuery.orientation)\n mediaQuerySections.push(\"(orientation: \" + mediaQuery.orientation + \")\");\n if (mediaQuery.minWidth)\n mediaQuerySections.push(\"(min-width: \" + mediaLength(mediaQuery.minWidth) + \")\");\n if (mediaQuery.maxWidth)\n mediaQuerySections.push(\"(max-width: \" + mediaLength(mediaQuery.maxWidth) + \")\");\n if (mediaQuery.minHeight)\n mediaQuerySections.push(\"(min-height: \" + mediaLength(mediaQuery.minHeight) + \")\");\n if (mediaQuery.maxHeight)\n mediaQuerySections.push(\"(max-height: \" + mediaLength(mediaQuery.maxHeight) + \")\");\n if (mediaQuery.prefersColorScheme)\n mediaQuerySections.push(\"(prefers-color-scheme: \" + mediaQuery.prefersColorScheme + \")\");\n var stringMediaQuery = \"@media \" + mediaQuerySections.join(' and ');\n var object = {\n $nest: (_a = {},\n _a[stringMediaQuery] = extend.apply(void 0, objects),\n _a)\n };\n return object;\n};\nvar mediaLength = function (value) {\n return typeof value === 'string' ? value : value + \"px\";\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.lumino_coreutils = {}));\n})(this, (function (exports) { 'use strict';\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for JSON-specific functions.\n */\n exports.JSONExt = void 0;\n (function (JSONExt) {\n /**\n * A shared frozen empty JSONObject\n */\n JSONExt.emptyObject = Object.freeze({});\n /**\n * A shared frozen empty JSONArray\n */\n JSONExt.emptyArray = Object.freeze([]);\n /**\n * Test whether a JSON value is a primitive.\n *\n * @param value - The JSON value of interest.\n *\n * @returns `true` if the value is a primitive,`false` otherwise.\n */\n function isPrimitive(value) {\n return (value === null ||\n typeof value === 'boolean' ||\n typeof value === 'number' ||\n typeof value === 'string');\n }\n JSONExt.isPrimitive = isPrimitive;\n function isArray(value) {\n return Array.isArray(value);\n }\n JSONExt.isArray = isArray;\n function isObject(value) {\n return !isPrimitive(value) && !isArray(value);\n }\n JSONExt.isObject = isObject;\n /**\n * Compare two JSON values for deep equality.\n *\n * @param first - The first JSON value of interest.\n *\n * @param second - The second JSON value of interest.\n *\n * @returns `true` if the values are equivalent, `false` otherwise.\n */\n function deepEqual(first, second) {\n // Check referential and primitive equality first.\n if (first === second) {\n return true;\n }\n // If one is a primitive, the `===` check ruled out the other.\n if (isPrimitive(first) || isPrimitive(second)) {\n return false;\n }\n // Test whether they are arrays.\n let a1 = isArray(first);\n let a2 = isArray(second);\n // Bail if the types are different.\n if (a1 !== a2) {\n return false;\n }\n // If they are both arrays, compare them.\n if (a1 && a2) {\n return deepArrayEqual(first, second);\n }\n // At this point, they must both be objects.\n return deepObjectEqual(first, second);\n }\n JSONExt.deepEqual = deepEqual;\n /**\n * Create a deep copy of a JSON value.\n *\n * @param value - The JSON value to copy.\n *\n * @returns A deep copy of the given JSON value.\n */\n function deepCopy(value) {\n // Do nothing for primitive values.\n if (isPrimitive(value)) {\n return value;\n }\n // Deep copy an array.\n if (isArray(value)) {\n return deepArrayCopy(value);\n }\n // Deep copy an object.\n return deepObjectCopy(value);\n }\n JSONExt.deepCopy = deepCopy;\n /**\n * Compare two JSON arrays for deep equality.\n */\n function deepArrayEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Test the arrays for equal length.\n if (first.length !== second.length) {\n return false;\n }\n // Compare the values for equality.\n for (let i = 0, n = first.length; i < n; ++i) {\n if (!deepEqual(first[i], second[i])) {\n return false;\n }\n }\n // At this point, the arrays are equal.\n return true;\n }\n /**\n * Compare two JSON objects for deep equality.\n */\n function deepObjectEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Check for the first object's keys in the second object.\n for (let key in first) {\n if (first[key] !== undefined && !(key in second)) {\n return false;\n }\n }\n // Check for the second object's keys in the first object.\n for (let key in second) {\n if (second[key] !== undefined && !(key in first)) {\n return false;\n }\n }\n // Compare the values for equality.\n for (let key in first) {\n // Get the values.\n let firstValue = first[key];\n let secondValue = second[key];\n // If both are undefined, ignore the key.\n if (firstValue === undefined && secondValue === undefined) {\n continue;\n }\n // If only one value is undefined, the objects are not equal.\n if (firstValue === undefined || secondValue === undefined) {\n return false;\n }\n // Compare the values.\n if (!deepEqual(firstValue, secondValue)) {\n return false;\n }\n }\n // At this point, the objects are equal.\n return true;\n }\n /**\n * Create a deep copy of a JSON array.\n */\n function deepArrayCopy(value) {\n let result = new Array(value.length);\n for (let i = 0, n = value.length; i < n; ++i) {\n result[i] = deepCopy(value[i]);\n }\n return result;\n }\n /**\n * Create a deep copy of a JSON object.\n */\n function deepObjectCopy(value) {\n let result = {};\n for (let key in value) {\n // Ignore undefined values.\n let subvalue = value[key];\n if (subvalue === undefined) {\n continue;\n }\n result[key] = deepCopy(subvalue);\n }\n return result;\n }\n })(exports.JSONExt || (exports.JSONExt = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * An object which stores MIME data for general application use.\n *\n * #### Notes\n * This class does not attempt to enforce \"correctness\" of MIME types\n * and their associated data. Since this class is designed to transfer\n * arbitrary data and objects within the same application, it assumes\n * that the user provides correct and accurate data.\n */\n class MimeData {\n constructor() {\n this._types = [];\n this._values = [];\n }\n /**\n * Get an array of the MIME types contained within the dataset.\n *\n * @returns A new array of the MIME types, in order of insertion.\n */\n types() {\n return this._types.slice();\n }\n /**\n * Test whether the dataset has an entry for the given type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns `true` if the dataset contains a value for the given\n * MIME type, `false` otherwise.\n */\n hasData(mime) {\n return this._types.indexOf(mime) !== -1;\n }\n /**\n * Get the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns The value for the given MIME type, or `undefined` if\n * the dataset does not contain a value for the type.\n */\n getData(mime) {\n let i = this._types.indexOf(mime);\n return i !== -1 ? this._values[i] : undefined;\n }\n /**\n * Set the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @param data - The data value for the given MIME type.\n *\n * #### Notes\n * This will overwrite any previous entry for the MIME type.\n */\n setData(mime, data) {\n this.clearData(mime);\n this._types.push(mime);\n this._values.push(data);\n }\n /**\n * Remove the data entry for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * #### Notes\n * This is a no-op if there is no entry for the given MIME type.\n */\n clearData(mime) {\n let i = this._types.indexOf(mime);\n if (i !== -1) {\n this._types.splice(i, 1);\n this._values.splice(i, 1);\n }\n }\n /**\n * Remove all data entries from the dataset.\n */\n clear() {\n this._types.length = 0;\n this._values.length = 0;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A class which wraps a promise into a delegate object.\n *\n * #### Notes\n * This class is useful when the logic to resolve or reject a promise\n * cannot be defined at the point where the promise is created.\n */\n class PromiseDelegate {\n /**\n * Construct a new promise delegate.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n /**\n * Resolve the wrapped promise with the given value.\n *\n * @param value - The value to use for resolving the promise.\n */\n resolve(value) {\n let resolve = this._resolve;\n resolve(value);\n }\n /**\n * Reject the wrapped promise with the given value.\n *\n * @reason - The reason for rejecting the promise.\n */\n reject(reason) {\n let reject = this._reject;\n reject(reason);\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A runtime object which captures compile-time type information.\n *\n * #### Notes\n * A token captures the compile-time type of an interface or class in\n * an object which can be used at runtime in a type-safe fashion.\n */\n class Token {\n /**\n * Construct a new token.\n *\n * @param name - A human readable name for the token.\n * @param description - Token purpose description for documentation.\n */\n constructor(name, description) {\n this.name = name;\n this.description = description !== null && description !== void 0 ? description : '';\n this._tokenStructuralPropertyT = null;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n // Fallback\n function fallbackRandomValues(buffer) {\n let value = 0;\n for (let i = 0, n = buffer.length; i < n; ++i) {\n if (i % 4 === 0) {\n value = (Math.random() * 0xffffffff) >>> 0;\n }\n buffer[i] = value & 0xff;\n value >>>= 8;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for random number related functionality.\n */\n exports.Random = void 0;\n (function (Random) {\n /**\n * A function which generates random bytes.\n *\n * @param buffer - The `Uint8Array` to fill with random bytes.\n *\n * #### Notes\n * A cryptographically strong random number generator will be used if\n * available. Otherwise, `Math.random` will be used as a fallback for\n * randomness.\n *\n * The following RNGs are supported, listed in order of precedence:\n * - `window.crypto.getRandomValues`\n * - `window.msCrypto.getRandomValues`\n * - `require('crypto').randomFillSync\n * - `require('crypto').randomBytes\n * - `Math.random`\n */\n Random.getRandomValues = (() => {\n // Look up the crypto module if available.\n const crypto = (typeof window !== 'undefined' && (window.crypto || window.msCrypto)) ||\n null;\n // Modern browsers and IE 11\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return function getRandomValues(buffer) {\n return crypto.getRandomValues(buffer);\n };\n }\n // Fallback\n return fallbackRandomValues;\n })();\n })(exports.Random || (exports.Random = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A function which creates a function that generates UUID v4 identifiers.\n *\n * @returns A new function that creates a UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n function uuid4Factory(getRandomValues) {\n // Create a 16 byte array to hold the random values.\n const bytes = new Uint8Array(16);\n // Create a look up table from bytes to hex strings.\n const lut = new Array(256);\n // Pad the single character hex digits with a leading zero.\n for (let i = 0; i < 16; ++i) {\n lut[i] = '0' + i.toString(16);\n }\n // Populate the rest of the hex digits.\n for (let i = 16; i < 256; ++i) {\n lut[i] = i.toString(16);\n }\n // Return a function which generates the UUID.\n return function uuid4() {\n // Get a new batch of random values.\n getRandomValues(bytes);\n // Set the UUID version number to 4.\n bytes[6] = 0x40 | (bytes[6] & 0x0f);\n // Set the clock sequence bit to the RFC spec.\n bytes[8] = 0x80 | (bytes[8] & 0x3f);\n // Assemble the UUID string.\n return (lut[bytes[0]] +\n lut[bytes[1]] +\n lut[bytes[2]] +\n lut[bytes[3]] +\n '-' +\n lut[bytes[4]] +\n lut[bytes[5]] +\n '-' +\n lut[bytes[6]] +\n lut[bytes[7]] +\n '-' +\n lut[bytes[8]] +\n lut[bytes[9]] +\n '-' +\n lut[bytes[10]] +\n lut[bytes[11]] +\n lut[bytes[12]] +\n lut[bytes[13]] +\n lut[bytes[14]] +\n lut[bytes[15]]);\n };\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for UUID related functionality.\n */\n exports.UUID = void 0;\n (function (UUID) {\n /**\n * A function which generates UUID v4 identifiers.\n *\n * @returns A new UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n UUID.uuid4 = uuid4Factory(exports.Random.getRandomValues);\n })(exports.UUID || (exports.UUID = {}));\n\n exports.MimeData = MimeData;\n exports.PromiseDelegate = PromiseDelegate;\n exports.Token = Token;\n\n}));\n//# sourceMappingURL=index.js.map\n","import { Annotation, Facet, combineConfig, StateField, EditorSelection, Transaction, ChangeSet, ChangeDesc, StateEffect, Text, findClusterBreak, countColumn, CharCategory } from '@codemirror/state';\nimport { EditorView, Direction } from '@codemirror/view';\nimport { IndentContext, getIndentation, indentString, matchBrackets, syntaxTree, getIndentUnit, indentUnit } from '@codemirror/language';\nimport { NodeProp } from '@lezer/common';\n\n/**\nComment or uncomment the current selection. Will use line comments\nif available, otherwise falling back to block comments.\n*/\nconst toggleComment = target => {\n let { state } = target, line = state.doc.lineAt(state.selection.main.from), config = getConfig(target.state, line.from);\n return config.line ? toggleLineComment(target) : config.block ? toggleBlockCommentByLine(target) : false;\n};\nfunction command(f, option) {\n return ({ state, dispatch }) => {\n if (state.readOnly)\n return false;\n let tr = f(option, state);\n if (!tr)\n return false;\n dispatch(state.update(tr));\n return true;\n };\n}\n/**\nComment or uncomment the current selection using line comments.\nThe line comment syntax is taken from the\n[`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language\ndata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt).\n*/\nconst toggleLineComment = /*@__PURE__*/command(changeLineComment, 0 /* CommentOption.Toggle */);\n/**\nComment the current selection using line comments.\n*/\nconst lineComment = /*@__PURE__*/command(changeLineComment, 1 /* CommentOption.Comment */);\n/**\nUncomment the current selection using line comments.\n*/\nconst lineUncomment = /*@__PURE__*/command(changeLineComment, 2 /* CommentOption.Uncomment */);\n/**\nComment or uncomment the current selection using block comments.\nThe block comment syntax is taken from the\n[`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language\ndata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt).\n*/\nconst toggleBlockComment = /*@__PURE__*/command(changeBlockComment, 0 /* CommentOption.Toggle */);\n/**\nComment the current selection using block comments.\n*/\nconst blockComment = /*@__PURE__*/command(changeBlockComment, 1 /* CommentOption.Comment */);\n/**\nUncomment the current selection using block comments.\n*/\nconst blockUncomment = /*@__PURE__*/command(changeBlockComment, 2 /* CommentOption.Uncomment */);\n/**\nComment or uncomment the lines around the current selection using\nblock comments.\n*/\nconst toggleBlockCommentByLine = /*@__PURE__*/command((o, s) => changeBlockComment(o, s, selectedLineRanges(s)), 0 /* CommentOption.Toggle */);\nfunction getConfig(state, pos) {\n let data = state.languageDataAt(\"commentTokens\", pos);\n return data.length ? data[0] : {};\n}\nconst SearchMargin = 50;\n/**\nDetermines if the given range is block-commented in the given\nstate.\n*/\nfunction findBlockComment(state, { open, close }, from, to) {\n let textBefore = state.sliceDoc(from - SearchMargin, from);\n let textAfter = state.sliceDoc(to, to + SearchMargin);\n let spaceBefore = /\\s*$/.exec(textBefore)[0].length, spaceAfter = /^\\s*/.exec(textAfter)[0].length;\n let beforeOff = textBefore.length - spaceBefore;\n if (textBefore.slice(beforeOff - open.length, beforeOff) == open &&\n textAfter.slice(spaceAfter, spaceAfter + close.length) == close) {\n return { open: { pos: from - spaceBefore, margin: spaceBefore && 1 },\n close: { pos: to + spaceAfter, margin: spaceAfter && 1 } };\n }\n let startText, endText;\n if (to - from <= 2 * SearchMargin) {\n startText = endText = state.sliceDoc(from, to);\n }\n else {\n startText = state.sliceDoc(from, from + SearchMargin);\n endText = state.sliceDoc(to - SearchMargin, to);\n }\n let startSpace = /^\\s*/.exec(startText)[0].length, endSpace = /\\s*$/.exec(endText)[0].length;\n let endOff = endText.length - endSpace - close.length;\n if (startText.slice(startSpace, startSpace + open.length) == open &&\n endText.slice(endOff, endOff + close.length) == close) {\n return { open: { pos: from + startSpace + open.length,\n margin: /\\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0 },\n close: { pos: to - endSpace - close.length,\n margin: /\\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } };\n }\n return null;\n}\nfunction selectedLineRanges(state) {\n let ranges = [];\n for (let r of state.selection.ranges) {\n let fromLine = state.doc.lineAt(r.from);\n let toLine = r.to <= fromLine.to ? fromLine : state.doc.lineAt(r.to);\n let last = ranges.length - 1;\n if (last >= 0 && ranges[last].to > fromLine.from)\n ranges[last].to = toLine.to;\n else\n ranges.push({ from: fromLine.from + /^\\s*/.exec(fromLine.text)[0].length, to: toLine.to });\n }\n return ranges;\n}\n// Performs toggle, comment and uncomment of block comments in\n// languages that support them.\nfunction changeBlockComment(option, state, ranges = state.selection.ranges) {\n let tokens = ranges.map(r => getConfig(state, r.from).block);\n if (!tokens.every(c => c))\n return null;\n let comments = ranges.map((r, i) => findBlockComment(state, tokens[i], r.from, r.to));\n if (option != 2 /* CommentOption.Uncomment */ && !comments.every(c => c)) {\n return { changes: state.changes(ranges.map((range, i) => {\n if (comments[i])\n return [];\n return [{ from: range.from, insert: tokens[i].open + \" \" }, { from: range.to, insert: \" \" + tokens[i].close }];\n })) };\n }\n else if (option != 1 /* CommentOption.Comment */ && comments.some(c => c)) {\n let changes = [];\n for (let i = 0, comment; i < comments.length; i++)\n if (comment = comments[i]) {\n let token = tokens[i], { open, close } = comment;\n changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close.pos - close.margin, to: close.pos + token.close.length });\n }\n return { changes };\n }\n return null;\n}\n// Performs toggle, comment and uncomment of line comments.\nfunction changeLineComment(option, state, ranges = state.selection.ranges) {\n let lines = [];\n let prevLine = -1;\n for (let { from, to } of ranges) {\n let startI = lines.length, minIndent = 1e9;\n let token = getConfig(state, from).line;\n if (!token)\n continue;\n for (let pos = from; pos <= to;) {\n let line = state.doc.lineAt(pos);\n if (line.from > prevLine && (from == to || to > line.from)) {\n prevLine = line.from;\n let indent = /^\\s*/.exec(line.text)[0].length;\n let empty = indent == line.length;\n let comment = line.text.slice(indent, indent + token.length) == token ? indent : -1;\n if (indent < line.text.length && indent < minIndent)\n minIndent = indent;\n lines.push({ line, comment, token, indent, empty, single: false });\n }\n pos = line.to + 1;\n }\n if (minIndent < 1e9)\n for (let i = startI; i < lines.length; i++)\n if (lines[i].indent < lines[i].line.text.length)\n lines[i].indent = minIndent;\n if (lines.length == startI + 1)\n lines[startI].single = true;\n }\n if (option != 2 /* CommentOption.Uncomment */ && lines.some(l => l.comment < 0 && (!l.empty || l.single))) {\n let changes = [];\n for (let { line, token, indent, empty, single } of lines)\n if (single || !empty)\n changes.push({ from: line.from + indent, insert: token + \" \" });\n let changeSet = state.changes(changes);\n return { changes: changeSet, selection: state.selection.map(changeSet, 1) };\n }\n else if (option != 1 /* CommentOption.Comment */ && lines.some(l => l.comment >= 0)) {\n let changes = [];\n for (let { line, comment, token } of lines)\n if (comment >= 0) {\n let from = line.from + comment, to = from + token.length;\n if (line.text[to - line.from] == \" \")\n to++;\n changes.push({ from, to });\n }\n return { changes };\n }\n return null;\n}\n\nconst fromHistory = /*@__PURE__*/Annotation.define();\n/**\nTransaction annotation that will prevent that transaction from\nbeing combined with other transactions in the undo history. Given\n`\"before\"`, it'll prevent merging with previous transactions. With\n`\"after\"`, subsequent transactions won't be combined with this\none. With `\"full\"`, the transaction is isolated on both sides.\n*/\nconst isolateHistory = /*@__PURE__*/Annotation.define();\n/**\nThis facet provides a way to register functions that, given a\ntransaction, provide a set of effects that the history should\nstore when inverting the transaction. This can be used to\nintegrate some kinds of effects in the history, so that they can\nbe undone (and redone again).\n*/\nconst invertedEffects = /*@__PURE__*/Facet.define();\nconst historyConfig = /*@__PURE__*/Facet.define({\n combine(configs) {\n return combineConfig(configs, {\n minDepth: 100,\n newGroupDelay: 500,\n joinToEvent: (_t, isAdjacent) => isAdjacent,\n }, {\n minDepth: Math.max,\n newGroupDelay: Math.min,\n joinToEvent: (a, b) => (tr, adj) => a(tr, adj) || b(tr, adj)\n });\n }\n});\nfunction changeEnd(changes) {\n let end = 0;\n changes.iterChangedRanges((_, to) => end = to);\n return end;\n}\nconst historyField_ = /*@__PURE__*/StateField.define({\n create() {\n return HistoryState.empty;\n },\n update(state, tr) {\n let config = tr.state.facet(historyConfig);\n let fromHist = tr.annotation(fromHistory);\n if (fromHist) {\n let selection = tr.docChanged ? EditorSelection.single(changeEnd(tr.changes)) : undefined;\n let item = HistEvent.fromTransaction(tr, selection), from = fromHist.side;\n let other = from == 0 /* BranchName.Done */ ? state.undone : state.done;\n if (item)\n other = updateBranch(other, other.length, config.minDepth, item);\n else\n other = addSelection(other, tr.startState.selection);\n return new HistoryState(from == 0 /* BranchName.Done */ ? fromHist.rest : other, from == 0 /* BranchName.Done */ ? other : fromHist.rest);\n }\n let isolate = tr.annotation(isolateHistory);\n if (isolate == \"full\" || isolate == \"before\")\n state = state.isolate();\n if (tr.annotation(Transaction.addToHistory) === false)\n return !tr.changes.empty ? state.addMapping(tr.changes.desc) : state;\n let event = HistEvent.fromTransaction(tr);\n let time = tr.annotation(Transaction.time), userEvent = tr.annotation(Transaction.userEvent);\n if (event)\n state = state.addChanges(event, time, userEvent, config, tr);\n else if (tr.selection)\n state = state.addSelection(tr.startState.selection, time, userEvent, config.newGroupDelay);\n if (isolate == \"full\" || isolate == \"after\")\n state = state.isolate();\n return state;\n },\n toJSON(value) {\n return { done: value.done.map(e => e.toJSON()), undone: value.undone.map(e => e.toJSON()) };\n },\n fromJSON(json) {\n return new HistoryState(json.done.map(HistEvent.fromJSON), json.undone.map(HistEvent.fromJSON));\n }\n});\n/**\nCreate a history extension with the given configuration.\n*/\nfunction history(config = {}) {\n return [\n historyField_,\n historyConfig.of(config),\n EditorView.domEventHandlers({\n beforeinput(e, view) {\n let command = e.inputType == \"historyUndo\" ? undo : e.inputType == \"historyRedo\" ? redo : null;\n if (!command)\n return false;\n e.preventDefault();\n return command(view);\n }\n })\n ];\n}\n/**\nThe state field used to store the history data. Should probably\nonly be used when you want to\n[serialize](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) or\n[deserialize](https://codemirror.net/6/docs/ref/#state.EditorState^fromJSON) state objects in a way\nthat preserves history.\n*/\nconst historyField = historyField_;\nfunction cmd(side, selection) {\n return function ({ state, dispatch }) {\n if (!selection && state.readOnly)\n return false;\n let historyState = state.field(historyField_, false);\n if (!historyState)\n return false;\n let tr = historyState.pop(side, state, selection);\n if (!tr)\n return false;\n dispatch(tr);\n return true;\n };\n}\n/**\nUndo a single group of history events. Returns false if no group\nwas available.\n*/\nconst undo = /*@__PURE__*/cmd(0 /* BranchName.Done */, false);\n/**\nRedo a group of history events. Returns false if no group was\navailable.\n*/\nconst redo = /*@__PURE__*/cmd(1 /* BranchName.Undone */, false);\n/**\nUndo a change or selection change.\n*/\nconst undoSelection = /*@__PURE__*/cmd(0 /* BranchName.Done */, true);\n/**\nRedo a change or selection change.\n*/\nconst redoSelection = /*@__PURE__*/cmd(1 /* BranchName.Undone */, true);\nfunction depth(side) {\n return function (state) {\n let histState = state.field(historyField_, false);\n if (!histState)\n return 0;\n let branch = side == 0 /* BranchName.Done */ ? histState.done : histState.undone;\n return branch.length - (branch.length && !branch[0].changes ? 1 : 0);\n };\n}\n/**\nThe amount of undoable change events available in a given state.\n*/\nconst undoDepth = /*@__PURE__*/depth(0 /* BranchName.Done */);\n/**\nThe amount of redoable change events available in a given state.\n*/\nconst redoDepth = /*@__PURE__*/depth(1 /* BranchName.Undone */);\n// History events store groups of changes or effects that need to be\n// undone/redone together.\nclass HistEvent {\n constructor(\n // The changes in this event. Normal events hold at least one\n // change or effect. But it may be necessary to store selection\n // events before the first change, in which case a special type of\n // instance is created which doesn't hold any changes, with\n // changes == startSelection == undefined\n changes, \n // The effects associated with this event\n effects, \n // Accumulated mapping (from addToHistory==false) that should be\n // applied to events below this one.\n mapped, \n // The selection before this event\n startSelection, \n // Stores selection changes after this event, to be used for\n // selection undo/redo.\n selectionsAfter) {\n this.changes = changes;\n this.effects = effects;\n this.mapped = mapped;\n this.startSelection = startSelection;\n this.selectionsAfter = selectionsAfter;\n }\n setSelAfter(after) {\n return new HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after);\n }\n toJSON() {\n var _a, _b, _c;\n return {\n changes: (_a = this.changes) === null || _a === void 0 ? void 0 : _a.toJSON(),\n mapped: (_b = this.mapped) === null || _b === void 0 ? void 0 : _b.toJSON(),\n startSelection: (_c = this.startSelection) === null || _c === void 0 ? void 0 : _c.toJSON(),\n selectionsAfter: this.selectionsAfter.map(s => s.toJSON())\n };\n }\n static fromJSON(json) {\n return new HistEvent(json.changes && ChangeSet.fromJSON(json.changes), [], json.mapped && ChangeDesc.fromJSON(json.mapped), json.startSelection && EditorSelection.fromJSON(json.startSelection), json.selectionsAfter.map(EditorSelection.fromJSON));\n }\n // This does not check `addToHistory` and such, it assumes the\n // transaction needs to be converted to an item. Returns null when\n // there are no changes or effects in the transaction.\n static fromTransaction(tr, selection) {\n let effects = none;\n for (let invert of tr.startState.facet(invertedEffects)) {\n let result = invert(tr);\n if (result.length)\n effects = effects.concat(result);\n }\n if (!effects.length && tr.changes.empty)\n return null;\n return new HistEvent(tr.changes.invert(tr.startState.doc), effects, undefined, selection || tr.startState.selection, none);\n }\n static selection(selections) {\n return new HistEvent(undefined, none, undefined, undefined, selections);\n }\n}\nfunction updateBranch(branch, to, maxLen, newEvent) {\n let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0;\n let newBranch = branch.slice(start, to);\n newBranch.push(newEvent);\n return newBranch;\n}\nfunction isAdjacent(a, b) {\n let ranges = [], isAdjacent = false;\n a.iterChangedRanges((f, t) => ranges.push(f, t));\n b.iterChangedRanges((_f, _t, f, t) => {\n for (let i = 0; i < ranges.length;) {\n let from = ranges[i++], to = ranges[i++];\n if (t >= from && f <= to)\n isAdjacent = true;\n }\n });\n return isAdjacent;\n}\nfunction eqSelectionShape(a, b) {\n return a.ranges.length == b.ranges.length &&\n a.ranges.filter((r, i) => r.empty != b.ranges[i].empty).length === 0;\n}\nfunction conc(a, b) {\n return !a.length ? b : !b.length ? a : a.concat(b);\n}\nconst none = [];\nconst MaxSelectionsPerEvent = 200;\nfunction addSelection(branch, selection) {\n if (!branch.length) {\n return [HistEvent.selection([selection])];\n }\n else {\n let lastEvent = branch[branch.length - 1];\n let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent));\n if (sels.length && sels[sels.length - 1].eq(selection))\n return branch;\n sels.push(selection);\n return updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels));\n }\n}\n// Assumes the top item has one or more selectionAfter values\nfunction popSelection(branch) {\n let last = branch[branch.length - 1];\n let newBranch = branch.slice();\n newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1));\n return newBranch;\n}\n// Add a mapping to the top event in the given branch. If this maps\n// away all the changes and effects in that item, drop it and\n// propagate the mapping to the next item.\nfunction addMappingToBranch(branch, mapping) {\n if (!branch.length)\n return branch;\n let length = branch.length, selections = none;\n while (length) {\n let event = mapEvent(branch[length - 1], mapping, selections);\n if (event.changes && !event.changes.empty || event.effects.length) { // Event survived mapping\n let result = branch.slice(0, length);\n result[length - 1] = event;\n return result;\n }\n else { // Drop this event, since there's no changes or effects left\n mapping = event.mapped;\n length--;\n selections = event.selectionsAfter;\n }\n }\n return selections.length ? [HistEvent.selection(selections)] : none;\n}\nfunction mapEvent(event, mapping, extraSelections) {\n let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map(s => s.map(mapping)) : none, extraSelections);\n // Change-less events don't store mappings (they are always the last event in a branch)\n if (!event.changes)\n return HistEvent.selection(selections);\n let mappedChanges = event.changes.map(mapping), before = mapping.mapDesc(event.changes, true);\n let fullMapping = event.mapped ? event.mapped.composeDesc(before) : before;\n return new HistEvent(mappedChanges, StateEffect.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections);\n}\nconst joinableUserEvent = /^(input\\.type|delete)($|\\.)/;\nclass HistoryState {\n constructor(done, undone, prevTime = 0, prevUserEvent = undefined) {\n this.done = done;\n this.undone = undone;\n this.prevTime = prevTime;\n this.prevUserEvent = prevUserEvent;\n }\n isolate() {\n return this.prevTime ? new HistoryState(this.done, this.undone) : this;\n }\n addChanges(event, time, userEvent, config, tr) {\n let done = this.done, lastEvent = done[done.length - 1];\n if (lastEvent && lastEvent.changes && !lastEvent.changes.empty && event.changes &&\n (!userEvent || joinableUserEvent.test(userEvent)) &&\n ((!lastEvent.selectionsAfter.length &&\n time - this.prevTime < config.newGroupDelay &&\n config.joinToEvent(tr, isAdjacent(lastEvent.changes, event.changes))) ||\n // For compose (but not compose.start) events, always join with previous event\n userEvent == \"input.type.compose\")) {\n done = updateBranch(done, done.length - 1, config.minDepth, new HistEvent(event.changes.compose(lastEvent.changes), conc(event.effects, lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none));\n }\n else {\n done = updateBranch(done, done.length, config.minDepth, event);\n }\n return new HistoryState(done, none, time, userEvent);\n }\n addSelection(selection, time, userEvent, newGroupDelay) {\n let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none;\n if (last.length > 0 &&\n time - this.prevTime < newGroupDelay &&\n userEvent == this.prevUserEvent && userEvent && /^select($|\\.)/.test(userEvent) &&\n eqSelectionShape(last[last.length - 1], selection))\n return this;\n return new HistoryState(addSelection(this.done, selection), this.undone, time, userEvent);\n }\n addMapping(mapping) {\n return new HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent);\n }\n pop(side, state, selection) {\n let branch = side == 0 /* BranchName.Done */ ? this.done : this.undone;\n if (branch.length == 0)\n return null;\n let event = branch[branch.length - 1];\n if (selection && event.selectionsAfter.length) {\n return state.update({\n selection: event.selectionsAfter[event.selectionsAfter.length - 1],\n annotations: fromHistory.of({ side, rest: popSelection(branch) }),\n userEvent: side == 0 /* BranchName.Done */ ? \"select.undo\" : \"select.redo\",\n scrollIntoView: true\n });\n }\n else if (!event.changes) {\n return null;\n }\n else {\n let rest = branch.length == 1 ? none : branch.slice(0, branch.length - 1);\n if (event.mapped)\n rest = addMappingToBranch(rest, event.mapped);\n return state.update({\n changes: event.changes,\n selection: event.startSelection,\n effects: event.effects,\n annotations: fromHistory.of({ side, rest }),\n filter: false,\n userEvent: side == 0 /* BranchName.Done */ ? \"undo\" : \"redo\",\n scrollIntoView: true\n });\n }\n }\n}\nHistoryState.empty = /*@__PURE__*/new HistoryState(none, none);\n/**\nDefault key bindings for the undo history.\n\n- Mod-z: [`undo`](https://codemirror.net/6/docs/ref/#commands.undo).\n- Mod-y (Mod-Shift-z on macOS) + Ctrl-Shift-z on Linux: [`redo`](https://codemirror.net/6/docs/ref/#commands.redo).\n- Mod-u: [`undoSelection`](https://codemirror.net/6/docs/ref/#commands.undoSelection).\n- Alt-u (Mod-Shift-u on macOS): [`redoSelection`](https://codemirror.net/6/docs/ref/#commands.redoSelection).\n*/\nconst historyKeymap = [\n { key: \"Mod-z\", run: undo, preventDefault: true },\n { key: \"Mod-y\", mac: \"Mod-Shift-z\", run: redo, preventDefault: true },\n { linux: \"Ctrl-Shift-z\", run: redo, preventDefault: true },\n { key: \"Mod-u\", run: undoSelection, preventDefault: true },\n { key: \"Alt-u\", mac: \"Mod-Shift-u\", run: redoSelection, preventDefault: true }\n];\n\nfunction updateSel(sel, by) {\n return EditorSelection.create(sel.ranges.map(by), sel.mainIndex);\n}\nfunction setSel(state, selection) {\n return state.update({ selection, scrollIntoView: true, userEvent: \"select\" });\n}\nfunction moveSel({ state, dispatch }, how) {\n let selection = updateSel(state.selection, how);\n if (selection.eq(state.selection))\n return false;\n dispatch(setSel(state, selection));\n return true;\n}\nfunction rangeEnd(range, forward) {\n return EditorSelection.cursor(forward ? range.to : range.from);\n}\nfunction cursorByChar(view, forward) {\n return moveSel(view, range => range.empty ? view.moveByChar(range, forward) : rangeEnd(range, forward));\n}\nfunction ltrAtCursor(view) {\n return view.textDirectionAt(view.state.selection.main.head) == Direction.LTR;\n}\n/**\nMove the selection one character to the left (which is backward in\nleft-to-right text, forward in right-to-left text).\n*/\nconst cursorCharLeft = view => cursorByChar(view, !ltrAtCursor(view));\n/**\nMove the selection one character to the right.\n*/\nconst cursorCharRight = view => cursorByChar(view, ltrAtCursor(view));\n/**\nMove the selection one character forward.\n*/\nconst cursorCharForward = view => cursorByChar(view, true);\n/**\nMove the selection one character backward.\n*/\nconst cursorCharBackward = view => cursorByChar(view, false);\nfunction cursorByGroup(view, forward) {\n return moveSel(view, range => range.empty ? view.moveByGroup(range, forward) : rangeEnd(range, forward));\n}\n/**\nMove the selection to the left across one group of word or\nnon-word (but also non-space) characters.\n*/\nconst cursorGroupLeft = view => cursorByGroup(view, !ltrAtCursor(view));\n/**\nMove the selection one group to the right.\n*/\nconst cursorGroupRight = view => cursorByGroup(view, ltrAtCursor(view));\n/**\nMove the selection one group forward.\n*/\nconst cursorGroupForward = view => cursorByGroup(view, true);\n/**\nMove the selection one group backward.\n*/\nconst cursorGroupBackward = view => cursorByGroup(view, false);\nconst segmenter = typeof Intl != \"undefined\" && Intl.Segmenter ?\n /*@__PURE__*/new (Intl.Segmenter)(undefined, { granularity: \"word\" }) : null;\nfunction moveBySubword(view, range, forward) {\n let categorize = view.state.charCategorizer(range.from);\n let cat = CharCategory.Space, pos = range.from, steps = 0;\n let done = false, sawUpper = false, sawLower = false;\n let step = (next) => {\n if (done)\n return false;\n pos += forward ? next.length : -next.length;\n let nextCat = categorize(next), ahead;\n if (nextCat == CharCategory.Word && next.charCodeAt(0) < 128 && /[\\W_]/.test(next))\n nextCat = -1; // Treat word punctuation specially\n if (cat == CharCategory.Space)\n cat = nextCat;\n if (cat != nextCat)\n return false;\n if (cat == CharCategory.Word) {\n if (next.toLowerCase() == next) {\n if (!forward && sawUpper)\n return false;\n sawLower = true;\n }\n else if (sawLower) {\n if (forward)\n return false;\n done = true;\n }\n else {\n if (sawUpper && forward && categorize(ahead = view.state.sliceDoc(pos, pos + 1)) == CharCategory.Word &&\n ahead.toLowerCase() == ahead)\n return false;\n sawUpper = true;\n }\n }\n steps++;\n return true;\n };\n let end = view.moveByChar(range, forward, start => {\n step(start);\n return step;\n });\n if (segmenter && cat == CharCategory.Word && end.from == range.from + steps * (forward ? 1 : -1)) {\n let from = Math.min(range.head, end.head), to = Math.max(range.head, end.head);\n let skipped = view.state.sliceDoc(from, to);\n if (skipped.length > 1 && /[\\u4E00-\\uffff]/.test(skipped)) {\n let segments = Array.from(segmenter.segment(skipped));\n if (segments.length > 1) {\n if (forward)\n return EditorSelection.cursor(range.head + segments[1].index, -1);\n return EditorSelection.cursor(end.head + segments[segments.length - 1].index, 1);\n }\n }\n }\n return end;\n}\nfunction cursorBySubword(view, forward) {\n return moveSel(view, range => range.empty ? moveBySubword(view, range, forward) : rangeEnd(range, forward));\n}\n/**\nMove the selection one group or camel-case subword forward.\n*/\nconst cursorSubwordForward = view => cursorBySubword(view, true);\n/**\nMove the selection one group or camel-case subword backward.\n*/\nconst cursorSubwordBackward = view => cursorBySubword(view, false);\nfunction interestingNode(state, node, bracketProp) {\n if (node.type.prop(bracketProp))\n return true;\n let len = node.to - node.from;\n return len && (len > 2 || /[^\\s,.;:]/.test(state.sliceDoc(node.from, node.to))) || node.firstChild;\n}\nfunction moveBySyntax(state, start, forward) {\n let pos = syntaxTree(state).resolveInner(start.head);\n let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy;\n // Scan forward through child nodes to see if there's an interesting\n // node ahead.\n for (let at = start.head;;) {\n let next = forward ? pos.childAfter(at) : pos.childBefore(at);\n if (!next)\n break;\n if (interestingNode(state, next, bracketProp))\n pos = next;\n else\n at = forward ? next.to : next.from;\n }\n let bracket = pos.type.prop(bracketProp), match, newPos;\n if (bracket && (match = forward ? matchBrackets(state, pos.from, 1) : matchBrackets(state, pos.to, -1)) && match.matched)\n newPos = forward ? match.end.to : match.end.from;\n else\n newPos = forward ? pos.to : pos.from;\n return EditorSelection.cursor(newPos, forward ? -1 : 1);\n}\n/**\nMove the cursor over the next syntactic element to the left.\n*/\nconst cursorSyntaxLeft = view => moveSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view)));\n/**\nMove the cursor over the next syntactic element to the right.\n*/\nconst cursorSyntaxRight = view => moveSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view)));\nfunction cursorByLine(view, forward) {\n return moveSel(view, range => {\n if (!range.empty)\n return rangeEnd(range, forward);\n let moved = view.moveVertically(range, forward);\n return moved.head != range.head ? moved : view.moveToLineBoundary(range, forward);\n });\n}\n/**\nMove the selection one line up.\n*/\nconst cursorLineUp = view => cursorByLine(view, false);\n/**\nMove the selection one line down.\n*/\nconst cursorLineDown = view => cursorByLine(view, true);\nfunction pageInfo(view) {\n let selfScroll = view.scrollDOM.clientHeight < view.scrollDOM.scrollHeight - 2;\n let marginTop = 0, marginBottom = 0, height;\n if (selfScroll) {\n for (let source of view.state.facet(EditorView.scrollMargins)) {\n let margins = source(view);\n if (margins === null || margins === void 0 ? void 0 : margins.top)\n marginTop = Math.max(margins === null || margins === void 0 ? void 0 : margins.top, marginTop);\n if (margins === null || margins === void 0 ? void 0 : margins.bottom)\n marginBottom = Math.max(margins === null || margins === void 0 ? void 0 : margins.bottom, marginBottom);\n }\n height = view.scrollDOM.clientHeight - marginTop - marginBottom;\n }\n else {\n height = (view.dom.ownerDocument.defaultView || window).innerHeight;\n }\n return { marginTop, marginBottom, selfScroll,\n height: Math.max(view.defaultLineHeight, height - 5) };\n}\nfunction cursorByPage(view, forward) {\n let page = pageInfo(view);\n let { state } = view, selection = updateSel(state.selection, range => {\n return range.empty ? view.moveVertically(range, forward, page.height)\n : rangeEnd(range, forward);\n });\n if (selection.eq(state.selection))\n return false;\n let effect;\n if (page.selfScroll) {\n let startPos = view.coordsAtPos(state.selection.main.head);\n let scrollRect = view.scrollDOM.getBoundingClientRect();\n let scrollTop = scrollRect.top + page.marginTop, scrollBottom = scrollRect.bottom - page.marginBottom;\n if (startPos && startPos.top > scrollTop && startPos.bottom < scrollBottom)\n effect = EditorView.scrollIntoView(selection.main.head, { y: \"start\", yMargin: startPos.top - scrollTop });\n }\n view.dispatch(setSel(state, selection), { effects: effect });\n return true;\n}\n/**\nMove the selection one page up.\n*/\nconst cursorPageUp = view => cursorByPage(view, false);\n/**\nMove the selection one page down.\n*/\nconst cursorPageDown = view => cursorByPage(view, true);\nfunction moveByLineBoundary(view, start, forward) {\n let line = view.lineBlockAt(start.head), moved = view.moveToLineBoundary(start, forward);\n if (moved.head == start.head && moved.head != (forward ? line.to : line.from))\n moved = view.moveToLineBoundary(start, forward, false);\n if (!forward && moved.head == line.from && line.length) {\n let space = /^\\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length;\n if (space && start.head != line.from + space)\n moved = EditorSelection.cursor(line.from + space);\n }\n return moved;\n}\n/**\nMove the selection to the next line wrap point, or to the end of\nthe line if there isn't one left on this line.\n*/\nconst cursorLineBoundaryForward = view => moveSel(view, range => moveByLineBoundary(view, range, true));\n/**\nMove the selection to previous line wrap point, or failing that to\nthe start of the line. If the line is indented, and the cursor\nisn't already at the end of the indentation, this will move to the\nend of the indentation instead of the start of the line.\n*/\nconst cursorLineBoundaryBackward = view => moveSel(view, range => moveByLineBoundary(view, range, false));\n/**\nMove the selection one line wrap point to the left.\n*/\nconst cursorLineBoundaryLeft = view => moveSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view)));\n/**\nMove the selection one line wrap point to the right.\n*/\nconst cursorLineBoundaryRight = view => moveSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view)));\n/**\nMove the selection to the start of the line.\n*/\nconst cursorLineStart = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from, 1));\n/**\nMove the selection to the end of the line.\n*/\nconst cursorLineEnd = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to, -1));\nfunction toMatchingBracket(state, dispatch, extend) {\n let found = false, selection = updateSel(state.selection, range => {\n let matching = matchBrackets(state, range.head, -1)\n || matchBrackets(state, range.head, 1)\n || (range.head > 0 && matchBrackets(state, range.head - 1, 1))\n || (range.head < state.doc.length && matchBrackets(state, range.head + 1, -1));\n if (!matching || !matching.end)\n return range;\n found = true;\n let head = matching.start.from == range.head ? matching.end.to : matching.end.from;\n return extend ? EditorSelection.range(range.anchor, head) : EditorSelection.cursor(head);\n });\n if (!found)\n return false;\n dispatch(setSel(state, selection));\n return true;\n}\n/**\nMove the selection to the bracket matching the one it is currently\non, if any.\n*/\nconst cursorMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, false);\n/**\nExtend the selection to the bracket matching the one the selection\nhead is currently on, if any.\n*/\nconst selectMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, true);\nfunction extendSel(view, how) {\n let selection = updateSel(view.state.selection, range => {\n let head = how(range);\n return EditorSelection.range(range.anchor, head.head, head.goalColumn, head.bidiLevel || undefined);\n });\n if (selection.eq(view.state.selection))\n return false;\n view.dispatch(setSel(view.state, selection));\n return true;\n}\nfunction selectByChar(view, forward) {\n return extendSel(view, range => view.moveByChar(range, forward));\n}\n/**\nMove the selection head one character to the left, while leaving\nthe anchor in place.\n*/\nconst selectCharLeft = view => selectByChar(view, !ltrAtCursor(view));\n/**\nMove the selection head one character to the right.\n*/\nconst selectCharRight = view => selectByChar(view, ltrAtCursor(view));\n/**\nMove the selection head one character forward.\n*/\nconst selectCharForward = view => selectByChar(view, true);\n/**\nMove the selection head one character backward.\n*/\nconst selectCharBackward = view => selectByChar(view, false);\nfunction selectByGroup(view, forward) {\n return extendSel(view, range => view.moveByGroup(range, forward));\n}\n/**\nMove the selection head one [group](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) to\nthe left.\n*/\nconst selectGroupLeft = view => selectByGroup(view, !ltrAtCursor(view));\n/**\nMove the selection head one group to the right.\n*/\nconst selectGroupRight = view => selectByGroup(view, ltrAtCursor(view));\n/**\nMove the selection head one group forward.\n*/\nconst selectGroupForward = view => selectByGroup(view, true);\n/**\nMove the selection head one group backward.\n*/\nconst selectGroupBackward = view => selectByGroup(view, false);\nfunction selectBySubword(view, forward) {\n return extendSel(view, range => moveBySubword(view, range, forward));\n}\n/**\nMove the selection head one group or camel-case subword forward.\n*/\nconst selectSubwordForward = view => selectBySubword(view, true);\n/**\nMove the selection head one group or subword backward.\n*/\nconst selectSubwordBackward = view => selectBySubword(view, false);\n/**\nMove the selection head over the next syntactic element to the left.\n*/\nconst selectSyntaxLeft = view => extendSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view)));\n/**\nMove the selection head over the next syntactic element to the right.\n*/\nconst selectSyntaxRight = view => extendSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view)));\nfunction selectByLine(view, forward) {\n return extendSel(view, range => view.moveVertically(range, forward));\n}\n/**\nMove the selection head one line up.\n*/\nconst selectLineUp = view => selectByLine(view, false);\n/**\nMove the selection head one line down.\n*/\nconst selectLineDown = view => selectByLine(view, true);\nfunction selectByPage(view, forward) {\n return extendSel(view, range => view.moveVertically(range, forward, pageInfo(view).height));\n}\n/**\nMove the selection head one page up.\n*/\nconst selectPageUp = view => selectByPage(view, false);\n/**\nMove the selection head one page down.\n*/\nconst selectPageDown = view => selectByPage(view, true);\n/**\nMove the selection head to the next line boundary.\n*/\nconst selectLineBoundaryForward = view => extendSel(view, range => moveByLineBoundary(view, range, true));\n/**\nMove the selection head to the previous line boundary.\n*/\nconst selectLineBoundaryBackward = view => extendSel(view, range => moveByLineBoundary(view, range, false));\n/**\nMove the selection head one line boundary to the left.\n*/\nconst selectLineBoundaryLeft = view => extendSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view)));\n/**\nMove the selection head one line boundary to the right.\n*/\nconst selectLineBoundaryRight = view => extendSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view)));\n/**\nMove the selection head to the start of the line.\n*/\nconst selectLineStart = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from));\n/**\nMove the selection head to the end of the line.\n*/\nconst selectLineEnd = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to));\n/**\nMove the selection to the start of the document.\n*/\nconst cursorDocStart = ({ state, dispatch }) => {\n dispatch(setSel(state, { anchor: 0 }));\n return true;\n};\n/**\nMove the selection to the end of the document.\n*/\nconst cursorDocEnd = ({ state, dispatch }) => {\n dispatch(setSel(state, { anchor: state.doc.length }));\n return true;\n};\n/**\nMove the selection head to the start of the document.\n*/\nconst selectDocStart = ({ state, dispatch }) => {\n dispatch(setSel(state, { anchor: state.selection.main.anchor, head: 0 }));\n return true;\n};\n/**\nMove the selection head to the end of the document.\n*/\nconst selectDocEnd = ({ state, dispatch }) => {\n dispatch(setSel(state, { anchor: state.selection.main.anchor, head: state.doc.length }));\n return true;\n};\n/**\nSelect the entire document.\n*/\nconst selectAll = ({ state, dispatch }) => {\n dispatch(state.update({ selection: { anchor: 0, head: state.doc.length }, userEvent: \"select\" }));\n return true;\n};\n/**\nExpand the selection to cover entire lines.\n*/\nconst selectLine = ({ state, dispatch }) => {\n let ranges = selectedLineBlocks(state).map(({ from, to }) => EditorSelection.range(from, Math.min(to + 1, state.doc.length)));\n dispatch(state.update({ selection: EditorSelection.create(ranges), userEvent: \"select\" }));\n return true;\n};\n/**\nSelect the next syntactic construct that is larger than the\nselection. Note that this will only work insofar as the language\n[provider](https://codemirror.net/6/docs/ref/#language.language) you use builds up a full\nsyntax tree.\n*/\nconst selectParentSyntax = ({ state, dispatch }) => {\n let selection = updateSel(state.selection, range => {\n var _a;\n let stack = syntaxTree(state).resolveStack(range.from, 1);\n for (let cur = stack; cur; cur = cur.next) {\n let { node } = cur;\n if (((node.from < range.from && node.to >= range.to) ||\n (node.to > range.to && node.from <= range.from)) &&\n ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent))\n return EditorSelection.range(node.to, node.from);\n }\n return range;\n });\n dispatch(setSel(state, selection));\n return true;\n};\n/**\nSimplify the current selection. When multiple ranges are selected,\nreduce it to its main range. Otherwise, if the selection is\nnon-empty, convert it to a cursor selection.\n*/\nconst simplifySelection = ({ state, dispatch }) => {\n let cur = state.selection, selection = null;\n if (cur.ranges.length > 1)\n selection = EditorSelection.create([cur.main]);\n else if (!cur.main.empty)\n selection = EditorSelection.create([EditorSelection.cursor(cur.main.head)]);\n if (!selection)\n return false;\n dispatch(setSel(state, selection));\n return true;\n};\nfunction deleteBy(target, by) {\n if (target.state.readOnly)\n return false;\n let event = \"delete.selection\", { state } = target;\n let changes = state.changeByRange(range => {\n let { from, to } = range;\n if (from == to) {\n let towards = by(range);\n if (towards < from) {\n event = \"delete.backward\";\n towards = skipAtomic(target, towards, false);\n }\n else if (towards > from) {\n event = \"delete.forward\";\n towards = skipAtomic(target, towards, true);\n }\n from = Math.min(from, towards);\n to = Math.max(to, towards);\n }\n else {\n from = skipAtomic(target, from, false);\n to = skipAtomic(target, to, true);\n }\n return from == to ? { range } : { changes: { from, to }, range: EditorSelection.cursor(from, from < range.head ? -1 : 1) };\n });\n if (changes.changes.empty)\n return false;\n target.dispatch(state.update(changes, {\n scrollIntoView: true,\n userEvent: event,\n effects: event == \"delete.selection\" ? EditorView.announce.of(state.phrase(\"Selection deleted\")) : undefined\n }));\n return true;\n}\nfunction skipAtomic(target, pos, forward) {\n if (target instanceof EditorView)\n for (let ranges of target.state.facet(EditorView.atomicRanges).map(f => f(target)))\n ranges.between(pos, pos, (from, to) => {\n if (from < pos && to > pos)\n pos = forward ? to : from;\n });\n return pos;\n}\nconst deleteByChar = (target, forward) => deleteBy(target, range => {\n let pos = range.from, { state } = target, line = state.doc.lineAt(pos), before, targetPos;\n if (!forward && pos > line.from && pos < line.from + 200 &&\n !/[^ \\t]/.test(before = line.text.slice(0, pos - line.from))) {\n if (before[before.length - 1] == \"\\t\")\n return pos - 1;\n let col = countColumn(before, state.tabSize), drop = col % getIndentUnit(state) || getIndentUnit(state);\n for (let i = 0; i < drop && before[before.length - 1 - i] == \" \"; i++)\n pos--;\n targetPos = pos;\n }\n else {\n targetPos = findClusterBreak(line.text, pos - line.from, forward, forward) + line.from;\n if (targetPos == pos && line.number != (forward ? state.doc.lines : 1))\n targetPos += forward ? 1 : -1;\n }\n return targetPos;\n});\n/**\nDelete the selection, or, for cursor selections, the character\nbefore the cursor.\n*/\nconst deleteCharBackward = view => deleteByChar(view, false);\n/**\nDelete the selection or the character after the cursor.\n*/\nconst deleteCharForward = view => deleteByChar(view, true);\nconst deleteByGroup = (target, forward) => deleteBy(target, range => {\n let pos = range.head, { state } = target, line = state.doc.lineAt(pos);\n let categorize = state.charCategorizer(pos);\n for (let cat = null;;) {\n if (pos == (forward ? line.to : line.from)) {\n if (pos == range.head && line.number != (forward ? state.doc.lines : 1))\n pos += forward ? 1 : -1;\n break;\n }\n let next = findClusterBreak(line.text, pos - line.from, forward) + line.from;\n let nextChar = line.text.slice(Math.min(pos, next) - line.from, Math.max(pos, next) - line.from);\n let nextCat = categorize(nextChar);\n if (cat != null && nextCat != cat)\n break;\n if (nextChar != \" \" || pos != range.head)\n cat = nextCat;\n pos = next;\n }\n return pos;\n});\n/**\nDelete the selection or backward until the end of the next\n[group](https://codemirror.net/6/docs/ref/#view.EditorView.moveByGroup), only skipping groups of\nwhitespace when they consist of a single space.\n*/\nconst deleteGroupBackward = target => deleteByGroup(target, false);\n/**\nDelete the selection or forward until the end of the next group.\n*/\nconst deleteGroupForward = target => deleteByGroup(target, true);\n/**\nDelete the selection, or, if it is a cursor selection, delete to\nthe end of the line. If the cursor is directly at the end of the\nline, delete the line break after it.\n*/\nconst deleteToLineEnd = view => deleteBy(view, range => {\n let lineEnd = view.lineBlockAt(range.head).to;\n return range.head < lineEnd ? lineEnd : Math.min(view.state.doc.length, range.head + 1);\n});\n/**\nDelete the selection, or, if it is a cursor selection, delete to\nthe start of the line. If the cursor is directly at the start of the\nline, delete the line break before it.\n*/\nconst deleteToLineStart = view => deleteBy(view, range => {\n let lineStart = view.lineBlockAt(range.head).from;\n return range.head > lineStart ? lineStart : Math.max(0, range.head - 1);\n});\n/**\nDelete the selection, or, if it is a cursor selection, delete to\nthe start of the line or the next line wrap before the cursor.\n*/\nconst deleteLineBoundaryBackward = view => deleteBy(view, range => {\n let lineStart = view.moveToLineBoundary(range, false).head;\n return range.head > lineStart ? lineStart : Math.max(0, range.head - 1);\n});\n/**\nDelete the selection, or, if it is a cursor selection, delete to\nthe end of the line or the next line wrap after the cursor.\n*/\nconst deleteLineBoundaryForward = view => deleteBy(view, range => {\n let lineStart = view.moveToLineBoundary(range, true).head;\n return range.head < lineStart ? lineStart : Math.min(view.state.doc.length, range.head + 1);\n});\n/**\nDelete all whitespace directly before a line end from the\ndocument.\n*/\nconst deleteTrailingWhitespace = ({ state, dispatch }) => {\n if (state.readOnly)\n return false;\n let changes = [];\n for (let pos = 0, prev = \"\", iter = state.doc.iter();;) {\n iter.next();\n if (iter.lineBreak || iter.done) {\n let trailing = prev.search(/\\s+$/);\n if (trailing > -1)\n changes.push({ from: pos - (prev.length - trailing), to: pos });\n if (iter.done)\n break;\n prev = \"\";\n }\n else {\n prev = iter.value;\n }\n pos += iter.value.length;\n }\n if (!changes.length)\n return false;\n dispatch(state.update({ changes, userEvent: \"delete\" }));\n return true;\n};\n/**\nReplace each selection range with a line break, leaving the cursor\non the line before the break.\n*/\nconst splitLine = ({ state, dispatch }) => {\n if (state.readOnly)\n return false;\n let changes = state.changeByRange(range => {\n return { changes: { from: range.from, to: range.to, insert: Text.of([\"\", \"\"]) },\n range: EditorSelection.cursor(range.from) };\n });\n dispatch(state.update(changes, { scrollIntoView: true, userEvent: \"input\" }));\n return true;\n};\n/**\nFlip the characters before and after the cursor(s).\n*/\nconst transposeChars = ({ state, dispatch }) => {\n if (state.readOnly)\n return false;\n let changes = state.changeByRange(range => {\n if (!range.empty || range.from == 0 || range.from == state.doc.length)\n return { range };\n let pos = range.from, line = state.doc.lineAt(pos);\n let from = pos == line.from ? pos - 1 : findClusterBreak(line.text, pos - line.from, false) + line.from;\n let to = pos == line.to ? pos + 1 : findClusterBreak(line.text, pos - line.from, true) + line.from;\n return { changes: { from, to, insert: state.doc.slice(pos, to).append(state.doc.slice(from, pos)) },\n range: EditorSelection.cursor(to) };\n });\n if (changes.changes.empty)\n return false;\n dispatch(state.update(changes, { scrollIntoView: true, userEvent: \"move.character\" }));\n return true;\n};\nfunction selectedLineBlocks(state) {\n let blocks = [], upto = -1;\n for (let range of state.selection.ranges) {\n let startLine = state.doc.lineAt(range.from), endLine = state.doc.lineAt(range.to);\n if (!range.empty && range.to == endLine.from)\n endLine = state.doc.lineAt(range.to - 1);\n if (upto >= startLine.number) {\n let prev = blocks[blocks.length - 1];\n prev.to = endLine.to;\n prev.ranges.push(range);\n }\n else {\n blocks.push({ from: startLine.from, to: endLine.to, ranges: [range] });\n }\n upto = endLine.number + 1;\n }\n return blocks;\n}\nfunction moveLine(state, dispatch, forward) {\n if (state.readOnly)\n return false;\n let changes = [], ranges = [];\n for (let block of selectedLineBlocks(state)) {\n if (forward ? block.to == state.doc.length : block.from == 0)\n continue;\n let nextLine = state.doc.lineAt(forward ? block.to + 1 : block.from - 1);\n let size = nextLine.length + 1;\n if (forward) {\n changes.push({ from: block.to, to: nextLine.to }, { from: block.from, insert: nextLine.text + state.lineBreak });\n for (let r of block.ranges)\n ranges.push(EditorSelection.range(Math.min(state.doc.length, r.anchor + size), Math.min(state.doc.length, r.head + size)));\n }\n else {\n changes.push({ from: nextLine.from, to: block.from }, { from: block.to, insert: state.lineBreak + nextLine.text });\n for (let r of block.ranges)\n ranges.push(EditorSelection.range(r.anchor - size, r.head - size));\n }\n }\n if (!changes.length)\n return false;\n dispatch(state.update({\n changes,\n scrollIntoView: true,\n selection: EditorSelection.create(ranges, state.selection.mainIndex),\n userEvent: \"move.line\"\n }));\n return true;\n}\n/**\nMove the selected lines up one line.\n*/\nconst moveLineUp = ({ state, dispatch }) => moveLine(state, dispatch, false);\n/**\nMove the selected lines down one line.\n*/\nconst moveLineDown = ({ state, dispatch }) => moveLine(state, dispatch, true);\nfunction copyLine(state, dispatch, forward) {\n if (state.readOnly)\n return false;\n let changes = [];\n for (let block of selectedLineBlocks(state)) {\n if (forward)\n changes.push({ from: block.from, insert: state.doc.slice(block.from, block.to) + state.lineBreak });\n else\n changes.push({ from: block.to, insert: state.lineBreak + state.doc.slice(block.from, block.to) });\n }\n dispatch(state.update({ changes, scrollIntoView: true, userEvent: \"input.copyline\" }));\n return true;\n}\n/**\nCreate a copy of the selected lines. Keep the selection in the top copy.\n*/\nconst copyLineUp = ({ state, dispatch }) => copyLine(state, dispatch, false);\n/**\nCreate a copy of the selected lines. Keep the selection in the bottom copy.\n*/\nconst copyLineDown = ({ state, dispatch }) => copyLine(state, dispatch, true);\n/**\nDelete selected lines.\n*/\nconst deleteLine = view => {\n if (view.state.readOnly)\n return false;\n let { state } = view, changes = state.changes(selectedLineBlocks(state).map(({ from, to }) => {\n if (from > 0)\n from--;\n else if (to < state.doc.length)\n to++;\n return { from, to };\n }));\n let selection = updateSel(state.selection, range => view.moveVertically(range, true)).map(changes);\n view.dispatch({ changes, selection, scrollIntoView: true, userEvent: \"delete.line\" });\n return true;\n};\n/**\nReplace the selection with a newline.\n*/\nconst insertNewline = ({ state, dispatch }) => {\n dispatch(state.update(state.replaceSelection(state.lineBreak), { scrollIntoView: true, userEvent: \"input\" }));\n return true;\n};\nfunction isBetweenBrackets(state, pos) {\n if (/\\(\\)|\\[\\]|\\{\\}/.test(state.sliceDoc(pos - 1, pos + 1)))\n return { from: pos, to: pos };\n let context = syntaxTree(state).resolveInner(pos);\n let before = context.childBefore(pos), after = context.childAfter(pos), closedBy;\n if (before && after && before.to <= pos && after.from >= pos &&\n (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 &&\n state.doc.lineAt(before.to).from == state.doc.lineAt(after.from).from &&\n !/\\S/.test(state.sliceDoc(before.to, after.from)))\n return { from: before.to, to: after.from };\n return null;\n}\n/**\nReplace the selection with a newline and indent the newly created\nline(s). If the current line consists only of whitespace, this\nwill also delete that whitespace. When the cursor is between\nmatching brackets, an additional newline will be inserted after\nthe cursor.\n*/\nconst insertNewlineAndIndent = /*@__PURE__*/newlineAndIndent(false);\n/**\nCreate a blank, indented line below the current line.\n*/\nconst insertBlankLine = /*@__PURE__*/newlineAndIndent(true);\nfunction newlineAndIndent(atEof) {\n return ({ state, dispatch }) => {\n if (state.readOnly)\n return false;\n let changes = state.changeByRange(range => {\n let { from, to } = range, line = state.doc.lineAt(from);\n let explode = !atEof && from == to && isBetweenBrackets(state, from);\n if (atEof)\n from = to = (to <= line.to ? line : state.doc.lineAt(to)).to;\n let cx = new IndentContext(state, { simulateBreak: from, simulateDoubleBreak: !!explode });\n let indent = getIndentation(cx, from);\n if (indent == null)\n indent = countColumn(/^\\s*/.exec(state.doc.lineAt(from).text)[0], state.tabSize);\n while (to < line.to && /\\s/.test(line.text[to - line.from]))\n to++;\n if (explode)\n ({ from, to } = explode);\n else if (from > line.from && from < line.from + 100 && !/\\S/.test(line.text.slice(0, from)))\n from = line.from;\n let insert = [\"\", indentString(state, indent)];\n if (explode)\n insert.push(indentString(state, cx.lineIndent(line.from, -1)));\n return { changes: { from, to, insert: Text.of(insert) },\n range: EditorSelection.cursor(from + 1 + insert[1].length) };\n });\n dispatch(state.update(changes, { scrollIntoView: true, userEvent: \"input\" }));\n return true;\n };\n}\nfunction changeBySelectedLine(state, f) {\n let atLine = -1;\n return state.changeByRange(range => {\n let changes = [];\n for (let pos = range.from; pos <= range.to;) {\n let line = state.doc.lineAt(pos);\n if (line.number > atLine && (range.empty || range.to > line.from)) {\n f(line, changes, range);\n atLine = line.number;\n }\n pos = line.to + 1;\n }\n let changeSet = state.changes(changes);\n return { changes,\n range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1)) };\n });\n}\n/**\nAuto-indent the selected lines. This uses the [indentation service\nfacet](https://codemirror.net/6/docs/ref/#language.indentService) as source for auto-indent\ninformation.\n*/\nconst indentSelection = ({ state, dispatch }) => {\n if (state.readOnly)\n return false;\n let updated = Object.create(null);\n let context = new IndentContext(state, { overrideIndentation: start => {\n let found = updated[start];\n return found == null ? -1 : found;\n } });\n let changes = changeBySelectedLine(state, (line, changes, range) => {\n let indent = getIndentation(context, line.from);\n if (indent == null)\n return;\n if (!/\\S/.test(line.text))\n indent = 0;\n let cur = /^\\s*/.exec(line.text)[0];\n let norm = indentString(state, indent);\n if (cur != norm || range.from < line.from + cur.length) {\n updated[line.from] = indent;\n changes.push({ from: line.from, to: line.from + cur.length, insert: norm });\n }\n });\n if (!changes.changes.empty)\n dispatch(state.update(changes, { userEvent: \"indent\" }));\n return true;\n};\n/**\nAdd a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation to all selected\nlines.\n*/\nconst indentMore = ({ state, dispatch }) => {\n if (state.readOnly)\n return false;\n dispatch(state.update(changeBySelectedLine(state, (line, changes) => {\n changes.push({ from: line.from, insert: state.facet(indentUnit) });\n }), { userEvent: \"input.indent\" }));\n return true;\n};\n/**\nRemove a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation from all\nselected lines.\n*/\nconst indentLess = ({ state, dispatch }) => {\n if (state.readOnly)\n return false;\n dispatch(state.update(changeBySelectedLine(state, (line, changes) => {\n let space = /^\\s*/.exec(line.text)[0];\n if (!space)\n return;\n let col = countColumn(space, state.tabSize), keep = 0;\n let insert = indentString(state, Math.max(0, col - getIndentUnit(state)));\n while (keep < space.length && keep < insert.length && space.charCodeAt(keep) == insert.charCodeAt(keep))\n keep++;\n changes.push({ from: line.from + keep, to: line.from + space.length, insert: insert.slice(keep) });\n }), { userEvent: \"delete.dedent\" }));\n return true;\n};\n/**\nInsert a tab character at the cursor or, if something is selected,\nuse [`indentMore`](https://codemirror.net/6/docs/ref/#commands.indentMore) to indent the entire\nselection.\n*/\nconst insertTab = ({ state, dispatch }) => {\n if (state.selection.ranges.some(r => !r.empty))\n return indentMore({ state, dispatch });\n dispatch(state.update(state.replaceSelection(\"\\t\"), { scrollIntoView: true, userEvent: \"input\" }));\n return true;\n};\n/**\nArray of key bindings containing the Emacs-style bindings that are\navailable on macOS by default.\n\n - Ctrl-b: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift)\n - Ctrl-f: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift)\n - Ctrl-p: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift)\n - Ctrl-n: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift)\n - Ctrl-a: [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift)\n - Ctrl-e: [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift)\n - Ctrl-d: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward)\n - Ctrl-h: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward)\n - Ctrl-k: [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd)\n - Ctrl-Alt-h: [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward)\n - Ctrl-o: [`splitLine`](https://codemirror.net/6/docs/ref/#commands.splitLine)\n - Ctrl-t: [`transposeChars`](https://codemirror.net/6/docs/ref/#commands.transposeChars)\n - Ctrl-v: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown)\n - Alt-v: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp)\n*/\nconst emacsStyleKeymap = [\n { key: \"Ctrl-b\", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true },\n { key: \"Ctrl-f\", run: cursorCharRight, shift: selectCharRight },\n { key: \"Ctrl-p\", run: cursorLineUp, shift: selectLineUp },\n { key: \"Ctrl-n\", run: cursorLineDown, shift: selectLineDown },\n { key: \"Ctrl-a\", run: cursorLineStart, shift: selectLineStart },\n { key: \"Ctrl-e\", run: cursorLineEnd, shift: selectLineEnd },\n { key: \"Ctrl-d\", run: deleteCharForward },\n { key: \"Ctrl-h\", run: deleteCharBackward },\n { key: \"Ctrl-k\", run: deleteToLineEnd },\n { key: \"Ctrl-Alt-h\", run: deleteGroupBackward },\n { key: \"Ctrl-o\", run: splitLine },\n { key: \"Ctrl-t\", run: transposeChars },\n { key: \"Ctrl-v\", run: cursorPageDown },\n];\n/**\nAn array of key bindings closely sticking to platform-standard or\nwidely used bindings. (This includes the bindings from\n[`emacsStyleKeymap`](https://codemirror.net/6/docs/ref/#commands.emacsStyleKeymap), with their `key`\nproperty changed to `mac`.)\n\n - ArrowLeft: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift)\n - ArrowRight: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift)\n - Ctrl-ArrowLeft (Alt-ArrowLeft on macOS): [`cursorGroupLeft`](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) ([`selectGroupLeft`](https://codemirror.net/6/docs/ref/#commands.selectGroupLeft) with Shift)\n - Ctrl-ArrowRight (Alt-ArrowRight on macOS): [`cursorGroupRight`](https://codemirror.net/6/docs/ref/#commands.cursorGroupRight) ([`selectGroupRight`](https://codemirror.net/6/docs/ref/#commands.selectGroupRight) with Shift)\n - Cmd-ArrowLeft (on macOS): [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift)\n - Cmd-ArrowRight (on macOS): [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift)\n - ArrowUp: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift)\n - ArrowDown: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift)\n - Cmd-ArrowUp (on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift)\n - Cmd-ArrowDown (on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift)\n - Ctrl-ArrowUp (on macOS): [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift)\n - Ctrl-ArrowDown (on macOS): [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift)\n - PageUp: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift)\n - PageDown: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift)\n - Home: [`cursorLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryBackward) ([`selectLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryBackward) with Shift)\n - End: [`cursorLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryForward) ([`selectLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryForward) with Shift)\n - Ctrl-Home (Cmd-Home on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift)\n - Ctrl-End (Cmd-Home on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift)\n - Enter: [`insertNewlineAndIndent`](https://codemirror.net/6/docs/ref/#commands.insertNewlineAndIndent)\n - Ctrl-a (Cmd-a on macOS): [`selectAll`](https://codemirror.net/6/docs/ref/#commands.selectAll)\n - Backspace: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward)\n - Delete: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward)\n - Ctrl-Backspace (Alt-Backspace on macOS): [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward)\n - Ctrl-Delete (Alt-Delete on macOS): [`deleteGroupForward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupForward)\n - Cmd-Backspace (macOS): [`deleteLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.deleteLineBoundaryBackward).\n - Cmd-Delete (macOS): [`deleteLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.deleteLineBoundaryForward).\n*/\nconst standardKeymap = /*@__PURE__*/[\n { key: \"ArrowLeft\", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true },\n { key: \"Mod-ArrowLeft\", mac: \"Alt-ArrowLeft\", run: cursorGroupLeft, shift: selectGroupLeft, preventDefault: true },\n { mac: \"Cmd-ArrowLeft\", run: cursorLineBoundaryLeft, shift: selectLineBoundaryLeft, preventDefault: true },\n { key: \"ArrowRight\", run: cursorCharRight, shift: selectCharRight, preventDefault: true },\n { key: \"Mod-ArrowRight\", mac: \"Alt-ArrowRight\", run: cursorGroupRight, shift: selectGroupRight, preventDefault: true },\n { mac: \"Cmd-ArrowRight\", run: cursorLineBoundaryRight, shift: selectLineBoundaryRight, preventDefault: true },\n { key: \"ArrowUp\", run: cursorLineUp, shift: selectLineUp, preventDefault: true },\n { mac: \"Cmd-ArrowUp\", run: cursorDocStart, shift: selectDocStart },\n { mac: \"Ctrl-ArrowUp\", run: cursorPageUp, shift: selectPageUp },\n { key: \"ArrowDown\", run: cursorLineDown, shift: selectLineDown, preventDefault: true },\n { mac: \"Cmd-ArrowDown\", run: cursorDocEnd, shift: selectDocEnd },\n { mac: \"Ctrl-ArrowDown\", run: cursorPageDown, shift: selectPageDown },\n { key: \"PageUp\", run: cursorPageUp, shift: selectPageUp },\n { key: \"PageDown\", run: cursorPageDown, shift: selectPageDown },\n { key: \"Home\", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward, preventDefault: true },\n { key: \"Mod-Home\", run: cursorDocStart, shift: selectDocStart },\n { key: \"End\", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward, preventDefault: true },\n { key: \"Mod-End\", run: cursorDocEnd, shift: selectDocEnd },\n { key: \"Enter\", run: insertNewlineAndIndent },\n { key: \"Mod-a\", run: selectAll },\n { key: \"Backspace\", run: deleteCharBackward, shift: deleteCharBackward },\n { key: \"Delete\", run: deleteCharForward },\n { key: \"Mod-Backspace\", mac: \"Alt-Backspace\", run: deleteGroupBackward },\n { key: \"Mod-Delete\", mac: \"Alt-Delete\", run: deleteGroupForward },\n { mac: \"Mod-Backspace\", run: deleteLineBoundaryBackward },\n { mac: \"Mod-Delete\", run: deleteLineBoundaryForward }\n].concat(/*@__PURE__*/emacsStyleKeymap.map(b => ({ mac: b.key, run: b.run, shift: b.shift })));\n/**\nThe default keymap. Includes all bindings from\n[`standardKeymap`](https://codemirror.net/6/docs/ref/#commands.standardKeymap) plus the following:\n\n- Alt-ArrowLeft (Ctrl-ArrowLeft on macOS): [`cursorSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxLeft) ([`selectSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxLeft) with Shift)\n- Alt-ArrowRight (Ctrl-ArrowRight on macOS): [`cursorSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxRight) ([`selectSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxRight) with Shift)\n- Alt-ArrowUp: [`moveLineUp`](https://codemirror.net/6/docs/ref/#commands.moveLineUp)\n- Alt-ArrowDown: [`moveLineDown`](https://codemirror.net/6/docs/ref/#commands.moveLineDown)\n- Shift-Alt-ArrowUp: [`copyLineUp`](https://codemirror.net/6/docs/ref/#commands.copyLineUp)\n- Shift-Alt-ArrowDown: [`copyLineDown`](https://codemirror.net/6/docs/ref/#commands.copyLineDown)\n- Escape: [`simplifySelection`](https://codemirror.net/6/docs/ref/#commands.simplifySelection)\n- Ctrl-Enter (Cmd-Enter on macOS): [`insertBlankLine`](https://codemirror.net/6/docs/ref/#commands.insertBlankLine)\n- Alt-l (Ctrl-l on macOS): [`selectLine`](https://codemirror.net/6/docs/ref/#commands.selectLine)\n- Ctrl-i (Cmd-i on macOS): [`selectParentSyntax`](https://codemirror.net/6/docs/ref/#commands.selectParentSyntax)\n- Ctrl-[ (Cmd-[ on macOS): [`indentLess`](https://codemirror.net/6/docs/ref/#commands.indentLess)\n- Ctrl-] (Cmd-] on macOS): [`indentMore`](https://codemirror.net/6/docs/ref/#commands.indentMore)\n- Ctrl-Alt-\\\\ (Cmd-Alt-\\\\ on macOS): [`indentSelection`](https://codemirror.net/6/docs/ref/#commands.indentSelection)\n- Shift-Ctrl-k (Shift-Cmd-k on macOS): [`deleteLine`](https://codemirror.net/6/docs/ref/#commands.deleteLine)\n- Shift-Ctrl-\\\\ (Shift-Cmd-\\\\ on macOS): [`cursorMatchingBracket`](https://codemirror.net/6/docs/ref/#commands.cursorMatchingBracket)\n- Ctrl-/ (Cmd-/ on macOS): [`toggleComment`](https://codemirror.net/6/docs/ref/#commands.toggleComment).\n- Shift-Alt-a: [`toggleBlockComment`](https://codemirror.net/6/docs/ref/#commands.toggleBlockComment).\n*/\nconst defaultKeymap = /*@__PURE__*/[\n { key: \"Alt-ArrowLeft\", mac: \"Ctrl-ArrowLeft\", run: cursorSyntaxLeft, shift: selectSyntaxLeft },\n { key: \"Alt-ArrowRight\", mac: \"Ctrl-ArrowRight\", run: cursorSyntaxRight, shift: selectSyntaxRight },\n { key: \"Alt-ArrowUp\", run: moveLineUp },\n { key: \"Shift-Alt-ArrowUp\", run: copyLineUp },\n { key: \"Alt-ArrowDown\", run: moveLineDown },\n { key: \"Shift-Alt-ArrowDown\", run: copyLineDown },\n { key: \"Escape\", run: simplifySelection },\n { key: \"Mod-Enter\", run: insertBlankLine },\n { key: \"Alt-l\", mac: \"Ctrl-l\", run: selectLine },\n { key: \"Mod-i\", run: selectParentSyntax, preventDefault: true },\n { key: \"Mod-[\", run: indentLess },\n { key: \"Mod-]\", run: indentMore },\n { key: \"Mod-Alt-\\\\\", run: indentSelection },\n { key: \"Shift-Mod-k\", run: deleteLine },\n { key: \"Shift-Mod-\\\\\", run: cursorMatchingBracket },\n { key: \"Mod-/\", run: toggleComment },\n { key: \"Alt-A\", run: toggleBlockComment }\n].concat(standardKeymap);\n/**\nA binding that binds Tab to [`indentMore`](https://codemirror.net/6/docs/ref/#commands.indentMore) and\nShift-Tab to [`indentLess`](https://codemirror.net/6/docs/ref/#commands.indentLess).\nPlease see the [Tab example](../../examples/tab/) before using\nthis.\n*/\nconst indentWithTab = { key: \"Tab\", run: indentMore, shift: indentLess };\n\nexport { blockComment, blockUncomment, copyLineDown, copyLineUp, cursorCharBackward, cursorCharForward, cursorCharLeft, cursorCharRight, cursorDocEnd, cursorDocStart, cursorGroupBackward, cursorGroupForward, cursorGroupLeft, cursorGroupRight, cursorLineBoundaryBackward, cursorLineBoundaryForward, cursorLineBoundaryLeft, cursorLineBoundaryRight, cursorLineDown, cursorLineEnd, cursorLineStart, cursorLineUp, cursorMatchingBracket, cursorPageDown, cursorPageUp, cursorSubwordBackward, cursorSubwordForward, cursorSyntaxLeft, cursorSyntaxRight, defaultKeymap, deleteCharBackward, deleteCharForward, deleteGroupBackward, deleteGroupForward, deleteLine, deleteLineBoundaryBackward, deleteLineBoundaryForward, deleteToLineEnd, deleteToLineStart, deleteTrailingWhitespace, emacsStyleKeymap, history, historyField, historyKeymap, indentLess, indentMore, indentSelection, indentWithTab, insertBlankLine, insertNewline, insertNewlineAndIndent, insertTab, invertedEffects, isolateHistory, lineComment, lineUncomment, moveLineDown, moveLineUp, redo, redoDepth, redoSelection, selectAll, selectCharBackward, selectCharForward, selectCharLeft, selectCharRight, selectDocEnd, selectDocStart, selectGroupBackward, selectGroupForward, selectGroupLeft, selectGroupRight, selectLine, selectLineBoundaryBackward, selectLineBoundaryForward, selectLineBoundaryLeft, selectLineBoundaryRight, selectLineDown, selectLineEnd, selectLineStart, selectLineUp, selectMatchingBracket, selectPageDown, selectPageUp, selectParentSyntax, selectSubwordBackward, selectSubwordForward, selectSyntaxLeft, selectSyntaxRight, simplifySelection, splitLine, standardKeymap, toggleBlockComment, toggleBlockCommentByLine, toggleComment, toggleLineComment, transposeChars, undo, undoDepth, undoSelection };\n","/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\nimport { indentMore, insertTab } from '@codemirror/commands';\n/**\n * CodeMirror commands namespace\n */\nexport var StateCommands;\n(function (StateCommands) {\n /**\n * Indent or insert a tab as appropriate.\n */\n function indentMoreOrInsertTab(target) {\n const arg = { state: target.state, dispatch: target.dispatch };\n const from = target.state.selection.main.from;\n const to = target.state.selection.main.to;\n if (from != to) {\n return indentMore(arg);\n }\n const line = target.state.doc.lineAt(from);\n const before = target.state.doc.slice(line.from, from).toString();\n if (/^\\s*$/.test(before)) {\n return indentMore(arg);\n }\n else {\n return insertTab(arg);\n }\n }\n StateCommands.indentMoreOrInsertTab = indentMoreOrInsertTab;\n})(StateCommands || (StateCommands = {}));\n//# sourceMappingURL=commands.js.map","/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\nimport { combineConfig, Facet } from '@codemirror/state';\nimport { EditorView } from '@codemirror/view';\n/**\n * Custom theme configuration\n *\n * The first non-null value takes precedence\n */\nconst customThemeConfig = Facet.define({\n combine(configs) {\n return combineConfig(configs, {\n fontFamily: null,\n fontSize: null,\n lineHeight: null\n }, {\n fontFamily: (a, b) => a !== null && a !== void 0 ? a : b,\n fontSize: (a, b) => a !== null && a !== void 0 ? a : b,\n lineHeight: (a, b) => a !== null && a !== void 0 ? a : b\n });\n }\n});\nfunction setEditorStyle(view) {\n const { fontFamily, fontSize, lineHeight } = view.state.facet(customThemeConfig);\n let style = '';\n if (fontSize) {\n style += `font-size: ${fontSize}px !important;`;\n }\n if (fontFamily) {\n style += `font-family: ${fontFamily} !important;`;\n }\n if (lineHeight) {\n style += `line-height: ${lineHeight.toString()} !important`;\n }\n return { style: style };\n}\n/**\n * Get the extension to customize an editor theme.\n *\n * @param config Theme customization\n * @returns Editor extension\n */\nexport function customTheme(config) {\n return [\n customThemeConfig.of(config),\n EditorView.editorAttributes.of(setEditorStyle)\n ];\n}\n//# sourceMappingURL=customStyle.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { parseMixed } from '@lezer/common';\nimport { tags } from '@lezer/highlight';\n// Mathematical expression delimiters\nconst INLINE_MATH_DOLLAR = 'InlineMathDollar';\nconst INLINE_MATH_BRACKET = 'InlineMathBracket';\nconst BLOCK_MATH_DOLLAR = 'BlockMathDollar';\nconst BLOCK_MATH_BRACKET = 'BlockMathBracket';\n/**\n * Lengh of the delimiter for a math expression\n */\nconst DELIMITER_LENGTH = {\n [INLINE_MATH_DOLLAR]: 1,\n [INLINE_MATH_BRACKET]: 3,\n [BLOCK_MATH_DOLLAR]: 2,\n [BLOCK_MATH_BRACKET]: 3\n};\n/**\n * Delimiters for math expressions\n */\n// Delimiters must be defined as constant because they are used in object match tests\nconst DELIMITERS = Object.keys(DELIMITER_LENGTH).reduce((agg, name) => {\n agg[name] = { mark: `${name}Mark`, resolve: name };\n return agg;\n}, {});\n/**\n * Define an IPython mathematical expression parser for Markdown.\n *\n * @param latexParser CodeMirror {@link Parser} for LaTeX mathematical expression\n * @returns Markdown extension\n */\nexport function parseMathIPython(latexParser) {\n const defineNodes = new Array();\n Object.keys(DELIMITER_LENGTH).forEach(name => {\n defineNodes.push({\n name,\n style: tags.emphasis\n }, { name: `${name}Mark`, style: tags.processingInstruction });\n });\n return {\n defineNodes,\n parseInline: [\n {\n name: BLOCK_MATH_DOLLAR,\n parse(cx, next, pos) {\n if (next != 36 /* '$' */ || cx.char(pos + 1) != 36) {\n return -1;\n }\n return cx.addDelimiter(DELIMITERS[BLOCK_MATH_DOLLAR], pos, pos + DELIMITER_LENGTH[BLOCK_MATH_DOLLAR], true, true);\n }\n },\n {\n name: INLINE_MATH_DOLLAR,\n parse(cx, next, pos) {\n if (next != 36 /* '$' */ || cx.char(pos + 1) == 36) {\n return -1;\n }\n return cx.addDelimiter(DELIMITERS[INLINE_MATH_DOLLAR], pos, pos + DELIMITER_LENGTH[INLINE_MATH_DOLLAR], true, true);\n }\n },\n // Inline expression wrapped in \\\\( ... \\\\)\n {\n name: INLINE_MATH_BRACKET,\n before: 'Escape',\n parse(cx, next, pos) {\n if (next != 92 /* '\\' */ ||\n cx.char(pos + 1) != 92 ||\n ![40 /* '(' */, 41 /* ')' */].includes(cx.char(pos + 2))) {\n return -1;\n }\n return cx.addDelimiter(DELIMITERS[INLINE_MATH_BRACKET], pos, pos + DELIMITER_LENGTH[INLINE_MATH_BRACKET], cx.char(pos + 2) == 40, cx.char(pos + 2) == 41);\n }\n },\n // Block expression wrapped in \\\\[ ... \\\\]\n {\n name: BLOCK_MATH_BRACKET,\n before: 'Escape',\n parse(cx, next, pos) {\n if (next != 92 /* '\\' */ ||\n cx.char(pos + 1) != 92 ||\n ![91 /* '[' */, 93 /* ']' */].includes(cx.char(pos + 2))) {\n return -1;\n }\n return cx.addDelimiter(DELIMITERS[BLOCK_MATH_BRACKET], pos, pos + DELIMITER_LENGTH[BLOCK_MATH_BRACKET], cx.char(pos + 2) == 91, cx.char(pos + 2) == 93);\n }\n }\n ],\n wrap: latexParser\n ? parseMixed((node, input) => {\n // Test if the node type is one of the math expression\n const delimiterLength = DELIMITER_LENGTH[node.type.name];\n if (delimiterLength) {\n return {\n parser: latexParser,\n // Remove delimiter from LaTeX parser otherwise it won't be highlighted\n overlay: [\n {\n from: node.from + delimiterLength,\n to: node.to - delimiterLength\n }\n ]\n };\n }\n return null;\n })\n : undefined\n };\n}\n//# sourceMappingURL=ipython-md.js.map","/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\n// Inspired by https://discuss.codemirror.net/t/how-to-implement-ruler/4616/\nimport { Facet } from '@codemirror/state';\nimport { EditorView, ViewPlugin } from '@codemirror/view';\nimport { JSONExt } from '@lumino/coreutils';\nconst RULERS_CLASSNAME = 'cm-rulers';\n/**\n * Rulers style\n */\nconst baseTheme = EditorView.baseTheme({\n [`.${RULERS_CLASSNAME}`]: { borderRight: '1px dotted gray', opacity: 0.7 }\n});\n/**\n * Rulers facet\n */\nconst rulerConfig = Facet.define({\n // Merge all unique values\n combine(value) {\n const final = value.reduce((agg, arr) => agg.concat(\n // Check value is not in aggregate nor multiple time in the array.\n arr.filter((v, idx) => !agg.includes(v) && idx == arr.lastIndexOf(v))), []);\n return final;\n }\n});\n/**\n * View plugin displaying the rulers\n */\nconst plugin = ViewPlugin.fromClass(class {\n constructor(view) {\n var _a, _b;\n this.rulersContainer = view.dom.appendChild(document.createElement('div'));\n this.rulersContainer.style.cssText = `\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n pointer-events: none;\n overflow: hidden;\n `;\n const defaultCharacterWidth = view.defaultCharacterWidth;\n const widths = view.state.facet(rulerConfig);\n const guttersWidths = (_b = (_a = view.scrollDOM.querySelector('.cm-gutters')) === null || _a === void 0 ? void 0 : _a.clientWidth) !== null && _b !== void 0 ? _b : 0;\n this.rulers = widths.map(width => {\n const ruler = this.rulersContainer.appendChild(document.createElement('div'));\n ruler.classList.add(RULERS_CLASSNAME);\n ruler.style.cssText = `\n position: absolute;\n left: ${guttersWidths + width * defaultCharacterWidth}px;\n height: 100%;\n `;\n // FIXME: This should be equal to the amount of padding on a line.\n // This value should be extracted from CodeMirror rather than hardcoded.\n ruler.style.width = '6px';\n return ruler;\n });\n }\n update(update) {\n var _a, _b;\n const widths = update.view.state.facet(rulerConfig);\n if (update.viewportChanged ||\n update.geometryChanged ||\n !JSONExt.deepEqual(widths, update.startState.facet(rulerConfig))) {\n const guttersWidth = (_b = (_a = update.view.scrollDOM.querySelector('.cm-gutters')) === null || _a === void 0 ? void 0 : _a.clientWidth) !== null && _b !== void 0 ? _b : 0;\n const defaultCharacterWidth = update.view.defaultCharacterWidth;\n this.rulers.forEach((ruler, rulerIdx) => {\n ruler.style.left = `${guttersWidth + widths[rulerIdx] * defaultCharacterWidth}px`;\n });\n }\n }\n destroy() {\n this.rulers.forEach(ruler => {\n ruler.remove();\n });\n this.rulersContainer.remove();\n }\n});\n/**\n * Extension for CodeMirror 6 displaying rulers.\n *\n * @param value Rulers position\n * @returns CodeMirror 6 extension\n */\nexport function rulers(value) {\n return [baseTheme, rulerConfig.of(value), plugin];\n}\n//# sourceMappingURL=rulers.js.map","/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n *\n * Binding for yjs and codemirror\n *\n * It is a simplification of https://github.com/yjs/y-codemirror.next\n * licensed under MIT License by Kevin Jahns\n */\nimport { Annotation, EditorSelection, Facet } from '@codemirror/state';\nimport { ViewPlugin } from '@codemirror/view';\nimport { createAbsolutePositionFromRelativePosition, createRelativePositionFromJSON, createRelativePositionFromTypeIndex, relativePositionToJSON } from 'yjs';\n/**\n * Defines a range on text using relative positions that can be transformed back to\n * absolute positions. (https://docs.yjs.dev/api/relative-positions)\n */\nexport class YRange {\n /**\n * @param yanchor\n * @param yhead\n */\n constructor(yanchor, yhead) {\n this.yanchor = yanchor;\n this.yhead = yhead;\n }\n /**\n * Convert the position to JSON\n */\n toJSON() {\n return {\n yanchor: relativePositionToJSON(this.yanchor),\n yhead: relativePositionToJSON(this.yhead)\n };\n }\n /**\n * Convert a JSON range to a YRange\n * @param json Range to convert\n * @return The range as YRange\n */\n static fromJSON(json) {\n return new YRange(createRelativePositionFromJSON(json.yanchor), createRelativePositionFromJSON(json.yhead));\n }\n}\n/**\n * Yjs binding configuration\n */\nexport class YSyncConfig {\n /**\n * Create a new binding configuration\n *\n * @param ytext Yjs text to synchronize\n */\n constructor(ytext) {\n this.ytext = ytext;\n }\n /**\n * Helper function to transform an absolute index position to a Yjs-based relative position\n * (https://docs.yjs.dev/api/relative-positions).\n *\n * A relative position can be transformed back to an absolute position even after the document has changed. The position is\n * automatically adapted. This does not require any position transformations. Relative positions are computed based on\n * the internal Yjs document model. Peers that share content through Yjs are guaranteed that their positions will always\n * synced up when using relative positions.\n *\n * ```js\n * import { ySyncFacet } from 'y-codemirror'\n *\n * ..\n * const ysync = view.state.facet(ySyncFacet)\n * // transform an absolute index position to a ypos\n * const ypos = ysync.getYPos(3)\n * // transform the ypos back to an absolute position\n * ysync.fromYPos(ypos) // => 3\n * ```\n *\n * It cannot be guaranteed that absolute index positions can be synced up between peers.\n * This might lead to undesired behavior when implementing features that require that all peers see the\n * same marked range (e.g. a comment plugin).\n *\n * @param pos\n * @param assoc\n */\n toYPos(pos, assoc = 0) {\n return createRelativePositionFromTypeIndex(this.ytext, pos, assoc);\n }\n /**\n * @param rpos\n */\n fromYPos(rpos) {\n const pos = createAbsolutePositionFromRelativePosition(createRelativePositionFromJSON(rpos), this.ytext.doc);\n if (pos == null || pos.type !== this.ytext) {\n throw new Error('[y-codemirror] The position you want to retrieve was created by a different document');\n }\n return {\n pos: pos.index,\n assoc: pos.assoc\n };\n }\n /**\n * @param range\n * @return\n */\n toYRange(range) {\n const assoc = range.assoc;\n const yanchor = this.toYPos(range.anchor, assoc);\n const yhead = this.toYPos(range.head, assoc);\n return new YRange(yanchor, yhead);\n }\n /**\n * @param yrange\n */\n fromYRange(yrange) {\n const anchor = this.fromYPos(yrange.yanchor);\n const head = this.fromYPos(yrange.yhead);\n if (anchor.pos === head.pos) {\n return EditorSelection.cursor(head.pos, head.assoc);\n }\n return EditorSelection.range(anchor.pos, head.pos);\n }\n}\n/**\n * Yjs binding facet\n */\nexport const ySyncFacet = Facet.define({\n combine(inputs) {\n return inputs[inputs.length - 1];\n }\n});\n/**\n * Yjs binding annotation\n *\n * It is used to track the origin of the document changes\n */\nexport const ySyncAnnotation = Annotation.define();\n/**\n * Yjs binding view plugin to synchronize the\n * editor state with the Yjs document.\n */\nexport const ySync = ViewPlugin.fromClass(class {\n constructor(view) {\n this.conf = view.state.facet(ySyncFacet);\n this._observer = (event, tr) => {\n var _a;\n if (tr.origin !== this.conf) {\n const delta = event.delta;\n const changes = [];\n let pos = 0;\n for (let i = 0; i < delta.length; i++) {\n const d = delta[i];\n if (d.insert != null) {\n changes.push({ from: pos, to: pos, insert: d.insert });\n }\n else if (d.delete != null) {\n changes.push({ from: pos, to: pos + d.delete, insert: '' });\n pos += d.delete;\n }\n else {\n pos += (_a = d.retain) !== null && _a !== void 0 ? _a : 0;\n }\n }\n view.dispatch({\n changes,\n // Specified the changes origin to not loop when synchronizing\n annotations: [ySyncAnnotation.of(this.conf)]\n });\n }\n };\n this._ytext = this.conf.ytext;\n this._ytext.observe(this._observer);\n }\n update(update) {\n if (!update.docChanged ||\n (update.transactions.length > 0 &&\n update.transactions[0].annotation(ySyncAnnotation) === this.conf)) {\n return;\n }\n const ytext = this.conf.ytext;\n ytext.doc.transact(() => {\n /**\n * This variable adjusts the fromA position to the current position in the Y.Text type.\n */\n let adj = 0;\n update.changes.iterChanges((fromA, toA, fromB, toB, insert) => {\n const insertText = insert.sliceString(0, insert.length, '\\n');\n if (fromA !== toA) {\n ytext.delete(fromA + adj, toA - fromA);\n }\n if (insertText.length > 0) {\n ytext.insert(fromA + adj, insertText);\n }\n adj += insertText.length - (toA - fromA);\n });\n // Set the configuration as origin to not loop when synchronizing\n }, this.conf);\n }\n destroy() {\n this._ytext.unobserve(this._observer);\n }\n});\n/**\n * Extension for CodeMirror 6 binding the Yjs text (source of truth)\n * and the editor state.\n *\n * @param ytext Yjs text to bind\n * @param undoManager Yjs text undo manager\n * @returns CodeMirror 6 extension\n */\nexport function ybinding({ ytext, undoManager }) {\n const ySyncConfig = new YSyncConfig(ytext);\n // We don't need the undo manager extension as in y-codemirror.next\n // because we deal with undo/redo with our own keyboard shortcut mechanism.\n return [\n ySyncFacet.of(ySyncConfig),\n ySync,\n // We need to add a new origin to the undo manager to ensure text updates\n // are tracked.\n undoManager\n ? ViewPlugin.define(() => {\n undoManager.addTrackedOrigin(ySyncConfig);\n return {\n destroy: () => {\n undoManager.removeTrackedOrigin(ySyncConfig);\n }\n };\n })\n : []\n ];\n}\n//# sourceMappingURL=ybinding.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { closeBrackets, closeBracketsKeymap } from '@codemirror/autocomplete';\nimport { defaultKeymap, indentLess } from '@codemirror/commands';\nimport { bracketMatching, foldGutter, indentOnInput, indentUnit } from '@codemirror/language';\nimport { Compartment, EditorState, Prec, StateEffect } from '@codemirror/state';\nimport { crosshairCursor, drawSelection, EditorView, highlightActiveLine, highlightTrailingWhitespace, highlightWhitespace, keymap, lineNumbers, rectangularSelection, scrollPastEnd, tooltips } from '@codemirror/view';\nimport { nullTranslator } from '@jupyterlab/translation';\nimport { JSONExt } from '@lumino/coreutils';\nimport { Signal } from '@lumino/signaling';\nimport { StateCommands } from './commands';\nimport { customTheme, rulers } from './extensions';\n/**\n * The class name added to read only editor widgets.\n */\nconst READ_ONLY_CLASS = 'jp-mod-readOnly';\n/**\n * Editor configuration handler\n *\n * It stores the editor configuration and the editor extensions.\n * It also allows to inject new extensions into an editor.\n */\nexport class ExtensionsHandler {\n constructor({ baseConfiguration, config, defaultExtensions } = {}) {\n this._configChanged = new Signal(this);\n this._disposed = new Signal(this);\n this._isDisposed = false;\n this._immutables = new Set();\n this._baseConfig = baseConfiguration !== null && baseConfiguration !== void 0 ? baseConfiguration : {};\n this._config = config !== null && config !== void 0 ? config : {};\n this._configurableBuilderMap = new Map(defaultExtensions);\n const configurables = Object.keys(this._config).concat(Object.keys(this._baseConfig));\n this._immutables = new Set([...this._configurableBuilderMap.keys()].filter(key => !configurables.includes(key)));\n }\n /**\n * Signal triggered when the editor configuration changes.\n * It provides the mapping of the new configuration (only those that changed).\n *\n * It should result in a call to `IExtensionsHandler.reconfigureExtensions`.\n */\n get configChanged() {\n return this._configChanged;\n }\n /**\n * A signal emitted when the object is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * Tests whether the object is disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the resources held by the object.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n this._disposed.emit();\n Signal.clearData(this);\n }\n /**\n * Get a config option for the editor.\n */\n getOption(option) {\n var _a;\n return (_a = this._config[option]) !== null && _a !== void 0 ? _a : this._baseConfig[option];\n }\n /**\n * Whether the option exists or not.\n */\n hasOption(option) {\n return (Object.keys(this._config).includes(option) ||\n Object.keys(this._baseConfig).includes(option));\n }\n /**\n * Set a config option for the editor.\n *\n * You will need to reconfigure the editor extensions by listening\n * to `IExtensionsHandler.configChanged`.\n */\n setOption(option, value) {\n // Don't bother setting the option if it is already the same.\n if (this._config[option] !== value) {\n this._config[option] = value;\n this._configChanged.emit({ [option]: value });\n }\n }\n /**\n * Set a base config option for the editor.\n *\n * You will need to reconfigure the editor extensions by listening\n * to `IExtensionsHandler.configChanged`.\n */\n setBaseOptions(options) {\n const changed = this._getChangedOptions(options, this._baseConfig);\n if (changed.length > 0) {\n this._baseConfig = options;\n const customizedKeys = Object.keys(this._config);\n const notOverridden = changed.filter(k => !customizedKeys.includes(k));\n if (notOverridden.length > 0) {\n this._configChanged.emit(notOverridden.reduce((agg, key) => {\n agg[key] = this._baseConfig[key];\n return agg;\n }, {}));\n }\n }\n }\n /**\n * Set config options for the editor.\n *\n * You will need to reconfigure the editor extensions by listening\n * to `EditorHandler.configChanged`.\n *\n * This method is preferred when setting several options. The\n * options are set within an operation, which only performs\n * the costly update at the end, and not after every option\n * is set.\n */\n setOptions(options) {\n const changed = this._getChangedOptions(options, this._config);\n if (changed.length > 0) {\n this._config = { ...options };\n this._configChanged.emit(changed.reduce((agg, key) => {\n var _a;\n agg[key] = (_a = this._config[key]) !== null && _a !== void 0 ? _a : this._baseConfig[key];\n return agg;\n }, {}));\n }\n }\n /**\n * Reconfigures the extension mapped with key with the provided value.\n *\n * @param view Editor view\n * @param key Parameter unique key\n * @param value Parameter value to be applied\n */\n reconfigureExtension(view, key, value) {\n const effect = this.getEffect(view.state, key, value);\n if (effect) {\n view.dispatch({\n effects: [effect]\n });\n }\n }\n /**\n * Reconfigures all the extensions mapped with the options from the\n * provided partial configuration.\n *\n * @param view Editor view\n * @param configuration Editor configuration\n */\n reconfigureExtensions(view, configuration) {\n const effects = Object.keys(configuration)\n .filter(key => this.has(key))\n .map(key => this.getEffect(view.state, key, configuration[key]));\n view.dispatch({\n effects: effects.filter(effect => effect !== null)\n });\n }\n /**\n * Appends extensions to the top-level configuration of the\n * editor.\n *\n * Injected extension cannot be removed.\n *\n * ### Notes\n * You should prefer registering a IEditorExtensionFactory instead\n * of this feature.\n *\n * @alpha\n * @param view Editor view\n * @param extension Editor extension to inject\n */\n injectExtension(view, extension) {\n view.dispatch({\n effects: StateEffect.appendConfig.of(extension)\n });\n }\n /**\n * Returns the list of initial extensions of an editor\n * based on the configuration.\n *\n * @returns The initial editor extensions\n */\n getInitialExtensions() {\n const configuration = { ...this._baseConfig, ...this._config };\n const extensions = [...this._immutables]\n .map(key => { var _a; return (_a = this.get(key)) === null || _a === void 0 ? void 0 : _a.instance(undefined); })\n .filter(ext => ext);\n for (const k of Object.keys(configuration)) {\n const builder = this.get(k);\n if (builder) {\n const value = configuration[k];\n extensions.push(builder.instance(value));\n }\n }\n return extensions;\n }\n /**\n * Get a extension builder\n * @param key Extension unique identifier\n * @returns The extension builder\n */\n get(key) {\n return this._configurableBuilderMap.get(key);\n }\n /**\n * Whether the editor has an extension for the identifier.\n *\n * @param key Extension unique identifier\n * @returns Extension existence\n */\n has(key) {\n return this._configurableBuilderMap.has(key);\n }\n getEffect(state, key, value) {\n var _a;\n const builder = this.get(key);\n return (_a = builder === null || builder === void 0 ? void 0 : builder.reconfigure(value)) !== null && _a !== void 0 ? _a : null;\n }\n _getChangedOptions(newConfig, oldConfig) {\n const changed = new Array();\n const newKeys = new Array();\n for (const [key, value] of Object.entries(newConfig)) {\n newKeys.push(key);\n if (oldConfig[key] !== value) {\n changed.push(key);\n }\n }\n // Add removed old keys\n changed.push(...Object.keys(oldConfig).filter(k => !newKeys.includes(k)));\n return changed;\n }\n}\n/**\n * CodeMirror extensions registry\n */\nexport class EditorExtensionRegistry {\n constructor() {\n this.configurationBuilder = new Map();\n this.configurationSchema = {};\n this.defaultOptions = {};\n this.handlers = new Set();\n this.immutableExtensions = new Set();\n this._baseConfiguration = {};\n }\n /**\n * Base editor configuration\n *\n * This is the default configuration optionally modified by the user;\n * e.g. through user settings.\n */\n get baseConfiguration() {\n return { ...this.defaultOptions, ...this._baseConfiguration };\n }\n set baseConfiguration(v) {\n if (!JSONExt.deepEqual(v, this._baseConfiguration)) {\n this._baseConfiguration = v;\n for (const handler of this.handlers) {\n handler.setBaseOptions(this.baseConfiguration);\n }\n }\n }\n /**\n * Default editor configuration\n *\n * This is the default configuration as defined when extensions\n * are registered.\n */\n get defaultConfiguration() {\n // Only options with schema should be JSON serializable\n // So we cannot use `JSONExt.deepCopy` on the default options.\n return Object.freeze({ ...this.defaultOptions });\n }\n /**\n * Editor configuration JSON schema\n */\n get settingsSchema() {\n return Object.freeze(JSONExt.deepCopy(this.configurationSchema));\n }\n /**\n * Add a default editor extension\n *\n * @template T Extension parameter type\n * @param factory Extension factory\n */\n addExtension(factory) {\n var _a;\n if (this.configurationBuilder.has(factory.name)) {\n throw new Error(`Extension named ${factory.name} is already registered.`);\n }\n this.configurationBuilder.set(factory.name, factory);\n if (typeof factory.default != 'undefined') {\n this.defaultOptions[factory.name] = factory.default;\n }\n if (factory.schema) {\n this.configurationSchema[factory.name] = {\n default: (_a = factory.default) !== null && _a !== void 0 ? _a : null,\n ...factory.schema\n };\n this.defaultOptions[factory.name] =\n this.configurationSchema[factory.name].default;\n }\n }\n /**\n * Create a new extensions handler for an editor\n *\n * @param options Extensions options and initial editor configuration\n */\n createNew(options) {\n const configuration = new Array();\n for (const [key, builder] of this.configurationBuilder.entries()) {\n const extension = builder.factory(options);\n if (extension) {\n configuration.push([key, extension]);\n }\n }\n const handler = new ExtensionsHandler({\n baseConfiguration: this.baseConfiguration,\n config: options.config,\n defaultExtensions: configuration\n });\n this.handlers.add(handler);\n handler.disposed.connect(() => {\n this.handlers.delete(handler);\n });\n return handler;\n }\n}\n/**\n * Editor extension registry namespace\n */\n(function (EditorExtensionRegistry) {\n /**\n * Dynamically configurable editor extension.\n */\n class ConfigurableExtension {\n /**\n * Create a dynamic editor extension.\n *\n * @param builder Extension builder\n */\n constructor(builder) {\n this._compartment = new Compartment();\n this._builder = builder;\n }\n /**\n * Create an editor extension for the provided value.\n *\n * @param value Editor extension parameter value\n * @returns The editor extension\n */\n instance(value) {\n return this._compartment.of(this._builder(value));\n }\n /**\n * Reconfigure an editor extension.\n *\n * @param value Editor extension value\n * @returns Editor state effect\n */\n reconfigure(value) {\n return this._compartment.reconfigure(this._builder(value));\n }\n }\n /**\n * Immutable editor extension class\n */\n class ImmutableExtension {\n /**\n * Create an immutable editor extension.\n *\n * @param extension Extension\n */\n constructor(extension) {\n this._extension = extension;\n }\n /**\n * Create an editor extension.\n *\n * @returns The editor extension\n */\n instance() {\n return this._extension;\n }\n /**\n * Reconfigure an editor extension.\n *\n * This is a no-op\n */\n reconfigure() {\n // This is a no-op\n return null;\n }\n }\n /**\n * Creates a dynamically configurable editor extension.\n *\n * @param builder Extension builder\n * @return The extension\n */\n function createConfigurableExtension(builder) {\n return new ConfigurableExtension(builder);\n }\n EditorExtensionRegistry.createConfigurableExtension = createConfigurableExtension;\n /**\n * Creates a configurable extension returning\n * one of two extensions depending on a boolean value.\n *\n * @param truthy Extension to apply when the parameter is true\n * @param falsy Extension to apply when the parameter is false\n * @return The extension\n */\n function createConditionalExtension(truthy, falsy = []) {\n return new ConfigurableExtension(value => value ? truthy : falsy);\n }\n EditorExtensionRegistry.createConditionalExtension = createConditionalExtension;\n /**\n * Creates an immutable extension.\n *\n * @param extension Immutable extension\n * @return The extension\n */\n function createImmutableExtension(extension) {\n return new ImmutableExtension(extension);\n }\n EditorExtensionRegistry.createImmutableExtension = createImmutableExtension;\n /**\n * Get the default editor extensions.\n *\n * @returns CodeMirror 6 extension factories\n */\n function getDefaultExtensions(options = {}) {\n const { themes, translator } = options;\n const trans = (translator !== null && translator !== void 0 ? translator : nullTranslator).load('jupyterlab');\n const extensions = [\n Object.freeze({\n name: 'autoClosingBrackets',\n default: false,\n factory: () => createConditionalExtension(closeBrackets()),\n schema: {\n type: 'boolean',\n title: trans.__('Auto Closing Brackets')\n }\n }),\n Object.freeze({\n name: 'codeFolding',\n default: false,\n factory: () => createConditionalExtension(foldGutter()),\n schema: {\n type: 'boolean',\n title: trans.__('Code Folding')\n }\n }),\n Object.freeze({\n name: 'cursorBlinkRate',\n default: 1200,\n factory: () => createConfigurableExtension((value) => drawSelection({ cursorBlinkRate: value })),\n schema: {\n type: 'number',\n title: trans.__('Cursor blinking rate'),\n description: trans.__('Half-period in milliseconds used for cursor blinking. The default blink rate is 1200ms. By setting this to zero, blinking can be disabled.')\n }\n }),\n Object.freeze({\n name: 'highlightActiveLine',\n default: false,\n factory: () => createConditionalExtension(highlightActiveLine()),\n schema: {\n type: 'boolean',\n title: trans.__('Highlight the active line')\n }\n }),\n Object.freeze({\n name: 'highlightTrailingWhitespace',\n default: false,\n factory: () => createConditionalExtension(highlightTrailingWhitespace()),\n schema: {\n type: 'boolean',\n title: trans.__('Highlight trailing white spaces')\n }\n }),\n Object.freeze({\n name: 'highlightWhitespace',\n default: false,\n factory: () => createConditionalExtension(highlightWhitespace()),\n schema: {\n type: 'boolean',\n title: trans.__('Highlight white spaces')\n }\n }),\n Object.freeze({\n name: 'indentUnit',\n default: '4',\n factory: () => createConfigurableExtension((value) => value == 'Tab'\n ? indentUnit.of('\\t')\n : indentUnit.of(' '.repeat(parseInt(value, 10)))),\n schema: {\n type: 'string',\n title: trans.__('Indentation unit'),\n description: trans.__('The indentation is a `Tab` or the number of spaces. This defaults to 4 spaces.'),\n enum: ['Tab', '1', '2', '4', '8']\n }\n }),\n // Default keyboard shortcuts\n // TODO at some point we may want to get this configurable\n Object.freeze({\n name: 'keymap',\n default: [\n ...defaultKeymap,\n {\n key: 'Tab',\n run: StateCommands.indentMoreOrInsertTab,\n shift: indentLess\n }\n ],\n factory: () => createConfigurableExtension(value => keymap.of(value))\n }),\n Object.freeze({\n name: 'lineNumbers',\n default: true,\n factory: () => createConditionalExtension(lineNumbers()),\n schema: {\n type: 'boolean',\n title: trans.__('Line Numbers')\n }\n }),\n Object.freeze({\n name: 'lineWrap',\n factory: () => createConditionalExtension(EditorView.lineWrapping),\n default: true,\n schema: {\n type: 'boolean',\n title: trans.__('Line Wrap')\n }\n }),\n Object.freeze({\n name: 'matchBrackets',\n default: true,\n factory: () => createConditionalExtension([\n bracketMatching(),\n // closeBracketsKeymap must have higher precedence over defaultKeymap\n Prec.high(keymap.of(closeBracketsKeymap))\n ]),\n schema: {\n type: 'boolean',\n title: trans.__('Match Brackets')\n }\n }),\n Object.freeze({\n name: 'rectangularSelection',\n default: true,\n factory: () => createConditionalExtension([\n rectangularSelection(),\n crosshairCursor()\n ]),\n schema: {\n type: 'boolean',\n title: trans.__('Rectangular selection'),\n description: trans.__('Rectangular (block) selection can be created by dragging the mouse pointer while holding the left mouse button and the Alt key. When the Alt key is pressed, a crosshair cursor will appear, indicating that the rectangular selection mode is active.')\n }\n }),\n Object.freeze({\n name: 'readOnly',\n default: false,\n factory: () => createConfigurableExtension((value) => [\n EditorState.readOnly.of(value),\n value\n ? EditorView.editorAttributes.of({ class: READ_ONLY_CLASS })\n : []\n ])\n }),\n Object.freeze({\n name: 'rulers',\n default: [],\n factory: () => createConfigurableExtension((value) => value.length > 0 ? rulers(value) : []),\n schema: {\n type: 'array',\n title: trans.__('Rulers'),\n items: {\n type: 'number',\n minimum: 0\n }\n }\n }),\n Object.freeze({\n name: 'scrollPastEnd',\n default: false,\n factory: (options) => options.inline ? null : createConditionalExtension(scrollPastEnd())\n }),\n Object.freeze({\n name: 'smartIndent',\n default: true,\n factory: () => createConditionalExtension(indentOnInput()),\n schema: {\n type: 'boolean',\n title: trans.__('Smart Indentation')\n }\n }),\n Object.freeze({\n name: 'tabSize',\n default: 4,\n factory: () => createConfigurableExtension((value) => EditorState.tabSize.of(value)),\n schema: {\n type: 'number',\n title: trans.__('Tab size')\n }\n }),\n Object.freeze({\n name: 'tooltips',\n factory: () => \n // we need `absolute` due to use of `contain: layout` in lumino;\n // we attach to body to ensure cursor collaboration tooltip is\n // visible in first line of the editor.\n createImmutableExtension(tooltips({\n position: 'absolute',\n parent: document.body\n }))\n }),\n Object.freeze({\n name: 'allowMultipleSelections',\n default: true,\n factory: () => createConfigurableExtension((value) => EditorState.allowMultipleSelections.of(value)),\n schema: {\n type: 'boolean',\n title: trans.__('Multiple selections')\n }\n }),\n Object.freeze({\n name: 'customStyles',\n factory: () => createConfigurableExtension(config => customTheme(config)),\n default: {\n fontFamily: null,\n fontSize: null,\n lineHeight: null\n },\n schema: {\n title: trans.__('Custom editor styles'),\n type: 'object',\n properties: {\n fontFamily: {\n type: ['string', 'null'],\n title: trans.__('Font Family')\n },\n fontSize: {\n type: ['number', 'null'],\n minimum: 1,\n maximum: 100,\n title: trans.__('Font Size')\n },\n lineHeight: {\n type: ['number', 'null'],\n title: trans.__('Line Height')\n }\n },\n additionalProperties: false\n }\n })\n ];\n if (themes) {\n extensions.push(Object.freeze({\n name: 'theme',\n default: 'jupyter',\n factory: () => createConfigurableExtension(value => themes.getTheme(value)),\n schema: {\n type: 'string',\n title: trans.__('Theme'),\n description: trans.__('CodeMirror theme')\n }\n }));\n }\n if (translator) {\n extensions.push(Object.freeze({\n name: 'translation',\n // The list of internal strings is available at https://codemirror.net/examples/translate/\n default: {\n // @codemirror/view\n 'Control character': trans.__('Control character'),\n // @codemirror/commands\n 'Selection deleted': trans.__('Selection deleted'),\n // @codemirror/language\n 'Folded lines': trans.__('Folded lines'),\n 'Unfolded lines': trans.__('Unfolded lines'),\n to: trans.__('to'),\n 'folded code': trans.__('folded code'),\n unfold: trans.__('unfold'),\n 'Fold line': trans.__('Fold line'),\n 'Unfold line': trans.__('Unfold line'),\n // @codemirror/search\n 'Go to line': trans.__('Go to line'),\n go: trans.__('go'),\n Find: trans.__('Find'),\n Replace: trans.__('Replace'),\n next: trans.__('next'),\n previous: trans.__('previous'),\n all: trans.__('all'),\n 'match case': trans.__('match case'),\n replace: trans.__('replace'),\n 'replace all': trans.__('replace all'),\n close: trans.__('close'),\n 'current match': trans.__('current match'),\n 'replaced $ matches': trans.__('replaced $ matches'),\n 'replaced match on line $': trans.__('replaced match on line $'),\n 'on line': trans.__('on line'),\n // @codemirror/autocomplete\n Completions: trans.__('Completions'),\n // @codemirror/lint\n Diagnostics: trans.__('Diagnostics'),\n 'No diagnostics': trans.__('No diagnostics')\n },\n factory: () => createConfigurableExtension(value => EditorState.phrases.of(value))\n }));\n }\n return extensions;\n }\n EditorExtensionRegistry.getDefaultExtensions = getDefaultExtensions;\n})(EditorExtensionRegistry || (EditorExtensionRegistry = {}));\n//# sourceMappingURL=extension.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/**\n * A namespace for `IEditorMimeTypeService`.\n */\nexport var IEditorMimeTypeService;\n(function (IEditorMimeTypeService) {\n /**\n * The default mime type.\n */\n IEditorMimeTypeService.defaultMimeType = 'text/plain';\n})(IEditorMimeTypeService || (IEditorMimeTypeService = {}));\n//# sourceMappingURL=mimetype.js.map","import { NodeProp } from '@lezer/common';\nimport { LRParser, LocalTokenGroup } from '@lezer/lr';\n\nclass Node {\n constructor(start) {\n this.start = start;\n }\n}\nclass GrammarDeclaration extends Node {\n constructor(start, rules, topRules, tokens, localTokens, context, externalTokens, externalSpecializers, externalPropSources, precedences, mainSkip, scopedSkip, dialects, externalProps, autoDelim) {\n super(start);\n this.rules = rules;\n this.topRules = topRules;\n this.tokens = tokens;\n this.localTokens = localTokens;\n this.context = context;\n this.externalTokens = externalTokens;\n this.externalSpecializers = externalSpecializers;\n this.externalPropSources = externalPropSources;\n this.precedences = precedences;\n this.mainSkip = mainSkip;\n this.scopedSkip = scopedSkip;\n this.dialects = dialects;\n this.externalProps = externalProps;\n this.autoDelim = autoDelim;\n }\n toString() { return Object.values(this.rules).join(\"\\n\"); }\n}\nclass RuleDeclaration extends Node {\n constructor(start, id, props, params, expr) {\n super(start);\n this.id = id;\n this.props = props;\n this.params = params;\n this.expr = expr;\n }\n toString() {\n return this.id.name + (this.params.length ? `<${this.params.join()}>` : \"\") + \" -> \" + this.expr;\n }\n}\nclass PrecDeclaration extends Node {\n constructor(start, items) {\n super(start);\n this.items = items;\n }\n}\nclass TokenPrecDeclaration extends Node {\n constructor(start, items) {\n super(start);\n this.items = items;\n }\n}\nclass TokenConflictDeclaration extends Node {\n constructor(start, a, b) {\n super(start);\n this.a = a;\n this.b = b;\n }\n}\nclass TokenDeclaration extends Node {\n constructor(start, precedences, conflicts, rules, literals) {\n super(start);\n this.precedences = precedences;\n this.conflicts = conflicts;\n this.rules = rules;\n this.literals = literals;\n }\n}\nclass LocalTokenDeclaration extends Node {\n constructor(start, precedences, rules, fallback) {\n super(start);\n this.precedences = precedences;\n this.rules = rules;\n this.fallback = fallback;\n }\n}\nclass LiteralDeclaration extends Node {\n constructor(start, literal, props) {\n super(start);\n this.literal = literal;\n this.props = props;\n }\n}\nclass ContextDeclaration extends Node {\n constructor(start, id, source) {\n super(start);\n this.id = id;\n this.source = source;\n }\n}\nclass ExternalTokenDeclaration extends Node {\n constructor(start, id, source, tokens) {\n super(start);\n this.id = id;\n this.source = source;\n this.tokens = tokens;\n }\n}\nclass ExternalSpecializeDeclaration extends Node {\n constructor(start, type, token, id, source, tokens) {\n super(start);\n this.type = type;\n this.token = token;\n this.id = id;\n this.source = source;\n this.tokens = tokens;\n }\n}\nclass ExternalPropSourceDeclaration extends Node {\n constructor(start, id, source) {\n super(start);\n this.id = id;\n this.source = source;\n }\n}\nclass ExternalPropDeclaration extends Node {\n constructor(start, id, externalID, source) {\n super(start);\n this.id = id;\n this.externalID = externalID;\n this.source = source;\n }\n}\nclass Identifier extends Node {\n constructor(start, name) {\n super(start);\n this.name = name;\n }\n toString() { return this.name; }\n}\nclass Expression extends Node {\n walk(f) { return f(this); }\n eq(_other) { return false; }\n}\nExpression.prototype.prec = 10;\nclass NameExpression extends Expression {\n constructor(start, id, args) {\n super(start);\n this.id = id;\n this.args = args;\n }\n toString() { return this.id.name + (this.args.length ? `<${this.args.join()}>` : \"\"); }\n eq(other) {\n return this.id.name == other.id.name && exprsEq(this.args, other.args);\n }\n walk(f) {\n let args = walkExprs(this.args, f);\n return f(args == this.args ? this : new NameExpression(this.start, this.id, args));\n }\n}\nclass SpecializeExpression extends Expression {\n constructor(start, type, props, token, content) {\n super(start);\n this.type = type;\n this.props = props;\n this.token = token;\n this.content = content;\n }\n toString() { return `@${this.type}[${this.props.join(\",\")}]<${this.token}, ${this.content}>`; }\n eq(other) {\n return this.type == other.type && Prop.eqProps(this.props, other.props) && exprEq(this.token, other.token) &&\n exprEq(this.content, other.content);\n }\n walk(f) {\n let token = this.token.walk(f), content = this.content.walk(f);\n return f(token == this.token && content == this.content ? this : new SpecializeExpression(this.start, this.type, this.props, token, content));\n }\n}\nclass InlineRuleExpression extends Expression {\n constructor(start, rule) {\n super(start);\n this.rule = rule;\n }\n toString() {\n let rule = this.rule;\n return `${rule.id}${rule.props.length ? `[${rule.props.join(\",\")}]` : \"\"} { ${rule.expr} }`;\n }\n eq(other) {\n let rule = this.rule, oRule = other.rule;\n return exprEq(rule.expr, oRule.expr) && rule.id.name == oRule.id.name && Prop.eqProps(rule.props, oRule.props);\n }\n walk(f) {\n let rule = this.rule, expr = rule.expr.walk(f);\n return f(expr == rule.expr ? this :\n new InlineRuleExpression(this.start, new RuleDeclaration(rule.start, rule.id, rule.props, [], expr)));\n }\n}\nclass ChoiceExpression extends Expression {\n constructor(start, exprs) {\n super(start);\n this.exprs = exprs;\n }\n toString() { return this.exprs.map(e => maybeParens(e, this)).join(\" | \"); }\n eq(other) {\n return exprsEq(this.exprs, other.exprs);\n }\n walk(f) {\n let exprs = walkExprs(this.exprs, f);\n return f(exprs == this.exprs ? this : new ChoiceExpression(this.start, exprs));\n }\n}\nChoiceExpression.prototype.prec = 1;\nclass SequenceExpression extends Expression {\n constructor(start, exprs, markers, empty = false) {\n super(start);\n this.exprs = exprs;\n this.markers = markers;\n this.empty = empty;\n }\n toString() { return this.empty ? \"()\" : this.exprs.map(e => maybeParens(e, this)).join(\" \"); }\n eq(other) {\n return exprsEq(this.exprs, other.exprs) && this.markers.every((m, i) => {\n let om = other.markers[i];\n return m.length == om.length && m.every((x, i) => x.eq(om[i]));\n });\n }\n walk(f) {\n let exprs = walkExprs(this.exprs, f);\n return f(exprs == this.exprs ? this : new SequenceExpression(this.start, exprs, this.markers, this.empty && !exprs.length));\n }\n}\nSequenceExpression.prototype.prec = 2;\nclass ConflictMarker extends Node {\n constructor(start, id, type) {\n super(start);\n this.id = id;\n this.type = type;\n }\n toString() { return (this.type == \"ambig\" ? \"~\" : \"!\") + this.id.name; }\n eq(other) { return this.id.name == other.id.name && this.type == other.type; }\n}\nclass RepeatExpression extends Expression {\n constructor(start, expr, kind) {\n super(start);\n this.expr = expr;\n this.kind = kind;\n }\n toString() { return maybeParens(this.expr, this) + this.kind; }\n eq(other) {\n return exprEq(this.expr, other.expr) && this.kind == other.kind;\n }\n walk(f) {\n let expr = this.expr.walk(f);\n return f(expr == this.expr ? this : new RepeatExpression(this.start, expr, this.kind));\n }\n}\nRepeatExpression.prototype.prec = 3;\nclass LiteralExpression extends Expression {\n // value.length is always > 0\n constructor(start, value) {\n super(start);\n this.value = value;\n }\n toString() { return JSON.stringify(this.value); }\n eq(other) { return this.value == other.value; }\n}\nclass SetExpression extends Expression {\n constructor(start, ranges, inverted) {\n super(start);\n this.ranges = ranges;\n this.inverted = inverted;\n }\n toString() {\n return `[${this.inverted ? \"^\" : \"\"}${this.ranges.map(([a, b]) => {\n return String.fromCodePoint(a) + (b == a + 1 ? \"\" : \"-\" + String.fromCodePoint(b));\n })}]`;\n }\n eq(other) {\n return this.inverted == other.inverted && this.ranges.length == other.ranges.length &&\n this.ranges.every(([a, b], i) => { let [x, y] = other.ranges[i]; return a == x && b == y; });\n }\n}\nclass AnyExpression extends Expression {\n constructor(start) {\n super(start);\n }\n toString() { return \"_\"; }\n eq() { return true; }\n}\nfunction walkExprs(exprs, f) {\n let result = null;\n for (let i = 0; i < exprs.length; i++) {\n let expr = exprs[i].walk(f);\n if (expr != exprs[i] && !result)\n result = exprs.slice(0, i);\n if (result)\n result.push(expr);\n }\n return result || exprs;\n}\nconst CharClasses = {\n asciiLetter: [[65, 91], [97, 123]],\n asciiLowercase: [[97, 123]],\n asciiUppercase: [[65, 91]],\n digit: [[48, 58]],\n whitespace: [[9, 14], [32, 33], [133, 134], [160, 161], [5760, 5761], [8192, 8203],\n [8232, 8234], [8239, 8240], [8287, 8288], [12288, 12289]],\n eof: [[0xffff, 0xffff]]\n};\nclass CharClass extends Expression {\n constructor(start, type) {\n super(start);\n this.type = type;\n }\n toString() { return \"@\" + this.type; }\n eq(expr) { return this.type == expr.type; }\n}\nfunction exprEq(a, b) {\n return a.constructor == b.constructor && a.eq(b);\n}\nfunction exprsEq(a, b) {\n return a.length == b.length && a.every((e, i) => exprEq(e, b[i]));\n}\nclass Prop extends Node {\n constructor(start, at, name, value) {\n super(start);\n this.at = at;\n this.name = name;\n this.value = value;\n }\n eq(other) {\n return this.name == other.name && this.value.length == other.value.length &&\n this.value.every((v, i) => v.value == other.value[i].value && v.name == other.value[i].name);\n }\n toString() {\n let result = (this.at ? \"@\" : \"\") + this.name;\n if (this.value.length) {\n result += \"=\";\n for (let { name, value } of this.value)\n result += name ? `{${name}}` : /[^\\w-]/.test(value) ? JSON.stringify(value) : value;\n }\n return result;\n }\n static eqProps(a, b) {\n return a.length == b.length && a.every((p, i) => p.eq(b[i]));\n }\n}\nclass PropPart extends Node {\n constructor(start, value, name) {\n super(start);\n this.value = value;\n this.name = name;\n }\n}\nfunction maybeParens(node, parent) {\n return node.prec < parent.prec ? \"(\" + node.toString() + \")\" : node.toString();\n}\n\n/**\nThe type of error raised when the parser generator finds an issue.\n*/\nclass GenError extends Error {\n}\n\nfunction hasProps(props) {\n for (let _p in props)\n return true;\n return false;\n}\nlet termHash = 0;\nclass Term {\n constructor(name, flags, nodeName, props = {}) {\n this.name = name;\n this.flags = flags;\n this.nodeName = nodeName;\n this.props = props;\n this.hash = ++termHash; // Used for sorting and hashing during parser generation\n this.id = -1; // Assigned in a later stage, used in actual output\n // Filled in only after the rules are simplified, used in automaton.ts\n this.rules = [];\n }\n toString() { return this.name; }\n get nodeType() { return this.top || this.nodeName != null || hasProps(this.props) || this.repeated; }\n get terminal() { return (this.flags & 1 /* TermFlag.Terminal */) > 0; }\n get eof() { return (this.flags & 4 /* TermFlag.Eof */) > 0; }\n get error() { return \"error\" in this.props; }\n get top() { return (this.flags & 2 /* TermFlag.Top */) > 0; }\n get interesting() { return this.flags > 0 || this.nodeName != null; }\n get repeated() { return (this.flags & 16 /* TermFlag.Repeated */) > 0; }\n set preserve(value) { this.flags = value ? this.flags | 8 /* TermFlag.Preserve */ : this.flags & ~8 /* TermFlag.Preserve */; }\n get preserve() { return (this.flags & 8 /* TermFlag.Preserve */) > 0; }\n set inline(value) { this.flags = value ? this.flags | 32 /* TermFlag.Inline */ : this.flags & ~32 /* TermFlag.Inline */; }\n get inline() { return (this.flags & 32 /* TermFlag.Inline */) > 0; }\n cmp(other) { return this.hash - other.hash; }\n}\nclass TermSet {\n constructor() {\n this.terms = [];\n // Map from term names to Term instances\n this.names = Object.create(null);\n this.tops = [];\n this.eof = this.term(\"␄\", null, 1 /* TermFlag.Terminal */ | 4 /* TermFlag.Eof */);\n this.error = this.term(\"⚠\", \"⚠\", 8 /* TermFlag.Preserve */);\n }\n term(name, nodeName, flags = 0, props = {}) {\n let term = new Term(name, flags, nodeName, props);\n this.terms.push(term);\n this.names[name] = term;\n return term;\n }\n makeTop(nodeName, props) {\n const term = this.term(\"@top\", nodeName, 2 /* TermFlag.Top */, props);\n this.tops.push(term);\n return term;\n }\n makeTerminal(name, nodeName, props = {}) {\n return this.term(name, nodeName, 1 /* TermFlag.Terminal */, props);\n }\n makeNonTerminal(name, nodeName, props = {}) {\n return this.term(name, nodeName, 0, props);\n }\n makeRepeat(name) {\n return this.term(name, null, 16 /* TermFlag.Repeated */);\n }\n uniqueName(name) {\n for (let i = 0;; i++) {\n let cur = i ? `${name}-${i}` : name;\n if (!this.names[cur])\n return cur;\n }\n }\n finish(rules) {\n for (let rule of rules)\n rule.name.rules.push(rule);\n this.terms = this.terms.filter(t => t.terminal || t.preserve || rules.some(r => r.name == t || r.parts.includes(t)));\n let names = {};\n let nodeTypes = [this.error];\n this.error.id = 0 /* T.Err */;\n let nextID = 0 /* T.Err */ + 1;\n // Assign ids to terms that represent node types\n for (let term of this.terms)\n if (term.id < 0 && term.nodeType && !term.repeated) {\n term.id = nextID++;\n nodeTypes.push(term);\n }\n // Put all repeated terms after the regular node types\n let minRepeatTerm = nextID;\n for (let term of this.terms)\n if (term.repeated) {\n term.id = nextID++;\n nodeTypes.push(term);\n }\n // Then comes the EOF term\n this.eof.id = nextID++;\n // And then the remaining (non-node, non-repeat) terms.\n for (let term of this.terms) {\n if (term.id < 0)\n term.id = nextID++;\n if (term.name)\n names[term.id] = term.name;\n }\n if (nextID >= 0xfffe)\n throw new GenError(\"Too many terms\");\n return { nodeTypes, names, minRepeatTerm, maxTerm: nextID - 1 };\n }\n}\nfunction cmpSet(a, b, cmp) {\n if (a.length != b.length)\n return a.length - b.length;\n for (let i = 0; i < a.length; i++) {\n let diff = cmp(a[i], b[i]);\n if (diff)\n return diff;\n }\n return 0;\n}\nconst none$3 = [];\nclass Conflicts {\n constructor(precedence, ambigGroups = none$3, cut = 0) {\n this.precedence = precedence;\n this.ambigGroups = ambigGroups;\n this.cut = cut;\n }\n join(other) {\n if (this == Conflicts.none || this == other)\n return other;\n if (other == Conflicts.none)\n return this;\n return new Conflicts(Math.max(this.precedence, other.precedence), union(this.ambigGroups, other.ambigGroups), Math.max(this.cut, other.cut));\n }\n cmp(other) {\n return this.precedence - other.precedence || cmpSet(this.ambigGroups, other.ambigGroups, (a, b) => a < b ? -1 : a > b ? 1 : 0) ||\n this.cut - other.cut;\n }\n}\nConflicts.none = new Conflicts(0);\nfunction union(a, b) {\n if (a.length == 0 || a == b)\n return b;\n if (b.length == 0)\n return a;\n let result = a.slice();\n for (let value of b)\n if (!a.includes(value))\n result.push(value);\n return result.sort();\n}\nlet ruleID = 0;\nclass Rule {\n constructor(name, parts, conflicts, skip) {\n this.name = name;\n this.parts = parts;\n this.conflicts = conflicts;\n this.skip = skip;\n this.id = ruleID++;\n }\n cmp(rule) {\n return this.id - rule.id;\n }\n cmpNoName(rule) {\n return this.parts.length - rule.parts.length ||\n this.skip.hash - rule.skip.hash ||\n this.parts.reduce((r, s, i) => r || s.cmp(rule.parts[i]), 0) ||\n cmpSet(this.conflicts, rule.conflicts, (a, b) => a.cmp(b));\n }\n toString() {\n return this.name + \" -> \" + this.parts.join(\" \");\n }\n get isRepeatWrap() {\n return this.name.repeated && this.parts.length == 2 && this.parts[0] == this.name;\n }\n sameReduce(other) {\n return this.name == other.name && this.parts.length == other.parts.length && this.isRepeatWrap == other.isRepeatWrap;\n }\n}\n\nconst MAX_CHAR = 0xffff;\nclass Edge {\n constructor(from, to, target) {\n this.from = from;\n this.to = to;\n this.target = target;\n }\n toString() {\n return `-> ${this.target.id}[label=${JSON.stringify(this.from < 0 ? \"ε\" : charFor(this.from) +\n (this.to > this.from + 1 ? \"-\" + charFor(this.to - 1) : \"\"))}]`;\n }\n}\nfunction charFor(n) {\n return n > MAX_CHAR ? \"∞\"\n : n == 10 ? \"\\\\n\"\n : n == 13 ? \"\\\\r\"\n : n < 32 || n >= 0xd800 && n < 0xdfff ? \"\\\\u{\" + n.toString(16) + \"}\"\n : String.fromCharCode(n);\n}\nfunction minimize(states, start) {\n let partition = Object.create(null);\n let byAccepting = Object.create(null);\n for (let state of states) {\n let id = ids(state.accepting);\n let group = byAccepting[id] || (byAccepting[id] = []);\n group.push(state);\n partition[state.id] = group;\n }\n for (;;) {\n let split = false, newPartition = Object.create(null);\n for (let state of states) {\n if (newPartition[state.id])\n continue;\n let group = partition[state.id];\n if (group.length == 1) {\n newPartition[group[0].id] = group;\n continue;\n }\n let parts = [];\n groups: for (let state of group) {\n for (let p of parts) {\n if (isEquivalent(state, p[0], partition)) {\n p.push(state);\n continue groups;\n }\n }\n parts.push([state]);\n }\n if (parts.length > 1)\n split = true;\n for (let p of parts)\n for (let s of p)\n newPartition[s.id] = p;\n }\n if (!split)\n return applyMinimization(states, start, partition);\n partition = newPartition;\n }\n}\nfunction isEquivalent(a, b, partition) {\n if (a.edges.length != b.edges.length)\n return false;\n for (let i = 0; i < a.edges.length; i++) {\n let eA = a.edges[i], eB = b.edges[i];\n if (eA.from != eB.from || eA.to != eB.to || partition[eA.target.id] != partition[eB.target.id])\n return false;\n }\n return true;\n}\nfunction applyMinimization(states, start, partition) {\n for (let state of states) {\n for (let i = 0; i < state.edges.length; i++) {\n let edge = state.edges[i], target = partition[edge.target.id][0];\n if (target != edge.target)\n state.edges[i] = new Edge(edge.from, edge.to, target);\n }\n }\n return partition[start.id][0];\n}\nlet stateID = 1;\nlet State$1 = class State {\n constructor(accepting = [], id = stateID++) {\n this.accepting = accepting;\n this.id = id;\n this.edges = [];\n }\n edge(from, to, target) {\n this.edges.push(new Edge(from, to, target));\n }\n nullEdge(target) { this.edge(-1, -1, target); }\n compile() {\n let labeled = Object.create(null), localID = 0;\n let startState = explore(this.closure().sort((a, b) => a.id - b.id));\n return minimize(Object.values(labeled), startState);\n function explore(states) {\n let newState = labeled[ids(states)] =\n new State(states.reduce((a, s) => union(a, s.accepting), []), localID++);\n let out = [];\n for (let state of states)\n for (let edge of state.edges) {\n if (edge.from >= 0)\n out.push(edge);\n }\n let transitions = mergeEdges(out);\n for (let merged of transitions) {\n let targets = merged.targets.sort((a, b) => a.id - b.id);\n newState.edge(merged.from, merged.to, labeled[ids(targets)] || explore(targets));\n }\n return newState;\n }\n }\n closure() {\n let result = [], seen = Object.create(null);\n function explore(state) {\n if (seen[state.id])\n return;\n seen[state.id] = true;\n // States with only epsilon edges and no accepting term that\n // isn't also in the next states are left out to help reduce the\n // number of unique state combinations\n if (state.edges.some(e => e.from >= 0) ||\n (state.accepting.length > 0 && !state.edges.some(e => sameSet$1(state.accepting, e.target.accepting))))\n result.push(state);\n for (let edge of state.edges)\n if (edge.from < 0)\n explore(edge.target);\n }\n explore(this);\n return result;\n }\n findConflicts(occurTogether) {\n let conflicts = [], cycleTerms = this.cycleTerms();\n function add(a, b, soft, aEdges, bEdges) {\n if (a.id < b.id) {\n [a, b] = [b, a];\n soft = -soft;\n }\n let found = conflicts.find(c => c.a == a && c.b == b);\n if (!found)\n conflicts.push(new Conflict$1(a, b, soft, exampleFromEdges(aEdges), bEdges && exampleFromEdges(bEdges)));\n else if (found.soft != soft)\n found.soft = 0;\n }\n this.reachable((state, edges) => {\n if (state.accepting.length == 0)\n return;\n for (let i = 0; i < state.accepting.length; i++)\n for (let j = i + 1; j < state.accepting.length; j++)\n add(state.accepting[i], state.accepting[j], 0, edges);\n state.reachable((s, es) => {\n if (s != state)\n for (let term of s.accepting) {\n let hasCycle = cycleTerms.includes(term);\n for (let orig of state.accepting)\n if (term != orig)\n add(term, orig, hasCycle || cycleTerms.includes(orig) || !occurTogether(term, orig) ? 0 : 1, edges, edges.concat(es));\n }\n });\n });\n return conflicts;\n }\n cycleTerms() {\n let work = [];\n this.reachable(state => {\n for (let { target } of state.edges)\n work.push(state, target);\n });\n let table = new Map;\n let haveCycle = [];\n for (let i = 0; i < work.length;) {\n let from = work[i++], to = work[i++];\n let entry = table.get(from);\n if (!entry)\n table.set(from, entry = []);\n if (entry.includes(to))\n continue;\n if (from == to) {\n if (!haveCycle.includes(from))\n haveCycle.push(from);\n }\n else {\n for (let next of entry)\n work.push(from, next);\n entry.push(to);\n }\n }\n let result = [];\n for (let state of haveCycle) {\n for (let term of state.accepting) {\n if (!result.includes(term))\n result.push(term);\n }\n }\n return result;\n }\n reachable(f) {\n let seen = [], edges = [];\n (function explore(s) {\n f(s, edges);\n seen.push(s);\n for (let edge of s.edges)\n if (!seen.includes(edge.target)) {\n edges.push(edge);\n explore(edge.target);\n edges.pop();\n }\n })(this);\n }\n toString() {\n let out = \"digraph {\\n\";\n this.reachable(state => {\n if (state.accepting.length)\n out += ` ${state.id} [label=${JSON.stringify(state.accepting.join())}];\\n`;\n for (let edge of state.edges)\n out += ` ${state.id} ${edge};\\n`;\n });\n return out + \"}\";\n }\n // Tokenizer data is represented as a single flat array. This\n // contains regions for each tokenizer state. Region offsets are\n // used to identify states.\n //\n // Each state is laid out as:\n // - Token group mask\n // - Offset of the end of the accepting data\n // - Number of outgoing edges in the state\n // - Pairs of token masks and term ids that indicate the accepting\n // states, sorted by precedence\n // - Triples for the edges: each with a low and high bound and the\n // offset of the next state.\n toArray(groupMasks, precedence) {\n let offsets = []; // Used to 'link' the states after building the arrays\n let data = [];\n this.reachable(state => {\n let start = data.length;\n let acceptEnd = start + 3 + state.accepting.length * 2;\n offsets[state.id] = start;\n data.push(state.stateMask(groupMasks), acceptEnd, state.edges.length);\n state.accepting.sort((a, b) => precedence.indexOf(a.id) - precedence.indexOf(b.id));\n for (let term of state.accepting)\n data.push(term.id, groupMasks[term.id] || 0xffff);\n for (let edge of state.edges)\n data.push(edge.from, edge.to, -edge.target.id - 1);\n });\n // Replace negative numbers with resolved state offsets\n for (let i = 0; i < data.length; i++)\n if (data[i] < 0)\n data[i] = offsets[-data[i] - 1];\n if (data.length > Math.pow(2, 16))\n throw new GenError(\"Tokenizer tables too big to represent with 16-bit offsets.\");\n return Uint16Array.from(data);\n }\n stateMask(groupMasks) {\n let mask = 0;\n this.reachable(state => {\n for (let term of state.accepting)\n mask |= (groupMasks[term.id] || 0xffff);\n });\n return mask;\n }\n};\nlet Conflict$1 = class Conflict {\n constructor(a, b, \n // Conflicts between two non-cyclic tokens are marked as\n // 'soft', with a negative number if a is shorter than\n // b, and a positive if b is shorter than a.\n soft, exampleA, exampleB) {\n this.a = a;\n this.b = b;\n this.soft = soft;\n this.exampleA = exampleA;\n this.exampleB = exampleB;\n }\n};\nfunction exampleFromEdges(edges) {\n let str = \"\";\n for (let i = 0; i < edges.length; i++)\n str += String.fromCharCode(edges[i].from);\n return str;\n}\nfunction ids(elts) {\n let result = \"\";\n for (let elt of elts) {\n if (result.length)\n result += \"-\";\n result += elt.id;\n }\n return result;\n}\nfunction sameSet$1(a, b) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (a[i] != b[i])\n return false;\n return true;\n}\nclass MergedEdge {\n constructor(from, to, targets) {\n this.from = from;\n this.to = to;\n this.targets = targets;\n }\n}\n// Merge multiple edges (tagged by character ranges) into a set of\n// mutually exclusive ranges pointing at all target states for that\n// range\nfunction mergeEdges(edges) {\n let separate = [], result = [];\n for (let edge of edges) {\n if (!separate.includes(edge.from))\n separate.push(edge.from);\n if (!separate.includes(edge.to))\n separate.push(edge.to);\n }\n separate.sort((a, b) => a - b);\n for (let i = 1; i < separate.length; i++) {\n let from = separate[i - 1], to = separate[i];\n let found = [];\n for (let edge of edges)\n if (edge.to > from && edge.from < to) {\n for (let target of edge.target.closure())\n if (!found.includes(target))\n found.push(target);\n }\n if (found.length)\n result.push(new MergedEdge(from, to, found));\n }\n let eof = edges.filter(e => e.from == 65535 /* Seq.End */ && e.to == 65535 /* Seq.End */);\n if (eof.length) {\n let found = [];\n for (let edge of eof)\n for (let target of edge.target.closure())\n if (!found.includes(target))\n found.push(target);\n if (found.length)\n result.push(new MergedEdge(65535 /* Seq.End */, 65535 /* Seq.End */, found));\n }\n return result;\n}\n\n// Note that this is the parser for grammar files, not the generated parser\nlet word = /[\\w_-]+/gy;\n// Some engines (specifically SpiderMonkey) have still not implemented \\p\ntry {\n word = /[\\p{Alphabetic}\\d_-]+/ugy;\n}\ncatch (_) { }\nconst none$2 = [];\nclass Input {\n constructor(string, fileName = null) {\n this.string = string;\n this.fileName = fileName;\n this.type = \"sof\";\n this.value = null;\n this.start = 0;\n this.end = 0;\n this.next();\n }\n lineInfo(pos) {\n for (let line = 1, cur = 0;;) {\n let next = this.string.indexOf(\"\\n\", cur);\n if (next > -1 && next < pos) {\n ++line;\n cur = next + 1;\n }\n else {\n return { line, ch: pos - cur };\n }\n }\n }\n message(msg, pos = -1) {\n let posInfo = this.fileName || \"\";\n if (pos > -1) {\n let info = this.lineInfo(pos);\n posInfo += (posInfo ? \" \" : \"\") + info.line + \":\" + info.ch;\n }\n return posInfo ? msg + ` (${posInfo})` : msg;\n }\n raise(msg, pos = -1) {\n throw new GenError(this.message(msg, pos));\n }\n match(pos, re) {\n let match = re.exec(this.string.slice(pos));\n return match ? pos + match[0].length : -1;\n }\n next() {\n let start = this.match(this.end, /^(\\s|\\/\\/.*|\\/\\*[^]*?\\*\\/)*/);\n if (start == this.string.length)\n return this.set(\"eof\", null, start, start);\n let next = this.string[start];\n if (next == '\"') {\n let end = this.match(start + 1, /^(\\\\.|[^\"\\\\])*\"/);\n if (end == -1)\n this.raise(\"Unterminated string literal\", start);\n return this.set(\"string\", readString(this.string.slice(start + 1, end - 1)), start, end);\n }\n else if (next == \"'\") {\n let end = this.match(start + 1, /^(\\\\.|[^'\\\\])*'/);\n if (end == -1)\n this.raise(\"Unterminated string literal\", start);\n return this.set(\"string\", readString(this.string.slice(start + 1, end - 1)), start, end);\n }\n else if (next == \"@\") {\n word.lastIndex = start + 1;\n let m = word.exec(this.string);\n if (!m)\n return this.raise(\"@ without a name\", start);\n return this.set(\"at\", m[0], start, start + 1 + m[0].length);\n }\n else if ((next == \"$\" || next == \"!\") && this.string[start + 1] == \"[\") {\n let end = this.match(start + 2, /^(?:\\\\.|[^\\]\\\\])*\\]/);\n if (end == -1)\n this.raise(\"Unterminated character set\", start);\n return this.set(\"set\", this.string.slice(start + 2, end - 1), start, end);\n }\n else if (/[\\[\\]()!~+*?{}<>\\.,|:$=]/.test(next)) {\n return this.set(next, null, start, start + 1);\n }\n else {\n word.lastIndex = start;\n let m = word.exec(this.string);\n if (!m)\n return this.raise(\"Unexpected character \" + JSON.stringify(next), start);\n return this.set(\"id\", m[0], start, start + m[0].length);\n }\n }\n set(type, value, start, end) {\n this.type = type;\n this.value = value;\n this.start = start;\n this.end = end;\n }\n eat(type, value = null) {\n if (this.type == type && (value == null || this.value === value)) {\n this.next();\n return true;\n }\n else {\n return false;\n }\n }\n unexpected() {\n return this.raise(`Unexpected token '${this.string.slice(this.start, this.end)}'`, this.start);\n }\n expect(type, value = null) {\n let val = this.value;\n if (this.type != type || !(value == null || val === value))\n this.unexpected();\n this.next();\n return val;\n }\n parse() {\n return parseGrammar(this);\n }\n}\nfunction parseGrammar(input) {\n let start = input.start;\n let rules = [];\n let prec = null;\n let tokens = null;\n let localTokens = [];\n let mainSkip = null;\n let scopedSkip = [];\n let dialects = [];\n let context = null;\n let external = [];\n let specialized = [];\n let props = [];\n let propSources = [];\n let tops = [];\n let sawTop = false;\n let autoDelim = false;\n while (input.type != \"eof\") {\n let start = input.start;\n if (input.eat(\"at\", \"top\")) {\n if (input.type != \"id\")\n input.raise(`Top rules must have a name`, input.start);\n tops.push(parseRule(input, parseIdent(input)));\n sawTop = true;\n }\n else if (input.type == \"at\" && input.value == \"tokens\") {\n if (tokens)\n input.raise(`Multiple @tokens declaractions`, input.start);\n else\n tokens = parseTokens(input);\n }\n else if (input.eat(\"at\", \"local\")) {\n input.expect(\"id\", \"tokens\");\n localTokens.push(parseLocalTokens(input, start));\n }\n else if (input.eat(\"at\", \"context\")) {\n if (context)\n input.raise(`Multiple @context declarations`, start);\n let id = parseIdent(input);\n input.expect(\"id\", \"from\");\n let source = input.expect(\"string\");\n context = new ContextDeclaration(start, id, source);\n }\n else if (input.eat(\"at\", \"external\")) {\n if (input.eat(\"id\", \"tokens\"))\n external.push(parseExternalTokens(input, start));\n else if (input.eat(\"id\", \"prop\"))\n props.push(parseExternalProp(input, start));\n else if (input.eat(\"id\", \"extend\"))\n specialized.push(parseExternalSpecialize(input, \"extend\", start));\n else if (input.eat(\"id\", \"specialize\"))\n specialized.push(parseExternalSpecialize(input, \"specialize\", start));\n else if (input.eat(\"id\", \"propSource\"))\n propSources.push(parseExternalPropSource(input, start));\n else\n input.unexpected();\n }\n else if (input.eat(\"at\", \"dialects\")) {\n input.expect(\"{\");\n for (let first = true; !input.eat(\"}\"); first = false) {\n if (!first)\n input.eat(\",\");\n dialects.push(parseIdent(input));\n }\n }\n else if (input.type == \"at\" && input.value == \"precedence\") {\n if (prec)\n input.raise(`Multiple precedence declarations`, input.start);\n prec = parsePrecedence(input);\n }\n else if (input.eat(\"at\", \"detectDelim\")) {\n autoDelim = true;\n }\n else if (input.eat(\"at\", \"skip\")) {\n let skip = parseBracedExpr(input);\n if (input.type == \"{\") {\n input.next();\n let rules = [], topRules = [];\n while (!input.eat(\"}\")) {\n if (input.eat(\"at\", \"top\")) {\n topRules.push(parseRule(input, parseIdent(input)));\n sawTop = true;\n }\n else {\n rules.push(parseRule(input));\n }\n }\n scopedSkip.push({ expr: skip, topRules, rules });\n }\n else {\n if (mainSkip)\n input.raise(`Multiple top-level skip declarations`, input.start);\n mainSkip = skip;\n }\n }\n else {\n rules.push(parseRule(input));\n }\n }\n if (!sawTop)\n return input.raise(`Missing @top declaration`);\n return new GrammarDeclaration(start, rules, tops, tokens, localTokens, context, external, specialized, propSources, prec, mainSkip, scopedSkip, dialects, props, autoDelim);\n}\nfunction parseRule(input, named) {\n let start = named ? named.start : input.start;\n let id = named || parseIdent(input);\n let props = parseProps(input);\n let params = [];\n if (input.eat(\"<\"))\n while (!input.eat(\">\")) {\n if (params.length)\n input.expect(\",\");\n params.push(parseIdent(input));\n }\n let expr = parseBracedExpr(input);\n return new RuleDeclaration(start, id, props, params, expr);\n}\nfunction parseProps(input) {\n if (input.type != \"[\")\n return none$2;\n let props = [];\n input.expect(\"[\");\n while (!input.eat(\"]\")) {\n if (props.length)\n input.expect(\",\");\n props.push(parseProp(input));\n }\n return props;\n}\nfunction parseProp(input) {\n let start = input.start, value = [], name = input.value, at = input.type == \"at\";\n if (!input.eat(\"at\") && !input.eat(\"id\"))\n input.unexpected();\n if (input.eat(\"=\"))\n for (;;) {\n if (input.type == \"string\" || input.type == \"id\") {\n value.push(new PropPart(input.start, input.value, null));\n input.next();\n }\n else if (input.eat(\".\")) {\n value.push(new PropPart(input.start, \".\", null));\n }\n else if (input.eat(\"{\")) {\n value.push(new PropPart(input.start, null, input.expect(\"id\")));\n input.expect(\"}\");\n }\n else {\n break;\n }\n }\n return new Prop(start, at, name, value);\n}\nfunction parseBracedExpr(input) {\n input.expect(\"{\");\n let expr = parseExprChoice(input);\n input.expect(\"}\");\n return expr;\n}\nconst SET_MARKER = \"\\ufdda\"; // (Invalid unicode character)\nfunction parseExprInner(input) {\n let start = input.start;\n if (input.eat(\"(\")) {\n if (input.eat(\")\"))\n return new SequenceExpression(start, none$2, [none$2, none$2]);\n let expr = parseExprChoice(input);\n input.expect(\")\");\n return expr;\n }\n else if (input.type == \"string\") {\n let value = input.value;\n input.next();\n if (value.length == 0)\n return new SequenceExpression(start, none$2, [none$2, none$2]);\n return new LiteralExpression(start, value);\n }\n else if (input.eat(\"id\", \"_\")) {\n return new AnyExpression(start);\n }\n else if (input.type == \"set\") {\n let content = input.value, invert = input.string[input.start] == \"!\";\n let unescaped = readString(content.replace(/\\\\.|-|\"/g, (m) => {\n return m == \"-\" ? SET_MARKER : m == '\"' ? '\\\\\"' : m;\n }));\n let ranges = [];\n for (let pos = 0; pos < unescaped.length;) {\n let code = unescaped.codePointAt(pos);\n pos += code > 0xffff ? 2 : 1;\n if (pos < unescaped.length - 1 && unescaped[pos] == SET_MARKER) {\n let end = unescaped.codePointAt(pos + 1);\n pos += end > 0xffff ? 3 : 2;\n if (end < code)\n input.raise(\"Invalid character range\", input.start);\n addRange(input, ranges, code, end + 1);\n }\n else {\n if (code == SET_MARKER.charCodeAt(0))\n code = 45;\n addRange(input, ranges, code, code + 1);\n }\n }\n input.next();\n return new SetExpression(start, ranges.sort((a, b) => a[0] - b[0]), invert);\n }\n else if (input.type == \"at\" && (input.value == \"specialize\" || input.value == \"extend\")) {\n let { start, value } = input;\n input.next();\n let props = parseProps(input);\n input.expect(\"<\");\n let token = parseExprChoice(input), content;\n if (input.eat(\",\")) {\n content = parseExprChoice(input);\n }\n else if (token instanceof LiteralExpression) {\n content = token;\n }\n else {\n input.raise(`@${value} requires two arguments when its first argument isn't a literal string`);\n }\n input.expect(\">\");\n return new SpecializeExpression(start, value, props, token, content);\n }\n else if (input.type == \"at\" && CharClasses.hasOwnProperty(input.value)) {\n let cls = new CharClass(input.start, input.value);\n input.next();\n return cls;\n }\n else if (input.type == \"[\") {\n let rule = parseRule(input, new Identifier(start, \"_anon\"));\n if (rule.params.length)\n input.raise(`Inline rules can't have parameters`, rule.start);\n return new InlineRuleExpression(start, rule);\n }\n else {\n let id = parseIdent(input);\n if (input.type == \"[\" || input.type == \"{\") {\n let rule = parseRule(input, id);\n if (rule.params.length)\n input.raise(`Inline rules can't have parameters`, rule.start);\n return new InlineRuleExpression(start, rule);\n }\n else {\n if (input.eat(\".\") && id.name == \"std\" && CharClasses.hasOwnProperty(input.value)) {\n let cls = new CharClass(start, input.value);\n input.next();\n return cls;\n }\n return new NameExpression(start, id, parseArgs(input));\n }\n }\n}\nfunction parseArgs(input) {\n let args = [];\n if (input.eat(\"<\"))\n while (!input.eat(\">\")) {\n if (args.length)\n input.expect(\",\");\n args.push(parseExprChoice(input));\n }\n return args;\n}\nfunction addRange(input, ranges, from, to) {\n if (!ranges.every(([a, b]) => b <= from || a >= to))\n input.raise(\"Overlapping character range\", input.start);\n ranges.push([from, to]);\n}\nfunction parseExprSuffix(input) {\n let start = input.start;\n let expr = parseExprInner(input);\n for (;;) {\n let kind = input.type;\n if (input.eat(\"*\") || input.eat(\"?\") || input.eat(\"+\"))\n expr = new RepeatExpression(start, expr, kind);\n else\n return expr;\n }\n}\nfunction endOfSequence(input) {\n return input.type == \"}\" || input.type == \")\" || input.type == \"|\" || input.type == \"/\" ||\n input.type == \"/\\\\\" || input.type == \"{\" || input.type == \",\" || input.type == \">\";\n}\nfunction parseExprSequence(input) {\n let start = input.start, exprs = [], markers = [none$2];\n do {\n // Add markers at this position\n for (;;) {\n let localStart = input.start, markerType;\n if (input.eat(\"~\"))\n markerType = \"ambig\";\n else if (input.eat(\"!\"))\n markerType = \"prec\";\n else\n break;\n markers[markers.length - 1] =\n markers[markers.length - 1].concat(new ConflictMarker(localStart, parseIdent(input), markerType));\n }\n if (endOfSequence(input))\n break;\n exprs.push(parseExprSuffix(input));\n markers.push(none$2);\n } while (!endOfSequence(input));\n if (exprs.length == 1 && markers.every(ms => ms.length == 0))\n return exprs[0];\n return new SequenceExpression(start, exprs, markers, !exprs.length);\n}\nfunction parseExprChoice(input) {\n let start = input.start, left = parseExprSequence(input);\n if (!input.eat(\"|\"))\n return left;\n let exprs = [left];\n do {\n exprs.push(parseExprSequence(input));\n } while (input.eat(\"|\"));\n let empty = exprs.find(s => s instanceof SequenceExpression && s.empty);\n if (empty)\n input.raise(\"Empty expression in choice operator. If this is intentional, use () to make it explicit.\", empty.start);\n return new ChoiceExpression(start, exprs);\n}\nfunction parseIdent(input) {\n if (input.type != \"id\")\n input.unexpected();\n let start = input.start, name = input.value;\n input.next();\n return new Identifier(start, name);\n}\nfunction parsePrecedence(input) {\n let start = input.start;\n input.next();\n input.expect(\"{\");\n let items = [];\n while (!input.eat(\"}\")) {\n if (items.length)\n input.eat(\",\");\n items.push({\n id: parseIdent(input),\n type: input.eat(\"at\", \"left\") ? \"left\" : input.eat(\"at\", \"right\") ? \"right\" : input.eat(\"at\", \"cut\") ? \"cut\" : null\n });\n }\n return new PrecDeclaration(start, items);\n}\nfunction parseTokens(input) {\n let start = input.start;\n input.next();\n input.expect(\"{\");\n let tokenRules = [];\n let literals = [];\n let precedences = [];\n let conflicts = [];\n while (!input.eat(\"}\")) {\n if (input.type == \"at\" && input.value == \"precedence\") {\n precedences.push(parseTokenPrecedence(input));\n }\n else if (input.type == \"at\" && input.value == \"conflict\") {\n conflicts.push(parseTokenConflict(input));\n }\n else if (input.type == \"string\") {\n literals.push(new LiteralDeclaration(input.start, input.expect(\"string\"), parseProps(input)));\n }\n else {\n tokenRules.push(parseRule(input));\n }\n }\n return new TokenDeclaration(start, precedences, conflicts, tokenRules, literals);\n}\nfunction parseLocalTokens(input, start) {\n input.expect(\"{\");\n let tokenRules = [];\n let precedences = [];\n let fallback = null;\n while (!input.eat(\"}\")) {\n if (input.type == \"at\" && input.value == \"precedence\") {\n precedences.push(parseTokenPrecedence(input));\n }\n else if (input.eat(\"at\", \"else\") && !fallback) {\n fallback = { id: parseIdent(input), props: parseProps(input) };\n }\n else {\n tokenRules.push(parseRule(input));\n }\n }\n return new LocalTokenDeclaration(start, precedences, tokenRules, fallback);\n}\nfunction parseTokenPrecedence(input) {\n let start = input.start;\n input.next();\n input.expect(\"{\");\n let tokens = [];\n while (!input.eat(\"}\")) {\n if (tokens.length)\n input.eat(\",\");\n let expr = parseExprInner(input);\n if (expr instanceof LiteralExpression || expr instanceof NameExpression)\n tokens.push(expr);\n else\n input.raise(`Invalid expression in token precedences`, expr.start);\n }\n return new TokenPrecDeclaration(start, tokens);\n}\nfunction parseTokenConflict(input) {\n let start = input.start;\n input.next();\n input.expect(\"{\");\n let a = parseExprInner(input);\n if (!(a instanceof LiteralExpression || a instanceof NameExpression))\n input.raise(`Invalid expression in token conflict`, a.start);\n input.eat(\",\");\n let b = parseExprInner(input);\n if (!(b instanceof LiteralExpression || b instanceof NameExpression))\n input.raise(`Invalid expression in token conflict`, b.start);\n input.expect(\"}\");\n return new TokenConflictDeclaration(start, a, b);\n}\nfunction parseExternalTokenSet(input) {\n let tokens = [];\n input.expect(\"{\");\n while (!input.eat(\"}\")) {\n if (tokens.length)\n input.eat(\",\");\n let id = parseIdent(input);\n let props = parseProps(input);\n tokens.push({ id, props });\n }\n return tokens;\n}\nfunction parseExternalTokens(input, start) {\n let id = parseIdent(input);\n input.expect(\"id\", \"from\");\n let from = input.expect(\"string\");\n return new ExternalTokenDeclaration(start, id, from, parseExternalTokenSet(input));\n}\nfunction parseExternalSpecialize(input, type, start) {\n let token = parseBracedExpr(input);\n let id = parseIdent(input);\n input.expect(\"id\", \"from\");\n let from = input.expect(\"string\");\n return new ExternalSpecializeDeclaration(start, type, token, id, from, parseExternalTokenSet(input));\n}\nfunction parseExternalPropSource(input, start) {\n let id = parseIdent(input);\n input.expect(\"id\", \"from\");\n return new ExternalPropSourceDeclaration(start, id, input.expect(\"string\"));\n}\nfunction parseExternalProp(input, start) {\n let externalID = parseIdent(input);\n let id = input.eat(\"id\", \"as\") ? parseIdent(input) : externalID;\n input.expect(\"id\", \"from\");\n let from = input.expect(\"string\");\n return new ExternalPropDeclaration(start, id, externalID, from);\n}\nfunction readString(string) {\n let point = /\\\\(?:u\\{([\\da-f]+)\\}|u([\\da-f]{4})|x([\\da-f]{2})|([ntbrf0])|(.))|[^]/yig;\n let out = \"\", m;\n while (m = point.exec(string)) {\n let [all, u1, u2, u3, single, unknown] = m;\n if (u1 || u2 || u3)\n out += String.fromCodePoint(parseInt(u1 || u2 || u3, 16));\n else if (single)\n out += single == \"n\" ? \"\\n\" : single == \"t\" ? \"\\t\" : single == \"0\" ? \"\\0\" : single == \"r\" ? \"\\r\" : single == \"f\" ? \"\\f\" : \"\\b\";\n else if (unknown)\n out += unknown;\n else\n out += all;\n }\n return out;\n}\n\nfunction hash(a, b) { return (a << 5) + a + b; }\nfunction hashString(h, s) {\n for (let i = 0; i < s.length; i++)\n h = hash(h, s.charCodeAt(i));\n return h;\n}\n\nconst verbose = (typeof process != \"undefined\" && process.env.LOG) || \"\";\nconst timing = /\\btime\\b/.test(verbose);\nconst time = timing ? (label, f) => {\n let t0 = Date.now();\n let result = f();\n console.log(`${label} (${((Date.now() - t0) / 1000).toFixed(2)}s)`);\n return result;\n} : (_label, f) => f();\n\nclass Pos {\n constructor(rule, pos, \n // NOTE `ahead` and `ambigAhead` aren't mutated anymore after `finish()` has been called\n ahead, ambigAhead, skipAhead, via) {\n this.rule = rule;\n this.pos = pos;\n this.ahead = ahead;\n this.ambigAhead = ambigAhead;\n this.skipAhead = skipAhead;\n this.via = via;\n this.hash = 0;\n }\n finish() {\n let h = hash(hash(this.rule.id, this.pos), this.skipAhead.hash);\n for (let a of this.ahead)\n h = hash(h, a.hash);\n for (let group of this.ambigAhead)\n h = hashString(h, group);\n this.hash = h;\n return this;\n }\n get next() {\n return this.pos < this.rule.parts.length ? this.rule.parts[this.pos] : null;\n }\n advance() {\n return new Pos(this.rule, this.pos + 1, this.ahead, this.ambigAhead, this.skipAhead, this.via).finish();\n }\n get skip() {\n return this.pos == this.rule.parts.length ? this.skipAhead : this.rule.skip;\n }\n cmp(pos) {\n return this.rule.cmp(pos.rule) || this.pos - pos.pos || this.skipAhead.hash - pos.skipAhead.hash ||\n cmpSet(this.ahead, pos.ahead, (a, b) => a.cmp(b)) || cmpSet(this.ambigAhead, pos.ambigAhead, cmpStr);\n }\n eqSimple(pos) {\n return pos.rule == this.rule && pos.pos == this.pos;\n }\n toString() {\n let parts = this.rule.parts.map(t => t.name);\n parts.splice(this.pos, 0, \"·\");\n return `${this.rule.name} -> ${parts.join(\" \")}`;\n }\n eq(other) {\n return this == other ||\n this.hash == other.hash && this.rule == other.rule && this.pos == other.pos && this.skipAhead == other.skipAhead &&\n sameSet(this.ahead, other.ahead) &&\n sameSet(this.ambigAhead, other.ambigAhead);\n }\n trail(maxLen = 60) {\n let result = [];\n for (let pos = this; pos; pos = pos.via) {\n for (let i = pos.pos - 1; i >= 0; i--)\n result.push(pos.rule.parts[i]);\n }\n let value = result.reverse().join(\" \");\n if (value.length > maxLen)\n value = value.slice(value.length - maxLen).replace(/.*? /, \"… \");\n return value;\n }\n conflicts(pos = this.pos) {\n let result = this.rule.conflicts[pos];\n if (pos == this.rule.parts.length && this.ambigAhead.length)\n result = result.join(new Conflicts(0, this.ambigAhead));\n return result;\n }\n static addOrigins(group, context) {\n let result = group.slice();\n for (let i = 0; i < result.length; i++) {\n let next = result[i];\n if (next.pos == 0)\n for (let pos of context) {\n if (pos.next == next.rule.name && !result.includes(pos))\n result.push(pos);\n }\n }\n return result;\n }\n}\nfunction conflictsAt(group) {\n let result = Conflicts.none;\n for (let pos of group)\n result = result.join(pos.conflicts());\n return result;\n}\n// Applies automatic action precedence based on repeat productions.\n// These are left-associative, so reducing the `R -> R R` rule has\n// higher precedence.\nfunction compareRepeatPrec(a, b) {\n for (let pos of a)\n if (pos.rule.name.repeated) {\n for (let posB of b)\n if (posB.rule.name == pos.rule.name) {\n if (pos.rule.isRepeatWrap && pos.pos == 2)\n return 1;\n if (posB.rule.isRepeatWrap && posB.pos == 2)\n return -1;\n }\n }\n return 0;\n}\nfunction cmpStr(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n}\nfunction termsAhead(rule, pos, after, first) {\n let found = [];\n for (let i = pos + 1; i < rule.parts.length; i++) {\n let next = rule.parts[i], cont = false;\n if (next.terminal) {\n addTo(next, found);\n }\n else\n for (let term of first[next.name]) {\n if (term == null)\n cont = true;\n else\n addTo(term, found);\n }\n if (!cont)\n return found;\n }\n for (let a of after)\n addTo(a, found);\n return found;\n}\nfunction eqSet(a, b) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!a[i].eq(b[i]))\n return false;\n return true;\n}\nfunction sameSet(a, b) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (a[i] != b[i])\n return false;\n return true;\n}\nclass Shift {\n constructor(term, target) {\n this.term = term;\n this.target = target;\n }\n eq(other) { return other instanceof Shift && this.term == other.term && other.target.id == this.target.id; }\n cmp(other) { return other instanceof Reduce ? -1 : this.term.id - other.term.id || this.target.id - other.target.id; }\n matches(other, mapping) {\n return other instanceof Shift && mapping[other.target.id] == mapping[this.target.id];\n }\n toString() { return \"s\" + this.target.id; }\n map(mapping, states) {\n let mapped = states[mapping[this.target.id]];\n return mapped == this.target ? this : new Shift(this.term, mapped);\n }\n}\nclass Reduce {\n constructor(term, rule) {\n this.term = term;\n this.rule = rule;\n }\n eq(other) {\n return other instanceof Reduce && this.term == other.term && other.rule.sameReduce(this.rule);\n }\n cmp(other) {\n return other instanceof Shift ? 1 : this.term.id - other.term.id || this.rule.name.id - other.rule.name.id ||\n this.rule.parts.length - other.rule.parts.length;\n }\n matches(other, mapping) {\n return other instanceof Reduce && other.rule.sameReduce(this.rule);\n }\n toString() { return `${this.rule.name.name}(${this.rule.parts.length})`; }\n map() { return this; }\n}\nfunction hashPositions(set) {\n let h = 5381;\n for (let pos of set)\n h = hash(h, pos.hash);\n return h;\n}\nclass State {\n constructor(id, set, flags = 0, skip, hash = hashPositions(set), startRule = null) {\n this.id = id;\n this.set = set;\n this.flags = flags;\n this.skip = skip;\n this.hash = hash;\n this.startRule = startRule;\n this.actions = [];\n this.actionPositions = [];\n this.goto = [];\n this.tokenGroup = -1;\n this.defaultReduce = null;\n this._actionsByTerm = null;\n }\n toString() {\n let actions = this.actions.map(t => t.term + \"=\" + t).join(\",\") +\n (this.goto.length ? \" | \" + this.goto.map(g => g.term + \"=\" + g).join(\",\") : \"\");\n return this.id + \": \" + this.set.filter(p => p.pos > 0).join() +\n (this.defaultReduce ? `\\n always ${this.defaultReduce.name}(${this.defaultReduce.parts.length})`\n : actions.length ? \"\\n \" + actions : \"\");\n }\n addActionInner(value, positions) {\n check: for (let i = 0; i < this.actions.length; i++) {\n let action = this.actions[i];\n if (action.term == value.term) {\n if (action.eq(value))\n return null;\n let fullPos = Pos.addOrigins(positions, this.set), actionFullPos = Pos.addOrigins(this.actionPositions[i], this.set);\n let conflicts = conflictsAt(fullPos), actionConflicts = conflictsAt(actionFullPos);\n let diff = compareRepeatPrec(fullPos, actionFullPos) || conflicts.precedence - actionConflicts.precedence;\n if (diff > 0) { // Drop the existing action\n this.actions.splice(i, 1);\n this.actionPositions.splice(i, 1);\n i--;\n continue check;\n }\n else if (diff < 0) { // Drop this one\n return null;\n }\n else if (conflicts.ambigGroups.some(g => actionConflicts.ambigGroups.includes(g))) { // Explicitly allowed ambiguity\n continue check;\n }\n else { // Not resolved\n return action;\n }\n }\n }\n this.actions.push(value);\n this.actionPositions.push(positions);\n return null;\n }\n addAction(value, positions, conflicts) {\n let conflict = this.addActionInner(value, positions);\n if (conflict) {\n let conflictPos = this.actionPositions[this.actions.indexOf(conflict)][0];\n let rules = [positions[0].rule.name, conflictPos.rule.name];\n if (conflicts.some(c => c.rules.some(r => rules.includes(r))))\n return;\n let error;\n if (conflict instanceof Shift)\n error = `shift/reduce conflict between\\n ${conflictPos}\\nand\\n ${positions[0].rule}`;\n else\n error = `reduce/reduce conflict between\\n ${conflictPos.rule}\\nand\\n ${positions[0].rule}`;\n error += `\\nWith input:\\n ${positions[0].trail(70)} · ${value.term} …`;\n error += findConflictOrigin(conflictPos, positions[0]);\n conflicts.push(new Conflict(error, rules));\n }\n }\n getGoto(term) {\n return this.goto.find(a => a.term == term);\n }\n hasSet(set) {\n return eqSet(this.set, set);\n }\n actionsByTerm() {\n let result = this._actionsByTerm;\n if (!result) {\n this._actionsByTerm = result = Object.create(null);\n for (let action of this.actions)\n (result[action.term.id] || (result[action.term.id] = [])).push(action);\n }\n return result;\n }\n finish() {\n if (this.actions.length) {\n let first = this.actions[0];\n if (first instanceof Reduce) {\n let { rule } = first;\n if (this.actions.every(a => a instanceof Reduce && a.rule.sameReduce(rule)))\n this.defaultReduce = rule;\n }\n }\n this.actions.sort((a, b) => a.cmp(b));\n this.goto.sort((a, b) => a.cmp(b));\n }\n eq(other) {\n let dThis = this.defaultReduce, dOther = other.defaultReduce;\n if (dThis || dOther)\n return dThis && dOther ? dThis.sameReduce(dOther) : false;\n return this.skip == other.skip &&\n this.tokenGroup == other.tokenGroup &&\n eqSet(this.actions, other.actions) &&\n eqSet(this.goto, other.goto);\n }\n}\nfunction closure(set, first) {\n let added = [], redo = [];\n function addFor(name, ahead, ambigAhead, skipAhead, via) {\n for (let rule of name.rules) {\n let add = added.find(a => a.rule == rule);\n if (!add) {\n let existing = set.find(p => p.pos == 0 && p.rule == rule);\n add = existing ? new Pos(rule, 0, existing.ahead.slice(), existing.ambigAhead, existing.skipAhead, existing.via)\n : new Pos(rule, 0, [], none$1, skipAhead, via);\n added.push(add);\n }\n if (add.skipAhead != skipAhead)\n throw new GenError(\"Inconsistent skip sets after \" + via.trail());\n add.ambigAhead = union(add.ambigAhead, ambigAhead);\n for (let term of ahead)\n if (!add.ahead.includes(term)) {\n add.ahead.push(term);\n if (add.rule.parts.length && !add.rule.parts[0].terminal)\n addTo(add, redo);\n }\n }\n }\n for (let pos of set) {\n let next = pos.next;\n if (next && !next.terminal)\n addFor(next, termsAhead(pos.rule, pos.pos, pos.ahead, first), pos.conflicts(pos.pos + 1).ambigGroups, pos.pos == pos.rule.parts.length - 1 ? pos.skipAhead : pos.rule.skip, pos);\n }\n while (redo.length) {\n let add = redo.pop();\n addFor(add.rule.parts[0], termsAhead(add.rule, 0, add.ahead, first), union(add.rule.conflicts[1].ambigGroups, add.rule.parts.length == 1 ? add.ambigAhead : none$1), add.rule.parts.length == 1 ? add.skipAhead : add.rule.skip, add);\n }\n let result = set.slice();\n for (let add of added) {\n add.ahead.sort((a, b) => a.hash - b.hash);\n add.finish();\n let origIndex = set.findIndex(p => p.pos == 0 && p.rule == add.rule);\n if (origIndex > -1)\n result[origIndex] = add;\n else\n result.push(add);\n }\n return result.sort((a, b) => a.cmp(b));\n}\nfunction addTo(value, array) {\n if (!array.includes(value))\n array.push(value);\n}\nfunction computeFirstSets(terms) {\n let table = Object.create(null);\n for (let t of terms.terms)\n if (!t.terminal)\n table[t.name] = [];\n for (;;) {\n let change = false;\n for (let nt of terms.terms)\n if (!nt.terminal)\n for (let rule of nt.rules) {\n let set = table[nt.name];\n let found = false, startLen = set.length;\n for (let part of rule.parts) {\n found = true;\n if (part.terminal) {\n addTo(part, set);\n }\n else {\n for (let t of table[part.name]) {\n if (t == null)\n found = false;\n else\n addTo(t, set);\n }\n }\n if (found)\n break;\n }\n if (!found)\n addTo(null, set);\n if (set.length > startLen)\n change = true;\n }\n if (!change)\n return table;\n }\n}\nclass Core {\n constructor(set, state) {\n this.set = set;\n this.state = state;\n }\n}\nclass Conflict {\n constructor(error, rules) {\n this.error = error;\n this.rules = rules;\n }\n}\nfunction findConflictOrigin(a, b) {\n if (a.eqSimple(b))\n return \"\";\n function via(root, start) {\n let hist = [];\n for (let p = start.via; !p.eqSimple(root); p = p.via)\n hist.push(p);\n if (!hist.length)\n return \"\";\n hist.unshift(start);\n return hist.reverse().map((p, i) => \"\\n\" + \" \".repeat(i + 1) + (p == start ? \"\" : \"via \") + p).join(\"\");\n }\n for (let p = a; p; p = p.via)\n for (let p2 = b; p2; p2 = p2.via) {\n if (p.eqSimple(p2))\n return \"\\nShared origin: \" + p + via(p, a) + via(p, b);\n }\n return \"\";\n}\n// Builds a full LR(1) automaton\nfunction buildFullAutomaton(terms, startTerms, first) {\n let states = [], statesBySetHash = {};\n let cores = {};\n let t0 = Date.now();\n function getState(core, top) {\n if (core.length == 0)\n return null;\n let coreHash = hashPositions(core), byHash = cores[coreHash];\n let skip;\n for (let pos of core) {\n if (!skip)\n skip = pos.skip;\n else if (skip != pos.skip)\n throw new GenError(\"Inconsistent skip sets after \" + pos.trail());\n }\n if (byHash)\n for (let known of byHash)\n if (eqSet(core, known.set)) {\n if (known.state.skip != skip)\n throw new GenError(\"Inconsistent skip sets after \" + known.set[0].trail());\n return known.state;\n }\n let set = closure(core, first);\n let hash = hashPositions(set), forHash = statesBySetHash[hash] || (statesBySetHash[hash] = []);\n let found;\n if (!top)\n for (let state of forHash)\n if (state.hasSet(set))\n found = state;\n if (!found) {\n found = new State(states.length, set, 0, skip, hash, top);\n forHash.push(found);\n states.push(found);\n if (timing && states.length % 500 == 0)\n console.log(`${states.length} states after ${((Date.now() - t0) / 1000).toFixed(2)}s`);\n }\n (cores[coreHash] || (cores[coreHash] = [])).push(new Core(core, found));\n return found;\n }\n for (const startTerm of startTerms) {\n const startSkip = startTerm.rules.length ? startTerm.rules[0].skip : terms.names[\"%noskip\"];\n getState(startTerm.rules.map(rule => new Pos(rule, 0, [terms.eof], none$1, startSkip, null).finish()), startTerm);\n }\n let conflicts = [];\n for (let filled = 0; filled < states.length; filled++) {\n let state = states[filled];\n let byTerm = [], byTermPos = [], atEnd = [];\n for (let pos of state.set) {\n if (pos.pos == pos.rule.parts.length) {\n if (!pos.rule.name.top)\n atEnd.push(pos);\n }\n else {\n let next = pos.rule.parts[pos.pos];\n let index = byTerm.indexOf(next);\n if (index < 0) {\n byTerm.push(next);\n byTermPos.push([pos]);\n }\n else {\n byTermPos[index].push(pos);\n }\n }\n }\n for (let i = 0; i < byTerm.length; i++) {\n let term = byTerm[i], positions = byTermPos[i].map(p => p.advance());\n if (term.terminal) {\n let set = applyCut(positions);\n let next = getState(set);\n if (next)\n state.addAction(new Shift(term, next), byTermPos[i], conflicts);\n }\n else {\n let goto = getState(positions);\n if (goto)\n state.goto.push(new Shift(term, goto));\n }\n }\n let replaced = false;\n for (let pos of atEnd)\n for (let ahead of pos.ahead) {\n let count = state.actions.length;\n state.addAction(new Reduce(ahead, pos.rule), [pos], conflicts);\n if (state.actions.length == count)\n replaced = true;\n }\n // If some actions were replaced by others, double-check whether\n // goto entries are now superfluous (for example, in an operator\n // precedence-related state that has a shift for `*` but only a\n // reduce for `+`, we don't need a goto entry for rules that start\n // with `+`)\n if (replaced)\n for (let i = 0; i < state.goto.length; i++) {\n let start = first[state.goto[i].term.name];\n if (!start.some(term => state.actions.some(a => a.term == term && (a instanceof Shift))))\n state.goto.splice(i--, 1);\n }\n }\n if (conflicts.length)\n throw new GenError(conflicts.map(c => c.error).join(\"\\n\\n\"));\n // Resolve alwaysReduce and sort actions\n for (let state of states)\n state.finish();\n if (timing)\n console.log(`${states.length} states total.`);\n return states;\n}\nfunction applyCut(set) {\n let found = null, cut = 1;\n for (let pos of set) {\n let value = pos.rule.conflicts[pos.pos - 1].cut;\n if (value < cut)\n continue;\n if (!found || value > cut) {\n cut = value;\n found = [];\n }\n found.push(pos);\n }\n return found || set;\n}\n// Verify that there are no conflicting actions or goto entries in the\n// two given states (using the state ID remapping provided in mapping)\nfunction canMerge(a, b, mapping) {\n // If a goto for the same term differs, that makes the states\n // incompatible\n for (let goto of a.goto)\n for (let other of b.goto) {\n if (goto.term == other.term && mapping[goto.target.id] != mapping[other.target.id])\n return false;\n }\n // If there is an action where a conflicting action exists in the\n // other state, the merge is only allowed when both states have the\n // exact same set of actions for this term.\n let byTerm = b.actionsByTerm();\n for (let action of a.actions) {\n let setB = byTerm[action.term.id];\n if (setB && setB.some(other => !other.matches(action, mapping))) {\n if (setB.length == 1)\n return false;\n let setA = a.actionsByTerm()[action.term.id];\n if (setA.length != setB.length || setA.some(a1 => !setB.some(a2 => a1.matches(a2, mapping))))\n return false;\n }\n }\n return true;\n}\nfunction mergeStates(states, mapping) {\n let newStates = [];\n for (let state of states) {\n let newID = mapping[state.id];\n if (!newStates[newID]) {\n newStates[newID] = new State(newID, state.set, 0, state.skip, state.hash, state.startRule);\n newStates[newID].tokenGroup = state.tokenGroup;\n newStates[newID].defaultReduce = state.defaultReduce;\n }\n }\n for (let state of states) {\n let newID = mapping[state.id], target = newStates[newID];\n target.flags |= state.flags;\n for (let i = 0; i < state.actions.length; i++) {\n let action = state.actions[i].map(mapping, newStates);\n if (!target.actions.some(a => a.eq(action))) {\n target.actions.push(action);\n target.actionPositions.push(state.actionPositions[i]);\n }\n }\n for (let goto of state.goto) {\n let mapped = goto.map(mapping, newStates);\n if (!target.goto.some(g => g.eq(mapped)))\n target.goto.push(mapped);\n }\n }\n return newStates;\n}\nclass Group {\n constructor(origin, member) {\n this.origin = origin;\n this.members = [member];\n }\n}\nfunction samePosSet(a, b) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!a[i].eqSimple(b[i]))\n return false;\n return true;\n}\n// Collapse an LR(1) automaton to an LALR-like automaton\nfunction collapseAutomaton(states) {\n let mapping = [], groups = [];\n assignGroups: for (let i = 0; i < states.length; i++) {\n let state = states[i];\n if (!state.startRule)\n for (let j = 0; j < groups.length; j++) {\n let group = groups[j], other = states[group.members[0]];\n if (state.tokenGroup == other.tokenGroup &&\n state.skip == other.skip &&\n !other.startRule &&\n samePosSet(state.set, other.set)) {\n group.members.push(i);\n mapping.push(j);\n continue assignGroups;\n }\n }\n mapping.push(groups.length);\n groups.push(new Group(groups.length, i));\n }\n function spill(groupIndex, index) {\n let group = groups[groupIndex], state = states[group.members[index]];\n let pop = group.members.pop();\n if (index != group.members.length)\n group.members[index] = pop;\n for (let i = groupIndex + 1; i < groups.length; i++) {\n mapping[state.id] = i;\n if (groups[i].origin == group.origin &&\n groups[i].members.every(id => canMerge(state, states[id], mapping))) {\n groups[i].members.push(state.id);\n return;\n }\n }\n mapping[state.id] = groups.length;\n groups.push(new Group(group.origin, state.id));\n }\n for (let pass = 1;; pass++) {\n let conflicts = false, t0 = Date.now();\n for (let g = 0, startLen = groups.length; g < startLen; g++) {\n let group = groups[g];\n for (let i = 0; i < group.members.length - 1; i++) {\n for (let j = i + 1; j < group.members.length; j++) {\n let idA = group.members[i], idB = group.members[j];\n if (!canMerge(states[idA], states[idB], mapping)) {\n conflicts = true;\n spill(g, j--);\n }\n }\n }\n }\n if (timing)\n console.log(`Collapse pass ${pass}${conflicts ? `` : `, done`} (${((Date.now() - t0) / 1000).toFixed(2)}s)`);\n if (!conflicts)\n return mergeStates(states, mapping);\n }\n}\nfunction mergeIdentical(states) {\n for (let pass = 1;; pass++) {\n let mapping = [], didMerge = false, t0 = Date.now();\n let newStates = [];\n // Find states that either have the same alwaysReduce or the same\n // actions, and merge them.\n for (let i = 0; i < states.length; i++) {\n let state = states[i];\n let match = newStates.findIndex(s => state.eq(s));\n if (match < 0) {\n mapping[i] = newStates.length;\n newStates.push(state);\n }\n else {\n mapping[i] = match;\n didMerge = true;\n let other = newStates[match], add = null;\n for (let pos of state.set)\n if (!other.set.some(p => p.eqSimple(pos)))\n (add || (add = [])).push(pos);\n if (add)\n other.set = add.concat(other.set).sort((a, b) => a.cmp(b));\n }\n }\n if (timing)\n console.log(`Merge identical pass ${pass}${didMerge ? \"\" : \", done\"} (${((Date.now() - t0) / 1000).toFixed(2)}s)`);\n if (!didMerge)\n return states;\n // Make sure actions point at merged state objects\n for (let state of newStates)\n if (!state.defaultReduce) {\n state.actions = state.actions.map(a => a.map(mapping, newStates));\n state.goto = state.goto.map(a => a.map(mapping, newStates));\n }\n // Renumber ids\n for (let i = 0; i < newStates.length; i++)\n newStates[i].id = i;\n states = newStates;\n }\n}\nconst none$1 = [];\nfunction finishAutomaton(full) {\n return mergeIdentical(collapseAutomaton(full));\n}\n\n// Encode numbers as groups of printable ascii characters\n//\n// - 0xffff, which is often used as placeholder, is encoded as \"~\"\n//\n// - The characters from \" \" (32) to \"}\" (125), excluding '\"' and\n// \"\\\\\", indicate values from 0 to 92\n//\n// - The first bit in a 'digit' is used to indicate whether this is\n// the end of a number.\n//\n// - That leaves 46 other values, which are actually significant.\n//\n// - The digits in a number are ordered from high to low significance.\nfunction digitToChar(digit) {\n let ch = digit + 32 /* Encode.Start */;\n if (ch >= 34 /* Encode.Gap1 */)\n ch++;\n if (ch >= 92 /* Encode.Gap2 */)\n ch++;\n return String.fromCharCode(ch);\n}\nfunction encode(value, max = 0xffff) {\n if (value > max)\n throw new Error(\"Trying to encode a number that's too big: \" + value);\n if (value == 65535 /* Encode.BigVal */)\n return String.fromCharCode(126 /* Encode.BigValCode */);\n let result = \"\";\n for (let first = 46 /* Encode.Base */;; first = 0) {\n let low = value % 46 /* Encode.Base */, rest = value - low;\n result = digitToChar(low + first) + result;\n if (rest == 0)\n break;\n value = rest / 46 /* Encode.Base */;\n }\n return result;\n}\nfunction encodeArray(values, max = 0xffff) {\n let result = '\"' + encode(values.length, 0xffffffff);\n for (let i = 0; i < values.length; i++)\n result += encode(values[i], max);\n result += '\"';\n return result;\n}\n\nconst none = [];\nclass Parts {\n constructor(terms, conflicts) {\n this.terms = terms;\n this.conflicts = conflicts;\n }\n concat(other) {\n if (this == Parts.none)\n return other;\n if (other == Parts.none)\n return this;\n let conflicts = null;\n if (this.conflicts || other.conflicts) {\n conflicts = this.conflicts ? this.conflicts.slice() : this.ensureConflicts();\n let otherConflicts = other.ensureConflicts();\n conflicts[conflicts.length - 1] = conflicts[conflicts.length - 1].join(otherConflicts[0]);\n for (let i = 1; i < otherConflicts.length; i++)\n conflicts.push(otherConflicts[i]);\n }\n return new Parts(this.terms.concat(other.terms), conflicts);\n }\n withConflicts(pos, conflicts) {\n if (conflicts == Conflicts.none)\n return this;\n let array = this.conflicts ? this.conflicts.slice() : this.ensureConflicts();\n array[pos] = array[pos].join(conflicts);\n return new Parts(this.terms, array);\n }\n ensureConflicts() {\n if (this.conflicts)\n return this.conflicts;\n let empty = [];\n for (let i = 0; i <= this.terms.length; i++)\n empty.push(Conflicts.none);\n return empty;\n }\n}\nParts.none = new Parts(none, null);\nfunction p(...terms) { return new Parts(terms, null); }\nclass BuiltRule {\n constructor(id, args, term) {\n this.id = id;\n this.args = args;\n this.term = term;\n }\n matches(expr) {\n return this.id == expr.id.name && exprsEq(expr.args, this.args);\n }\n matchesRepeat(expr) {\n return this.id == \"+\" && exprEq(expr.expr, this.args[0]);\n }\n}\nclass Builder {\n constructor(text, options) {\n this.options = options;\n this.terms = new TermSet;\n this.specialized = Object.create(null);\n this.tokenOrigins = Object.create(null);\n this.rules = [];\n this.built = [];\n this.ruleNames = Object.create(null);\n this.namespaces = Object.create(null);\n this.namedTerms = Object.create(null);\n this.termTable = Object.create(null);\n this.knownProps = Object.create(null);\n this.dynamicRulePrecedences = [];\n this.definedGroups = [];\n this.astRules = [];\n this.currentSkip = [];\n time(\"Parse\", () => {\n this.input = new Input(text, options.fileName);\n this.ast = this.input.parse();\n });\n let NP = NodeProp;\n for (let prop in NP) {\n if (NP[prop] instanceof NodeProp && !NP[prop].perNode)\n this.knownProps[prop] = { prop: NP[prop], source: { name: prop, from: null } };\n }\n for (let prop of this.ast.externalProps) {\n this.knownProps[prop.id.name] = {\n prop: this.options.externalProp ? this.options.externalProp(prop.id.name) : new NodeProp(),\n source: { name: prop.externalID.name, from: prop.source }\n };\n }\n this.dialects = this.ast.dialects.map(d => d.name);\n this.tokens = new MainTokenSet(this, this.ast.tokens);\n this.localTokens = this.ast.localTokens.map(g => new LocalTokenSet(this, g));\n this.externalTokens = this.ast.externalTokens.map(ext => new ExternalTokenSet(this, ext));\n this.externalSpecializers = this.ast.externalSpecializers.map(decl => new ExternalSpecializer(this, decl));\n time(\"Build rules\", () => {\n let noSkip = this.newName(\"%noskip\", true);\n this.defineRule(noSkip, []);\n let mainSkip = this.ast.mainSkip ? this.newName(\"%mainskip\", true) : noSkip;\n let scopedSkip = [], topRules = [];\n for (let rule of this.ast.rules)\n this.astRules.push({ skip: mainSkip, rule });\n for (let rule of this.ast.topRules)\n topRules.push({ skip: mainSkip, rule });\n for (let scoped of this.ast.scopedSkip) {\n let skip = noSkip, found = this.ast.scopedSkip.findIndex((sc, i) => i < scopedSkip.length && exprEq(sc.expr, scoped.expr));\n if (found > -1)\n skip = scopedSkip[found];\n else if (this.ast.mainSkip && exprEq(scoped.expr, this.ast.mainSkip))\n skip = mainSkip;\n else if (!isEmpty(scoped.expr))\n skip = this.newName(\"%skip\", true);\n scopedSkip.push(skip);\n for (let rule of scoped.rules)\n this.astRules.push({ skip, rule });\n for (let rule of scoped.topRules)\n topRules.push({ skip, rule });\n }\n for (let { rule } of this.astRules) {\n this.unique(rule.id);\n }\n this.currentSkip.push(noSkip);\n this.skipRules = mainSkip == noSkip ? [mainSkip] : [noSkip, mainSkip];\n if (mainSkip != noSkip)\n this.defineRule(mainSkip, this.normalizeExpr(this.ast.mainSkip));\n for (let i = 0; i < this.ast.scopedSkip.length; i++) {\n let skip = scopedSkip[i];\n if (!this.skipRules.includes(skip)) {\n this.skipRules.push(skip);\n if (skip != noSkip)\n this.defineRule(skip, this.normalizeExpr(this.ast.scopedSkip[i].expr));\n }\n }\n this.currentSkip.pop();\n for (let { rule, skip } of topRules.sort((a, b) => a.rule.start - b.rule.start)) {\n this.unique(rule.id);\n this.used(rule.id.name);\n this.currentSkip.push(skip);\n let { name, props } = this.nodeInfo(rule.props, \"a\", rule.id.name, none, none, rule.expr);\n let term = this.terms.makeTop(name, props);\n this.namedTerms[name] = term;\n this.defineRule(term, this.normalizeExpr(rule.expr));\n this.currentSkip.pop();\n }\n for (let ext of this.externalSpecializers)\n ext.finish();\n for (let { skip, rule } of this.astRules) {\n if (this.ruleNames[rule.id.name] && isExported(rule) && !rule.params.length) {\n this.buildRule(rule, [], skip, false);\n if (rule.expr instanceof SequenceExpression && rule.expr.exprs.length == 0)\n this.used(rule.id.name);\n }\n }\n });\n for (let name in this.ruleNames) {\n let value = this.ruleNames[name];\n if (value)\n this.warn(`Unused rule '${value.name}'`, value.start);\n }\n this.tokens.takePrecedences();\n this.tokens.takeConflicts();\n for (let lt of this.localTokens)\n lt.takePrecedences();\n for (let { name, group, rule } of this.definedGroups)\n this.defineGroup(name, group, rule);\n this.checkGroups();\n }\n unique(id) {\n if (id.name in this.ruleNames)\n this.raise(`Duplicate definition of rule '${id.name}'`, id.start);\n this.ruleNames[id.name] = id;\n }\n used(name) {\n this.ruleNames[name] = null;\n }\n newName(base, nodeName = null, props = {}) {\n for (let i = nodeName ? 0 : 1;; i++) {\n let name = i ? `${base}-${i}` : base;\n if (!this.terms.names[name])\n return this.terms.makeNonTerminal(name, nodeName === true ? null : nodeName, props);\n }\n }\n prepareParser() {\n let rules = time(\"Simplify rules\", () => simplifyRules(this.rules, [\n ...this.skipRules,\n ...this.terms.tops\n ]));\n let { nodeTypes, names: termNames, minRepeatTerm, maxTerm } = this.terms.finish(rules);\n for (let prop in this.namedTerms)\n this.termTable[prop] = this.namedTerms[prop].id;\n if (/\\bgrammar\\b/.test(verbose))\n console.log(rules.join(\"\\n\"));\n let startTerms = this.terms.tops.slice();\n let first = computeFirstSets(this.terms);\n let skipInfo = this.skipRules.map((name, id) => {\n let skip = [], startTokens = [], rules = [];\n for (let rule of name.rules) {\n if (!rule.parts.length)\n continue;\n let start = rule.parts[0];\n for (let t of start.terminal ? [start] : first[start.name] || [])\n if (!startTokens.includes(t))\n startTokens.push(t);\n if (start.terminal && rule.parts.length == 1 && !rules.some(r => r != rule && r.parts[0] == start))\n skip.push(start);\n else\n rules.push(rule);\n }\n name.rules = rules;\n if (rules.length)\n startTerms.push(name);\n return { skip, rule: rules.length ? name : null, startTokens, id };\n });\n let fullTable = time(\"Build full automaton\", () => buildFullAutomaton(this.terms, startTerms, first));\n let localTokens = this.localTokens\n .map((grp, i) => grp.buildLocalGroup(fullTable, skipInfo, i));\n let { tokenGroups, tokenPrec, tokenData } = time(\"Build token groups\", () => this.tokens.buildTokenGroups(fullTable, skipInfo, localTokens.length));\n let table = time(\"Finish automaton\", () => finishAutomaton(fullTable));\n let skipState = findSkipStates(table, this.terms.tops);\n if (/\\blr\\b/.test(verbose))\n console.log(table.join(\"\\n\"));\n let specialized = [];\n for (let ext of this.externalSpecializers)\n specialized.push(ext);\n for (let name in this.specialized)\n specialized.push({ token: this.terms.names[name], table: buildSpecializeTable(this.specialized[name]) });\n let tokStart = (tokenizer) => {\n if (tokenizer instanceof ExternalTokenSet)\n return tokenizer.ast.start;\n return this.tokens.ast ? this.tokens.ast.start : -1;\n };\n let tokenizers = tokenGroups\n .concat(this.externalTokens)\n .sort((a, b) => tokStart(a) - tokStart(b))\n .concat(localTokens);\n let data = new DataBuilder;\n let skipData = skipInfo.map(info => {\n let actions = [];\n for (let term of info.skip)\n actions.push(term.id, 0, 262144 /* Action.StayFlag */ >> 16);\n if (info.rule) {\n let state = table.find(s => s.startRule == info.rule);\n for (let action of state.actions)\n actions.push(action.term.id, state.id, 131072 /* Action.GotoFlag */ >> 16);\n }\n actions.push(65535 /* Seq.End */, 0 /* Seq.Done */);\n return data.storeArray(actions);\n });\n let states = time(\"Finish states\", () => {\n let states = new Uint32Array(table.length * 6 /* ParseState.Size */);\n let forceReductions = this.computeForceReductions(table, skipInfo);\n let finishCx = new FinishStateContext(tokenizers, data, states, skipData, skipInfo, table, this);\n for (let s of table)\n finishCx.finish(s, skipState(s.id), forceReductions[s.id]);\n return states;\n });\n let dialects = Object.create(null);\n for (let i = 0; i < this.dialects.length; i++)\n dialects[this.dialects[i]] = data.storeArray((this.tokens.byDialect[i] || none).map(t => t.id).concat(65535 /* Seq.End */));\n let dynamicPrecedences = null;\n if (this.dynamicRulePrecedences.length) {\n dynamicPrecedences = Object.create(null);\n for (let { rule, prec } of this.dynamicRulePrecedences)\n dynamicPrecedences[rule.id] = prec;\n }\n let topRules = Object.create(null);\n for (let term of this.terms.tops)\n topRules[term.nodeName] = [table.find(state => state.startRule == term).id, term.id];\n let precTable = data.storeArray(tokenPrec.concat(65535 /* Seq.End */));\n let { nodeProps, skippedTypes } = this.gatherNodeProps(nodeTypes);\n return {\n states,\n stateData: data.finish(),\n goto: computeGotoTable(table),\n nodeNames: nodeTypes.filter(t => t.id < minRepeatTerm).map(t => t.nodeName).join(\" \"),\n nodeProps,\n skippedTypes,\n maxTerm,\n repeatNodeCount: nodeTypes.length - minRepeatTerm,\n tokenizers,\n tokenData,\n topRules,\n dialects,\n dynamicPrecedences,\n specialized,\n tokenPrec: precTable,\n termNames\n };\n }\n getParser() {\n let { states, stateData, goto, nodeNames, nodeProps: rawNodeProps, skippedTypes, maxTerm, repeatNodeCount, tokenizers, tokenData, topRules, dialects, dynamicPrecedences, specialized: rawSpecialized, tokenPrec, termNames } = this.prepareParser();\n let specialized = rawSpecialized.map(v => {\n if (v instanceof ExternalSpecializer) {\n let ext = this.options.externalSpecializer(v.ast.id.name, this.termTable);\n return {\n term: v.term.id,\n get: (value, stack) => (ext(value, stack) << 1) |\n (v.ast.type == \"extend\" ? 1 /* Specialize.Extend */ : 0 /* Specialize.Specialize */),\n external: ext,\n extend: v.ast.type == \"extend\"\n };\n }\n else {\n return { term: v.token.id, get: (value) => v.table[value] || -1 };\n }\n });\n return LRParser.deserialize({\n version: 14 /* File.Version */,\n states,\n stateData,\n goto,\n nodeNames,\n maxTerm,\n repeatNodeCount,\n nodeProps: rawNodeProps.map(({ prop, terms }) => [this.knownProps[prop].prop, ...terms]),\n propSources: !this.options.externalPropSource ? undefined\n : this.ast.externalPropSources.map(s => this.options.externalPropSource(s.id.name)),\n skippedNodes: skippedTypes,\n tokenData,\n tokenizers: tokenizers.map(tok => tok.create()),\n context: !this.ast.context ? undefined\n : typeof this.options.contextTracker == \"function\" ? this.options.contextTracker(this.termTable)\n : this.options.contextTracker,\n topRules,\n dialects,\n dynamicPrecedences,\n specialized,\n tokenPrec,\n termNames\n });\n }\n getParserFile() {\n let { states, stateData, goto, nodeNames, nodeProps: rawNodeProps, skippedTypes, maxTerm, repeatNodeCount, tokenizers: rawTokenizers, tokenData, topRules, dialects: rawDialects, dynamicPrecedences, specialized: rawSpecialized, tokenPrec, termNames } = this.prepareParser();\n let mod = this.options.moduleStyle || \"es\", ts = this.options.typeScript ? \": any\" : \"\";\n let gen = \"// This file was generated by lezer-generator. You probably shouldn't edit it.\\n\", head = gen;\n let imports = {}, imported = Object.create(null);\n let defined = Object.create(null);\n for (let word of KEYWORDS)\n defined[word] = true;\n let exportName = this.options.exportName || \"parser\";\n defined[exportName] = true;\n let getName = (prefix) => {\n for (let i = 0;; i++) {\n let id = prefix + (i ? \"_\" + i : \"\");\n if (!defined[id])\n return id;\n }\n };\n let importName = (name, source, prefix = name) => {\n let spec = name + \" from \" + source;\n if (imported[spec])\n return imported[spec];\n let src = JSON.stringify(source), varName = name;\n if (name in defined) {\n varName = getName(prefix);\n name += `${mod == \"cjs\" ? \":\" : \" as\"} ${varName}`;\n }\n defined[varName] = true;\n (imports[src] || (imports[src] = [])).push(name);\n return imported[spec] = varName;\n };\n let lrParser = importName(\"LRParser\", \"@lezer/lr\");\n let tokenizers = rawTokenizers.map(tok => tok.createSource(importName));\n let context = this.ast.context ? importName(this.ast.context.id.name, this.ast.context.source) : null;\n let nodeProps = rawNodeProps.map(({ prop, terms }) => {\n let { source } = this.knownProps[prop];\n let propID = source.from ? importName(source.name, source.from) : JSON.stringify(source.name);\n return `[${propID}, ${terms.map(serializePropValue).join(\",\")}]`;\n });\n function specializationTableString(table) {\n return \"{__proto__:null,\" + Object.keys(table).map(key => `${/\\W/.test(key) ? JSON.stringify(key) : key}:${table[key]}`)\n .join(\", \") + \"}\";\n }\n let specHead = \"\";\n let specialized = rawSpecialized.map(v => {\n if (v instanceof ExternalSpecializer) {\n let name = importName(v.ast.id.name, v.ast.source);\n return `{term: ${v.term.id}, get: (value${ts}, stack${ts}) => (${name}(value, stack) << 1)${v.ast.type == \"extend\" ? ` | ${1 /* Specialize.Extend */}` : ''}, external: ${name}${v.ast.type == \"extend\" ? ', extend: true' : ''}}`;\n }\n else {\n let tableName = getName(\"spec_\" + v.token.name.replace(/\\W/g, \"\"));\n defined[tableName] = true;\n specHead += `const ${tableName} = ${specializationTableString(v.table)}\\n`;\n return `{term: ${v.token.id}, get: (value${ts}) => ${tableName}[value] || -1}`;\n }\n });\n let propSources = this.ast.externalPropSources.map(s => importName(s.id.name, s.source));\n for (let source in imports) {\n if (mod == \"cjs\")\n head += `const {${imports[source].join(\", \")}} = require(${source})\\n`;\n else\n head += `import {${imports[source].join(\", \")}} from ${source}\\n`;\n }\n head += specHead;\n function serializePropValue(value) {\n return typeof value != \"string\" || /^(true|false|\\d+(\\.\\d+)?|\\.\\d+)$/.test(value) ? value : JSON.stringify(value);\n }\n let dialects = Object.keys(rawDialects).map(d => `${d}: ${rawDialects[d]}`);\n let parserStr = `${lrParser}.deserialize({\n version: ${14 /* File.Version */},\n states: ${encodeArray(states, 0xffffffff)},\n stateData: ${encodeArray(stateData)},\n goto: ${encodeArray(goto)},\n nodeNames: ${JSON.stringify(nodeNames)},\n maxTerm: ${maxTerm}${context ? `,\n context: ${context}` : \"\"}${nodeProps.length ? `,\n nodeProps: [\n ${nodeProps.join(\",\\n \")}\n ]` : \"\"}${propSources.length ? `,\n propSources: [${propSources.join()}]` : \"\"}${skippedTypes.length ? `,\n skippedNodes: ${JSON.stringify(skippedTypes)}` : \"\"},\n repeatNodeCount: ${repeatNodeCount},\n tokenData: ${encodeArray(tokenData)},\n tokenizers: [${tokenizers.join(\", \")}],\n topRules: ${JSON.stringify(topRules)}${dialects.length ? `,\n dialects: {${dialects.join(\", \")}}` : \"\"}${dynamicPrecedences ? `,\n dynamicPrecedences: ${JSON.stringify(dynamicPrecedences)}` : \"\"}${specialized.length ? `,\n specialized: [${specialized.join(\",\")}]` : \"\"},\n tokenPrec: ${tokenPrec}${this.options.includeNames ? `,\n termNames: ${JSON.stringify(termNames)}` : ''}\n})`;\n let terms = [];\n for (let name in this.termTable) {\n let id = name;\n if (KEYWORDS.includes(id))\n for (let i = 1;; i++) {\n id = \"_\".repeat(i) + name;\n if (!(id in this.termTable))\n break;\n }\n terms.push(`${id}${mod == \"cjs\" ? \":\" : \" =\"} ${this.termTable[name]}`);\n }\n for (let id = 0; id < this.dialects.length; id++)\n terms.push(`Dialect_${this.dialects[id]}${mod == \"cjs\" ? \":\" : \" =\"} ${id}`);\n return {\n parser: head + (mod == \"cjs\" ? `exports.${exportName} = ${parserStr}\\n` : `export const ${exportName} = ${parserStr}\\n`),\n terms: mod == \"cjs\" ? `${gen}module.exports = {\\n ${terms.join(\",\\n \")}\\n}`\n : `${gen}export const\\n ${terms.join(\",\\n \")}\\n`\n };\n }\n gatherNonSkippedNodes() {\n let seen = Object.create(null);\n let work = [];\n let add = (term) => {\n if (!seen[term.id]) {\n seen[term.id] = true;\n work.push(term);\n }\n };\n this.terms.tops.forEach(add);\n for (let i = 0; i < work.length; i++) {\n for (let rule of work[i].rules)\n for (let part of rule.parts)\n add(part);\n }\n return seen;\n }\n gatherNodeProps(nodeTypes) {\n let notSkipped = this.gatherNonSkippedNodes(), skippedTypes = [];\n let nodeProps = [];\n for (let type of nodeTypes) {\n if (!notSkipped[type.id] && !type.error)\n skippedTypes.push(type.id);\n for (let prop in type.props) {\n let known = this.knownProps[prop];\n if (!known)\n throw new GenError(\"No known prop type for \" + prop);\n if (known.source.from == null && (known.source.name == \"repeated\" || known.source.name == \"error\"))\n continue;\n let rec = nodeProps.find(r => r.prop == prop);\n if (!rec)\n nodeProps.push(rec = { prop, values: {} });\n (rec.values[type.props[prop]] || (rec.values[type.props[prop]] = [])).push(type.id);\n }\n }\n return {\n nodeProps: nodeProps.map(({ prop, values }) => {\n let terms = [];\n for (let val in values) {\n let ids = values[val];\n if (ids.length == 1) {\n terms.push(ids[0], val);\n }\n else {\n terms.push(-ids.length);\n for (let id of ids)\n terms.push(id);\n terms.push(val);\n }\n }\n return { prop, terms };\n }),\n skippedTypes\n };\n }\n makeTerminal(name, tag, props) {\n return this.terms.makeTerminal(this.terms.uniqueName(name), tag, props);\n }\n computeForceReductions(states, skipInfo) {\n // This finds a forced reduction for every state, trying to guard\n // against cyclic forced reductions, where a given parse stack can\n // endlessly continue running forced reductions without making any\n // progress.\n //\n // This occurs with length-1 reductions. We never generate\n // length-0 reductions, and length-2+ reductions always shrink the\n // stack, so they are guaranteed to make progress.\n //\n // If there are states S1 and S2 whose forced reductions reduce\n // terms T1 and T2 respectively, both with a length of 1, _and_\n // there is a state S3, which has goto entries T1 -> S2, T2 -> S1,\n // you can get cyclic reductions. Of course, the cycle may also\n // contain more than two steps.\n let reductions = [];\n let candidates = [];\n // A map from terms to states that they are mapped to in goto\n // entries.\n let gotoEdges = Object.create(null);\n for (let state of states) {\n reductions.push(0);\n for (let edge of state.goto) {\n let array = gotoEdges[edge.term.id] || (gotoEdges[edge.term.id] = []);\n let found = array.find(o => o.target == edge.target.id);\n if (found)\n found.parents.push(state.id);\n else\n array.push({ parents: [state.id], target: edge.target.id });\n }\n candidates[state.id] = state.set.filter(pos => pos.pos > 0 && !pos.rule.name.top)\n .sort((a, b) => b.pos - a.pos || a.rule.parts.length - b.rule.parts.length);\n }\n // Mapping from state ids to terms that that state has a length-1\n // forced reduction for.\n let length1Reductions = Object.create(null);\n function createsCycle(term, startState, parents = null) {\n let edges = gotoEdges[term];\n if (!edges)\n return false;\n return edges.some(val => {\n let parentIntersection = parents ? parents.filter(id => val.parents.includes(id)) : val.parents;\n if (parentIntersection.length == 0)\n return false;\n if (val.target == startState)\n return true;\n let found = length1Reductions[val.target];\n return found != null && createsCycle(found, startState, parentIntersection);\n });\n }\n for (let state of states) {\n if (state.defaultReduce && state.defaultReduce.parts.length > 0) {\n reductions[state.id] = reduceAction(state.defaultReduce, skipInfo);\n if (state.defaultReduce.parts.length == 1)\n length1Reductions[state.id] = state.defaultReduce.name.id;\n }\n }\n // To avoid painting states that only have one potential forced\n // reduction into a corner, reduction assignment is done by\n // candidate size, starting with the states with fewer candidates.\n for (let setSize = 1;; setSize++) {\n let done = true;\n for (let state of states) {\n if (state.defaultReduce)\n continue;\n let set = candidates[state.id];\n if (set.length != setSize) {\n if (set.length > setSize)\n done = false;\n continue;\n }\n for (let pos of set) {\n if (pos.pos != 1 || !createsCycle(pos.rule.name.id, state.id)) {\n reductions[state.id] = reduceAction(pos.rule, skipInfo, pos.pos);\n if (pos.pos == 1)\n length1Reductions[state.id] = pos.rule.name.id;\n break;\n }\n }\n }\n if (done)\n break;\n }\n return reductions;\n }\n substituteArgs(expr, args, params) {\n if (args.length == 0)\n return expr;\n return expr.walk(expr => {\n let found;\n if (expr instanceof NameExpression &&\n (found = params.findIndex(p => p.name == expr.id.name)) > -1) {\n let arg = args[found];\n if (expr.args.length) {\n if (arg instanceof NameExpression && !arg.args.length)\n return new NameExpression(expr.start, arg.id, expr.args);\n this.raise(`Passing arguments to a parameter that already has arguments`, expr.start);\n }\n return arg;\n }\n else if (expr instanceof InlineRuleExpression) {\n let r = expr.rule, props = this.substituteArgsInProps(r.props, args, params);\n return props == r.props ? expr :\n new InlineRuleExpression(expr.start, new RuleDeclaration(r.start, r.id, props, r.params, r.expr));\n }\n else if (expr instanceof SpecializeExpression) {\n let props = this.substituteArgsInProps(expr.props, args, params);\n return props == expr.props ? expr :\n new SpecializeExpression(expr.start, expr.type, props, expr.token, expr.content);\n }\n return expr;\n });\n }\n substituteArgsInProps(props, args, params) {\n let substituteInValue = (value) => {\n let result = value;\n for (let i = 0; i < value.length; i++) {\n let part = value[i];\n if (!part.name)\n continue;\n let found = params.findIndex(p => p.name == part.name);\n if (found < 0)\n continue;\n if (result == value)\n result = value.slice();\n let expr = args[found];\n if (expr instanceof NameExpression && !expr.args.length)\n result[i] = new PropPart(part.start, expr.id.name, null);\n else if (expr instanceof LiteralExpression)\n result[i] = new PropPart(part.start, expr.value, null);\n else\n this.raise(`Trying to interpolate expression '${expr}' into a prop`, part.start);\n }\n return result;\n };\n let result = props;\n for (let i = 0; i < props.length; i++) {\n let prop = props[i], value = substituteInValue(prop.value);\n if (value != prop.value) {\n if (result == props)\n result = props.slice();\n result[i] = new Prop(prop.start, prop.at, prop.name, value);\n }\n }\n return result;\n }\n conflictsFor(markers) {\n let here = Conflicts.none, atEnd = Conflicts.none;\n for (let marker of markers) {\n if (marker.type == \"ambig\") {\n here = here.join(new Conflicts(0, [marker.id.name]));\n }\n else {\n let precs = this.ast.precedences;\n let index = precs ? precs.items.findIndex(item => item.id.name == marker.id.name) : -1;\n if (index < 0)\n this.raise(`Reference to unknown precedence: '${marker.id.name}'`, marker.id.start);\n let prec = precs.items[index], value = precs.items.length - index;\n if (prec.type == \"cut\") {\n here = here.join(new Conflicts(0, none, value));\n }\n else {\n here = here.join(new Conflicts(value << 2));\n atEnd = atEnd.join(new Conflicts((value << 2) + (prec.type == \"left\" ? 1 : prec.type == \"right\" ? -1 : 0)));\n }\n }\n }\n return { here, atEnd };\n }\n raise(message, pos = 1) {\n return this.input.raise(message, pos);\n }\n warn(message, pos = -1) {\n let msg = this.input.message(message, pos);\n if (this.options.warn)\n this.options.warn(msg);\n else\n console.warn(msg);\n }\n defineRule(name, choices) {\n let skip = this.currentSkip[this.currentSkip.length - 1];\n for (let choice of choices)\n this.rules.push(new Rule(name, choice.terms, choice.ensureConflicts(), skip));\n }\n resolve(expr) {\n for (let built of this.built)\n if (built.matches(expr))\n return [p(built.term)];\n let found = this.tokens.getToken(expr);\n if (found)\n return [p(found)];\n for (let grp of this.localTokens) {\n let found = grp.getToken(expr);\n if (found)\n return [p(found)];\n }\n for (let ext of this.externalTokens) {\n let found = ext.getToken(expr);\n if (found)\n return [p(found)];\n }\n for (let ext of this.externalSpecializers) {\n let found = ext.getToken(expr);\n if (found)\n return [p(found)];\n }\n let known = this.astRules.find(r => r.rule.id.name == expr.id.name);\n if (!known)\n return this.raise(`Reference to undefined rule '${expr.id.name}'`, expr.start);\n if (known.rule.params.length != expr.args.length)\n this.raise(`Wrong number or arguments for '${expr.id.name}'`, expr.start);\n this.used(known.rule.id.name);\n return [p(this.buildRule(known.rule, expr.args, known.skip))];\n }\n // For tree-balancing reasons, repeat expressions X+ have to be\n // normalized to something like\n //\n // R -> X | R R\n //\n // Returns the `R` term.\n normalizeRepeat(expr) {\n let known = this.built.find(b => b.matchesRepeat(expr));\n if (known)\n return p(known.term);\n let name = expr.expr.prec < expr.prec ? `(${expr.expr})+` : `${expr.expr}+`;\n let term = this.terms.makeRepeat(this.terms.uniqueName(name));\n this.built.push(new BuiltRule(\"+\", [expr.expr], term));\n this.defineRule(term, this.normalizeExpr(expr.expr).concat(p(term, term)));\n return p(term);\n }\n normalizeSequence(expr) {\n let result = expr.exprs.map(e => this.normalizeExpr(e));\n let builder = this;\n function complete(start, from, endConflicts) {\n let { here, atEnd } = builder.conflictsFor(expr.markers[from]);\n if (from == result.length)\n return [start.withConflicts(start.terms.length, here.join(endConflicts))];\n let choices = [];\n for (let choice of result[from]) {\n for (let full of complete(start.concat(choice).withConflicts(start.terms.length, here), from + 1, endConflicts.join(atEnd)))\n choices.push(full);\n }\n return choices;\n }\n return complete(Parts.none, 0, Conflicts.none);\n }\n normalizeExpr(expr) {\n if (expr instanceof RepeatExpression && expr.kind == \"?\") {\n return [Parts.none, ...this.normalizeExpr(expr.expr)];\n }\n else if (expr instanceof RepeatExpression) {\n let repeated = this.normalizeRepeat(expr);\n return expr.kind == \"+\" ? [repeated] : [Parts.none, repeated];\n }\n else if (expr instanceof ChoiceExpression) {\n return expr.exprs.reduce((o, e) => o.concat(this.normalizeExpr(e)), []);\n }\n else if (expr instanceof SequenceExpression) {\n return this.normalizeSequence(expr);\n }\n else if (expr instanceof LiteralExpression) {\n return [p(this.tokens.getLiteral(expr))];\n }\n else if (expr instanceof NameExpression) {\n return this.resolve(expr);\n }\n else if (expr instanceof SpecializeExpression) {\n return [p(this.resolveSpecialization(expr))];\n }\n else if (expr instanceof InlineRuleExpression) {\n return [p(this.buildRule(expr.rule, none, this.currentSkip[this.currentSkip.length - 1], true))];\n }\n else {\n return this.raise(`This type of expression ('${expr}') may not occur in non-token rules`, expr.start);\n }\n }\n buildRule(rule, args, skip, inline = false) {\n let expr = this.substituteArgs(rule.expr, args, rule.params);\n let { name: nodeName, props, dynamicPrec, inline: explicitInline, group, exported } = this.nodeInfo(rule.props || none, inline ? \"pg\" : \"pgi\", rule.id.name, args, rule.params, rule.expr);\n if (exported && rule.params.length)\n this.warn(`Can't export parameterized rules`, rule.start);\n if (exported && inline)\n this.warn(`Can't export inline rule`, rule.start);\n let name = this.newName(rule.id.name + (args.length ? \"<\" + args.join(\",\") + \">\" : \"\"), nodeName || true, props);\n if (explicitInline)\n name.inline = true;\n if (dynamicPrec)\n this.registerDynamicPrec(name, dynamicPrec);\n if ((name.nodeType || exported) && rule.params.length == 0) {\n if (!nodeName)\n name.preserve = true;\n if (!inline)\n this.namedTerms[exported || rule.id.name] = name;\n }\n if (!inline)\n this.built.push(new BuiltRule(rule.id.name, args, name));\n this.currentSkip.push(skip);\n this.defineRule(name, this.normalizeExpr(expr));\n this.currentSkip.pop();\n if (group)\n this.definedGroups.push({ name, group, rule });\n return name;\n }\n nodeInfo(props, \n // p for dynamic precedence, d for dialect, i for inline, g for group, a for disabling the ignore test for default name\n allow, defaultName = null, args = none, params = none, expr, defaultProps) {\n let result = {};\n let name = defaultName && (allow.indexOf(\"a\") > -1 || !ignored(defaultName)) && !/ /.test(defaultName) ? defaultName : null;\n let dialect = null, dynamicPrec = 0, inline = false, group = null, exported = null;\n for (let prop of props) {\n if (!prop.at) {\n if (!this.knownProps[prop.name]) {\n let builtin = [\"name\", \"dialect\", \"dynamicPrecedence\", \"export\", \"isGroup\"].includes(prop.name)\n ? ` (did you mean '@${prop.name}'?)` : \"\";\n this.raise(`Unknown prop name '${prop.name}'${builtin}`, prop.start);\n }\n result[prop.name] = this.finishProp(prop, args, params);\n }\n else if (prop.name == \"name\") {\n name = this.finishProp(prop, args, params);\n if (/ /.test(name))\n this.raise(`Node names cannot have spaces ('${name}')`, prop.start);\n }\n else if (prop.name == \"dialect\") {\n if (allow.indexOf(\"d\") < 0)\n this.raise(\"Can't specify a dialect on non-token rules\", props[0].start);\n if (prop.value.length != 1 && !prop.value[0].value)\n this.raise(\"The '@dialect' rule prop must hold a plain string value\");\n let dialectID = this.dialects.indexOf(prop.value[0].value);\n if (dialectID < 0)\n this.raise(`Unknown dialect '${prop.value[0].value}'`, prop.value[0].start);\n dialect = dialectID;\n }\n else if (prop.name == \"dynamicPrecedence\") {\n if (allow.indexOf(\"p\") < 0)\n this.raise(\"Dynamic precedence can only be specified on nonterminals\");\n if (prop.value.length != 1 || !/^-?(?:10|\\d)$/.test(prop.value[0].value))\n this.raise(\"The '@dynamicPrecedence' rule prop must hold an integer between -10 and 10\");\n dynamicPrec = +prop.value[0].value;\n }\n else if (prop.name == \"inline\") {\n if (prop.value.length)\n this.raise(\"'@inline' doesn't take a value\", prop.value[0].start);\n if (allow.indexOf(\"i\") < 0)\n this.raise(\"Inline can only be specified on nonterminals\");\n inline = true;\n }\n else if (prop.name == \"isGroup\") {\n if (allow.indexOf(\"g\") < 0)\n this.raise(\"'@isGroup' can only be specified on nonterminals\");\n group = prop.value.length ? this.finishProp(prop, args, params) : defaultName;\n }\n else if (prop.name == \"export\") {\n if (prop.value.length)\n exported = this.finishProp(prop, args, params);\n else\n exported = defaultName;\n }\n else {\n this.raise(`Unknown built-in prop name '@${prop.name}'`, prop.start);\n }\n }\n if (expr && this.ast.autoDelim && (name || hasProps(result))) {\n let delim = this.findDelimiters(expr);\n if (delim) {\n addToProp(delim[0], \"closedBy\", delim[1].nodeName);\n addToProp(delim[1], \"openedBy\", delim[0].nodeName);\n }\n }\n if (defaultProps && hasProps(defaultProps)) {\n for (let prop in defaultProps)\n if (!(prop in result))\n result[prop] = defaultProps[prop];\n }\n if (hasProps(result) && !name)\n this.raise(`Node has properties but no name`, props.length ? props[0].start : expr.start);\n if (inline && (hasProps(result) || dialect || dynamicPrec))\n this.raise(`Inline nodes can't have props, dynamic precedence, or a dialect`, props[0].start);\n if (inline && name)\n name = null;\n return { name, props: result, dialect, dynamicPrec, inline, group, exported };\n }\n finishProp(prop, args, params) {\n return prop.value.map(part => {\n if (part.value)\n return part.value;\n let pos = params.findIndex(param => param.name == part.name);\n if (pos < 0)\n this.raise(`Property refers to '${part.name}', but no parameter by that name is in scope`, part.start);\n let expr = args[pos];\n if (expr instanceof NameExpression && !expr.args.length)\n return expr.id.name;\n if (expr instanceof LiteralExpression)\n return expr.value;\n return this.raise(`Expression '${expr}' can not be used as part of a property value`, part.start);\n }).join(\"\");\n }\n resolveSpecialization(expr) {\n let type = expr.type;\n let { name, props, dialect } = this.nodeInfo(expr.props, \"d\");\n let terminal = this.normalizeExpr(expr.token);\n if (terminal.length != 1 || terminal[0].terms.length != 1 || !terminal[0].terms[0].terminal)\n this.raise(`The first argument to '${type}' must resolve to a token`, expr.token.start);\n let values;\n if (expr.content instanceof LiteralExpression)\n values = [expr.content.value];\n else if ((expr.content instanceof ChoiceExpression) && expr.content.exprs.every(e => e instanceof LiteralExpression))\n values = expr.content.exprs.map(expr => expr.value);\n else\n return this.raise(`The second argument to '${expr.type}' must be a literal or choice of literals`, expr.content.start);\n let term = terminal[0].terms[0], token = null;\n let table = this.specialized[term.name] || (this.specialized[term.name] = []);\n for (let value of values) {\n let known = table.find(sp => sp.value == value);\n if (known == null) {\n if (!token) {\n token = this.makeTerminal(term.name + \"/\" + JSON.stringify(value), name, props);\n if (dialect != null)\n (this.tokens.byDialect[dialect] || (this.tokens.byDialect[dialect] = [])).push(token);\n }\n table.push({ value, term: token, type, dialect, name });\n this.tokenOrigins[token.name] = { spec: term };\n }\n else {\n if (known.type != type)\n this.raise(`Conflicting specialization types for ${JSON.stringify(value)} of ${term.name} (${type} vs ${known.type})`, expr.start);\n if (known.dialect != dialect)\n this.raise(`Conflicting dialects for specialization ${JSON.stringify(value)} of ${term.name}`, expr.start);\n if (known.name != name)\n this.raise(`Conflicting names for specialization ${JSON.stringify(value)} of ${term.name}`, expr.start);\n if (token && known.term != token)\n this.raise(`Conflicting specialization tokens for ${JSON.stringify(value)} of ${term.name}`, expr.start);\n token = known.term;\n }\n }\n return token;\n }\n findDelimiters(expr) {\n if (!(expr instanceof SequenceExpression) || expr.exprs.length < 2)\n return null;\n let findToken = (expr) => {\n if (expr instanceof LiteralExpression)\n return { term: this.tokens.getLiteral(expr), str: expr.value };\n if (expr instanceof NameExpression && expr.args.length == 0) {\n let rule = this.ast.rules.find(r => r.id.name == expr.id.name);\n if (rule)\n return findToken(rule.expr);\n let token = this.tokens.rules.find(r => r.id.name == expr.id.name);\n if (token && token.expr instanceof LiteralExpression)\n return { term: this.tokens.getToken(expr), str: token.expr.value };\n }\n return null;\n };\n let lastToken = findToken(expr.exprs[expr.exprs.length - 1]);\n if (!lastToken || !lastToken.term.nodeName)\n return null;\n const brackets = [\"()\", \"[]\", \"{}\", \"<>\"];\n let bracket = brackets.find(b => lastToken.str.indexOf(b[1]) > -1 && lastToken.str.indexOf(b[0]) < 0);\n if (!bracket)\n return null;\n let firstToken = findToken(expr.exprs[0]);\n if (!firstToken || !firstToken.term.nodeName ||\n firstToken.str.indexOf(bracket[0]) < 0 || firstToken.str.indexOf(bracket[1]) > -1)\n return null;\n return [firstToken.term, lastToken.term];\n }\n registerDynamicPrec(term, prec) {\n this.dynamicRulePrecedences.push({ rule: term, prec });\n term.preserve = true;\n }\n defineGroup(rule, group, ast) {\n var _a;\n let recur = [];\n let getNamed = (rule) => {\n if (rule.nodeName)\n return [rule];\n if (recur.includes(rule))\n this.raise(`Rule '${ast.id.name}' cannot define a group because it contains a non-named recursive rule ('${rule.name}')`, ast.start);\n let result = [];\n recur.push(rule);\n for (let r of this.rules)\n if (r.name == rule) {\n let names = r.parts.map(getNamed).filter(x => x.length);\n if (names.length > 1)\n this.raise(`Rule '${ast.id.name}' cannot define a group because some choices produce multiple named nodes`, ast.start);\n if (names.length == 1)\n for (let n of names[0])\n result.push(n);\n }\n recur.pop();\n return result;\n };\n for (let name of getNamed(rule))\n name.props[\"group\"] = (((_a = name.props[\"group\"]) === null || _a === void 0 ? void 0 : _a.split(\" \")) || []).concat(group).sort().join(\" \");\n }\n checkGroups() {\n let groups = Object.create(null), nodeNames = Object.create(null);\n for (let term of this.terms.terms)\n if (term.nodeName) {\n nodeNames[term.nodeName] = true;\n if (term.props[\"group\"])\n for (let group of term.props[\"group\"].split(\" \")) {\n (groups[group] || (groups[group] = [])).push(term);\n }\n }\n let names = Object.keys(groups);\n for (let i = 0; i < names.length; i++) {\n let name = names[i], terms = groups[name];\n if (nodeNames[name])\n this.warn(`Group name '${name}' conflicts with a node of the same name`);\n for (let j = i + 1; j < names.length; j++) {\n let other = groups[names[j]];\n if (terms.some(t => other.includes(t)) &&\n (terms.length > other.length ? other.some(t => !terms.includes(t)) : terms.some(t => !other.includes(t))))\n this.warn(`Groups '${name}' and '${names[j]}' overlap without one being a superset of the other`);\n }\n }\n }\n}\nconst MinSharedActions = 5;\nclass FinishStateContext {\n constructor(tokenizers, data, stateArray, skipData, skipInfo, states, builder) {\n this.tokenizers = tokenizers;\n this.data = data;\n this.stateArray = stateArray;\n this.skipData = skipData;\n this.skipInfo = skipInfo;\n this.states = states;\n this.builder = builder;\n this.sharedActions = [];\n }\n findSharedActions(state) {\n if (state.actions.length < MinSharedActions)\n return null;\n let found = null;\n for (let shared of this.sharedActions) {\n if ((!found || shared.actions.length > found.actions.length) &&\n shared.actions.every(a => state.actions.some(b => b.eq(a))))\n found = shared;\n }\n if (found)\n return found;\n let max = null, scratch = [];\n for (let i = state.id + 1; i < this.states.length; i++) {\n let other = this.states[i], fill = 0;\n if (other.defaultReduce || other.actions.length < MinSharedActions)\n continue;\n for (let a of state.actions)\n for (let b of other.actions)\n if (a.eq(b))\n scratch[fill++] = a;\n if (fill >= MinSharedActions && (!max || max.length < fill)) {\n max = scratch;\n scratch = [];\n }\n }\n if (!max)\n return null;\n let result = { actions: max, addr: this.storeActions(max, -1, null) };\n this.sharedActions.push(result);\n return result;\n }\n storeActions(actions, skipReduce, shared) {\n if (skipReduce < 0 && shared && shared.actions.length == actions.length)\n return shared.addr;\n let data = [];\n for (let action of actions) {\n if (shared && shared.actions.some(a => a.eq(action)))\n continue;\n if (action instanceof Shift) {\n data.push(action.term.id, action.target.id, 0);\n }\n else {\n let code = reduceAction(action.rule, this.skipInfo);\n if (code != skipReduce)\n data.push(action.term.id, code & 65535 /* Action.ValueMask */, code >> 16);\n }\n }\n data.push(65535 /* Seq.End */);\n if (skipReduce > -1)\n data.push(2 /* Seq.Other */, skipReduce & 65535 /* Action.ValueMask */, skipReduce >> 16);\n else if (shared)\n data.push(1 /* Seq.Next */, shared.addr & 0xffff, shared.addr >> 16);\n else\n data.push(0 /* Seq.Done */);\n return this.data.storeArray(data);\n }\n finish(state, isSkip, forcedReduce) {\n let b = this.builder;\n let skipID = b.skipRules.indexOf(state.skip);\n let skipTable = this.skipData[skipID], skipTerms = this.skipInfo[skipID].startTokens;\n let defaultReduce = state.defaultReduce ? reduceAction(state.defaultReduce, this.skipInfo) : 0;\n let flags = isSkip ? 1 /* StateFlag.Skipped */ : 0;\n let skipReduce = -1, shared = null;\n if (defaultReduce == 0) {\n if (isSkip)\n for (const action of state.actions)\n if (action instanceof Reduce && action.term.eof)\n skipReduce = reduceAction(action.rule, this.skipInfo);\n if (skipReduce < 0)\n shared = this.findSharedActions(state);\n }\n if (state.set.some(p => p.rule.name.top && p.pos == p.rule.parts.length))\n flags |= 2 /* StateFlag.Accepting */;\n let external = [];\n for (let i = 0; i < state.actions.length + skipTerms.length; i++) {\n let term = i < state.actions.length ? state.actions[i].term : skipTerms[i - state.actions.length];\n for (;;) {\n let orig = b.tokenOrigins[term.name];\n if (orig && orig.spec) {\n term = orig.spec;\n continue;\n }\n if (orig && (orig.external instanceof ExternalTokenSet))\n addToSet(external, orig.external);\n break;\n }\n }\n let tokenizerMask = 0;\n for (let i = 0; i < this.tokenizers.length; i++) {\n let tok = this.tokenizers[i];\n if (external.includes(tok) || tok.groupID == state.tokenGroup)\n tokenizerMask |= (1 << i);\n }\n let base = state.id * 6 /* ParseState.Size */;\n this.stateArray[base + 0 /* ParseState.Flags */] = flags;\n this.stateArray[base + 1 /* ParseState.Actions */] = this.storeActions(defaultReduce ? none : state.actions, skipReduce, shared);\n this.stateArray[base + 2 /* ParseState.Skip */] = skipTable;\n this.stateArray[base + 3 /* ParseState.TokenizerMask */] = tokenizerMask;\n this.stateArray[base + 4 /* ParseState.DefaultReduce */] = defaultReduce;\n this.stateArray[base + 5 /* ParseState.ForcedReduce */] = forcedReduce;\n }\n}\nfunction addToProp(term, prop, value) {\n let cur = term.props[prop];\n if (!cur || cur.split(\" \").indexOf(value) < 0)\n term.props[prop] = cur ? cur + \" \" + value : value;\n}\nfunction buildSpecializeTable(spec) {\n let table = Object.create(null);\n for (let { value, term, type } of spec) {\n let code = type == \"specialize\" ? 0 /* Specialize.Specialize */ : 1 /* Specialize.Extend */;\n table[value] = (term.id << 1) | code;\n }\n return table;\n}\nfunction reduceAction(rule, skipInfo, depth = rule.parts.length) {\n return rule.name.id | 65536 /* Action.ReduceFlag */ |\n (rule.isRepeatWrap && depth == rule.parts.length ? 131072 /* Action.RepeatFlag */ : 0) |\n (skipInfo.some(i => i.rule == rule.name) ? 262144 /* Action.StayFlag */ : 0) |\n (depth << 19 /* Action.ReduceDepthShift */);\n}\nfunction findArray(data, value) {\n search: for (let i = 0;;) {\n let next = data.indexOf(value[0], i);\n if (next == -1 || next + value.length > data.length)\n break;\n for (let j = 1; j < value.length; j++) {\n if (value[j] != data[next + j]) {\n i = next + 1;\n continue search;\n }\n }\n return next;\n }\n return -1;\n}\nfunction findSkipStates(table, startRules) {\n let nonSkip = Object.create(null);\n let work = [];\n let add = (state) => {\n if (!nonSkip[state.id]) {\n nonSkip[state.id] = true;\n work.push(state);\n }\n };\n for (let state of table)\n if (state.startRule && startRules.includes(state.startRule))\n add(state);\n for (let i = 0; i < work.length; i++) {\n for (let a of work[i].actions)\n if (a instanceof Shift)\n add(a.target);\n for (let a of work[i].goto)\n add(a.target);\n }\n return (id) => !nonSkip[id];\n}\nclass DataBuilder {\n constructor() {\n this.data = [];\n }\n storeArray(data) {\n let found = findArray(this.data, data);\n if (found > -1)\n return found;\n let pos = this.data.length;\n for (let num of data)\n this.data.push(num);\n return pos;\n }\n finish() {\n return Uint16Array.from(this.data);\n }\n}\n// The goto table maps a start state + a term to a new state, and is\n// used to determine the new state when reducing. Because this allows\n// more more efficient representation and access, unlike the action\n// tables, the goto table is organized by term, with groups of start\n// states that map to a given end state enumerated for each term.\n// Since many terms only have a single valid goto target, this makes\n// it cheaper to look those up.\n//\n// (Unfortunately, though the standard LR parsing mechanism never\n// looks up invalid goto states, the incremental parsing mechanism\n// needs accurate goto information for a state/term pair, so we do\n// need to store state ids even for terms that have only one target.)\n//\n// - First comes the amount of terms in the table\n//\n// - Then, for each term, the offset of the term's data\n//\n// - At these offsets, there's a record for each target state\n//\n// - Such a record starts with the amount of start states that go to\n// this target state, shifted one to the left, with the first bit\n// only set if this is the last record for this term.\n//\n// - Then follows the target state id\n//\n// - And then the start state ids\nfunction computeGotoTable(states) {\n let goto = {};\n let maxTerm = 0;\n for (let state of states) {\n for (let entry of state.goto) {\n maxTerm = Math.max(entry.term.id, maxTerm);\n let set = goto[entry.term.id] || (goto[entry.term.id] = {});\n (set[entry.target.id] || (set[entry.target.id] = [])).push(state.id);\n }\n }\n let data = new DataBuilder;\n let index = [];\n let offset = maxTerm + 2; // Offset of the data, taking index size into account\n for (let term = 0; term <= maxTerm; term++) {\n let entries = goto[term];\n if (!entries) {\n index.push(1);\n continue;\n }\n let termTable = [];\n let keys = Object.keys(entries);\n for (let target of keys) {\n let list = entries[target];\n termTable.push((target == keys[keys.length - 1] ? 1 : 0) + (list.length << 1));\n termTable.push(+target);\n for (let source of list)\n termTable.push(source);\n }\n index.push(data.storeArray(termTable) + offset);\n }\n if (index.some(n => n > 0xffff))\n throw new GenError(\"Goto table too large\");\n return Uint16Array.from([maxTerm + 1, ...index, ...data.data]);\n}\nclass TokenGroup {\n constructor(tokens, groupID) {\n this.tokens = tokens;\n this.groupID = groupID;\n }\n create() { return this.groupID; }\n createSource() { return String(this.groupID); }\n}\nfunction addToSet(set, value) {\n if (!set.includes(value))\n set.push(value);\n}\nfunction buildTokenMasks(groups) {\n let masks = Object.create(null);\n for (let group of groups) {\n let groupMask = 1 << group.groupID;\n for (let term of group.tokens) {\n masks[term.id] = (masks[term.id] || 0) | groupMask;\n }\n }\n return masks;\n}\nclass TokenArg {\n constructor(name, expr, scope) {\n this.name = name;\n this.expr = expr;\n this.scope = scope;\n }\n}\nclass BuildingRule {\n constructor(name, start, to, args) {\n this.name = name;\n this.start = start;\n this.to = to;\n this.args = args;\n }\n}\nclass TokenSet {\n constructor(b, ast) {\n this.b = b;\n this.ast = ast;\n this.startState = new State$1;\n this.built = [];\n this.building = []; // Used for recursion check\n this.byDialect = Object.create(null);\n this.precedenceRelations = [];\n this.rules = ast ? ast.rules : none;\n for (let rule of this.rules)\n b.unique(rule.id);\n }\n getToken(expr) {\n for (let built of this.built)\n if (built.matches(expr))\n return built.term;\n let name = expr.id.name;\n let rule = this.rules.find(r => r.id.name == name);\n if (!rule)\n return null;\n let { name: nodeName, props, dialect, exported } = this.b.nodeInfo(rule.props, \"d\", name, expr.args, rule.params.length != expr.args.length ? none : rule.params);\n let term = this.b.makeTerminal(expr.toString(), nodeName, props);\n if (dialect != null)\n (this.byDialect[dialect] || (this.byDialect[dialect] = [])).push(term);\n if ((term.nodeType || exported) && rule.params.length == 0) {\n if (!term.nodeType)\n term.preserve = true;\n this.b.namedTerms[exported || name] = term;\n }\n this.buildRule(rule, expr, this.startState, new State$1([term]));\n this.built.push(new BuiltRule(name, expr.args, term));\n return term;\n }\n buildRule(rule, expr, from, to, args = none) {\n let name = expr.id.name;\n if (rule.params.length != expr.args.length)\n this.b.raise(`Incorrect number of arguments for token '${name}'`, expr.start);\n let building = this.building.find(b => b.name == name && exprsEq(expr.args, b.args));\n if (building) {\n if (building.to == to) {\n from.nullEdge(building.start);\n return;\n }\n let lastIndex = this.building.length - 1;\n while (this.building[lastIndex].name != name)\n lastIndex--;\n this.b.raise(`Invalid (non-tail) recursion in token rules: ${this.building.slice(lastIndex).map(b => b.name).join(\" -> \")}`, expr.start);\n }\n this.b.used(rule.id.name);\n let start = new State$1;\n from.nullEdge(start);\n this.building.push(new BuildingRule(name, start, to, expr.args));\n this.build(this.b.substituteArgs(rule.expr, expr.args, rule.params), start, to, expr.args.map((e, i) => new TokenArg(rule.params[i].name, e, args)));\n this.building.pop();\n }\n build(expr, from, to, args) {\n if (expr instanceof NameExpression) {\n let name = expr.id.name, arg = args.find(a => a.name == name);\n if (arg)\n return this.build(arg.expr, from, to, arg.scope);\n let rule;\n for (let i = 0, lt = this.b.localTokens; i <= lt.length; i++) {\n let set = i == lt.length ? this.b.tokens : lt[i];\n rule = set.rules.find(r => r.id.name == name);\n }\n if (!rule)\n return this.b.raise(`Reference to token rule '${expr.id.name}', which isn't found`, expr.start);\n this.buildRule(rule, expr, from, to, args);\n }\n else if (expr instanceof CharClass) {\n for (let [a, b] of CharClasses[expr.type])\n from.edge(a, b, to);\n }\n else if (expr instanceof ChoiceExpression) {\n for (let choice of expr.exprs)\n this.build(choice, from, to, args);\n }\n else if (isEmpty(expr)) {\n from.nullEdge(to);\n }\n else if (expr instanceof SequenceExpression) {\n let conflict = expr.markers.find(c => c.length > 0);\n if (conflict)\n this.b.raise(\"Conflict marker in token expression\", conflict[0].start);\n for (let i = 0; i < expr.exprs.length; i++) {\n let next = i == expr.exprs.length - 1 ? to : new State$1;\n this.build(expr.exprs[i], from, next, args);\n from = next;\n }\n }\n else if (expr instanceof RepeatExpression) {\n if (expr.kind == \"*\") {\n let loop = new State$1;\n from.nullEdge(loop);\n this.build(expr.expr, loop, loop, args);\n loop.nullEdge(to);\n }\n else if (expr.kind == \"+\") {\n let loop = new State$1;\n this.build(expr.expr, from, loop, args);\n this.build(expr.expr, loop, loop, args);\n loop.nullEdge(to);\n }\n else { // expr.kind == \"?\"\n from.nullEdge(to);\n this.build(expr.expr, from, to, args);\n }\n }\n else if (expr instanceof SetExpression) {\n for (let [a, b] of expr.inverted ? invertRanges(expr.ranges) : expr.ranges)\n rangeEdges(from, to, a, b);\n }\n else if (expr instanceof LiteralExpression) {\n for (let i = 0; i < expr.value.length; i++) {\n let ch = expr.value.charCodeAt(i);\n let next = i == expr.value.length - 1 ? to : new State$1;\n from.edge(ch, ch + 1, next);\n from = next;\n }\n }\n else if (expr instanceof AnyExpression) {\n let mid = new State$1;\n from.edge(0, 0xDC00, to);\n from.edge(0xDC00, MAX_CHAR + 1, to);\n from.edge(0xD800, 0xDC00, mid);\n mid.edge(0xDC00, 0xE000, to);\n }\n else {\n return this.b.raise(`Unrecognized expression type in token`, expr.start);\n }\n }\n takePrecedences() {\n let rel = this.precedenceRelations = [];\n if (this.ast)\n for (let group of this.ast.precedences) {\n let prev = [];\n for (let item of group.items) {\n let level = [];\n if (item instanceof NameExpression) {\n for (let built of this.built)\n if (item.args.length ? built.matches(item) : built.id == item.id.name)\n level.push(built.term);\n }\n else {\n let id = JSON.stringify(item.value), found = this.built.find(b => b.id == id);\n if (found)\n level.push(found.term);\n }\n if (!level.length)\n this.b.warn(`Precedence specified for unknown token ${item}`, item.start);\n for (let term of level)\n addRel(rel, term, prev);\n prev = prev.concat(level);\n }\n }\n }\n precededBy(a, b) {\n let found = this.precedenceRelations.find(r => r.term == a);\n return found && found.after.includes(b);\n }\n buildPrecTable(softConflicts) {\n let precTable = [], rel = this.precedenceRelations.slice();\n // Add entries for soft-conflicting tokens that are in the\n // precedence table, to make sure they'll appear in the right\n // order and don't mess up the longer-wins default rule.\n for (let { a, b, soft } of softConflicts)\n if (soft) {\n if (!rel.some(r => r.term == a) || !rel.some(r => r.term == b))\n continue;\n if (soft < 0)\n [a, b] = [b, a]; // Now a is longer than b (and should thus take precedence)\n addRel(rel, b, [a]);\n addRel(rel, a, []);\n }\n add: while (rel.length) {\n for (let i = 0; i < rel.length; i++) {\n let record = rel[i];\n if (record.after.every(t => precTable.includes(t.id))) {\n precTable.push(record.term.id);\n if (rel.length == 1)\n break add;\n rel[i] = rel.pop();\n continue add;\n }\n }\n this.b.raise(`Cyclic token precedence relation between ${rel.map(r => r.term).join(\", \")}`);\n }\n return precTable;\n }\n}\nclass MainTokenSet extends TokenSet {\n constructor() {\n super(...arguments);\n this.explicitConflicts = [];\n }\n getLiteral(expr) {\n let id = JSON.stringify(expr.value);\n for (let built of this.built)\n if (built.id == id)\n return built.term;\n let name = null, props = {}, dialect = null, exported = null;\n let decl = this.ast ? this.ast.literals.find(l => l.literal == expr.value) : null;\n if (decl)\n ({ name, props, dialect, exported } = this.b.nodeInfo(decl.props, \"da\", expr.value));\n let term = this.b.makeTerminal(id, name, props);\n if (dialect != null)\n (this.byDialect[dialect] || (this.byDialect[dialect] = [])).push(term);\n if (exported)\n this.b.namedTerms[exported] = term;\n this.build(expr, this.startState, new State$1([term]), none);\n this.built.push(new BuiltRule(id, none, term));\n return term;\n }\n takeConflicts() {\n var _a;\n let resolve = (expr) => {\n if (expr instanceof NameExpression) {\n for (let built of this.built)\n if (built.matches(expr))\n return built.term;\n }\n else {\n let id = JSON.stringify(expr.value), found = this.built.find(b => b.id == id);\n if (found)\n return found.term;\n }\n this.b.warn(`Precedence specified for unknown token ${expr}`, expr.start);\n return null;\n };\n for (let c of ((_a = this.ast) === null || _a === void 0 ? void 0 : _a.conflicts) || []) {\n let a = resolve(c.a), b = resolve(c.b);\n if (a && b) {\n if (a.id < b.id)\n [a, b] = [b, a];\n this.explicitConflicts.push({ a, b });\n }\n }\n }\n // Token groups are a mechanism for allowing conflicting (matching\n // overlapping input, without an explicit precedence being given)\n // tokens to exist in a grammar _if_ they don't occur in the same\n // place (aren't used in the same states).\n //\n // States that use tokens that conflict will raise an error when any\n // of the conflicting pairs of tokens both occur in that state.\n // Otherwise, they are assigned a token group, which includes all\n // the potentially-conflicting tokens they use. If there's already a\n // group that doesn't have any conflicts with those tokens, that is\n // reused, otherwise a new group is created.\n //\n // So each state has zero or one token groups, and each conflicting\n // token may belong to one or more groups. Tokens get assigned a\n // 16-bit bitmask with the groups they belong to set to 1 (all-1s\n // for non-conflicting tokens). When tokenizing, that mask is\n // compared to the current state's group (again using all-1s for\n // group-less states) to determine whether a token is applicable for\n // this state.\n //\n // Extended/specialized tokens are treated as their parent token for\n // this purpose.\n buildTokenGroups(states, skipInfo, startID) {\n let tokens = this.startState.compile();\n if (tokens.accepting.length)\n this.b.raise(`Grammar contains zero-length tokens (in '${tokens.accepting[0].name}')`, this.rules.find(r => r.id.name == tokens.accepting[0].name).start);\n if (/\\btokens\\b/.test(verbose))\n console.log(tokens.toString());\n // If there is a precedence specified for the pair, the conflict is resolved\n let allConflicts = tokens.findConflicts(checkTogether(states, this.b, skipInfo))\n .filter(({ a, b }) => !this.precededBy(a, b) && !this.precededBy(b, a));\n for (let { a, b } of this.explicitConflicts) {\n if (!allConflicts.some(c => c.a == a && c.b == b))\n allConflicts.push(new Conflict$1(a, b, 0, \"\", \"\"));\n }\n let softConflicts = allConflicts.filter(c => c.soft), conflicts = allConflicts.filter(c => !c.soft);\n let errors = [];\n let groups = [];\n for (let state of states) {\n if (state.defaultReduce || state.tokenGroup > -1)\n continue;\n // Find potentially-conflicting terms (in terms) and the things\n // they conflict with (in conflicts), and raise an error if\n // there's a token conflict directly in this state.\n let terms = [], incompatible = [];\n let skip = skipInfo[this.b.skipRules.indexOf(state.skip)].startTokens;\n for (let term of skip)\n if (state.actions.some(a => a.term == term))\n this.b.raise(`Use of token ${term.name} conflicts with skip rule`);\n let stateTerms = [];\n for (let i = 0; i < state.actions.length + (skip ? skip.length : 0); i++) {\n let term = i < state.actions.length ? state.actions[i].term : skip[i - state.actions.length];\n let orig = this.b.tokenOrigins[term.name];\n if (orig && orig.spec)\n term = orig.spec;\n else if (orig && orig.external)\n continue;\n addToSet(stateTerms, term);\n }\n if (stateTerms.length == 0)\n continue;\n for (let term of stateTerms) {\n for (let conflict of conflicts) {\n let conflicting = conflict.a == term ? conflict.b : conflict.b == term ? conflict.a : null;\n if (!conflicting)\n continue;\n if (stateTerms.includes(conflicting) && !errors.some(e => e.conflict == conflict)) {\n let example = conflict.exampleA ? ` (example: ${JSON.stringify(conflict.exampleA)}${conflict.exampleB ? ` vs ${JSON.stringify(conflict.exampleB)}` : \"\"})` : \"\";\n errors.push({\n error: `Overlapping tokens ${term.name} and ${conflicting.name} used in same context${example}\\n` +\n `After: ${state.set[0].trail()}`,\n conflict\n });\n }\n addToSet(terms, term);\n addToSet(incompatible, conflicting);\n }\n }\n let tokenGroup = null;\n for (let group of groups) {\n if (incompatible.some(term => group.tokens.includes(term)))\n continue;\n for (let term of terms)\n addToSet(group.tokens, term);\n tokenGroup = group;\n break;\n }\n if (!tokenGroup) {\n tokenGroup = new TokenGroup(terms, groups.length + startID);\n groups.push(tokenGroup);\n }\n state.tokenGroup = tokenGroup.groupID;\n }\n if (errors.length)\n this.b.raise(errors.map(e => e.error).join(\"\\n\\n\"));\n if (groups.length + startID > 16)\n this.b.raise(`Too many different token groups (${groups.length}) to represent them as a 16-bit bitfield`);\n let precTable = this.buildPrecTable(softConflicts);\n return {\n tokenGroups: groups,\n tokenPrec: precTable,\n tokenData: tokens.toArray(buildTokenMasks(groups), precTable)\n };\n }\n}\nclass LocalTokenSet extends TokenSet {\n constructor(b, ast) {\n super(b, ast);\n this.fallback = null;\n if (ast.fallback)\n b.unique(ast.fallback.id);\n }\n getToken(expr) {\n let term = null;\n if (this.ast.fallback && this.ast.fallback.id.name == expr.id.name) {\n if (expr.args.length)\n this.b.raise(`Incorrect number of arguments for ${expr.id.name}`, expr.start);\n if (!this.fallback) {\n let { name: nodeName, props, exported } = this.b.nodeInfo(this.ast.fallback.props, \"\", expr.id.name, none, none);\n let term = this.fallback = this.b.makeTerminal(expr.id.name, nodeName, props);\n if (term.nodeType || exported) {\n if (!term.nodeType)\n term.preserve = true;\n this.b.namedTerms[exported || expr.id.name] = term;\n }\n this.b.used(expr.id.name);\n }\n term = this.fallback;\n }\n else {\n term = super.getToken(expr);\n }\n if (term && !this.b.tokenOrigins[term.name])\n this.b.tokenOrigins[term.name] = { group: this };\n return term;\n }\n buildLocalGroup(states, skipInfo, id) {\n let tokens = this.startState.compile();\n if (tokens.accepting.length)\n this.b.raise(`Grammar contains zero-length tokens (in '${tokens.accepting[0].name}')`, this.rules.find(r => r.id.name == tokens.accepting[0].name).start);\n for (let { a, b, exampleA } of tokens.findConflicts(() => true)) {\n if (!this.precededBy(a, b) && !this.precededBy(b, a))\n this.b.raise(`Overlapping tokens ${a.name} and ${b.name} in local token group${exampleA ? ` (example: ${JSON.stringify(exampleA)})` : ''}`);\n }\n for (let state of states) {\n if (state.defaultReduce)\n continue;\n // See if this state uses any of the tokens in this group, and\n // if so, make sure it *only* uses tokens from this group.\n let usesThis = null;\n let usesOther = skipInfo[this.b.skipRules.indexOf(state.skip)].startTokens[0];\n for (let { term } of state.actions) {\n let orig = this.b.tokenOrigins[term.name];\n if ((orig === null || orig === void 0 ? void 0 : orig.group) == this)\n usesThis = term;\n else\n usesOther = term;\n }\n if (usesThis) {\n if (usesOther)\n this.b.raise(`Tokens from a local token group used together with other tokens (${usesThis.name} with ${usesOther.name})`);\n state.tokenGroup = id;\n }\n }\n let precTable = this.buildPrecTable(none);\n let tokenData = tokens.toArray({ [id]: 65535 /* Seq.End */ }, precTable);\n let precOffset = tokenData.length;\n let fullData = new Uint16Array(tokenData.length + precTable.length + 1);\n fullData.set(tokenData, 0);\n fullData.set(precTable, precOffset);\n fullData[fullData.length - 1] = 65535 /* Seq.End */;\n return {\n groupID: id,\n create: () => new LocalTokenGroup(fullData, precOffset, this.fallback ? this.fallback.id : undefined),\n createSource: importName => `new ${importName(\"LocalTokenGroup\", \"@lezer/lr\")}(${encodeArray(fullData)}, ${precOffset}${this.fallback ? `, ${this.fallback.id}` : ''})`\n };\n }\n}\nfunction checkTogether(states, b, skipInfo) {\n let cache = Object.create(null);\n function hasTerm(state, term) {\n return state.actions.some(a => a.term == term) ||\n skipInfo[b.skipRules.indexOf(state.skip)].startTokens.includes(term);\n }\n return (a, b) => {\n if (a.id < b.id)\n [a, b] = [b, a];\n let key = a.id | (b.id << 16), cached = cache[key];\n if (cached != null)\n return cached;\n return cache[key] = states.some(state => hasTerm(state, a) && hasTerm(state, b));\n };\n}\nfunction invertRanges(ranges) {\n let pos = 0, result = [];\n for (let [a, b] of ranges) {\n if (a > pos)\n result.push([pos, a]);\n pos = b;\n }\n if (pos <= MAX_CODE)\n result.push([pos, MAX_CODE + 1]);\n return result;\n}\nconst ASTRAL = 0x10000, GAP_START = 0xd800, GAP_END = 0xe000, MAX_CODE = 0x10ffff;\nconst LOW_SURR_B = 0xdc00, HIGH_SURR_B = 0xdfff;\n// Create intermediate states for astral characters in a range, if\n// necessary, since the tokenizer acts on UTF16 characters\nfunction rangeEdges(from, to, low, hi) {\n if (low < ASTRAL) {\n if (low < GAP_START)\n from.edge(low, Math.min(hi, GAP_START), to);\n if (hi > GAP_END)\n from.edge(Math.max(low, GAP_END), Math.min(hi, MAX_CHAR + 1), to);\n low = ASTRAL;\n }\n if (hi <= ASTRAL)\n return;\n let lowStr = String.fromCodePoint(low), hiStr = String.fromCodePoint(hi - 1);\n let lowA = lowStr.charCodeAt(0), lowB = lowStr.charCodeAt(1);\n let hiA = hiStr.charCodeAt(0), hiB = hiStr.charCodeAt(1);\n if (lowA == hiA) { // Share the first char code\n let hop = new State$1;\n from.edge(lowA, lowA + 1, hop);\n hop.edge(lowB, hiB + 1, to);\n }\n else {\n let midStart = lowA, midEnd = hiA;\n if (lowB > LOW_SURR_B) {\n midStart++;\n let hop = new State$1;\n from.edge(lowA, lowA + 1, hop);\n hop.edge(lowB, HIGH_SURR_B + 1, to);\n }\n if (hiB < HIGH_SURR_B) {\n midEnd--;\n let hop = new State$1;\n from.edge(hiA, hiA + 1, hop);\n hop.edge(LOW_SURR_B, hiB + 1, to);\n }\n if (midStart <= midEnd) {\n let hop = new State$1;\n from.edge(midStart, midEnd + 1, hop);\n hop.edge(LOW_SURR_B, HIGH_SURR_B + 1, to);\n }\n }\n}\nfunction isEmpty(expr) {\n return expr instanceof SequenceExpression && expr.exprs.length == 0;\n}\nfunction gatherExtTokens(b, tokens) {\n let result = Object.create(null);\n for (let token of tokens) {\n b.unique(token.id);\n let { name, props, dialect } = b.nodeInfo(token.props, \"d\", token.id.name);\n let term = b.makeTerminal(token.id.name, name, props);\n if (dialect != null)\n (b.tokens.byDialect[dialect] || (b.tokens.byDialect[dialect] = [])).push(term);\n b.namedTerms[token.id.name] = result[token.id.name] = term;\n }\n return result;\n}\nfunction findExtToken(b, tokens, expr) {\n let found = tokens[expr.id.name];\n if (!found)\n return null;\n if (expr.args.length)\n b.raise(\"External tokens cannot take arguments\", expr.args[0].start);\n b.used(expr.id.name);\n return found;\n}\nfunction addRel(rel, term, after) {\n let found = rel.findIndex(r => r.term == term);\n if (found < 0)\n rel.push({ term, after });\n else\n rel[found] = { term, after: rel[found].after.concat(after) };\n}\nclass ExternalTokenSet {\n constructor(b, ast) {\n this.b = b;\n this.ast = ast;\n this.tokens = gatherExtTokens(b, ast.tokens);\n for (let name in this.tokens)\n this.b.tokenOrigins[this.tokens[name].name] = { external: this };\n }\n getToken(expr) { return findExtToken(this.b, this.tokens, expr); }\n create() {\n return this.b.options.externalTokenizer(this.ast.id.name, this.b.termTable);\n }\n createSource(importName) {\n let { source, id: { name } } = this.ast;\n return importName(name, source);\n }\n}\nclass ExternalSpecializer {\n constructor(b, ast) {\n this.b = b;\n this.ast = ast;\n this.term = null;\n this.tokens = gatherExtTokens(b, ast.tokens);\n }\n finish() {\n let terms = this.b.normalizeExpr(this.ast.token);\n if (terms.length != 1 || terms[0].terms.length != 1 || !terms[0].terms[0].terminal)\n this.b.raise(`The token expression to '@external ${this.ast.type}' must resolve to a token`, this.ast.token.start);\n this.term = terms[0].terms[0];\n for (let name in this.tokens)\n this.b.tokenOrigins[this.tokens[name].name] = { spec: this.term, external: this };\n }\n getToken(expr) { return findExtToken(this.b, this.tokens, expr); }\n}\nfunction inlineRules(rules, preserve) {\n for (let pass = 0;; pass++) {\n let inlinable = Object.create(null), found;\n if (pass == 0)\n for (let rule of rules) {\n if (rule.name.inline && !inlinable[rule.name.name]) {\n let group = rules.filter(r => r.name == rule.name);\n if (group.some(r => r.parts.includes(rule.name)))\n continue;\n found = inlinable[rule.name.name] = group;\n }\n }\n for (let i = 0; i < rules.length; i++) {\n let rule = rules[i];\n if (!rule.name.interesting && !rule.parts.includes(rule.name) && rule.parts.length < 3 &&\n !preserve.includes(rule.name) &&\n (rule.parts.length == 1 || rules.every(other => other.skip == rule.skip || !other.parts.includes(rule.name))) &&\n !rule.parts.some(p => !!inlinable[p.name]) &&\n !rules.some((r, j) => j != i && r.name == rule.name))\n found = inlinable[rule.name.name] = [rule];\n }\n if (!found)\n return rules;\n let newRules = [];\n for (let rule of rules) {\n if (inlinable[rule.name.name])\n continue;\n if (!rule.parts.some(p => !!inlinable[p.name])) {\n newRules.push(rule);\n continue;\n }\n function expand(at, conflicts, parts) {\n if (at == rule.parts.length) {\n newRules.push(new Rule(rule.name, parts, conflicts, rule.skip));\n return;\n }\n let next = rule.parts[at], replace = inlinable[next.name];\n if (!replace) {\n expand(at + 1, conflicts.concat(rule.conflicts[at + 1]), parts.concat(next));\n return;\n }\n for (let r of replace)\n expand(at + 1, conflicts.slice(0, conflicts.length - 1)\n .concat(conflicts[at].join(r.conflicts[0]))\n .concat(r.conflicts.slice(1, r.conflicts.length - 1))\n .concat(rule.conflicts[at + 1].join(r.conflicts[r.conflicts.length - 1])), parts.concat(r.parts));\n }\n expand(0, [rule.conflicts[0]], []);\n }\n rules = newRules;\n }\n}\nfunction mergeRules(rules) {\n let merged = Object.create(null), found;\n for (let i = 0; i < rules.length;) {\n let groupStart = i;\n let name = rules[i++].name;\n while (i < rules.length && rules[i].name == name)\n i++;\n let size = i - groupStart;\n if (name.interesting)\n continue;\n for (let j = i; j < rules.length;) {\n let otherStart = j, otherName = rules[j++].name;\n while (j < rules.length && rules[j].name == otherName)\n j++;\n if (j - otherStart != size || otherName.interesting)\n continue;\n let match = true;\n for (let k = 0; k < size && match; k++) {\n let a = rules[groupStart + k], b = rules[otherStart + k];\n if (a.cmpNoName(b) != 0)\n match = false;\n }\n if (match)\n found = merged[name.name] = otherName;\n }\n }\n if (!found)\n return rules;\n let newRules = [];\n for (let rule of rules)\n if (!merged[rule.name.name]) {\n newRules.push(rule.parts.every(p => !merged[p.name]) ? rule :\n new Rule(rule.name, rule.parts.map(p => merged[p.name] || p), rule.conflicts, rule.skip));\n }\n return newRules;\n}\nfunction simplifyRules(rules, preserve) {\n return mergeRules(inlineRules(rules, preserve));\n}\n/**\nBuild an in-memory parser instance for a given grammar. This is\nmostly useful for testing. If your grammar uses external\ntokenizers, you'll have to provide the `externalTokenizer` option\nfor the returned parser to be able to parse anything.\n*/\nfunction buildParser(text, options = {}) {\n let builder = new Builder(text, options), parser = builder.getParser();\n parser.termTable = builder.termTable;\n return parser;\n}\nconst KEYWORDS = [\"break\", \"case\", \"catch\", \"continue\", \"debugger\", \"default\", \"do\", \"else\", \"finally\",\n \"for\", \"function\", \"if\", \"return\", \"switch\", \"throw\", \"try\", \"var\", \"while\", \"with\",\n \"null\", \"true\", \"false\", \"instanceof\", \"typeof\", \"void\", \"delete\", \"new\", \"in\", \"this\",\n \"const\", \"class\", \"extends\", \"export\", \"import\", \"super\", \"enum\", \"implements\", \"interface\",\n \"let\", \"package\", \"private\", \"protected\", \"public\", \"static\", \"yield\", \"require\"];\n/**\nBuild the code that represents the parser tables for a given\ngrammar description. The `parser` property in the return value\nholds the main file that exports the `Parser` instance. The\n`terms` property holds a declaration file that defines constants\nfor all of the named terms in grammar, holding their ids as value.\nThis is useful when external code, such as a tokenizer, needs to\nbe able to use these ids. It is recommended to run a tree-shaking\nbundler when importing this file, since you usually only need a\nhandful of the many terms in your code.\n*/\nfunction buildParserFile(text, options = {}) {\n return new Builder(text, options).getParserFile();\n}\nfunction ignored(name) {\n let first = name[0];\n return first == \"_\" || first.toUpperCase() != first;\n}\nfunction isExported(rule) {\n return rule.props.some(p => p.at && p.name == \"export\");\n}\n\nexport { GenError, buildParser, buildParserFile };\n","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { defaultHighlightStyle, HighlightStyle, syntaxHighlighting } from '@codemirror/language';\nimport { EditorView } from '@codemirror/view';\nimport { nullTranslator } from '@jupyterlab/translation';\nimport { tags as t } from '@lezer/highlight';\nexport const jupyterEditorTheme = EditorView.theme({\n /**\n * CodeMirror themes are handling the background/color in this way. This works\n * fine for CodeMirror editors outside the notebook, but the notebook styles\n * these things differently.\n */\n '&': {\n background: 'var(--jp-layout-color0)',\n color: 'var(--jp-content-font-color1)'\n },\n /* In the notebook, we want this styling to be handled by its container */\n '.jp-CodeConsole &, .jp-Notebook &': {\n background: 'transparent'\n },\n '.cm-content': {\n caretColor: 'var(--jp-editor-cursor-color)'\n },\n /* Inherit font family from .cm-editor */\n '.cm-scroller': {\n fontFamily: 'inherit'\n },\n '.cm-cursor, .cm-dropCursor': {\n borderLeft: 'var(--jp-code-cursor-width0) solid var(--jp-editor-cursor-color)'\n },\n '.cm-selectionBackground, .cm-content ::selection': {\n backgroundColor: 'var(--jp-editor-selected-background)'\n },\n '&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground': {\n backgroundColor: 'var(--jp-editor-selected-focused-background)'\n },\n '.cm-gutters': {\n borderRight: '1px solid var(--jp-border-color2)',\n backgroundColor: 'var(--jp-layout-color2)'\n },\n '.cm-gutter': {\n backgroundColor: 'var(--jp-layout-color2)'\n },\n '.cm-activeLine': {\n backgroundColor: 'color-mix(in srgb, var(--jp-layout-color3) 25%, transparent)'\n },\n '.cm-lineNumbers': {\n color: 'var(--jp-ui-font-color2)'\n },\n '.cm-searchMatch': {\n backgroundColor: 'var(--jp-search-unselected-match-background-color)',\n color: 'var(--jp-search-unselected-match-color)'\n },\n '.cm-searchMatch.cm-searchMatch-selected': {\n backgroundColor: 'var(--jp-search-selected-match-background-color) !important',\n color: 'var(--jp-search-selected-match-color) !important'\n },\n '.cm-tooltip': {\n backgroundColor: 'var(--jp-layout-color1)'\n }\n});\n// The list of available tags for syntax highlighting is available at\n// https://lezer.codemirror.net/docs/ref/#highlight.tags\nexport const jupyterHighlightStyle = HighlightStyle.define([\n // Order matters - a rule will override the previous ones; important for example for in headings styles.\n { tag: t.meta, color: 'var(--jp-mirror-editor-meta-color)' },\n { tag: t.heading, color: 'var(--jp-mirror-editor-header-color)' },\n {\n tag: [t.heading1, t.heading2, t.heading3, t.heading4],\n color: 'var(--jp-mirror-editor-header-color)',\n fontWeight: 'bold'\n },\n {\n tag: t.keyword,\n color: 'var(--jp-mirror-editor-keyword-color)',\n fontWeight: 'bold'\n },\n { tag: t.atom, color: 'var(--jp-mirror-editor-atom-color)' },\n { tag: t.number, color: 'var(--jp-mirror-editor-number-color)' },\n {\n tag: [t.definition(t.name), t.function(t.definition(t.variableName))],\n color: 'var(--jp-mirror-editor-def-color)'\n },\n {\n tag: t.standard(t.variableName),\n color: 'var(--jp-mirror-editor-builtin-color)'\n },\n {\n tag: [t.special(t.variableName), t.self],\n color: 'var(--jp-mirror-editor-variable-2-color)'\n },\n { tag: t.punctuation, color: 'var(--jp-mirror-editor-punctuation-color)' },\n { tag: t.propertyName, color: 'var(--jp-mirror-editor-property-color)' },\n {\n tag: t.operator,\n color: 'var(--jp-mirror-editor-operator-color)',\n fontWeight: 'bold'\n },\n {\n tag: t.comment,\n color: 'var(--jp-mirror-editor-comment-color)',\n fontStyle: 'italic'\n },\n { tag: t.string, color: 'var(--jp-mirror-editor-string-color)' },\n {\n tag: [t.labelName, t.monospace, t.special(t.string)],\n color: 'var(--jp-mirror-editor-string-2-color)'\n },\n { tag: t.bracket, color: 'var(--jp-mirror-editor-bracket-color)' },\n { tag: t.tagName, color: 'var(--jp-mirror-editor-tag-color)' },\n { tag: t.attributeName, color: 'var(--jp-mirror-editor-attribute-color)' },\n { tag: t.quote, color: 'var(--jp-mirror-editor-quote-color)' },\n {\n tag: t.link,\n color: 'var(--jp-mirror-editor-link-color)',\n textDecoration: 'underline'\n },\n { tag: [t.separator, t.derefOperator, t.paren], color: '' },\n { tag: t.strong, fontWeight: 'bold' },\n { tag: t.emphasis, fontStyle: 'italic' },\n { tag: t.strikethrough, textDecoration: 'line-through' },\n {\n tag: t.bool,\n color: 'var(--jp-mirror-editor-keyword-color)',\n fontWeight: 'bold'\n }\n]);\n/**\n * JupyterLab CodeMirror 6 theme\n */\nexport const jupyterTheme = [\n jupyterEditorTheme,\n syntaxHighlighting(jupyterHighlightStyle)\n];\n/**\n * CodeMirror 6 theme registry\n */\nexport class EditorThemeRegistry {\n constructor() {\n /**\n * CodeMirror 6 themes\n */\n this._themeMap = new Map([\n ['jupyter', Object.freeze({ name: 'jupyter', theme: jupyterTheme })]\n ]);\n }\n /**\n * Get all themes\n */\n get themes() {\n return Array.from(this._themeMap.values());\n }\n /**\n * Get the default CodeMirror 6 theme for JupyterLab\n *\n * @returns Default theme\n */\n defaultTheme() {\n return this._themeMap.get('jupyter').theme;\n }\n /**\n * Register a new theme.\n *\n * @param theme Codemirror 6 theme\n */\n addTheme(theme) {\n if (this._themeMap.has(theme.name)) {\n throw new Error(`A theme named '${theme.name}' is already registered.`);\n }\n this._themeMap.set(theme.name, { displayName: theme.name, ...theme });\n }\n /**\n * Get a theme.\n *\n * #### Notes\n * It falls back to the default theme\n *\n * @param name Theme name\n * @returns Theme extension\n */\n getTheme(name) {\n var _a;\n const ext = (_a = this._themeMap.get(name)) === null || _a === void 0 ? void 0 : _a.theme;\n return ext !== null && ext !== void 0 ? ext : this.defaultTheme();\n }\n}\n/**\n * EditorThemeRegistry namespace\n */\n(function (EditorThemeRegistry) {\n /**\n * Get the default editor themes.\n *\n * @param translator Application translator\n * @returns Default CodeMirror 6 themes\n */\n function getDefaultThemes(translator) {\n const trans = (translator !== null && translator !== void 0 ? translator : nullTranslator).load('jupyterlab');\n return [\n Object.freeze({\n name: 'codemirror',\n displayName: trans.__('codemirror'),\n theme: [\n EditorView.baseTheme({}),\n syntaxHighlighting(defaultHighlightStyle)\n ]\n })\n ];\n }\n EditorThemeRegistry.getDefaultThemes = getDefaultThemes;\n})(EditorThemeRegistry || (EditorThemeRegistry = {}));\n//# sourceMappingURL=theme.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { LanguageDescription, LanguageSupport, LRLanguage, StreamLanguage } from '@codemirror/language';\nimport { IEditorMimeTypeService } from '@jupyterlab/codeeditor';\nimport { PathExt } from '@jupyterlab/coreutils';\nimport { nullTranslator } from '@jupyterlab/translation';\nimport { buildParser } from '@lezer/generator';\nimport { highlightTree } from '@lezer/highlight';\nimport { jupyterHighlightStyle } from './theme';\n/**\n * CodeMirror language registry\n */\nexport class EditorLanguageRegistry {\n constructor() {\n this._modeList = [];\n // Add default language text/plain -> No expressions to parse\n this.addLanguage({\n name: 'none',\n mime: 'text/plain',\n support: new LanguageSupport(\n // Create a dummy parser that as no expression to parse\n LRLanguage.define({ parser: buildParser('@top Program { }') }))\n });\n }\n /**\n * Register a new language for CodeMirror\n *\n * @param language Language to register\n */\n addLanguage(language) {\n var _a;\n const info = (_a = this.findByName(language.name)) !== null && _a !== void 0 ? _a : this.findByMIME(language.mime, true);\n if (info) {\n throw new Error(`${language.mime} already registered`);\n }\n this._modeList.push(this.makeSpec(language));\n }\n /**\n * Ensure a codemirror mode is available by name or Codemirror spec.\n *\n * @param language - The mode to ensure. If it is a string, uses [findBest]\n * to get the appropriate spec.\n *\n * @returns A promise that resolves when the mode is available.\n */\n async getLanguage(language) {\n const spec = this.findBest(language);\n if (spec && !spec.support) {\n spec.support = await spec.load();\n }\n return spec;\n }\n /**\n * Get the raw list of available modes specs.\n *\n * @returns The available modes\n */\n getLanguages() {\n return [...this._modeList];\n }\n /**\n * Find a codemirror mode by MIME.\n *\n * @param mime Mime type to look for\n * @param strict Whether xml and json should be assimilated to the generic mimetype\n * @returns The mode or null\n */\n findByMIME(mime, strict = false) {\n if (Array.isArray(mime)) {\n for (let i = 0; i < mime.length; i++) {\n const spec = this.findByMIME(mime[i]);\n if (spec)\n return spec;\n }\n return null;\n }\n mime = mime.toLowerCase();\n for (let i = 0; i < this._modeList.length; i++) {\n let info = this._modeList[i];\n if (Array.isArray(info.mime)) {\n for (let j = 0; j < info.mime.length; j++) {\n if (info.mime[j] == mime) {\n return info;\n }\n }\n }\n else if (info.mime == mime) {\n return info;\n }\n }\n if (!strict) {\n if (/\\+xml$/.test(mime))\n return this.findByMIME('application/xml');\n if (/\\+json$/.test(mime))\n return this.findByMIME('application/json');\n }\n return null;\n }\n /**\n * Find a codemirror mode by name.\n *\n * @param name The mode name\n * @returns The mode or null\n */\n findByName(name) {\n name = name.toLowerCase();\n for (let i = 0; i < this._modeList.length; i++) {\n let info = this._modeList[i];\n if (info.name.toLowerCase() == name)\n return info;\n if (info.alias) {\n for (let j = 0; j < info.alias.length; j++) {\n if (info.alias[j].toLowerCase() == name) {\n return info;\n }\n }\n }\n }\n return null;\n }\n /**\n * Find a codemirror mode by extension.\n *\n * @param ext The extension name\n * @returns The mode or null\n */\n findByExtension(ext) {\n if (Array.isArray(ext)) {\n for (let i = 0; i < ext.length; i++) {\n const spec = this.findByExtension(ext[i]);\n if (spec)\n return spec;\n }\n return null;\n }\n ext = ext.toLowerCase();\n for (let i = 0; i < this._modeList.length; i++) {\n let info = this._modeList[i];\n for (let j = 0; j < info.extensions.length; j++) {\n if (info.extensions[j].toLowerCase() == ext) {\n return info;\n }\n }\n }\n return null;\n }\n /**\n * Find a codemirror mode by filename.\n *\n * @param name File name\n * @returns The mode or null\n */\n findByFileName(name) {\n const basename = PathExt.basename(name);\n for (let i = 0; i < this._modeList.length; i++) {\n let info = this._modeList[i];\n if (info.filename && info.filename.test(basename)) {\n return info;\n }\n }\n let dot = basename.lastIndexOf('.');\n let ext = dot > -1 && basename.substring(dot + 1, basename.length);\n if (ext) {\n return this.findByExtension(ext);\n }\n return null;\n }\n /**\n * Find a codemirror mode by name or CodeMirror spec.\n *\n * @param language The CodeMirror mode\n * @param fallback Whether to fallback to default mimetype spec or not\n * @returns The mode or null\n */\n findBest(language, fallback = true) {\n var _a, _b, _c, _d;\n const modename = typeof language === 'string' ? language : language.name;\n const mimetype = typeof language !== 'string' ? language.mime : modename;\n const ext = typeof language !== 'string' ? (_a = language.extensions) !== null && _a !== void 0 ? _a : [] : [];\n return ((_d = (_c = (_b = (modename ? this.findByName(modename) : null)) !== null && _b !== void 0 ? _b : (mimetype ? this.findByMIME(mimetype) : null)) !== null && _c !== void 0 ? _c : this.findByExtension(ext)) !== null && _d !== void 0 ? _d : (fallback\n ? this.findByMIME(IEditorMimeTypeService.defaultMimeType)\n : null));\n }\n /**\n * Parse and style a string.\n *\n * @param code Code to highlight\n * @param language Code language\n * @param el HTML element into which the highlighted code will be inserted\n */\n async highlight(code, language, el) {\n var _a;\n if (language) {\n await this.getLanguage(language);\n }\n const language_ = (_a = language === null || language === void 0 ? void 0 : language.support) === null || _a === void 0 ? void 0 : _a.language;\n if (!language_) {\n el.appendChild(document.createTextNode(code));\n return;\n }\n const tree = language_.parser.parse(code);\n // position state required because unstyled tokens are not emitted\n // in highlightTree\n let pos = 0;\n highlightTree(tree, jupyterHighlightStyle, (from, to, classes) => {\n if (from > pos) {\n // No style applied to the token between pos and from\n el.appendChild(document.createTextNode(code.slice(pos, from)));\n }\n const sp = el.appendChild(document.createElement('span'));\n sp.className = classes;\n sp.appendChild(document.createTextNode(code.slice(from, to)));\n pos = to;\n });\n if (pos < tree.length - 1) {\n // No style applied on the trailing text\n el.appendChild(document.createTextNode(code.slice(pos, tree.length)));\n }\n }\n // Code mirror uses two similar structures, a plain object with optional fields,\n // and a class with the same fields but all mandatory. Maybe adopting the same\n // pattern would be less confusing (although far more verbose)\n makeSpec(spec) {\n let res = LanguageDescription.of(spec);\n // CodeMirror does not store/use mime type of a language\n res.mime = spec.mime;\n res.displayName = spec.displayName;\n return res;\n }\n}\n/**\n * EditorLanguageRegistry namespace\n */\n(function (EditorLanguageRegistry) {\n /**\n * Convert an CodeMirror 5 language parser to CodeMirror 6\n *\n * @param parser Legacy parser\n * @returns Language object\n */\n function legacy(parser) {\n return new LanguageSupport(StreamLanguage.define(parser));\n }\n EditorLanguageRegistry.legacy = legacy;\n /**\n * Create a dialect of SQL\n *\n * @param dialectName SQL dialect\n * @returns Language object\n */\n async function sql(dialectName) {\n const m = await import('@codemirror/lang-sql');\n return m.sql({ dialect: m[dialectName] });\n }\n /**\n * Get the default editor languages\n *\n * @param translator Application translator\n * @returns Default CodeMirror 6 languages\n */\n function getDefaultLanguages(translator) {\n const trans = (translator !== null && translator !== void 0 ? translator : nullTranslator).load('jupyterlab');\n return [\n {\n name: 'C',\n displayName: trans.__('C'),\n mime: 'text/x-csrc',\n extensions: ['c', 'h', 'ino'],\n async load() {\n const m = await import('@codemirror/lang-cpp');\n return m.cpp();\n }\n },\n {\n name: 'C++',\n displayName: trans.__('C++'),\n mime: 'text/x-c++src',\n extensions: ['cpp', 'c++', 'cc', 'cxx', 'hpp', 'h++', 'hh', 'hxx'],\n async load() {\n const m = await import('@codemirror/lang-cpp');\n return m.cpp();\n }\n },\n {\n name: 'CQL',\n displayName: trans.__('CQL'),\n mime: 'text/x-cassandra',\n extensions: ['cql'],\n load() {\n return sql('Cassandra');\n }\n },\n {\n name: 'CSS',\n displayName: trans.__('CSS'),\n mime: 'text/css',\n extensions: ['css'],\n async load() {\n const m = await import('@codemirror/lang-css');\n return m.css();\n }\n },\n {\n name: 'HTML',\n displayName: trans.__('HTML'),\n alias: ['xhtml'],\n mime: 'text/html',\n extensions: ['html', 'htm', 'handlebars', 'hbs'],\n async load() {\n const m = await import('@codemirror/lang-html');\n return m.html();\n }\n },\n {\n name: 'Java',\n displayName: trans.__('Java'),\n mime: 'text/x-java',\n extensions: ['java'],\n async load() {\n const m = await import('@codemirror/lang-java');\n return m.java();\n }\n },\n {\n name: 'Javascript',\n displayName: trans.__('Javascript'),\n alias: ['ecmascript', 'js', 'node'],\n mime: [\n 'text/javascript',\n 'text/ecmascript',\n 'application/javascript',\n 'application/x-javascript',\n 'application/ecmascript'\n ],\n extensions: ['js', 'mjs', 'cjs'],\n async load() {\n const m = await import('@codemirror/lang-javascript');\n return m.javascript();\n }\n },\n {\n name: 'JSON',\n displayName: trans.__('JSON'),\n alias: ['json5'],\n mime: ['application/json', 'application/x-json'],\n extensions: ['json', 'map'],\n async load() {\n const m = await import('@codemirror/lang-json');\n return m.json();\n }\n },\n {\n name: 'JSX',\n displayName: trans.__('JSX'),\n mime: 'text/jsx',\n extensions: ['jsx'],\n async load() {\n const m = await import('@codemirror/lang-javascript');\n return m.javascript({ jsx: true });\n }\n },\n {\n name: 'MariaDB SQL',\n displayName: trans.__('MariaDB SQL'),\n mime: 'text/x-mariadb',\n load() {\n return sql('MariaSQL');\n }\n },\n {\n name: 'Markdown',\n displayName: trans.__('Markdown'),\n mime: 'text/x-markdown',\n extensions: ['md', 'markdown', 'mkd'],\n async load() {\n const m = await import('@codemirror/lang-markdown');\n return m.markdown({ codeLanguages: this._modeList });\n }\n },\n {\n name: 'MS SQL',\n displayName: trans.__('MS SQL'),\n mime: 'text/x-mssql',\n load() {\n return sql('MSSQL');\n }\n },\n {\n name: 'MySQL',\n displayName: trans.__('MySQL'),\n mime: 'text/x-mysql',\n load() {\n return sql('MySQL');\n }\n },\n {\n name: 'PHP',\n displayName: trans.__('PHP'),\n mime: [\n 'text/x-php',\n 'application/x-httpd-php',\n 'application/x-httpd-php-open'\n ],\n extensions: ['php', 'php3', 'php4', 'php5', 'php7', 'phtml'],\n async load() {\n const m = await import('@codemirror/lang-php');\n return m.php();\n }\n },\n {\n name: 'PLSQL',\n displayName: trans.__('PLSQL'),\n mime: 'text/x-plsql',\n extensions: ['pls'],\n load() {\n return sql('PLSQL');\n }\n },\n {\n name: 'PostgreSQL',\n displayName: trans.__('PostgreSQL'),\n mime: 'text/x-pgsql',\n load() {\n return sql('PostgreSQL');\n }\n },\n {\n name: 'Python',\n displayName: trans.__('Python'),\n mime: 'text/x-python',\n extensions: ['BUILD', 'bzl', 'py', 'pyw'],\n filename: /^(BUCK|BUILD)$/,\n async load() {\n const m = await import('@codemirror/lang-python');\n return m.python();\n }\n },\n {\n name: 'ipython',\n displayName: trans.__('ipython'),\n mime: 'text/x-ipython',\n async load() {\n // FIXME Restore '?' operator - using the default python LanguageSupport allows\n // to activate feature such as code folding.\n // return Promise.resolve(legacy(mkPython({ singleOperators: /\\?/ })));\n const m = await import('@codemirror/lang-python');\n return m.python();\n }\n },\n {\n name: 'Rust',\n displayName: trans.__('Rust'),\n mime: 'text/x-rustsrc',\n extensions: ['rs'],\n async load() {\n const m = await import('@codemirror/lang-rust');\n return m.rust();\n }\n },\n {\n name: 'SQL',\n displayName: trans.__('SQL'),\n mime: ['application/sql', 'text/x-sql'],\n extensions: ['sql'],\n load() {\n return sql('StandardSQL');\n }\n },\n {\n name: 'SQLite',\n displayName: trans.__('SQLite'),\n mime: 'text/x-sqlite',\n load() {\n return sql('SQLite');\n }\n },\n {\n name: 'TSX',\n displayName: trans.__('TSX'),\n alias: ['TypeScript-JSX'],\n mime: 'text/typescript-jsx',\n extensions: ['tsx'],\n async load() {\n const m = await import('@codemirror/lang-javascript');\n return m.javascript({ jsx: true, typescript: true });\n }\n },\n {\n name: 'TypeScript',\n displayName: trans.__('TypeScript'),\n alias: ['ts'],\n mime: 'application/typescript',\n extensions: ['ts'],\n async load() {\n const m = await import('@codemirror/lang-javascript');\n return m.javascript({ typescript: true });\n }\n },\n {\n name: 'WebAssembly',\n displayName: trans.__('WebAssembly'),\n mime: 'text/webassembly',\n extensions: ['wat', 'wast'],\n async load() {\n const m = await import('@codemirror/lang-wast');\n return m.wast();\n }\n },\n {\n name: 'XML',\n displayName: trans.__('XML'),\n alias: ['rss', 'wsdl', 'xsd'],\n mime: ['application/xml', 'text/xml'],\n extensions: ['xml', 'xsl', 'xsd', 'svg'],\n async load() {\n const m = await import('@codemirror/lang-xml');\n return m.xml();\n }\n },\n // Legacy modes ported from CodeMirror 5\n {\n name: 'APL',\n displayName: trans.__('APL'),\n mime: 'text/apl',\n extensions: ['dyalog', 'apl'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/apl');\n return legacy(m.apl);\n }\n },\n {\n name: 'PGP',\n displayName: trans.__('PGP'),\n alias: ['asciiarmor'],\n mime: [\n 'application/pgp',\n 'application/pgp-encrypted',\n 'application/pgp-keys',\n 'application/pgp-signature'\n ],\n extensions: ['asc', 'pgp', 'sig'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/asciiarmor');\n return legacy(m.asciiArmor);\n }\n },\n {\n name: 'ASN.1',\n displayName: trans.__('ASN.1'),\n mime: 'text/x-ttcn-asn',\n extensions: ['asn', 'asn1'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/asn1');\n return legacy(m.asn1({}));\n }\n },\n {\n name: 'Asterisk',\n displayName: trans.__('Asterisk'),\n mime: 'text/x-asterisk',\n filename: /^extensions\\.conf$/i,\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/asterisk');\n return legacy(m.asterisk);\n }\n },\n {\n name: 'Brainfuck',\n displayName: trans.__('Brainfuck'),\n mime: 'text/x-brainfuck',\n extensions: ['b', 'bf'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/brainfuck');\n return legacy(m.brainfuck);\n }\n },\n {\n name: 'Cobol',\n displayName: trans.__('Cobol'),\n mime: 'text/x-cobol',\n extensions: ['cob', 'cpy'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/cobol');\n return legacy(m.cobol);\n }\n },\n {\n name: 'C#',\n displayName: trans.__('C#'),\n alias: ['csharp', 'cs'],\n mime: 'text/x-csharp',\n extensions: ['cs'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/clike');\n return legacy(m.csharp);\n }\n },\n {\n name: 'Clojure',\n displayName: trans.__('Clojure'),\n mime: 'text/x-clojure',\n extensions: ['clj', 'cljc', 'cljx'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/clojure');\n return legacy(m.clojure);\n }\n },\n {\n name: 'ClojureScript',\n displayName: trans.__('ClojureScript'),\n mime: 'text/x-clojurescript',\n extensions: ['cljs'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/clojure');\n return legacy(m.clojure);\n }\n },\n {\n name: 'Closure Stylesheets (GSS)',\n displayName: trans.__('Closure Stylesheets (GSS)'),\n mime: 'text/x-gss',\n extensions: ['gss'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/css');\n return legacy(m.gss);\n }\n },\n {\n name: 'CMake',\n displayName: trans.__('CMake'),\n mime: 'text/x-cmake',\n extensions: ['cmake', 'cmake.in'],\n filename: /^CMakeLists\\.txt$/,\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/cmake');\n return legacy(m.cmake);\n }\n },\n {\n name: 'CoffeeScript',\n displayName: trans.__('CoffeeScript'),\n alias: ['coffee', 'coffee-script'],\n mime: [\n 'application/vnd.coffeescript',\n 'text/coffeescript',\n 'text/x-coffeescript'\n ],\n extensions: ['coffee'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/coffeescript');\n return legacy(m.coffeeScript);\n }\n },\n {\n name: 'Common Lisp',\n displayName: trans.__('Common Lisp'),\n alias: ['lisp'],\n mime: 'text/x-common-lisp',\n extensions: ['cl', 'lisp', 'el'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/commonlisp');\n return legacy(m.commonLisp);\n }\n },\n {\n name: 'Cypher',\n displayName: trans.__('Cypher'),\n mime: 'application/x-cypher-query',\n extensions: ['cyp', 'cypher'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/cypher');\n return legacy(m.cypher);\n }\n },\n {\n name: 'Cython',\n displayName: trans.__('Cython'),\n mime: 'text/x-cython',\n extensions: ['pyx', 'pxd', 'pxi'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/python');\n return legacy(m.cython);\n }\n },\n {\n name: 'Crystal',\n displayName: trans.__('Crystal'),\n mime: 'text/x-crystal',\n extensions: ['cr'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/crystal');\n return legacy(m.crystal);\n }\n },\n {\n name: 'D',\n displayName: trans.__('D'),\n mime: 'text/x-d',\n extensions: ['d'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/d');\n return legacy(m.d);\n }\n },\n {\n name: 'Dart',\n displayName: trans.__('Dart'),\n mime: ['application/dart', 'text/x-dart'],\n extensions: ['dart'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/clike');\n return legacy(m.dart);\n }\n },\n {\n name: 'diff',\n displayName: trans.__('diff'),\n mime: 'text/x-diff',\n extensions: ['diff', 'patch'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/diff');\n return legacy(m.diff);\n }\n },\n {\n name: 'Dockerfile',\n displayName: trans.__('Dockerfile'),\n mime: 'text/x-dockerfile',\n filename: /^Dockerfile$/,\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/dockerfile');\n return legacy(m.dockerFile);\n }\n },\n {\n name: 'DTD',\n displayName: trans.__('DTD'),\n mime: 'application/xml-dtd',\n extensions: ['dtd'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/dtd');\n return legacy(m.dtd);\n }\n },\n {\n name: 'Dylan',\n displayName: trans.__('Dylan'),\n mime: 'text/x-dylan',\n extensions: ['dylan', 'dyl', 'intr'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/dylan');\n return legacy(m.dylan);\n }\n },\n {\n name: 'EBNF',\n displayName: trans.__('EBNF'),\n mime: 'text/x-ebnf',\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/ebnf');\n return legacy(m.ebnf);\n }\n },\n {\n name: 'ECL',\n displayName: trans.__('ECL'),\n mime: 'text/x-ecl',\n extensions: ['ecl'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/ecl');\n return legacy(m.ecl);\n }\n },\n {\n name: 'edn',\n displayName: trans.__('edn'),\n mime: 'application/edn',\n extensions: ['edn'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/clojure');\n return legacy(m.clojure);\n }\n },\n {\n name: 'Eiffel',\n displayName: trans.__('Eiffel'),\n mime: 'text/x-eiffel',\n extensions: ['e'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/eiffel');\n return legacy(m.eiffel);\n }\n },\n {\n name: 'Elm',\n displayName: trans.__('Elm'),\n mime: 'text/x-elm',\n extensions: ['elm'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/elm');\n return legacy(m.elm);\n }\n },\n {\n name: 'Erlang',\n displayName: trans.__('Erlang'),\n mime: 'text/x-erlang',\n extensions: ['erl'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/erlang');\n return legacy(m.erlang);\n }\n },\n {\n name: 'Esper',\n displayName: trans.__('Esper'),\n mime: 'text/x-esper',\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/sql');\n return legacy(m.esper);\n }\n },\n {\n name: 'Factor',\n displayName: trans.__('Factor'),\n mime: 'text/x-factor',\n extensions: ['factor'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/factor');\n return legacy(m.factor);\n }\n },\n {\n name: 'FCL',\n displayName: trans.__('FCL'),\n mime: 'text/x-fcl',\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/fcl');\n return legacy(m.fcl);\n }\n },\n {\n name: 'Forth',\n displayName: trans.__('Forth'),\n mime: 'text/x-forth',\n extensions: ['forth', 'fth', '4th'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/forth');\n return legacy(m.forth);\n }\n },\n {\n name: 'Fortran',\n displayName: trans.__('Fortran'),\n mime: 'text/x-fortran',\n extensions: ['f', 'for', 'f77', 'f90', 'f95'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/fortran');\n return legacy(m.fortran);\n }\n },\n {\n name: 'F#',\n displayName: trans.__('F#'),\n alias: ['fsharp'],\n mime: 'text/x-fsharp',\n extensions: ['fs'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/mllike');\n return legacy(m.fSharp);\n }\n },\n {\n name: 'Gas',\n displayName: trans.__('Gas'),\n mime: 'text/x-gas',\n extensions: ['s'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/gas');\n return legacy(m.gas);\n }\n },\n {\n name: 'Gherkin',\n displayName: trans.__('Gherkin'),\n mime: 'text/x-feature',\n extensions: ['feature'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/gherkin');\n return legacy(m.gherkin);\n }\n },\n {\n name: 'Go',\n displayName: trans.__('Go'),\n mime: 'text/x-go',\n extensions: ['go'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/go');\n return legacy(m.go);\n }\n },\n {\n name: 'Groovy',\n displayName: trans.__('Groovy'),\n mime: 'text/x-groovy',\n extensions: ['groovy', 'gradle'],\n filename: /^Jenkinsfile$/,\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/groovy');\n return legacy(m.groovy);\n }\n },\n {\n name: 'Haskell',\n displayName: trans.__('Haskell'),\n mime: 'text/x-haskell',\n extensions: ['hs'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/haskell');\n return legacy(m.haskell);\n }\n },\n {\n name: 'Haxe',\n displayName: trans.__('Haxe'),\n mime: 'text/x-haxe',\n extensions: ['hx'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/haxe');\n return legacy(m.haxe);\n }\n },\n {\n name: 'HXML',\n displayName: trans.__('HXML'),\n mime: 'text/x-hxml',\n extensions: ['hxml'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/haxe');\n return legacy(m.hxml);\n }\n },\n {\n name: 'HTTP',\n displayName: trans.__('HTTP'),\n mime: 'message/http',\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/http');\n return legacy(m.http);\n }\n },\n {\n name: 'IDL',\n displayName: trans.__('IDL'),\n mime: 'text/x-idl',\n extensions: ['pro'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/idl');\n return legacy(m.idl);\n }\n },\n {\n name: 'JSON-LD',\n displayName: trans.__('JSON-LD'),\n alias: ['jsonld'],\n mime: 'application/ld+json',\n extensions: ['jsonld'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/javascript');\n return legacy(m.jsonld);\n }\n },\n {\n name: 'Jinja2',\n displayName: trans.__('Jinja2'),\n mime: 'text/jinja2',\n extensions: ['j2', 'jinja', 'jinja2'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/jinja2');\n return legacy(m.jinja2);\n }\n },\n {\n name: 'Julia',\n displayName: trans.__('Julia'),\n mime: 'text/x-julia',\n extensions: ['jl'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/julia');\n return legacy(m.julia);\n }\n },\n {\n name: 'Kotlin',\n displayName: trans.__('Kotlin'),\n mime: 'text/x-kotlin',\n extensions: ['kt'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/clike');\n return legacy(m.kotlin);\n }\n },\n {\n name: 'LESS',\n displayName: trans.__('LESS'),\n mime: 'text/x-less',\n extensions: ['less'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/css');\n return legacy(m.less);\n }\n },\n {\n name: 'LiveScript',\n displayName: trans.__('LiveScript'),\n alias: ['ls'],\n mime: 'text/x-livescript',\n extensions: ['ls'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/livescript');\n return legacy(m.liveScript);\n }\n },\n {\n name: 'Lua',\n displayName: trans.__('Lua'),\n mime: 'text/x-lua',\n extensions: ['lua'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/lua');\n return legacy(m.lua);\n }\n },\n {\n name: 'mIRC',\n displayName: trans.__('mIRC'),\n mime: 'text/mirc',\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/mirc');\n return legacy(m.mirc);\n }\n },\n {\n name: 'Mathematica',\n displayName: trans.__('Mathematica'),\n mime: 'text/x-mathematica',\n extensions: ['m', 'nb', 'wl', 'wls'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/mathematica');\n return legacy(m.mathematica);\n }\n },\n {\n name: 'Modelica',\n displayName: trans.__('Modelica'),\n mime: 'text/x-modelica',\n extensions: ['mo'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/modelica');\n return legacy(m.modelica);\n }\n },\n {\n name: 'MUMPS',\n displayName: trans.__('MUMPS'),\n mime: 'text/x-mumps',\n extensions: ['mps'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/mumps');\n return legacy(m.mumps);\n }\n },\n {\n name: 'mbox',\n displayName: trans.__('mbox'),\n mime: 'application/mbox',\n extensions: ['mbox'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/mbox');\n return legacy(m.mbox);\n }\n },\n {\n name: 'Nginx',\n displayName: trans.__('Nginx'),\n mime: 'text/x-nginx-conf',\n filename: /nginx.*\\.conf$/i,\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/nginx');\n return legacy(m.nginx);\n }\n },\n {\n name: 'NSIS',\n displayName: trans.__('NSIS'),\n mime: 'text/x-nsis',\n extensions: ['nsh', 'nsi'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/nsis');\n return legacy(m.nsis);\n }\n },\n {\n name: 'NTriples',\n displayName: trans.__('NTriples'),\n mime: [\n 'application/n-triples',\n 'application/n-quads',\n 'text/n-triples'\n ],\n extensions: ['nt', 'nq'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/ntriples');\n return legacy(m.ntriples);\n }\n },\n {\n name: 'Objective-C',\n displayName: trans.__('Objective-C'),\n alias: ['objective-c', 'objc'],\n mime: 'text/x-objectivec',\n extensions: ['m'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/clike');\n return legacy(m.objectiveC);\n }\n },\n {\n name: 'Objective-C++',\n displayName: trans.__('Objective-C++'),\n alias: ['objective-c++', 'objc++'],\n mime: 'text/x-objectivec++',\n extensions: ['mm'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/clike');\n return legacy(m.objectiveCpp);\n }\n },\n {\n name: 'OCaml',\n displayName: trans.__('OCaml'),\n mime: 'text/x-ocaml',\n extensions: ['ml', 'mli', 'mll', 'mly'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/mllike');\n return legacy(m.oCaml);\n }\n },\n {\n name: 'Octave',\n displayName: trans.__('Octave'),\n mime: 'text/x-octave',\n extensions: ['m'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/octave');\n return legacy(m.octave);\n }\n },\n {\n name: 'Oz',\n displayName: trans.__('Oz'),\n mime: 'text/x-oz',\n extensions: ['oz'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/oz');\n return legacy(m.oz);\n }\n },\n {\n name: 'Pascal',\n displayName: trans.__('Pascal'),\n mime: 'text/x-pascal',\n extensions: ['p', 'pas'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/pascal');\n return legacy(m.pascal);\n }\n },\n {\n name: 'Perl',\n displayName: trans.__('Perl'),\n mime: 'text/x-perl',\n extensions: ['pl', 'pm'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/perl');\n return legacy(m.perl);\n }\n },\n {\n name: 'Pig',\n displayName: trans.__('Pig'),\n mime: 'text/x-pig',\n extensions: ['pig'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/pig');\n return legacy(m.pig);\n }\n },\n {\n name: 'PowerShell',\n displayName: trans.__('PowerShell'),\n mime: 'application/x-powershell',\n extensions: ['ps1', 'psd1', 'psm1'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/powershell');\n return legacy(m.powerShell);\n }\n },\n {\n name: 'Properties files',\n displayName: trans.__('Properties files'),\n alias: ['ini', 'properties'],\n mime: 'text/x-properties',\n extensions: ['properties', 'ini', 'in'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/properties');\n return legacy(m.properties);\n }\n },\n {\n name: 'ProtoBuf',\n displayName: trans.__('ProtoBuf'),\n mime: 'text/x-protobuf',\n extensions: ['proto'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/protobuf');\n return legacy(m.protobuf);\n }\n },\n {\n name: 'Puppet',\n displayName: trans.__('Puppet'),\n mime: 'text/x-puppet',\n extensions: ['pp'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/puppet');\n return legacy(m.puppet);\n }\n },\n {\n name: 'Q',\n displayName: trans.__('Q'),\n mime: 'text/x-q',\n extensions: ['q'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/q');\n return legacy(m.q);\n }\n },\n {\n name: 'R',\n displayName: trans.__('R'),\n alias: ['rscript'],\n mime: 'text/x-rsrc',\n extensions: ['r', 'R'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/r');\n return legacy(m.r);\n }\n },\n {\n name: 'RPM Changes',\n displayName: trans.__('RPM Changes'),\n mime: 'text/x-rpm-changes',\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/rpm');\n return legacy(m.rpmChanges);\n }\n },\n {\n name: 'RPM Spec',\n displayName: trans.__('RPM Spec'),\n mime: 'text/x-rpm-spec',\n extensions: ['spec'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/rpm');\n return legacy(m.rpmSpec);\n }\n },\n {\n name: 'Ruby',\n displayName: trans.__('Ruby'),\n alias: ['jruby', 'macruby', 'rake', 'rb', 'rbx'],\n mime: 'text/x-ruby',\n extensions: ['rb'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/ruby');\n return legacy(m.ruby);\n }\n },\n {\n name: 'SAS',\n displayName: trans.__('SAS'),\n mime: 'text/x-sas',\n extensions: ['sas'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/sas');\n return legacy(m.sas);\n }\n },\n {\n name: 'Scala',\n displayName: trans.__('Scala'),\n mime: 'text/x-scala',\n extensions: ['scala'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/clike');\n return legacy(m.scala);\n }\n },\n {\n name: 'Scheme',\n displayName: trans.__('Scheme'),\n mime: 'text/x-scheme',\n extensions: ['scm', 'ss'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/scheme');\n return legacy(m.scheme);\n }\n },\n {\n name: 'SCSS',\n displayName: trans.__('SCSS'),\n mime: 'text/x-scss',\n extensions: ['scss'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/css');\n return legacy(m.sCSS);\n }\n },\n {\n name: 'Shell',\n displayName: trans.__('Shell'),\n alias: ['bash', 'sh', 'zsh'],\n mime: ['text/x-sh', 'application/x-sh'],\n extensions: ['sh', 'ksh', 'bash'],\n filename: /^PKGBUILD$/,\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/shell');\n return legacy(m.shell);\n }\n },\n {\n name: 'Sieve',\n displayName: trans.__('Sieve'),\n mime: 'application/sieve',\n extensions: ['siv', 'sieve'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/sieve');\n return legacy(m.sieve);\n }\n },\n {\n name: 'Smalltalk',\n displayName: trans.__('Smalltalk'),\n mime: 'text/x-stsrc',\n extensions: ['st'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/smalltalk');\n return legacy(m.smalltalk);\n }\n },\n {\n name: 'Solr',\n displayName: trans.__('Solr'),\n mime: 'text/x-solr',\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/solr');\n return legacy(m.solr);\n }\n },\n {\n name: 'SML',\n displayName: trans.__('SML'),\n mime: 'text/x-sml',\n extensions: ['sml', 'sig', 'fun', 'smackspec'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/mllike');\n return legacy(m.sml);\n }\n },\n {\n name: 'SPARQL',\n displayName: trans.__('SPARQL'),\n alias: ['sparul'],\n mime: 'application/sparql-query',\n extensions: ['rq', 'sparql'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/sparql');\n return legacy(m.sparql);\n }\n },\n {\n name: 'Spreadsheet',\n displayName: trans.__('Spreadsheet'),\n alias: ['excel', 'formula'],\n mime: 'text/x-spreadsheet',\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/spreadsheet');\n return legacy(m.spreadsheet);\n }\n },\n {\n name: 'Squirrel',\n displayName: trans.__('Squirrel'),\n mime: 'text/x-squirrel',\n extensions: ['nut'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/clike');\n return legacy(m.squirrel);\n }\n },\n {\n name: 'Stylus',\n displayName: trans.__('Stylus'),\n mime: 'text/x-styl',\n extensions: ['styl'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/stylus');\n return legacy(m.stylus);\n }\n },\n {\n name: 'Swift',\n displayName: trans.__('Swift'),\n mime: 'text/x-swift',\n extensions: ['swift'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/swift');\n return legacy(m.swift);\n }\n },\n {\n name: 'sTeX',\n displayName: trans.__('sTeX'),\n mime: 'text/x-stex',\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/stex');\n return legacy(m.stex);\n }\n },\n {\n name: 'LaTeX',\n displayName: trans.__('LaTeX'),\n alias: ['tex'],\n mime: 'text/x-latex',\n extensions: ['text', 'ltx', 'tex'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/stex');\n return legacy(m.stex);\n }\n },\n {\n name: 'SystemVerilog',\n displayName: trans.__('SystemVerilog'),\n mime: 'text/x-systemverilog',\n extensions: ['v', 'sv', 'svh'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/verilog');\n return legacy(m.verilog);\n }\n },\n {\n name: 'Tcl',\n displayName: trans.__('Tcl'),\n mime: 'text/x-tcl',\n extensions: ['tcl'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/tcl');\n return legacy(m.tcl);\n }\n },\n {\n name: 'Textile',\n displayName: trans.__('Textile'),\n mime: 'text/x-textile',\n extensions: ['textile'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/textile');\n return legacy(m.textile);\n }\n },\n {\n name: 'TiddlyWiki',\n displayName: trans.__('TiddlyWiki'),\n mime: 'text/x-tiddlywiki',\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/tiddlywiki');\n return legacy(m.tiddlyWiki);\n }\n },\n {\n name: 'Tiki wiki',\n displayName: trans.__('Tiki wiki'),\n mime: 'text/tiki',\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/tiki');\n return legacy(m.tiki);\n }\n },\n {\n name: 'TOML',\n displayName: trans.__('TOML'),\n mime: 'text/x-toml',\n extensions: ['toml'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/toml');\n return legacy(m.toml);\n }\n },\n {\n name: 'troff',\n displayName: trans.__('troff'),\n mime: 'text/troff',\n extensions: ['1', '2', '3', '4', '5', '6', '7', '8', '9'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/troff');\n return legacy(m.troff);\n }\n },\n {\n name: 'TTCN',\n displayName: trans.__('TTCN'),\n mime: 'text/x-ttcn',\n extensions: ['ttcn', 'ttcn3', 'ttcnpp'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/ttcn');\n return legacy(m.ttcn);\n }\n },\n {\n name: 'TTCN_CFG',\n displayName: trans.__('TTCN_CFG'),\n mime: 'text/x-ttcn-cfg',\n extensions: ['cfg'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/ttcn-cfg');\n return legacy(m.ttcnCfg);\n }\n },\n {\n name: 'Turtle',\n displayName: trans.__('Turtle'),\n mime: 'text/turtle',\n extensions: ['ttl'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/turtle');\n return legacy(m.turtle);\n }\n },\n {\n name: 'Web IDL',\n displayName: trans.__('Web IDL'),\n mime: 'text/x-webidl',\n extensions: ['webidl'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/webidl');\n return legacy(m.webIDL);\n }\n },\n {\n name: 'VB.NET',\n displayName: trans.__('VB.NET'),\n mime: 'text/x-vb',\n extensions: ['vb'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/vb');\n return legacy(m.vb);\n }\n },\n {\n name: 'VBScript',\n displayName: trans.__('VBScript'),\n mime: 'text/vbscript',\n extensions: ['vbs'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/vbscript');\n return legacy(m.vbScript);\n }\n },\n {\n name: 'Velocity',\n displayName: trans.__('Velocity'),\n mime: 'text/velocity',\n extensions: ['vtl'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/velocity');\n return legacy(m.velocity);\n }\n },\n {\n name: 'Verilog',\n displayName: trans.__('Verilog'),\n mime: 'text/x-verilog',\n extensions: ['v'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/verilog');\n return legacy(m.verilog);\n }\n },\n {\n name: 'VHDL',\n displayName: trans.__('VHDL'),\n mime: 'text/x-vhdl',\n extensions: ['vhd', 'vhdl'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/vhdl');\n return legacy(m.vhdl);\n }\n },\n {\n name: 'XQuery',\n displayName: trans.__('XQuery'),\n mime: 'application/xquery',\n extensions: ['xy', 'xquery'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/xquery');\n return legacy(m.xQuery);\n }\n },\n {\n name: 'Yacas',\n displayName: trans.__('Yacas'),\n mime: 'text/x-yacas',\n extensions: ['ys'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/yacas');\n return legacy(m.yacas);\n }\n },\n {\n name: 'YAML',\n displayName: trans.__('YAML'),\n alias: ['yml'],\n mime: ['text/x-yaml', 'text/yaml'],\n extensions: ['yaml', 'yml'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/yaml');\n return legacy(m.yaml);\n }\n },\n {\n name: 'Z80',\n displayName: trans.__('Z80'),\n mime: 'text/x-z80',\n extensions: ['z80'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/z80');\n return legacy(m.z80);\n }\n },\n {\n name: 'mscgen',\n displayName: trans.__('mscgen'),\n mime: 'text/x-mscgen',\n extensions: ['mscgen', 'mscin', 'msc'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/mscgen');\n return legacy(m.mscgen);\n }\n },\n {\n name: 'xu',\n displayName: trans.__('xu'),\n mime: 'text/x-xu',\n extensions: ['xu'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/mscgen');\n return legacy(m.xu);\n }\n },\n {\n name: 'msgenny',\n displayName: trans.__('msgenny'),\n mime: 'text/x-msgenny',\n extensions: ['msgenny'],\n async load() {\n const m = await import('@codemirror/legacy-modes/mode/mscgen');\n return legacy(m.msgenny);\n }\n }\n ];\n }\n EditorLanguageRegistry.getDefaultLanguages = getDefaultLanguages;\n})(EditorLanguageRegistry || (EditorLanguageRegistry = {}));\n//# sourceMappingURL=language.js.map","/* eslint-disable @typescript-eslint/ban-types */\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { insertNewlineAndIndent } from '@codemirror/commands';\nimport { ensureSyntaxTree } from '@codemirror/language';\nimport { Compartment, EditorSelection, EditorState, Prec } from '@codemirror/state';\nimport { EditorView } from '@codemirror/view';\nimport { UUID } from '@lumino/coreutils';\nimport { Signal } from '@lumino/signaling';\nimport { ExtensionsHandler } from './extension';\nimport { EditorLanguageRegistry } from './language';\n/**\n * The class name added to CodeMirrorWidget instances.\n */\nconst EDITOR_CLASS = 'jp-CodeMirrorEditor';\n/**\n * The key code for the up arrow key.\n */\nconst UP_ARROW = 38;\n/**\n * The key code for the down arrow key.\n */\nconst DOWN_ARROW = 40;\n/**\n * CodeMirror editor.\n */\nexport class CodeMirrorEditor {\n /**\n * Construct a CodeMirror editor.\n */\n constructor(options) {\n var _a, _b, _c, _d, _e, _f;\n /**\n * A signal emitted when either the top or bottom edge is requested.\n */\n this.edgeRequested = new Signal(this);\n this._isDisposed = false;\n this._language = new Compartment();\n this._uuid = '';\n this._languages = (_a = options.languages) !== null && _a !== void 0 ? _a : new EditorLanguageRegistry();\n this._configurator =\n (_d = (_b = options.extensionsRegistry) === null || _b === void 0 ? void 0 : _b.createNew({\n ...options,\n inline: (_c = options.inline) !== null && _c !== void 0 ? _c : false\n })) !== null && _d !== void 0 ? _d : new ExtensionsHandler();\n const host = (this.host = options.host);\n host.classList.add(EDITOR_CLASS);\n host.classList.add('jp-Editor');\n host.addEventListener('focus', this, true);\n host.addEventListener('blur', this, true);\n host.addEventListener('scroll', this, true);\n this._uuid = (_e = options.uuid) !== null && _e !== void 0 ? _e : UUID.uuid4();\n const model = (this._model = options.model);\n // Default keydown handler - it will have low priority\n const onKeyDown = EditorView.domEventHandlers({\n keydown: (event, view) => {\n return this.onKeydown(event);\n }\n });\n const updateListener = EditorView.updateListener.of((update) => {\n this._onDocChanged(update);\n });\n this._editor = Private.createEditor(host, this._configurator, [\n // We need to set the order to high, otherwise the keybinding for ArrowUp/ArrowDown\n // will process the event shunting our edge detection code.\n Prec.high(onKeyDown),\n updateListener,\n // Initialize with empty extension\n this._language.of([]),\n ...((_f = options.extensions) !== null && _f !== void 0 ? _f : [])\n ], model.sharedModel.source);\n this._onMimeTypeChanged();\n this._onCursorActivity();\n this._configurator.configChanged.connect(this.onConfigChanged, this);\n model.mimeTypeChanged.connect(this._onMimeTypeChanged, this);\n }\n /**\n * The uuid of this editor;\n */\n get uuid() {\n return this._uuid;\n }\n set uuid(value) {\n this._uuid = value;\n }\n /**\n * Get the codemirror editor wrapped by the editor.\n */\n get editor() {\n return this._editor;\n }\n /**\n * Get the codemirror doc wrapped by the widget.\n */\n get doc() {\n return this._editor.state.doc;\n }\n /**\n * Get the number of lines in the editor.\n */\n get lineCount() {\n return this.doc.lines;\n }\n /**\n * Returns a model for this editor.\n */\n get model() {\n return this._model;\n }\n /**\n * The height of a line in the editor in pixels.\n */\n get lineHeight() {\n return this._editor.defaultLineHeight;\n }\n /**\n * The widget of a character in the editor in pixels.\n */\n get charWidth() {\n return this._editor.defaultCharacterWidth;\n }\n /**\n * Tests whether the editor is disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the resources held by the widget.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n this.host.removeEventListener('focus', this, true);\n this.host.removeEventListener('blur', this, true);\n this.host.removeEventListener('scroll', this, true);\n this._configurator.dispose();\n Signal.clearData(this);\n this.editor.destroy();\n }\n /**\n * Get a config option for the editor.\n */\n getOption(option) {\n return this._configurator.getOption(option);\n }\n /**\n * Whether the option exists or not.\n */\n hasOption(option) {\n return this._configurator.hasOption(option);\n }\n /**\n * Set a config option for the editor.\n */\n setOption(option, value) {\n this._configurator.setOption(option, value);\n }\n /**\n * Set config options for the editor.\n *\n * This method is preferred when setting several options. The\n * options are set within an operation, which only performs\n * the costly update at the end, and not after every option\n * is set.\n */\n setOptions(options) {\n this._configurator.setOptions(options);\n }\n /**\n * Inject an extension into the editor\n *\n * @alpha\n * @experimental\n * @param ext CodeMirror 6 extension\n */\n injectExtension(ext) {\n this._configurator.injectExtension(this._editor, ext);\n }\n /**\n * Returns the content for the given line number.\n */\n getLine(line) {\n // TODO: CM6 remove +1 when CM6 first line number has propagated\n line = line + 1;\n return line <= this.doc.lines ? this.doc.line(line).text : undefined;\n }\n /**\n * Find an offset for the given position.\n */\n getOffsetAt(position) {\n // TODO: CM6 remove +1 when CM6 first line number has propagated\n return this.doc.line(position.line + 1).from + position.column;\n }\n /**\n * Find a position for the given offset.\n */\n getPositionAt(offset) {\n // TODO: CM6 remove -1 when CM6 first line number has propagated\n const line = this.doc.lineAt(offset);\n return { line: line.number - 1, column: offset - line.from };\n }\n /**\n * Undo one edit (if any undo events are stored).\n */\n undo() {\n this.model.sharedModel.undo();\n }\n /**\n * Redo one undone edit.\n */\n redo() {\n this.model.sharedModel.redo();\n }\n /**\n * Clear the undo history.\n */\n clearHistory() {\n this.model.sharedModel.clearUndoHistory();\n }\n /**\n * Brings browser focus to this editor text.\n */\n focus() {\n this._editor.focus();\n }\n /**\n * Test whether the editor has keyboard focus.\n */\n hasFocus() {\n return this._editor.hasFocus;\n }\n /**\n * Explicitly blur the editor.\n */\n blur() {\n this._editor.contentDOM.blur();\n }\n get state() {\n return this._editor.state;\n }\n firstLine() {\n // TODO: return 1 when CM6 first line number has propagated\n return 0;\n }\n lastLine() {\n return this.doc.lines - 1;\n }\n cursorCoords(where, mode) {\n const selection = this.state.selection.main;\n const pos = where ? selection.from : selection.to;\n const rect = this.editor.coordsAtPos(pos);\n return rect;\n }\n getRange(from, to, separator) {\n const fromOffset = this.getOffsetAt(this._toPosition(from));\n const toOffset = this.getOffsetAt(this._toPosition(to));\n return this.state.sliceDoc(fromOffset, toOffset);\n }\n /**\n * Reveal the given position in the editor.\n */\n revealPosition(position) {\n const offset = this.getOffsetAt(position);\n this._editor.dispatch({\n effects: EditorView.scrollIntoView(offset)\n });\n }\n /**\n * Reveal the given selection in the editor.\n */\n revealSelection(selection) {\n const start = this.getOffsetAt(selection.start);\n const end = this.getOffsetAt(selection.end);\n this._editor.dispatch({\n effects: EditorView.scrollIntoView(EditorSelection.range(start, end))\n });\n }\n /**\n * Get the window coordinates given a cursor position.\n */\n getCoordinateForPosition(position) {\n const offset = this.getOffsetAt(position);\n const rect = this.editor.coordsAtPos(offset);\n return rect;\n }\n /**\n * Get the cursor position given window coordinates.\n *\n * @param coordinate - The desired coordinate.\n *\n * @returns The position of the coordinates, or null if not\n * contained in the editor.\n */\n getPositionForCoordinate(coordinate) {\n const offset = this.editor.posAtCoords({\n x: coordinate.left,\n y: coordinate.top\n });\n return this.getPositionAt(offset) || null;\n }\n /**\n * Returns the primary position of the cursor, never `null`.\n */\n getCursorPosition() {\n const offset = this.state.selection.main.head;\n return this.getPositionAt(offset);\n }\n /**\n * Set the primary position of the cursor.\n *\n * #### Notes\n * This will remove any secondary cursors.\n */\n setCursorPosition(position, options) {\n const offset = this.getOffsetAt(position);\n this.editor.dispatch({\n selection: { anchor: offset },\n scrollIntoView: true\n });\n // If the editor does not have focus, this cursor change\n // will get screened out in _onCursorsChanged(). Make an\n // exception for this method.\n if (!this.editor.hasFocus) {\n this.model.selections.set(this.uuid, this.getSelections());\n }\n }\n /**\n * Returns the primary selection, never `null`.\n */\n getSelection() {\n return this.getSelections()[0];\n }\n /**\n * Set the primary selection. This will remove any secondary cursors.\n */\n setSelection(selection) {\n this.setSelections([selection]);\n }\n /**\n * Gets the selections for all the cursors, never `null` or empty.\n */\n getSelections() {\n const selections = this.state.selection.ranges; //= [{anchor: number, head: number}]\n if (selections.length > 0) {\n const sel = selections.map(r => ({\n anchor: this._toCodeMirrorPosition(this.getPositionAt(r.from)),\n head: this._toCodeMirrorPosition(this.getPositionAt(r.to))\n }));\n return sel.map(selection => this._toSelection(selection));\n }\n const cursor = this._toCodeMirrorPosition(this.getPositionAt(this.state.selection.main.head));\n const selection = this._toSelection({ anchor: cursor, head: cursor });\n return [selection];\n }\n /**\n * Sets the selections for all the cursors, should not be empty.\n * Cursors will be removed or added, as necessary.\n * Passing an empty array resets a cursor position to the start of a document.\n */\n setSelections(selections) {\n const sel = selections.length\n ? selections.map(r => EditorSelection.range(this.getOffsetAt(r.start), this.getOffsetAt(r.end)))\n : [EditorSelection.range(0, 0)];\n this.editor.dispatch({ selection: EditorSelection.create(sel) });\n }\n /**\n * Replaces the current selection with the given text.\n *\n * Behaviour for multiple selections is undefined.\n *\n * @param text The text to be inserted.\n */\n replaceSelection(text) {\n const firstSelection = this.getSelections()[0];\n this.model.sharedModel.updateSource(this.getOffsetAt(firstSelection.start), this.getOffsetAt(firstSelection.end), text);\n const newPosition = this.getPositionAt(this.getOffsetAt(firstSelection.start) + text.length);\n this.setSelection({ start: newPosition, end: newPosition });\n }\n /**\n * Get a list of tokens for the current editor text content.\n */\n getTokens() {\n const tokens = [];\n const tree = ensureSyntaxTree(this.state, this.doc.length);\n if (tree) {\n tree.iterate({\n enter: (ref) => {\n if (ref.node.firstChild === null) {\n tokens.push({\n value: this.state.sliceDoc(ref.from, ref.to),\n offset: ref.from,\n type: ref.name\n });\n }\n return true;\n }\n });\n }\n return tokens;\n }\n /**\n * Get the token at a given editor position.\n */\n getTokenAt(offset) {\n const tree = ensureSyntaxTree(this.state, offset);\n let token = null;\n if (tree) {\n tree.iterate({\n enter: (ref) => {\n // If a token has already been discovered, stop iterating.\n if (token) {\n return false;\n }\n // If it is not a leaf, keep iterating.\n if (ref.node.firstChild) {\n return true;\n }\n // If the relevant leaf token has been found, stop iterating.\n if (offset >= ref.from && offset <= ref.to) {\n token = {\n value: this.state.sliceDoc(ref.from, ref.to),\n offset: ref.from,\n type: ref.name\n };\n return false;\n }\n return true;\n }\n });\n }\n return token || { offset, value: '' };\n }\n /**\n * Get the token a the cursor position.\n */\n getTokenAtCursor() {\n return this.getTokenAt(this.state.selection.main.head);\n }\n /**\n * Insert a new indented line at the current cursor position.\n */\n newIndentedLine() {\n insertNewlineAndIndent({\n state: this.state,\n dispatch: this.editor.dispatch\n });\n }\n /**\n * Execute a codemirror command on the editor.\n *\n * @param command - The name of the command to execute.\n */\n execCommand(command) {\n command(this.editor);\n }\n onConfigChanged(configurator, changes) {\n configurator.reconfigureExtensions(this._editor, changes);\n }\n /**\n * Handle keydown events from the editor.\n */\n onKeydown(event) {\n const position = this.state.selection.main.head;\n if (position === 0 && event.keyCode === UP_ARROW) {\n if (!event.shiftKey) {\n this.edgeRequested.emit('top');\n }\n return false;\n }\n const line = this.doc.lineAt(position).number;\n if (line === 1 && event.keyCode === UP_ARROW) {\n if (!event.shiftKey) {\n this.edgeRequested.emit('topLine');\n }\n return false;\n }\n const length = this.doc.length;\n if (position === length && event.keyCode === DOWN_ARROW) {\n if (!event.shiftKey) {\n this.edgeRequested.emit('bottom');\n }\n return false;\n }\n return false;\n }\n /**\n * Handles a mime type change.\n */\n _onMimeTypeChanged() {\n // TODO: should we provide a hook for when the mode is done being set?\n this._languages\n .getLanguage(this._model.mimeType)\n .then(language => {\n var _a;\n this._editor.dispatch({\n effects: this._language.reconfigure((_a = language === null || language === void 0 ? void 0 : language.support) !== null && _a !== void 0 ? _a : [])\n });\n })\n .catch(reason => {\n console.log(`Failed to load language for '${this._model.mimeType}'.`, reason);\n this._editor.dispatch({\n effects: this._language.reconfigure([])\n });\n });\n }\n /**\n * Handles a cursor activity event.\n */\n _onCursorActivity() {\n // Only add selections if the editor has focus. This avoids unwanted\n // triggering of cursor activity due to collaborator actions.\n if (this._editor.hasFocus) {\n const selections = this.getSelections();\n this.model.selections.set(this.uuid, selections);\n }\n }\n /**\n * Converts a code mirror selection to an editor selection.\n */\n _toSelection(selection) {\n return {\n uuid: this.uuid,\n start: this._toPosition(selection.anchor),\n end: this._toPosition(selection.head)\n };\n }\n /**\n * Convert a code mirror position to an editor position.\n */\n _toPosition(position) {\n return {\n line: position.line,\n column: position.ch\n };\n }\n /**\n * Convert an editor position to a code mirror position.\n */\n _toCodeMirrorPosition(position) {\n return {\n line: position.line,\n ch: position.column\n };\n }\n /**\n * Handles document changes.\n */\n _onDocChanged(update) {\n if (update.transactions.length && update.transactions[0].selection) {\n this._onCursorActivity();\n }\n }\n /**\n * Handle the DOM events for the editor.\n *\n * @param event - The DOM event sent to the editor.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the editor's DOM node. It should\n * not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'focus':\n this._evtFocus(event);\n break;\n case 'blur':\n this._evtBlur(event);\n break;\n default:\n break;\n }\n }\n /**\n * Handle `focus` events for the editor.\n */\n _evtFocus(event) {\n this.host.classList.add('jp-mod-focused');\n // Update the selections on editor gaining focus because\n // the onCursorActivity function filters usual cursor events\n // based on the editor's focus.\n this._onCursorActivity();\n }\n /**\n * Handle `blur` events for the editor.\n */\n _evtBlur(event) {\n this.host.classList.remove('jp-mod-focused');\n }\n}\n/**\n * The namespace for module private data.\n */\nvar Private;\n(function (Private) {\n function createEditor(host, editorConfig, additionalExtensions, doc) {\n const extensions = editorConfig.getInitialExtensions();\n extensions.push(...additionalExtensions);\n const view = new EditorView({\n state: EditorState.create({\n doc,\n extensions\n }),\n parent: host\n });\n return view;\n }\n Private.createEditor = createEditor;\n})(Private || (Private = {}));\n//# sourceMappingURL=editor.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { EditorSelection, StateEffect, StateField } from '@codemirror/state';\nimport { Decoration, EditorView } from '@codemirror/view';\nimport { GenericSearchProvider, TextSearchEngine } from '@jupyterlab/documentsearch';\nimport { Signal } from '@lumino/signaling';\n/**\n * Search provider for editors.\n */\nexport class EditorSearchProvider {\n /**\n * Constructor\n */\n constructor() {\n /**\n * Current match index\n */\n this.currentIndex = null;\n /**\n * Current search query\n */\n this.query = null;\n this._isActive = true;\n this._inSelection = null;\n this._isDisposed = false;\n this._cmHandler = null;\n this.currentIndex = null;\n this._stateChanged = new Signal(this);\n }\n /**\n * CodeMirror search highlighter\n */\n get cmHandler() {\n if (!this._cmHandler) {\n this._cmHandler = new CodeMirrorSearchHighlighter(this.editor);\n }\n return this._cmHandler;\n }\n /**\n * Changed signal to be emitted when search matches change.\n */\n get stateChanged() {\n return this._stateChanged;\n }\n /**\n * Current match index\n */\n get currentMatchIndex() {\n return this.isActive ? this.currentIndex : null;\n }\n /**\n * Whether the cell search is active.\n *\n * This is used when applying search only on selected cells.\n */\n get isActive() {\n return this._isActive;\n }\n /**\n * Whether the search provider is disposed or not.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Number of matches in the cell.\n */\n get matchesCount() {\n return this.isActive ? this.cmHandler.matches.length : 0;\n }\n /**\n * Clear currently highlighted match\n */\n clearHighlight() {\n this.currentIndex = null;\n this.cmHandler.clearHighlight();\n return Promise.resolve();\n }\n /**\n * Dispose the search provider\n */\n dispose() {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n Signal.clearData(this);\n if (this.isActive) {\n this.endQuery().catch(reason => {\n console.error(`Failed to end search query on cells.`, reason);\n });\n }\n }\n /**\n * Set `isActive` status.\n *\n * #### Notes\n * It will start or end the search\n *\n * @param v New value\n */\n async setIsActive(v) {\n if (this._isActive === v) {\n return;\n }\n this._isActive = v;\n if (this._isActive) {\n if (this.query !== null) {\n await this.startQuery(this.query, this.filters);\n }\n }\n else {\n await this.endQuery();\n }\n }\n /**\n * Set whether search should be limitted to specified text selection.\n */\n async setSearchSelection(selection) {\n if (this._inSelection === selection) {\n return;\n }\n this._inSelection = selection;\n await this.updateCodeMirror(this.model.sharedModel.getSource());\n this._stateChanged.emit();\n }\n /**\n * Set whether user selection should be protected from modifications.\n *\n * If disabled, the selection will be updated on search and on editor focus\n * to cover the current match. We need to protect selection from modifications\n * for both: search in text and search in cells; since `setSearchSelection`\n * is only telling us about search in text, we need to have an additional\n * way to signal that either search in text or in cells is active, or for\n * any other reason selection range should be protected.\n */\n setProtectSelection(v) {\n this.cmHandler.protectSelection = v;\n }\n /**\n * Initialize the search using the provided options. Should update the UI\n * to highlight all matches and \"select\" the first match.\n *\n * @param query A RegExp to be use to perform the search\n * @param filters Filter parameters to pass to provider\n */\n async startQuery(query, filters) {\n this.query = query;\n this.filters = filters;\n // Search input\n const content = this.model.sharedModel.getSource();\n await this.updateCodeMirror(content);\n this.model.sharedModel.changed.connect(this.onSharedModelChanged, this);\n }\n /**\n * Stop the search and clean any UI elements.\n */\n async endQuery() {\n await this.clearHighlight();\n await this.cmHandler.endQuery();\n this.currentIndex = null;\n }\n /**\n * Highlight the next match.\n *\n * @returns The next match if there is one.\n */\n async highlightNext(loop = true, options) {\n if (this.matchesCount === 0 || !this.isActive) {\n this.currentIndex = null;\n }\n else {\n let match = await this.cmHandler.highlightNext(options);\n if (match) {\n this.currentIndex = this.cmHandler.currentIndex;\n }\n else {\n // Note: the loop logic is only used in single-editor (e.g. file editor)\n // provider sub-classes, notebook has it's own loop logic and ignores\n // `currentIndex` as set here.\n this.currentIndex = loop ? 0 : null;\n }\n return match;\n }\n return Promise.resolve(this.getCurrentMatch());\n }\n /**\n * Highlight the previous match.\n *\n * @returns The previous match if there is one.\n */\n async highlightPrevious(loop = true, options) {\n if (this.matchesCount === 0 || !this.isActive) {\n this.currentIndex = null;\n }\n else {\n let match = await this.cmHandler.highlightPrevious(options);\n if (match) {\n this.currentIndex = this.cmHandler.currentIndex;\n }\n else {\n this.currentIndex = loop ? this.matchesCount - 1 : null;\n }\n return match;\n }\n return Promise.resolve(this.getCurrentMatch());\n }\n /**\n * Replace the currently selected match with the provided text.\n *\n * If no match is selected, it won't do anything.\n *\n * The caller of this method is expected to call `highlightNext` if after\n * calling `replaceCurrentMatch()` attribute `this.currentIndex` is null.\n * It is necesary to let the caller handle highlighting because this\n * method is used in composition pattern (search engine of notebook cells)\n * and highligthing on the composer (notebook) level needs to switch to next\n * engine (cell) with matches.\n *\n * @param newText The replacement text.\n * @returns Whether a replace occurred.\n */\n replaceCurrentMatch(newText, loop, options) {\n if (!this.isActive) {\n return Promise.resolve(false);\n }\n let occurred = false;\n if (this.currentIndex !== null &&\n this.currentIndex < this.cmHandler.matches.length) {\n const match = this.getCurrentMatch();\n // If cursor there is no match selected, highlight the next match\n if (!match) {\n this.currentIndex = null;\n }\n else {\n this.cmHandler.matches.splice(this.currentIndex, 1);\n this.currentIndex =\n this.currentIndex < this.cmHandler.matches.length\n ? Math.max(this.currentIndex - 1, 0)\n : null;\n const substitutedText = (options === null || options === void 0 ? void 0 : options.regularExpression)\n ? match.text.replace(this.query, newText)\n : newText;\n const insertText = (options === null || options === void 0 ? void 0 : options.preserveCase)\n ? GenericSearchProvider.preserveCase(match.text, substitutedText)\n : substitutedText;\n this.model.sharedModel.updateSource(match.position, match.position + match.text.length, insertText);\n occurred = true;\n }\n }\n return Promise.resolve(occurred);\n }\n /**\n * Replace all matches in the cell source with the provided text\n *\n * @param newText The replacement text.\n * @returns Whether a replace occurred.\n */\n replaceAllMatches(newText, options) {\n if (!this.isActive) {\n return Promise.resolve(false);\n }\n let occurred = this.cmHandler.matches.length > 0;\n let src = this.model.sharedModel.getSource();\n let lastEnd = 0;\n const finalSrc = this.cmHandler.matches.reduce((agg, match) => {\n const start = match.position;\n const end = start + match.text.length;\n const substitutedText = (options === null || options === void 0 ? void 0 : options.regularExpression)\n ? match.text.replace(this.query, newText)\n : newText;\n const insertText = (options === null || options === void 0 ? void 0 : options.preserveCase)\n ? GenericSearchProvider.preserveCase(match.text, substitutedText)\n : substitutedText;\n const newStep = `${agg}${src.slice(lastEnd, start)}${insertText}`;\n lastEnd = end;\n return newStep;\n }, '');\n if (occurred) {\n this.cmHandler.matches = [];\n this.currentIndex = null;\n this.model.sharedModel.setSource(`${finalSrc}${src.slice(lastEnd)}`);\n }\n return Promise.resolve(occurred);\n }\n /**\n * Get the current match if it exists.\n *\n * @returns The current match\n */\n getCurrentMatch() {\n if (this.currentIndex === null) {\n return undefined;\n }\n else {\n let match = undefined;\n if (this.currentIndex < this.cmHandler.matches.length) {\n match = this.cmHandler.matches[this.currentIndex];\n }\n return match;\n }\n }\n /**\n * Callback on source change\n *\n * @param emitter Source of the change\n * @param changes Source change\n */\n async onSharedModelChanged(emitter, changes) {\n if (changes.sourceChange) {\n await this.updateCodeMirror(emitter.getSource());\n this._stateChanged.emit();\n }\n }\n /**\n * Update matches\n */\n async updateCodeMirror(content) {\n if (this.query !== null && this.isActive) {\n const allMatches = await TextSearchEngine.search(this.query, content);\n if (this._inSelection) {\n const editor = this.editor;\n const start = editor.getOffsetAt(this._inSelection.start);\n const end = editor.getOffsetAt(this._inSelection.end);\n this.cmHandler.matches = allMatches.filter(match => match.position >= start && match.position <= end);\n // A special case to always have a current match when in line selection mode.\n if (this.cmHandler.currentIndex === null &&\n this.cmHandler.matches.length > 0) {\n await this.cmHandler.highlightNext({\n from: 'selection',\n select: false,\n scroll: false\n });\n }\n this.currentIndex = this.cmHandler.currentIndex;\n }\n else {\n this.cmHandler.matches = allMatches;\n }\n }\n else {\n this.cmHandler.matches = [];\n }\n }\n}\n/**\n * Helper class to highlight texts in a code mirror editor.\n *\n * Highlighted texts (aka `matches`) must be provided through\n * the `matches` attributes.\n *\n * **NOTES:**\n * - to retain the selection visibility `drawSelection` extension is needed.\n * - highlighting starts from the cursor (if editor is focused and `from` is set\n * to `'auto'`, cursor moved, or `from` argument is set to `'selection'` or\n * `'selection-start'`), or from last \"current\" match otherwise.\n * - `currentIndex` is the (readonly) source of truth for the current match.\n */\nexport class CodeMirrorSearchHighlighter {\n /**\n * Constructor\n *\n * @param editor The CodeMirror editor\n */\n constructor(editor) {\n this._current = null;\n this._cm = editor;\n this._matches = new Array();\n this._currentIndex = null;\n this._highlightEffect = StateEffect.define({\n map: (value, mapping) => {\n const transform = (v) => ({\n text: v.text,\n position: mapping.mapPos(v.position)\n });\n return {\n matches: value.matches.map(transform),\n currentMatch: value.currentMatch\n ? transform(value.currentMatch)\n : null\n };\n }\n });\n this._highlightMark = Decoration.mark({ class: 'cm-searching' });\n this._currentMark = Decoration.mark({ class: 'jp-current-match' });\n this._highlightField = StateField.define({\n create: () => {\n return Decoration.none;\n },\n update: (highlights, transaction) => {\n highlights = highlights.map(transaction.changes);\n for (let ef of transaction.effects) {\n if (ef.is(this._highlightEffect)) {\n const e = ef;\n if (e.value.matches.length) {\n // Note: nesting will vary; sometimes `.cm-searching` will be\n // inside `.jp-current-match`, sometime the other way round.\n highlights = highlights.update({\n add: e.value.matches.map(m => this._highlightMark.range(m.position, m.position + m.text.length)),\n // filter out old marks\n filter: () => false\n });\n highlights = highlights.update({\n add: e.value.currentMatch\n ? [\n this._currentMark.range(e.value.currentMatch.position, e.value.currentMatch.position +\n e.value.currentMatch.text.length)\n ]\n : []\n });\n }\n else {\n highlights = Decoration.none;\n }\n }\n }\n return highlights;\n },\n provide: f => EditorView.decorations.from(f)\n });\n this._domEventHandlers = EditorView.domEventHandlers({\n focus: () => {\n // Set cursor on active match when editor gets focused.\n this._selectCurrentMatch();\n }\n });\n }\n /**\n * The current index of the selected match.\n */\n get currentIndex() {\n return this._currentIndex;\n }\n /**\n * The list of matches\n */\n get matches() {\n return this._matches;\n }\n set matches(v) {\n this._matches = v;\n if (this._currentIndex !== null &&\n this._currentIndex > this._matches.length) {\n this._currentIndex = this._matches.length > 0 ? 0 : null;\n }\n this._highlightCurrentMatch({ select: false });\n }\n /**\n * Whether the cursor/selection should not be modified.\n */\n get protectSelection() {\n return this._protectSelection;\n }\n set protectSelection(v) {\n this._protectSelection = v;\n }\n /**\n * Clear all highlighted matches\n */\n clearHighlight() {\n this._currentIndex = null;\n this._highlightCurrentMatch();\n }\n /**\n * Clear the highlighted matches.\n */\n endQuery() {\n this._currentIndex = null;\n this._matches = [];\n if (this._cm) {\n this._cm.editor.dispatch({\n effects: this._highlightEffect.of({ matches: [], currentMatch: null })\n });\n }\n return Promise.resolve();\n }\n /**\n * Highlight the next match\n *\n * @returns The next match if available\n */\n highlightNext(options) {\n var _a;\n this._currentIndex = this._findNext(false, (_a = options === null || options === void 0 ? void 0 : options.from) !== null && _a !== void 0 ? _a : 'auto');\n this._highlightCurrentMatch(options);\n return Promise.resolve(this._currentIndex !== null\n ? this._matches[this._currentIndex]\n : undefined);\n }\n /**\n * Highlight the previous match\n *\n * @returns The previous match if available\n */\n highlightPrevious(options) {\n var _a;\n this._currentIndex = this._findNext(true, (_a = options === null || options === void 0 ? void 0 : options.from) !== null && _a !== void 0 ? _a : 'auto');\n this._highlightCurrentMatch(options);\n return Promise.resolve(this._currentIndex !== null\n ? this._matches[this._currentIndex]\n : undefined);\n }\n /**\n * Set the editor\n *\n * @param editor Editor\n */\n setEditor(editor) {\n if (this._cm) {\n throw new Error('CodeMirrorEditor already set.');\n }\n else {\n this._cm = editor;\n if (this._currentIndex !== null) {\n this._highlightCurrentMatch();\n }\n this._cm.editor.dispatch({\n effects: StateEffect.appendConfig.of(this._domEventHandlers)\n });\n this._refresh();\n }\n }\n _selectCurrentMatch(scroll = true) {\n // This method has two responsibilities:\n // 1) Scroll the current match into the view - useful for long lines,\n // and file editors with more lines that fit on the screen\n // 2) When user has focus on the editor (not search box) and presses\n // ctrl + g/ctrl + shift + g to jump to next match they want their\n // cursor to jump too.\n // We execute (1) and (2) together as CodeMirror has a special code path\n // to handle both in a single dispatch.\n // The (2) case is inapplicable to search in selection mode, as it would\n // invalidate the query selection, so in that case we only execute (1).\n const match = this._current;\n if (!match) {\n return;\n }\n if (!this._cm) {\n return;\n }\n const cursor = {\n anchor: match.position,\n head: match.position + match.text.length\n };\n const selection = this._cm.editor.state.selection.main;\n if ((selection.from === match.position &&\n selection.to === match.position + match.text.length) ||\n this._protectSelection) {\n // Correct selection is already set or search is restricted to selection:\n // scroll without changing the selection.\n if (scroll) {\n this._cm.editor.dispatch({\n effects: EditorView.scrollIntoView(EditorSelection.range(cursor.anchor, cursor.head))\n });\n return;\n }\n }\n else {\n this._cm.editor.dispatch({\n selection: cursor,\n scrollIntoView: scroll\n });\n }\n }\n _highlightCurrentMatch(options) {\n var _a, _b, _c;\n if (!this._cm) {\n // no-op\n return;\n }\n // Highlight the current index\n if (this._currentIndex !== null) {\n const match = this.matches[this._currentIndex];\n this._current = match;\n // We do not change selection nor scroll if:\n // - user is selecting text,\n // - document was modified\n if ((_a = options === null || options === void 0 ? void 0 : options.select) !== null && _a !== void 0 ? _a : true) {\n if (this._cm.hasFocus()) {\n // If editor is focused we actually set the cursor on the match.\n this._selectCurrentMatch((_b = options === null || options === void 0 ? void 0 : options.scroll) !== null && _b !== void 0 ? _b : true);\n }\n else if ((_c = options === null || options === void 0 ? void 0 : options.scroll) !== null && _c !== void 0 ? _c : true) {\n // otherwise we just scroll to preserve the selection.\n this._cm.editor.dispatch({\n effects: EditorView.scrollIntoView(match.position)\n });\n }\n }\n }\n else {\n this._current = null;\n }\n this._refresh();\n }\n _refresh() {\n if (!this._cm) {\n // no-op\n return;\n }\n let effects = [\n this._highlightEffect.of({\n matches: this.matches,\n currentMatch: this._current\n })\n ];\n if (!this._cm.state.field(this._highlightField, false)) {\n effects.push(StateEffect.appendConfig.of([this._highlightField]));\n }\n this._cm.editor.dispatch({ effects });\n }\n _findNext(reverse, from = 'auto') {\n if (this._matches.length === 0) {\n // No-op\n return null;\n }\n let lastPosition = 0;\n if ((from === 'auto' && this._cm.hasFocus()) || from === 'selection') {\n const cursor = this._cm.state.selection.main;\n lastPosition = reverse ? cursor.anchor : cursor.head;\n }\n else if (from === 'selection-start') {\n const cursor = this._cm.state.selection.main;\n lastPosition = Math.min(cursor.anchor, cursor.head);\n }\n else if (from === 'start') {\n lastPosition = 0;\n }\n else if (this._current) {\n lastPosition = reverse\n ? this._current.position\n : this._current.position + this._current.text.length;\n }\n if (lastPosition === 0 && reverse && this.currentIndex === null) {\n // The default position is (0, 0) but we want to start from the end in that case\n lastPosition = this._cm.doc.length;\n }\n const position = lastPosition;\n let found = Utils.findNext(this._matches, position, 0, this._matches.length - 1);\n if (found === null) {\n // Don't loop\n return reverse ? this._matches.length - 1 : null;\n }\n if (reverse) {\n found -= 1;\n if (found < 0) {\n // Don't loop\n return null;\n }\n }\n return found;\n }\n}\n/**\n * Helpers namespace\n */\nvar Utils;\n(function (Utils) {\n /**\n * Find the closest match at `position` just after it.\n *\n * #### Notes\n * Search is done using a binary search algorithm\n *\n * @param matches List of matches\n * @param position Searched position\n * @param lowerBound Lower range index\n * @param higherBound High range index\n * @returns The next match or null if none exists\n */\n function findNext(matches, position, lowerBound = 0, higherBound = Infinity) {\n higherBound = Math.min(matches.length - 1, higherBound);\n while (lowerBound <= higherBound) {\n let middle = Math.floor(0.5 * (lowerBound + higherBound));\n const currentPosition = matches[middle].position;\n if (currentPosition < position) {\n lowerBound = middle + 1;\n if (lowerBound < matches.length &&\n matches[lowerBound].position > position) {\n return lowerBound;\n }\n }\n else if (currentPosition > position) {\n higherBound = middle - 1;\n if (higherBound > 0 && matches[higherBound].position < position) {\n return middle;\n }\n }\n else {\n return middle;\n }\n }\n // Next could be the first item\n const first = lowerBound > 0 ? lowerBound - 1 : 0;\n const match = matches[first];\n return match.position >= position ? first : null;\n }\n Utils.findNext = findNext;\n})(Utils || (Utils = {}));\n//# sourceMappingURL=searchprovider.js.map","/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\nimport { Token } from '@lumino/coreutils';\n/**\n * Editor language token.\n */\nexport const IEditorExtensionRegistry = new Token('@jupyterlab/codemirror:IEditorExtensionRegistry', `A registry for CodeMirror extension factories.`);\n/**\n * Editor language token.\n */\nexport const IEditorLanguageRegistry = new Token('@jupyterlab/codemirror:IEditorLanguageRegistry', 'A registry for CodeMirror languages.');\n/**\n * Editor theme token.\n */\nexport const IEditorThemeRegistry = new Token('@jupyterlab/codemirror:IEditorThemeRegistry', 'A registry for CodeMirror theme.');\n//# sourceMappingURL=token.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { style as typestyleClass } from 'typestyle/lib';\nexport var LabIconStyle;\n(function (LabIconStyle) {\n /**\n * The builtin stylesheets\n */\n const builtinSheets = {\n breadCrumb: {\n container: {\n $nest: {\n // `&` will be substituted for the generated classname (interpolation)\n '&:first-child svg': {\n bottom: '1px',\n marginLeft: '0px',\n position: 'relative'\n },\n '&:hover': {\n backgroundColor: 'var(--jp-layout-color2)'\n },\n ['.jp-mod-dropTarget&']: {\n backgroundColor: 'var(--jp-brand-color2)',\n opacity: 0.7\n }\n }\n },\n element: {\n borderRadius: 'var(--jp-border-radius)',\n cursor: 'pointer',\n margin: '0px 2px',\n padding: '0px 2px',\n height: '16px',\n width: '16px',\n verticalAlign: 'middle'\n }\n },\n commandPaletteHeader: {\n container: {\n height: '14px',\n margin: '0 14px 0 auto'\n },\n element: {\n height: '14px',\n width: '14px'\n },\n options: {\n elementPosition: 'center'\n }\n },\n commandPaletteItem: {\n element: {\n height: '16px',\n width: '16px'\n },\n options: {\n elementPosition: 'center'\n }\n },\n launcherCard: {\n container: {\n height: '52px',\n width: '52px'\n },\n element: {\n height: '52px',\n width: '52px'\n },\n options: {\n elementPosition: 'center'\n }\n },\n launcherSection: {\n container: {\n boxSizing: 'border-box',\n marginRight: '12px',\n height: '32px',\n width: '32px'\n },\n element: {\n height: '32px',\n width: '32px'\n },\n options: {\n elementPosition: 'center'\n }\n },\n listing: {\n container: {\n flex: '0 0 20px',\n marginRight: '4px',\n position: 'relative'\n },\n element: {\n height: '16px',\n width: '16px'\n },\n options: {\n elementPosition: 'center'\n }\n },\n listingHeaderItem: {\n container: {\n display: 'inline',\n height: '16px',\n width: '16px'\n },\n element: {\n height: 'auto',\n margin: '-2px 0 0 0',\n width: '20px'\n },\n options: {\n elementPosition: 'center'\n }\n },\n mainAreaTab: {\n container: {\n $nest: {\n '.lm-DockPanel-tabBar &': {\n marginRight: '4px'\n }\n }\n },\n element: {\n $nest: {\n '.lm-DockPanel-tabBar &': {\n height: '14px',\n width: '14px'\n }\n }\n },\n options: {\n elementPosition: 'center'\n }\n },\n menuItem: {\n container: {\n display: 'inline-block',\n verticalAlign: 'middle'\n },\n element: {\n height: '16px',\n width: '16px'\n },\n options: {\n elementPosition: 'center'\n }\n },\n runningItem: {\n container: {\n margin: '0px 4px 0px 4px'\n },\n element: {\n height: '16px',\n width: '16px'\n },\n options: {\n elementPosition: 'center'\n }\n },\n select: {\n container: {\n pointerEvents: 'none'\n },\n element: {\n position: 'absolute',\n height: 'auto',\n width: '16px'\n }\n },\n settingsEditor: {\n container: {\n display: 'flex',\n flex: '0 0 20px',\n margin: '0 3px 0 0',\n position: 'relative',\n height: '20px',\n width: '20px'\n },\n element: {\n height: '16px',\n width: '16px'\n },\n options: {\n elementPosition: 'center'\n }\n },\n sideBar: {\n element: {\n height: 'auto',\n width: '20px'\n },\n options: {\n elementPosition: 'center'\n }\n },\n splash: {\n container: {\n animation: '0.3s fade-in linear forwards',\n height: '100%',\n width: '100%',\n zIndex: 1\n },\n element: {\n // width no height\n width: '100px'\n },\n options: {\n elementPosition: 'center'\n }\n },\n statusBar: {\n element: {\n left: '0px',\n top: '0px',\n height: '18px',\n width: '20px',\n position: 'relative'\n }\n },\n toolbarButton: {\n container: {\n display: 'inline-block',\n verticalAlign: 'middle'\n },\n element: {\n height: '16px',\n width: '16px'\n },\n options: {\n elementPosition: 'center'\n }\n }\n };\n function _elementPositionFactory(extra) {\n return {\n container: {\n alignItems: 'center',\n display: 'flex'\n },\n element: {\n display: 'block',\n ...extra\n }\n };\n }\n /**\n * Styles to help with positioning\n */\n const positionSheets = {\n center: _elementPositionFactory({ margin: '0 auto', width: '100%' }),\n top: _elementPositionFactory({ margin: '0 0 auto 0' }),\n right: _elementPositionFactory({ margin: '0 0 0 auto' }),\n bottom: _elementPositionFactory({ margin: 'auto 0 0 0' }),\n left: _elementPositionFactory({ margin: '0 auto 0 0' }),\n 'top right': _elementPositionFactory({ margin: '0 0 auto auto' }),\n 'bottom right': _elementPositionFactory({ margin: 'auto 0 0 auto' }),\n 'bottom left': _elementPositionFactory({ margin: 'auto auto 0 0' }),\n 'top left': _elementPositionFactory({ margin: '0 auto 0 auto' })\n };\n function _elementSizeFactory(size) {\n return {\n element: {\n height: size,\n width: size\n }\n };\n }\n /**\n * sheets that establish some default sizes\n */\n const sizeSheets = {\n small: _elementSizeFactory('14px'),\n normal: _elementSizeFactory('16px'),\n large: _elementSizeFactory('20px'),\n xlarge: _elementSizeFactory('24px')\n };\n /**\n * Merge two or more icon sheets into a single \"pure\"\n * icon style (ie collections of CSS props only)\n */\n function mergeSheets(sheets) {\n return {\n container: Object.assign({}, ...sheets.map(s => s.container)),\n element: Object.assign({}, ...sheets.map(s => s.element))\n };\n }\n /**\n * Resolve one or more stylesheets that may just be a string naming\n * one of the builtin stylesheets to an array of proper ISheet objects\n */\n function resolveSheet(stylesheet) {\n if (!stylesheet) {\n return [];\n }\n if (!Array.isArray(stylesheet)) {\n // wrap in array\n stylesheet = [stylesheet];\n }\n return stylesheet.map(k => (typeof k === 'string' ? builtinSheets[k] : k));\n }\n /**\n * Resolve and merge multiple icon stylesheets\n */\n function applySheetOptions(sheets) {\n const options = Object.assign({}, ...sheets.map(s => s.options));\n if (options.elementPosition) {\n sheets.unshift(positionSheets[options.elementPosition]);\n }\n if (options.elementSize) {\n sheets.unshift(sizeSheets[options.elementSize]);\n }\n return mergeSheets(sheets);\n }\n /**\n * Resolve a pure icon stylesheet into a typestyle class\n */\n function resolveStyleClass(stylesheet) {\n var _a;\n return typestyleClass({\n ...stylesheet.container,\n $nest: {\n ...(_a = stylesheet.container) === null || _a === void 0 ? void 0 : _a.$nest,\n ['svg']: stylesheet.element\n }\n });\n }\n // cache style classes for builtin stylesheets\n const _styleClassCache = new Map();\n /**\n * Get a typestyle class, given a set of icon styling props\n */\n function styleClass(props) {\n if (!props || Object.keys(props).length === 0) {\n // props is empty\n return '';\n }\n let { elementPosition, elementSize, stylesheet, ...elementCSS } = props;\n // add option args with defined values to overrides\n const options = {\n ...(elementPosition && { elementPosition }),\n ...(elementSize && { elementSize })\n };\n // try to look up the style class in the cache\n const cacheable = typeof stylesheet === 'string' && Object.keys(elementCSS).length === 0;\n const cacheKey = cacheable\n ? [stylesheet, elementPosition, elementSize].join(',')\n : '';\n if (cacheable && _styleClassCache.has(cacheKey)) {\n return _styleClassCache.get(cacheKey);\n }\n // resolve kind to an array of sheets, then stick overrides on the end\n const sheets = resolveSheet(stylesheet);\n sheets.push({ element: elementCSS, options });\n // apply style options/merge sheets, then convert to typestyle class\n const cls = resolveStyleClass(applySheetOptions(sheets));\n if (cacheable) {\n // store in cache for later reuse\n _styleClassCache.set(cacheKey, cls);\n }\n return cls;\n }\n LabIconStyle.styleClass = styleClass;\n})(LabIconStyle || (LabIconStyle = {}));\n//# sourceMappingURL=icon.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { UUID } from '@lumino/coreutils';\nimport { Signal } from '@lumino/signaling';\nimport React from 'react';\nimport { createRoot } from 'react-dom/client';\nimport badSvgstr from '../../style/debug/bad.svg';\nimport blankSvgstr from '../../style/debug/blank.svg';\nimport refreshSvgstr from '../../style/icons/toolbar/refresh.svg';\nimport { LabIconStyle } from '../style';\nimport { classes, getReactAttrs } from '../utils';\nclass LabIcon {\n /** *********\n * statics *\n ***********/\n /**\n * Remove any rendered icon from the element that contains it\n *\n * @param container - a DOM node into which an icon was\n * previously rendered\n *\n * @returns the cleaned container\n */\n static remove(container) {\n // clean up all children\n while (container.firstChild) {\n container.firstChild.remove();\n }\n // remove all classes\n container.className = '';\n return container;\n }\n /**\n * Resolve an icon name or a \\{name, svgstr\\} pair into an\n * actual LabIcon.\n *\n * @param icon - either a string with the name of an existing icon\n * or an object with \\{name: string, svgstr: string\\} fields.\n *\n * @returns a LabIcon instance\n */\n static resolve({ icon }) {\n if (icon instanceof LabIcon) {\n // icon already is a LabIcon; nothing to do here\n return icon;\n }\n if (typeof icon === 'string') {\n // do a dynamic lookup of existing icon by name\n const resolved = LabIcon._instances.get(icon);\n if (resolved) {\n return resolved;\n }\n // lookup failed\n if (LabIcon._debug) {\n // fail noisily\n console.warn(`Lookup failed for icon, creating loading icon. icon: ${icon}`);\n }\n // no matching icon currently registered, create a new loading icon\n // TODO: find better icon (maybe animate?) for loading icon\n return new LabIcon({ name: icon, svgstr: refreshSvgstr, _loading: true });\n }\n // icon was provided as a non-LabIcon \\{name, svgstr\\} pair, communicating\n // an intention to create a new icon\n return new LabIcon(icon);\n }\n /**\n * Resolve an icon name or a \\{name, svgstr\\} pair into a DOM element.\n * If icon arg is undefined, the function will fall back to trying to render\n * the icon as a CSS background image, via the iconClass arg.\n * If both icon and iconClass are undefined, this function will return\n * an empty div.\n *\n * @param icon - optional, either a string with the name of an existing icon\n * or an object with \\{name: string, svgstr: string\\} fields\n *\n * @param iconClass - optional, if the icon arg is not set, the iconClass arg\n * should be a CSS class associated with an existing CSS background-image\n *\n * @param fallback - DEPRECATED, optional, a LabIcon instance that will\n * be used if neither icon nor iconClass are defined\n *\n * @param props - any additional args are passed though to the element method\n * of the resolved icon on render\n *\n * @returns a DOM node with the resolved icon rendered into it\n */\n static resolveElement({ icon, iconClass, fallback, ...props }) {\n if (!Private.isResolvable(icon)) {\n if (!iconClass && fallback) {\n // if neither icon nor iconClass are defined/resolvable, use fallback\n return fallback.element(props);\n }\n // set the icon's class to iconClass plus props.className\n props.className = classes(iconClass, props.className);\n // render icon as css background image, assuming one is set on iconClass\n return Private.blankElement(props);\n }\n return LabIcon.resolve({ icon }).element(props);\n }\n /**\n * Resolve an icon name or a \\{name, svgstr\\} pair into a React component.\n * If icon arg is undefined, the function will fall back to trying to render\n * the icon as a CSS background image, via the iconClass arg.\n * If both icon and iconClass are undefined, the returned component\n * will simply render an empty div.\n *\n * @param icon - optional, either a string with the name of an existing icon\n * or an object with \\{name: string, svgstr: string\\} fields\n *\n * @param iconClass - optional, if the icon arg is not set, the iconClass arg\n * should be a CSS class associated with an existing CSS background-image\n *\n * @param fallback - DEPRECATED, optional, a LabIcon instance that will\n * be used if neither icon nor iconClass are defined\n *\n * @param props - any additional args are passed though to the React component\n * of the resolved icon on render\n *\n * @returns a React component that will render the resolved icon\n */\n static resolveReact({ icon, iconClass, fallback, ...props }) {\n if (!Private.isResolvable(icon)) {\n if (!iconClass && fallback) {\n // if neither icon nor iconClass are defined/resolvable, use fallback\n return React.createElement(fallback.react, { ...props });\n }\n // set the icon's class to iconClass plus props.className\n props.className = classes(iconClass, props.className);\n // render icon as css background image, assuming one is set on iconClass\n return React.createElement(Private.blankReact, { ...props });\n }\n const resolved = LabIcon.resolve({ icon });\n return React.createElement(resolved.react, { ...props });\n }\n /**\n * Resolve a \\{name, svgstr\\} pair into an actual svg node.\n */\n static resolveSvg({ name, svgstr }) {\n const svgDoc = new DOMParser().parseFromString(Private.svgstrShim(svgstr), 'image/svg+xml');\n const svgError = svgDoc.querySelector('parsererror');\n // structure of error element varies by browser, search at top level\n if (svgError) {\n // parse failed, svgElement will be an error box\n const errmsg = `SVG HTML was malformed for LabIcon instance.\\nname: ${name}, svgstr: ${svgstr}`;\n if (LabIcon._debug) {\n // fail noisily, render the error box\n console.error(errmsg);\n return svgError;\n }\n else {\n // bad svg is always a real error, fail silently but warn\n console.warn(errmsg);\n return null;\n }\n }\n else {\n // parse succeeded\n return svgDoc.documentElement;\n }\n }\n /**\n * Toggle icon debug from off-to-on, or vice-versa.\n *\n * @param debug - optional boolean to force debug on or off\n */\n static toggleDebug(debug) {\n LabIcon._debug = debug !== null && debug !== void 0 ? debug : !LabIcon._debug;\n }\n /** *********\n * members *\n ***********/\n constructor({ name, svgstr, render, unrender, _loading = false }) {\n this._props = {};\n this._svgReplaced = new Signal(this);\n /**\n * Cache for svg parsing intermediates\n * - undefined: the cache has not yet been populated\n * - null: a valid, but empty, value\n */\n this._svgElement = undefined;\n this._svgInnerHTML = undefined;\n this._svgReactAttrs = undefined;\n if (!(name && svgstr)) {\n // sanity check failed\n console.error(`When defining a new LabIcon, name and svgstr must both be non-empty strings. name: ${name}, svgstr: ${svgstr}`);\n return badIcon;\n }\n // currently this needs to be set early, before checks for existing icons\n this._loading = _loading;\n // check to see if this is a redefinition of an existing icon\n if (LabIcon._instances.has(name)) {\n // fetch the existing icon, replace its svg, then return it\n const icon = LabIcon._instances.get(name);\n if (this._loading) {\n // replace the placeholder svg in icon\n icon.svgstr = svgstr;\n this._loading = false;\n return icon;\n }\n else {\n // already loaded icon svg exists; replace it and warn\n if (LabIcon._debug) {\n console.warn(`Redefining previously loaded icon svgstr. name: ${name}, svgstrOld: ${icon.svgstr}, svgstr: ${svgstr}`);\n }\n icon.svgstr = svgstr;\n return icon;\n }\n }\n this.name = name;\n this.react = this._initReact(name);\n this.svgstr = svgstr;\n // setup custom render/unrender methods, if passed in\n this._initRender({ render, unrender });\n LabIcon._instances.set(this.name, this);\n }\n /**\n * Get a view of this icon that is bound to the specified icon/style props\n *\n * @param optional icon/style props (same as args for .element\n * and .react methods). These will be bound to the resulting view\n *\n * @returns a view of this LabIcon instance\n */\n bindprops(props) {\n const view = Object.create(this);\n view._props = props;\n view.react = view._initReact(view.name + '_bind');\n return view;\n }\n /**\n * Create an icon as a DOM element\n *\n * @param className - a string that will be used as the class\n * of the container element. Overrides any existing class\n *\n * @param container - a preexisting DOM element that\n * will be used as the container for the svg element\n *\n * @param label - text that will be displayed adjacent\n * to the icon\n *\n * @param title - a tooltip for the icon\n *\n * @param tag - if container is not explicitly\n * provided, this tag will be used when creating the container\n *\n * @param stylesheet - optional string naming a builtin icon\n * stylesheet, for example 'menuItem' or `statusBar`. Can also be an\n * object defining a custom icon stylesheet, or a list of builtin\n * stylesheet names and/or custom stylesheet objects. If array,\n * the given stylesheets will be merged.\n *\n * See @jupyterlab/ui-components/src/style/icon.ts for details\n *\n * @param elementPosition - optional position for the inner svg element\n *\n * @param elementSize - optional size for the inner svg element.\n * Set to 'normal' to get a standard 16px x 16px icon\n *\n * @param ...elementCSS - all additional args are treated as\n * overrides for the CSS props applied to the inner svg element\n *\n * @returns A DOM element that contains an (inline) svg element\n * that displays an icon\n */\n element(props = {}) {\n var _a;\n let { className, container, label, title, tag = 'div', ...styleProps } = { ...this._props, ...props };\n // check if icon element is already set\n const maybeSvgElement = container === null || container === void 0 ? void 0 : container.firstChild;\n if (((_a = maybeSvgElement === null || maybeSvgElement === void 0 ? void 0 : maybeSvgElement.dataset) === null || _a === void 0 ? void 0 : _a.iconId) === this._uuid) {\n // return the existing icon element\n return maybeSvgElement;\n }\n // ensure that svg html is valid\n if (!this.svgElement) {\n // bail if failing silently, return blank element\n return document.createElement('div');\n }\n let returnSvgElement = true;\n if (container) {\n // take ownership by removing any existing children\n while (container.firstChild) {\n container.firstChild.remove();\n }\n }\n else {\n // create a container if needed\n container = document.createElement(tag);\n returnSvgElement = false;\n }\n if (label != null) {\n container.textContent = label;\n }\n Private.initContainer({ container, className, styleProps, title });\n // add the svg node to the container\n const svgElement = this.svgElement.cloneNode(true);\n container.appendChild(svgElement);\n return returnSvgElement ? svgElement : container;\n }\n render(container, options) {\n var _a;\n let label = (_a = options === null || options === void 0 ? void 0 : options.children) === null || _a === void 0 ? void 0 : _a[0];\n // narrow type of label\n if (typeof label !== 'string') {\n label = undefined;\n }\n this.element({\n container,\n label,\n ...options === null || options === void 0 ? void 0 : options.props\n });\n }\n get svgElement() {\n if (this._svgElement === undefined) {\n this._svgElement = this._initSvg({ uuid: this._uuid });\n }\n return this._svgElement;\n }\n get svgInnerHTML() {\n if (this._svgInnerHTML === undefined) {\n if (this.svgElement === null) {\n // the svg element resolved to null, mark this null too\n this._svgInnerHTML = null;\n }\n else {\n this._svgInnerHTML = this.svgElement.innerHTML;\n }\n }\n return this._svgInnerHTML;\n }\n get svgReactAttrs() {\n if (this._svgReactAttrs === undefined) {\n if (this.svgElement === null) {\n // the svg element resolved to null, mark this null too\n this._svgReactAttrs = null;\n }\n else {\n this._svgReactAttrs = getReactAttrs(this.svgElement, {\n ignore: ['data-icon-id']\n });\n }\n }\n return this._svgReactAttrs;\n }\n get svgstr() {\n return this._svgstr;\n }\n set svgstr(svgstr) {\n this._svgstr = svgstr;\n // associate a new unique id with this particular svgstr\n const uuid = UUID.uuid4();\n const uuidOld = this._uuid;\n this._uuid = uuid;\n // empty the svg parsing intermediates cache\n this._svgElement = undefined;\n this._svgInnerHTML = undefined;\n this._svgReactAttrs = undefined;\n // update icon elements created using .element method\n document\n .querySelectorAll(`[data-icon-id=\"${uuidOld}\"]`)\n .forEach(oldSvgElement => {\n if (this.svgElement) {\n oldSvgElement.replaceWith(this.svgElement.cloneNode(true));\n }\n });\n // trigger update of icon elements created using other methods\n this._svgReplaced.emit();\n }\n _initReact(displayName) {\n const component = React.forwardRef((props = {}, ref) => {\n const { className, container, label, title, tag = 'div', ...styleProps } = { ...this._props, ...props };\n // set up component state via useState hook\n const [, setId] = React.useState(this._uuid);\n // subscribe to svg replacement via useEffect hook\n React.useEffect(() => {\n const onSvgReplaced = () => {\n setId(this._uuid);\n };\n this._svgReplaced.connect(onSvgReplaced);\n // specify cleanup callback as hook return\n return () => {\n this._svgReplaced.disconnect(onSvgReplaced);\n };\n });\n // make it so that tag can be used as a jsx component\n const Tag = tag;\n // ensure that svg html is valid\n if (!(this.svgInnerHTML && this.svgReactAttrs)) {\n // bail if failing silently\n return React.createElement(React.Fragment, null);\n }\n const svgComponent = (React.createElement(\"svg\", { ...this.svgReactAttrs, dangerouslySetInnerHTML: { __html: this.svgInnerHTML }, ref: ref }));\n if (container) {\n Private.initContainer({ container, className, styleProps, title });\n return (React.createElement(React.Fragment, null,\n svgComponent,\n label));\n }\n else {\n return (React.createElement(Tag, { className: className || styleProps\n ? classes(className, LabIconStyle.styleClass(styleProps))\n : undefined, title: title },\n svgComponent,\n label));\n }\n });\n component.displayName = `LabIcon_${displayName}`;\n return component;\n }\n _initRender({ render, unrender }) {\n if (render) {\n this.render = render;\n if (unrender) {\n this.unrender = unrender;\n }\n }\n else if (unrender) {\n console.warn('In _initRender, ignoring unrender arg since render is undefined');\n }\n }\n _initSvg({ title, uuid } = {}) {\n const svgElement = LabIcon.resolveSvg(this);\n if (!svgElement) {\n // bail on null svg element\n return svgElement;\n }\n if (svgElement.tagName !== 'parsererror') {\n // svgElement is an actual svg node, augment it\n svgElement.dataset.icon = this.name;\n if (uuid) {\n svgElement.dataset.iconId = uuid;\n }\n if (title) {\n Private.setTitleSvg(svgElement, title);\n }\n }\n return svgElement;\n }\n}\nLabIcon._debug = false;\nLabIcon._instances = new Map();\nexport { LabIcon };\nvar Private;\n(function (Private) {\n function blankElement({ className = '', container, label, title, tag = 'div', ...styleProps }) {\n if ((container === null || container === void 0 ? void 0 : container.className) === className) {\n // nothing needs doing, return the icon node\n return container;\n }\n if (container) {\n // take ownership by removing any existing children\n while (container.firstChild) {\n container.firstChild.remove();\n }\n }\n else {\n // create a container if needed\n container = document.createElement(tag);\n }\n if (label != null) {\n container.textContent = label;\n }\n Private.initContainer({ container, className, styleProps, title });\n return container;\n }\n Private.blankElement = blankElement;\n Private.blankReact = React.forwardRef(({ className = '', container, label, title, tag = 'div', ...styleProps }, ref) => {\n // make it so that tag can be used as a jsx component\n const Tag = tag;\n if (container) {\n initContainer({ container, className, styleProps, title });\n return React.createElement(React.Fragment, null);\n }\n else {\n // if ref is defined, we create a blank svg node and point ref to it\n return (React.createElement(Tag, { className: classes(className, LabIconStyle.styleClass(styleProps)) },\n ref && blankIcon.react({ ref }),\n label));\n }\n });\n Private.blankReact.displayName = 'BlankReact';\n function initContainer({ container, className, styleProps, title }) {\n if (title != null) {\n container.title = title;\n }\n const styleClass = LabIconStyle.styleClass(styleProps);\n if (className != null) {\n // override the container class with explicitly passed-in class + style class\n const classResolved = classes(className, styleClass);\n container.className = classResolved;\n return classResolved;\n }\n else if (styleClass) {\n // add the style class to the container class\n container.classList.add(styleClass);\n return styleClass;\n }\n else {\n return '';\n }\n }\n Private.initContainer = initContainer;\n function isResolvable(icon) {\n return !!(icon &&\n (typeof icon === 'string' ||\n (icon.name && icon.svgstr)));\n }\n Private.isResolvable = isResolvable;\n function setTitleSvg(svgNode, title) {\n // add a title node to the top level svg node\n const titleNodes = svgNode.getElementsByTagName('title');\n if (titleNodes.length) {\n titleNodes[0].textContent = title;\n }\n else {\n const titleNode = document.createElement('title');\n titleNode.textContent = title;\n svgNode.appendChild(titleNode);\n }\n }\n Private.setTitleSvg = setTitleSvg;\n /**\n * A shim for svgstrs loaded using any loader other than raw-loader.\n * This function assumes that svgstr will look like one of:\n *\n * - the raw contents of an .svg file:\n * \n *\n * - a data URL:\n * data:[][;base64],\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs\n */\n function svgstrShim(svgstr, strict = true) {\n // decode any uri escaping, condense leading/lagging whitespace,\n // then match to raw svg string\n const [, base64, raw] = decodeURIComponent(svgstr)\n .replace(/>\\s*\\n\\s*<')\n .replace(/\\s*\\n\\s*/g, ' ')\n .match(strict\n ? // match based on data url schema\n /^(?:data:.*?(;base64)?,)?(.*)/\n : // match based on open of svg tag\n /(?:(base64).*)?( c && typeof c === 'object'\n ? Object.keys(c).map(key => !!c[key] && key)\n : typeof c === 'string'\n ? c.split(/\\s+/)\n : [])\n .reduce((flattened, c) => flattened.concat(c), [])\n .filter(c => !!c);\n}\n/**\n * Combines classNames.\n *\n * @param classes - A list of classNames\n *\n * @returns A single string with the combined className\n */\nexport function classes(...classes) {\n return _classes(classes).join(' ');\n}\n/**\n * Combines classNames. Removes all duplicates\n *\n * @param classes - A list of classNames\n *\n * @returns A single string with the combined className\n */\nexport function classesDedupe(...classes) {\n return [...new Set(_classes(classes))].join(' ');\n}\n/**\n * Translates the attributes of a DOM element into attributes that can\n * be understood by React. Currently not comprehensive, we will add special\n * cases as they become relevant.\n *\n * @param elem - A DOM element\n *\n * @param ignore - An optional list of attribute names to ignore\n *\n * @returns An object with key:value pairs that are the React-friendly\n * translation of elem's attributes\n */\nexport function getReactAttrs(elem, { ignore = [] } = {}) {\n return elem\n .getAttributeNames()\n .reduce((d, name) => {\n if (name === 'style' || ignore.includes(name)) {\n void 0;\n }\n else if (name.startsWith('data')) {\n d[name] = elem.getAttribute(name);\n }\n else {\n d[Text.camelCase(name)] = elem.getAttribute(name);\n }\n return d;\n }, {});\n}\n//# sourceMappingURL=utils.js.map","export default \"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgdmlld0JveD0iMCAwIDE4IDE4Ij4KICAgIDxnIGNsYXNzPSJqcC1pY29uMyIgZmlsbD0iIzYxNjE2MSI+CiAgICAgICAgPHBhdGggZD0iTTkgMTMuNWMtMi40OSAwLTQuNS0yLjAxLTQuNS00LjVTNi41MSA0LjUgOSA0LjVjMS4yNCAwIDIuMzYuNTIgMy4xNyAxLjMzTDEwIDhoNVYzbC0xLjc2IDEuNzZDMTIuMTUgMy42OCAxMC42NiAzIDkgMyA1LjY5IDMgMy4wMSA1LjY5IDMuMDEgOVM1LjY5IDE1IDkgMTVjMi45NyAwIDUuNDMtMi4xNiA1LjktNWgtMS41MmMtLjQ2IDItMi4yNCAzLjUtNC4zOCAzLjV6Ii8+CiAgICA8L2c+Cjwvc3ZnPgo=\"","export default \"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij4KICAgIDxwYXRoCiAgICAgICAgY2xhc3M9ImpwLWljb24wIgogICAgICAgIGZpbGw9IiMwMDAiCiAgICAgICAgZD0iTTI0IDIwLjE4OGwtOC4zMTUtOC4yMDkgOC4yLTguMjgyLTMuNjk3LTMuNjk3LTguMjEyIDguMzE4LTguMzEtOC4yMDMtMy42NjYgMy42NjYgOC4zMjEgOC4yNC04LjIwNiA4LjMxMyAzLjY2NiAzLjY2NiA4LjIzNy04LjMxOCA4LjI4NSA4LjIwM3oiCiAgICAvPgo8L3N2Zz4K\"","export default \"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij4KICAgIDxwYXRoCiAgICAgICAgZmlsbD0iIzAwMCIKICAgICAgICBmaWxsLW9wYWNpdHk9IjAuMCIKICAgICAgICBkPSJNMjQgMjAuMTg4bC04LjMxNS04LjIwOSA4LjItOC4yODItMy42OTctMy42OTctOC4yMTIgOC4zMTgtOC4zMS04LjIwMy0zLjY2NiAzLjY2NiA4LjMyMSA4LjI0LTguMjA2IDguMzEzIDMuNjY2IDMuNjY2IDguMjM3LTguMzE4IDguMjg1IDguMjAzeiIKICAgIC8+Cjwvc3ZnPgo=\"","/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\nimport React from 'react';\nimport { LabIcon } from '../icon';\nimport { classes } from '../utils';\n/**\n * InputGroup component\n *\n * @param props Component properties\n * @returns Component\n */\nexport function InputGroup(props) {\n const { className, inputRef, rightIcon, ...others } = props;\n return (React.createElement(\"div\", { className: classes('jp-InputGroup', className) },\n React.createElement(\"input\", { ref: inputRef, ...others }),\n rightIcon && (React.createElement(\"span\", { className: \"jp-InputGroupAction\" }, typeof rightIcon === 'string' ? (React.createElement(LabIcon.resolveReact, { icon: rightIcon, elementPosition: \"center\", tag: \"span\" })) : (React.createElement(rightIcon.react, { elementPosition: \"center\", tag: \"span\" }))))));\n}\n//# sourceMappingURL=inputgroup.js.map","export default function _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}","import _extends from \"@babel/runtime/helpers/extends\";\nimport React from 'react';\nexport default function JSONArrow(_ref) {\n let {\n styling,\n arrowStyle = 'single',\n expanded,\n nodeType,\n onClick\n } = _ref;\n return /*#__PURE__*/React.createElement(\"div\", _extends({}, styling('arrowContainer', arrowStyle), {\n onClick: onClick\n }), /*#__PURE__*/React.createElement(\"div\", styling(['arrow', 'arrowSign'], nodeType, expanded, arrowStyle), '\\u25B6', arrowStyle === 'double' && /*#__PURE__*/React.createElement(\"div\", styling(['arrowSign', 'arrowSignInner']), '\\u25B6')));\n}","function getLength(type, collection) {\n if (type === 'Object') {\n // eslint-disable-next-line @typescript-eslint/ban-types\n return Object.keys(collection).length;\n } else if (type === 'Array') {\n return collection.length;\n }\n return Infinity;\n}\nfunction isIterableMap(collection) {\n return typeof collection.set === 'function';\n}\nfunction getEntries(type, collection, sortObjectKeys) {\n let from = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;\n let to = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : Infinity;\n let res;\n if (type === 'Object') {\n let keys = Object.getOwnPropertyNames(collection);\n if (sortObjectKeys) {\n keys.sort(sortObjectKeys === true ? undefined : sortObjectKeys);\n }\n keys = keys.slice(from, to + 1);\n res = {\n entries: keys.map(key => ({\n key,\n value: collection[key]\n }))\n };\n } else if (type === 'Array') {\n res = {\n entries: collection.slice(from, to + 1).map((val, idx) => ({\n key: idx + from,\n value: val\n }))\n };\n } else {\n let idx = 0;\n const entries = [];\n let done = true;\n const isMap = isIterableMap(collection);\n for (const item of collection) {\n if (idx > to) {\n done = false;\n break;\n }\n if (from <= idx) {\n if (isMap && Array.isArray(item)) {\n if (typeof item[0] === 'string' || typeof item[0] === 'number') {\n entries.push({\n key: item[0],\n value: item[1]\n });\n } else {\n entries.push({\n key: `[entry ${idx}]`,\n value: {\n '[key]': item[0],\n '[value]': item[1]\n }\n });\n }\n } else {\n entries.push({\n key: idx,\n value: item\n });\n }\n }\n idx++;\n }\n res = {\n hasMore: !done,\n entries\n };\n }\n return res;\n}\nfunction getRanges(from, to, limit) {\n const ranges = [];\n while (to - from > limit * limit) {\n limit = limit * limit;\n }\n for (let i = from; i <= to; i += limit) {\n ranges.push({\n from: i,\n to: Math.min(to, i + limit - 1)\n });\n }\n return ranges;\n}\nexport default function getCollectionEntries(type, collection, sortObjectKeys, limit) {\n let from = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;\n let to = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : Infinity;\n const getEntriesBound = getEntries.bind(null, type, collection, sortObjectKeys);\n if (!limit) {\n return getEntriesBound().entries;\n }\n const isSubset = to < Infinity;\n const length = Math.min(to - from, getLength(type, collection));\n if (type !== 'Iterable') {\n if (length <= limit || limit < 7) {\n return getEntriesBound(from, to).entries;\n }\n } else {\n if (length <= limit && !isSubset) {\n return getEntriesBound(from, to).entries;\n }\n }\n let limitedEntries;\n if (type === 'Iterable') {\n const {\n hasMore,\n entries\n } = getEntriesBound(from, from + limit - 1);\n limitedEntries = hasMore ? [...entries, ...getRanges(from + limit, from + 2 * limit - 1, limit)] : entries;\n } else {\n limitedEntries = isSubset ? getRanges(from, to, limit) : [...getEntriesBound(0, limit - 5).entries, ...getRanges(limit - 4, length - 5, limit), ...getEntriesBound(length - 4, length - 1).entries];\n }\n return limitedEntries;\n}","import _extends from \"@babel/runtime/helpers/extends\";\nimport React, { useCallback, useState } from 'react';\nimport JSONArrow from './JSONArrow';\nexport default function ItemRange(props) {\n const {\n styling,\n from,\n to,\n renderChildNodes,\n nodeType\n } = props;\n const [expanded, setExpanded] = useState(false);\n const handleClick = useCallback(() => {\n setExpanded(!expanded);\n }, [expanded]);\n return expanded ? /*#__PURE__*/React.createElement(\"div\", styling('itemRange', expanded), renderChildNodes(props, from, to)) : /*#__PURE__*/React.createElement(\"div\", _extends({}, styling('itemRange', expanded), {\n onClick: handleClick\n }), /*#__PURE__*/React.createElement(JSONArrow, {\n nodeType: nodeType,\n styling: styling,\n expanded: false,\n onClick: handleClick,\n arrowStyle: \"double\"\n }), `${from} ... ${to}`);\n}","import _extends from \"@babel/runtime/helpers/extends\";\nimport React, { useCallback, useState } from 'react';\nimport JSONArrow from './JSONArrow';\nimport getCollectionEntries from './getCollectionEntries';\nimport JSONNode from './JSONNode';\nimport ItemRange from './ItemRange';\nfunction isRange(rangeOrEntry) {\n return rangeOrEntry.to !== undefined;\n}\nfunction renderChildNodes(props, from, to) {\n const {\n nodeType,\n data,\n collectionLimit,\n circularCache,\n keyPath,\n postprocessValue,\n sortObjectKeys\n } = props;\n const childNodes = [];\n getCollectionEntries(nodeType, data, sortObjectKeys, collectionLimit, from, to).forEach(entry => {\n if (isRange(entry)) {\n childNodes.push( /*#__PURE__*/React.createElement(ItemRange, _extends({}, props, {\n key: `ItemRange--${entry.from}-${entry.to}`,\n from: entry.from,\n to: entry.to,\n renderChildNodes: renderChildNodes\n })));\n } else {\n const {\n key,\n value\n } = entry;\n const isCircular = circularCache.indexOf(value) !== -1;\n childNodes.push( /*#__PURE__*/React.createElement(JSONNode, _extends({}, props, {\n postprocessValue,\n collectionLimit,\n key: `Node--${key}`,\n keyPath: [key, ...keyPath],\n value: postprocessValue(value),\n circularCache: [...circularCache, value],\n isCircular: isCircular,\n hideRoot: false\n })));\n }\n });\n return childNodes;\n}\nexport default function JSONNestedNode(props) {\n const {\n circularCache = [],\n collectionLimit,\n createItemString,\n data,\n expandable,\n getItemString,\n hideRoot,\n isCircular,\n keyPath,\n labelRenderer,\n level = 0,\n nodeType,\n nodeTypeIndicator,\n shouldExpandNodeInitially,\n styling\n } = props;\n const [expanded, setExpanded] = useState(\n // calculate individual node expansion if necessary\n isCircular ? false : shouldExpandNodeInitially(keyPath, data, level));\n const handleClick = useCallback(() => {\n if (expandable) setExpanded(!expanded);\n }, [expandable, expanded]);\n const renderedChildren = expanded || hideRoot && level === 0 ? renderChildNodes({\n ...props,\n circularCache,\n level: level + 1\n }) : null;\n const itemType = /*#__PURE__*/React.createElement(\"span\", styling('nestedNodeItemType', expanded), nodeTypeIndicator);\n const renderedItemString = getItemString(nodeType, data, itemType, createItemString(data, collectionLimit), keyPath);\n const stylingArgs = [keyPath, nodeType, expanded, expandable];\n return hideRoot ? /*#__PURE__*/React.createElement(\"li\", styling('rootNode', ...stylingArgs), /*#__PURE__*/React.createElement(\"ul\", styling('rootNodeChildren', ...stylingArgs), renderedChildren)) : /*#__PURE__*/React.createElement(\"li\", styling('nestedNode', ...stylingArgs), expandable && /*#__PURE__*/React.createElement(JSONArrow, {\n styling: styling,\n nodeType: nodeType,\n expanded: expanded,\n onClick: handleClick\n }), /*#__PURE__*/React.createElement(\"label\", _extends({}, styling(['label', 'nestedNodeLabel'], ...stylingArgs), {\n onClick: handleClick\n }), labelRenderer(...stylingArgs)), /*#__PURE__*/React.createElement(\"span\", _extends({}, styling('nestedNodeItemString', ...stylingArgs), {\n onClick: handleClick\n }), renderedItemString), /*#__PURE__*/React.createElement(\"ul\", styling('nestedNodeChildren', ...stylingArgs), renderedChildren));\n}","import _extends from \"@babel/runtime/helpers/extends\";\nimport React from 'react';\nimport JSONNestedNode from './JSONNestedNode';\n// Returns the \"n Items\" string for this node,\n// generating and caching it if it hasn't been created yet.\nfunction createItemString(data) {\n const len = Object.getOwnPropertyNames(data).length;\n return `${len} ${len !== 1 ? 'keys' : 'key'}`;\n}\n// Configures to render an Object\nexport default function JSONObjectNode(_ref) {\n let {\n data,\n ...props\n } = _ref;\n return /*#__PURE__*/React.createElement(JSONNestedNode, _extends({}, props, {\n data: data,\n nodeType: \"Object\",\n nodeTypeIndicator: props.nodeType === 'Error' ? 'Error()' : '{}',\n createItemString: createItemString,\n expandable: Object.getOwnPropertyNames(data).length > 0\n }));\n}","import _extends from \"@babel/runtime/helpers/extends\";\nimport React from 'react';\nimport JSONNestedNode from './JSONNestedNode';\n// Returns the \"n Items\" string for this node,\n// generating and caching it if it hasn't been created yet.\nfunction createItemString(data) {\n return `${data.length} ${data.length !== 1 ? 'items' : 'item'}`;\n}\n// Configures to render an Array\nexport default function JSONArrayNode(_ref) {\n let {\n data,\n ...props\n } = _ref;\n return /*#__PURE__*/React.createElement(JSONNestedNode, _extends({}, props, {\n data: data,\n nodeType: \"Array\",\n nodeTypeIndicator: \"[]\",\n createItemString: createItemString,\n expandable: data.length > 0\n }));\n}","import _extends from \"@babel/runtime/helpers/extends\";\nimport React from 'react';\nimport JSONNestedNode from './JSONNestedNode';\n// Returns the \"n Items\" string for this node,\n// generating and caching it if it hasn't been created yet.\nfunction createItemString(data, limit) {\n let count = 0;\n let hasMore = false;\n if (Number.isSafeInteger(data.size)) {\n count = data.size;\n } else {\n // eslint-disable-next-line no-unused-vars\n for (const entry of data) {\n if (limit && count + 1 > limit) {\n hasMore = true;\n break;\n }\n count += 1;\n }\n }\n return `${hasMore ? '>' : ''}${count} ${count !== 1 ? 'entries' : 'entry'}`;\n}\n// Configures to render an iterable\nexport default function JSONIterableNode(props) {\n return /*#__PURE__*/React.createElement(JSONNestedNode, _extends({}, props, {\n nodeType: \"Iterable\",\n nodeTypeIndicator: \"()\",\n createItemString: createItemString,\n expandable: true\n }));\n}","import React from 'react';\nexport default function JSONValueNode(_ref) {\n let {\n nodeType,\n styling,\n labelRenderer,\n keyPath,\n valueRenderer,\n value,\n valueGetter = value => value\n } = _ref;\n return /*#__PURE__*/React.createElement(\"li\", styling('value', nodeType, keyPath), /*#__PURE__*/React.createElement(\"label\", styling(['label', 'valueLabel'], nodeType, keyPath), labelRenderer(keyPath, nodeType, false, false)), /*#__PURE__*/React.createElement(\"span\", styling('valueText', nodeType, keyPath), valueRenderer(valueGetter(value), value, ...keyPath)));\n}","import _extends from \"@babel/runtime/helpers/extends\";\nimport React from 'react';\nimport objType from './objType';\nimport JSONObjectNode from './JSONObjectNode';\nimport JSONArrayNode from './JSONArrayNode';\nimport JSONIterableNode from './JSONIterableNode';\nimport JSONValueNode from './JSONValueNode';\nexport default function JSONNode(_ref) {\n let {\n getItemString,\n keyPath,\n labelRenderer,\n styling,\n value,\n valueRenderer,\n isCustomNode,\n ...rest\n } = _ref;\n const nodeType = isCustomNode(value) ? 'Custom' : objType(value);\n const simpleNodeProps = {\n getItemString,\n key: keyPath[0],\n keyPath,\n labelRenderer,\n nodeType,\n styling,\n value,\n valueRenderer\n };\n const nestedNodeProps = {\n ...rest,\n ...simpleNodeProps,\n data: value,\n isCustomNode\n };\n switch (nodeType) {\n case 'Object':\n case 'Error':\n case 'WeakMap':\n case 'WeakSet':\n return /*#__PURE__*/React.createElement(JSONObjectNode, nestedNodeProps);\n case 'Array':\n return /*#__PURE__*/React.createElement(JSONArrayNode, nestedNodeProps);\n case 'Iterable':\n case 'Map':\n case 'Set':\n return /*#__PURE__*/React.createElement(JSONIterableNode, nestedNodeProps);\n case 'String':\n return /*#__PURE__*/React.createElement(JSONValueNode, _extends({}, simpleNodeProps, {\n valueGetter: raw => `\"${raw}\"`\n }));\n case 'Number':\n return /*#__PURE__*/React.createElement(JSONValueNode, simpleNodeProps);\n case 'Boolean':\n return /*#__PURE__*/React.createElement(JSONValueNode, _extends({}, simpleNodeProps, {\n valueGetter: raw => raw ? 'true' : 'false'\n }));\n case 'Date':\n return /*#__PURE__*/React.createElement(JSONValueNode, _extends({}, simpleNodeProps, {\n valueGetter: raw => raw.toISOString()\n }));\n case 'Null':\n return /*#__PURE__*/React.createElement(JSONValueNode, _extends({}, simpleNodeProps, {\n valueGetter: () => 'null'\n }));\n case 'Undefined':\n return /*#__PURE__*/React.createElement(JSONValueNode, _extends({}, simpleNodeProps, {\n valueGetter: () => 'undefined'\n }));\n case 'Function':\n case 'Symbol':\n return /*#__PURE__*/React.createElement(JSONValueNode, _extends({}, simpleNodeProps, {\n valueGetter: raw => raw.toString()\n }));\n case 'Custom':\n return /*#__PURE__*/React.createElement(JSONValueNode, simpleNodeProps);\n default:\n return /*#__PURE__*/React.createElement(JSONValueNode, _extends({}, simpleNodeProps, {\n valueGetter: () => `<${nodeType}>`\n }));\n }\n}","export default function objType(obj) {\n const type = Object.prototype.toString.call(obj).slice(8, -1);\n if (type === 'Object' && typeof obj[Symbol.iterator] === 'function') {\n return 'Iterable';\n }\n if (type === 'Custom' && obj.constructor !== Object && obj instanceof Object) {\n // For projects implementing objects overriding `.prototype[Symbol.toStringTag]`\n return 'Object';\n }\n return type;\n}","export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}","import toPropertyKey from \"./toPropertyKey.js\";\nexport default function _defineProperty(obj, key, value) {\n key = toPropertyKey(key);\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}","import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nexport default function _toPropertyKey(arg) {\n var key = toPrimitive(arg, \"string\");\n return _typeof(key) === \"symbol\" ? key : String(key);\n}","import _typeof from \"./typeof.js\";\nexport default function _toPrimitive(input, hint) {\n if (_typeof(input) !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (_typeof(res) !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n}","export default function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n return arr2;\n}","import arrayWithHoles from \"./arrayWithHoles.js\";\nimport iterableToArrayLimit from \"./iterableToArrayLimit.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableRest from \"./nonIterableRest.js\";\nexport default function _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}","export default function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}","export default function _iterableToArrayLimit(arr, i) {\n var _i = null == arr ? null : \"undefined\" != typeof Symbol && arr[Symbol.iterator] || arr[\"@@iterator\"];\n if (null != _i) {\n var _s,\n _e,\n _x,\n _r,\n _arr = [],\n _n = !0,\n _d = !1;\n try {\n if (_x = (_i = _i.call(arr)).next, 0 === i) {\n if (Object(_i) !== _i) return;\n _n = !1;\n } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);\n } catch (err) {\n _d = !0, _e = err;\n } finally {\n try {\n if (!_n && null != _i[\"return\"] && (_r = _i[\"return\"](), Object(_r) !== _r)) return;\n } finally {\n if (_d) throw _e;\n }\n }\n return _arr;\n }\n}","import arrayLikeToArray from \"./arrayLikeToArray.js\";\nexport default function _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}","export default function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}","import _typeof from \"@babel/runtime/helpers/typeof\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nimport _slicedToArray from \"@babel/runtime/helpers/slicedToArray\";\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\n\nimport * as base16 from 'base16';\nimport Color from 'color';\nimport curry from 'lodash.curry';\nimport { yuv2rgb, rgb2yuv } from './colorConverters';\nvar DEFAULT_BASE16 = base16.default;\nvar BASE16_KEYS = Object.keys(DEFAULT_BASE16); // we need a correcting factor, so that a dark, but not black background color\n// converts to bright enough inversed color\n\nvar flip = function flip(x) {\n return x < 0.25 ? 1 : x < 0.5 ? 0.9 - x : 1.1 - x;\n};\n\nvar invertColor = function invertColor(hexString) {\n var color = Color(hexString);\n\n var _rgb2yuv = rgb2yuv(color.array()),\n _rgb2yuv2 = _slicedToArray(_rgb2yuv, 3),\n y = _rgb2yuv2[0],\n u = _rgb2yuv2[1],\n v = _rgb2yuv2[2];\n\n var flippedYuv = [flip(y), u, v];\n var rgb = yuv2rgb(flippedYuv);\n return Color.rgb(rgb).hex();\n};\n\nvar merger = function merger(styling) {\n return function (prevStyling) {\n return {\n className: [prevStyling.className, styling.className].filter(Boolean).join(' '),\n style: _objectSpread(_objectSpread({}, prevStyling.style || {}), styling.style || {})\n };\n };\n};\n\nvar mergeStyling = function mergeStyling(customStyling, defaultStyling) {\n if (customStyling === undefined) {\n return defaultStyling;\n }\n\n if (defaultStyling === undefined) {\n return customStyling;\n }\n\n var customType = _typeof(customStyling);\n\n var defaultType = _typeof(defaultStyling);\n\n switch (customType) {\n case 'string':\n switch (defaultType) {\n case 'string':\n return [defaultStyling, customStyling].filter(Boolean).join(' ');\n\n case 'object':\n return merger({\n className: customStyling,\n style: defaultStyling\n });\n\n case 'function':\n return function (styling) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n return merger({\n className: customStyling\n })(defaultStyling.apply(void 0, [styling].concat(args)));\n };\n }\n\n break;\n\n case 'object':\n switch (defaultType) {\n case 'string':\n return merger({\n className: defaultStyling,\n style: customStyling\n });\n\n case 'object':\n return _objectSpread(_objectSpread({}, defaultStyling), customStyling);\n\n case 'function':\n return function (styling) {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n return merger({\n style: customStyling\n })(defaultStyling.apply(void 0, [styling].concat(args)));\n };\n }\n\n break;\n\n case 'function':\n switch (defaultType) {\n case 'string':\n return function (styling) {\n for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {\n args[_key3 - 1] = arguments[_key3];\n }\n\n return customStyling.apply(void 0, [merger(styling)({\n className: defaultStyling\n })].concat(args));\n };\n\n case 'object':\n return function (styling) {\n for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {\n args[_key4 - 1] = arguments[_key4];\n }\n\n return customStyling.apply(void 0, [merger(styling)({\n style: defaultStyling\n })].concat(args));\n };\n\n case 'function':\n return function (styling) {\n for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {\n args[_key5 - 1] = arguments[_key5];\n }\n\n return customStyling.apply(void 0, [defaultStyling.apply(void 0, [styling].concat(args))].concat(args));\n };\n }\n\n }\n};\n\nvar mergeStylings = function mergeStylings(customStylings, defaultStylings) {\n var keys = Object.keys(defaultStylings);\n\n for (var key in customStylings) {\n if (keys.indexOf(key) === -1) keys.push(key);\n }\n\n return keys.reduce(function (mergedStyling, key) {\n return mergedStyling[key] = mergeStyling(customStylings[key], defaultStylings[key]), mergedStyling;\n }, {});\n};\n\nvar getStylingByKeys = function getStylingByKeys(mergedStyling, keys) {\n for (var _len6 = arguments.length, args = new Array(_len6 > 2 ? _len6 - 2 : 0), _key6 = 2; _key6 < _len6; _key6++) {\n args[_key6 - 2] = arguments[_key6];\n }\n\n if (keys === null) {\n return mergedStyling;\n }\n\n if (!Array.isArray(keys)) {\n keys = [keys];\n }\n\n var styles = keys.map(function (key) {\n return mergedStyling[key];\n }).filter(Boolean);\n var props = styles.reduce(function (obj, s) {\n if (typeof s === 'string') {\n obj.className = [obj.className, s].filter(Boolean).join(' ');\n } else if (_typeof(s) === 'object') {\n obj.style = _objectSpread(_objectSpread({}, obj.style), s);\n } else if (typeof s === 'function') {\n obj = _objectSpread(_objectSpread({}, obj), s.apply(void 0, [obj].concat(args)));\n }\n\n return obj;\n }, {\n className: '',\n style: {}\n });\n\n if (!props.className) {\n delete props.className;\n }\n\n if (Object.keys(props.style).length === 0) {\n delete props.style;\n }\n\n return props;\n};\n\nexport var invertBase16Theme = function invertBase16Theme(base16Theme) {\n return Object.keys(base16Theme).reduce(function (t, key) {\n return t[key] = /^base/.test(key) ? invertColor(base16Theme[key]) : key === 'scheme' ? base16Theme[key] + ':inverted' : base16Theme[key], t;\n }, {});\n};\nexport var createStyling = curry(function (getStylingFromBase16) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var themeOrStyling = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var _options$defaultBase = options.defaultBase16,\n defaultBase16 = _options$defaultBase === void 0 ? DEFAULT_BASE16 : _options$defaultBase,\n _options$base16Themes = options.base16Themes,\n base16Themes = _options$base16Themes === void 0 ? null : _options$base16Themes;\n var base16Theme = getBase16Theme(themeOrStyling, base16Themes);\n\n if (base16Theme) {\n themeOrStyling = _objectSpread(_objectSpread({}, base16Theme), themeOrStyling);\n }\n\n var theme = BASE16_KEYS.reduce(function (t, key) {\n return t[key] = themeOrStyling[key] || defaultBase16[key], t;\n }, {});\n var customStyling = Object.keys(themeOrStyling).reduce(function (s, key) {\n return BASE16_KEYS.indexOf(key) === -1 ? (s[key] = themeOrStyling[key], s) : s;\n }, {});\n var defaultStyling = getStylingFromBase16(theme);\n var mergedStyling = mergeStylings(customStyling, defaultStyling);\n\n for (var _len7 = arguments.length, args = new Array(_len7 > 3 ? _len7 - 3 : 0), _key7 = 3; _key7 < _len7; _key7++) {\n args[_key7 - 3] = arguments[_key7];\n }\n\n return curry(getStylingByKeys, 2).apply(void 0, [mergedStyling].concat(args));\n}, 3);\n\nvar isStylingConfig = function isStylingConfig(theme) {\n return !!theme.extend;\n};\n\nexport var getBase16Theme = function getBase16Theme(theme, base16Themes) {\n if (theme && isStylingConfig(theme) && theme.extend) {\n theme = theme.extend;\n }\n\n if (typeof theme === 'string') {\n var _theme$split = theme.split(':'),\n _theme$split2 = _slicedToArray(_theme$split, 2),\n _themeName = _theme$split2[0],\n modifier = _theme$split2[1];\n\n if (base16Themes) {\n theme = base16Themes[_themeName];\n } else {\n theme = base16[_themeName];\n }\n\n if (modifier === 'inverted') {\n theme = invertBase16Theme(theme);\n }\n }\n\n return theme && Object.prototype.hasOwnProperty.call(theme, 'base00') ? theme : undefined;\n};\nexport var invertTheme = function invertTheme(theme) {\n if (typeof theme === 'string') {\n return \"\".concat(theme, \":inverted\");\n }\n\n if (theme && isStylingConfig(theme) && theme.extend) {\n if (typeof theme.extend === 'string') {\n return _objectSpread(_objectSpread({}, theme), {}, {\n extend: \"\".concat(theme.extend, \":inverted\")\n });\n }\n\n return _objectSpread(_objectSpread({}, theme), {}, {\n extend: invertBase16Theme(theme.extend)\n });\n }\n\n if (theme) {\n return invertBase16Theme(theme);\n }\n\n return theme;\n};\nexport * from './types';","export function yuv2rgb(yuv) {\n var y = yuv[0],\n u = yuv[1],\n v = yuv[2];\n var r, g, b;\n r = y * 1 + u * 0 + v * 1.13983;\n g = y * 1 + u * -0.39465 + v * -0.5806;\n b = y * 1 + u * 2.02311 + v * 0;\n r = Math.min(Math.max(0, r), 1);\n g = Math.min(Math.max(0, g), 1);\n b = Math.min(Math.max(0, b), 1);\n return [r * 255, g * 255, b * 255];\n}\nexport function rgb2yuv(rgb) {\n var r = rgb[0] / 255,\n g = rgb[1] / 255,\n b = rgb[2] / 255;\n var y = r * 0.299 + g * 0.587 + b * 0.114;\n var u = r * -0.14713 + g * -0.28886 + b * 0.436;\n var v = r * 0.615 + g * -0.51499 + b * -0.10001;\n return [y, u, v];\n}","export default {\n scheme: 'solarized',\n author: 'ethan schoonover (http://ethanschoonover.com/solarized)',\n base00: '#002b36',\n base01: '#073642',\n base02: '#586e75',\n base03: '#657b83',\n base04: '#839496',\n base05: '#93a1a1',\n base06: '#eee8d5',\n base07: '#fdf6e3',\n base08: '#dc322f',\n base09: '#cb4b16',\n base0A: '#b58900',\n base0B: '#859900',\n base0C: '#2aa198',\n base0D: '#268bd2',\n base0E: '#6c71c4',\n base0F: '#d33682'\n};","import { createStyling } from 'react-base16-styling';\nimport solarized from './themes/solarized';\nconst colorMap = theme => ({\n BACKGROUND_COLOR: theme.base00,\n TEXT_COLOR: theme.base07,\n STRING_COLOR: theme.base0B,\n DATE_COLOR: theme.base0B,\n NUMBER_COLOR: theme.base09,\n BOOLEAN_COLOR: theme.base09,\n NULL_COLOR: theme.base08,\n UNDEFINED_COLOR: theme.base08,\n FUNCTION_COLOR: theme.base08,\n SYMBOL_COLOR: theme.base08,\n LABEL_COLOR: theme.base0D,\n ARROW_COLOR: theme.base0D,\n ITEM_STRING_COLOR: theme.base0B,\n ITEM_STRING_EXPANDED_COLOR: theme.base03\n});\nconst valueColorMap = colors => ({\n String: colors.STRING_COLOR,\n Date: colors.DATE_COLOR,\n Number: colors.NUMBER_COLOR,\n Boolean: colors.BOOLEAN_COLOR,\n Null: colors.NULL_COLOR,\n Undefined: colors.UNDEFINED_COLOR,\n Function: colors.FUNCTION_COLOR,\n Symbol: colors.SYMBOL_COLOR\n});\nconst getDefaultThemeStyling = theme => {\n const colors = colorMap(theme);\n return {\n tree: {\n border: 0,\n padding: 0,\n marginTop: '0.5em',\n marginBottom: '0.5em',\n marginLeft: '0.125em',\n marginRight: 0,\n listStyle: 'none',\n MozUserSelect: 'none',\n WebkitUserSelect: 'none',\n backgroundColor: colors.BACKGROUND_COLOR\n },\n value: (_ref, nodeType, keyPath) => {\n let {\n style\n } = _ref;\n return {\n style: {\n ...style,\n paddingTop: '0.25em',\n paddingRight: 0,\n marginLeft: '0.875em',\n WebkitUserSelect: 'text',\n MozUserSelect: 'text',\n wordWrap: 'break-word',\n paddingLeft: keyPath.length > 1 ? '2.125em' : '1.25em',\n textIndent: '-0.5em',\n wordBreak: 'break-all'\n }\n };\n },\n label: {\n display: 'inline-block',\n color: colors.LABEL_COLOR\n },\n valueLabel: {\n margin: '0 0.5em 0 0'\n },\n valueText: (_ref2, nodeType) => {\n let {\n style\n } = _ref2;\n return {\n style: {\n ...style,\n color: valueColorMap(colors)[nodeType]\n }\n };\n },\n itemRange: (styling, expanded) => ({\n style: {\n paddingTop: expanded ? 0 : '0.25em',\n cursor: 'pointer',\n color: colors.LABEL_COLOR\n }\n }),\n arrow: (_ref3, nodeType, expanded) => {\n let {\n style\n } = _ref3;\n return {\n style: {\n ...style,\n marginLeft: 0,\n transition: '150ms',\n WebkitTransition: '150ms',\n MozTransition: '150ms',\n WebkitTransform: expanded ? 'rotateZ(90deg)' : 'rotateZ(0deg)',\n MozTransform: expanded ? 'rotateZ(90deg)' : 'rotateZ(0deg)',\n transform: expanded ? 'rotateZ(90deg)' : 'rotateZ(0deg)',\n transformOrigin: '45% 50%',\n WebkitTransformOrigin: '45% 50%',\n MozTransformOrigin: '45% 50%',\n position: 'relative',\n lineHeight: '1.1em',\n fontSize: '0.75em'\n }\n };\n },\n arrowContainer: (_ref4, arrowStyle) => {\n let {\n style\n } = _ref4;\n return {\n style: {\n ...style,\n display: 'inline-block',\n paddingRight: '0.5em',\n paddingLeft: arrowStyle === 'double' ? '1em' : 0,\n cursor: 'pointer'\n }\n };\n },\n arrowSign: {\n color: colors.ARROW_COLOR\n },\n arrowSignInner: {\n position: 'absolute',\n top: 0,\n left: '-0.4em'\n },\n nestedNode: (_ref5, keyPath, nodeType, expanded, expandable) => {\n let {\n style\n } = _ref5;\n return {\n style: {\n ...style,\n position: 'relative',\n paddingTop: '0.25em',\n marginLeft: keyPath.length > 1 ? '0.875em' : 0,\n paddingLeft: !expandable ? '1.125em' : 0\n }\n };\n },\n rootNode: {\n padding: 0,\n margin: 0\n },\n nestedNodeLabel: (_ref6, keyPath, nodeType, expanded, expandable) => {\n let {\n style\n } = _ref6;\n return {\n style: {\n ...style,\n margin: 0,\n padding: 0,\n WebkitUserSelect: expandable ? 'inherit' : 'text',\n MozUserSelect: expandable ? 'inherit' : 'text',\n cursor: expandable ? 'pointer' : 'default'\n }\n };\n },\n nestedNodeItemString: (_ref7, keyPath, nodeType, expanded) => {\n let {\n style\n } = _ref7;\n return {\n style: {\n ...style,\n paddingLeft: '0.5em',\n cursor: 'default',\n color: expanded ? colors.ITEM_STRING_EXPANDED_COLOR : colors.ITEM_STRING_COLOR\n }\n };\n },\n nestedNodeItemType: {\n marginLeft: '0.3em',\n marginRight: '0.3em'\n },\n nestedNodeChildren: (_ref8, nodeType, expanded) => {\n let {\n style\n } = _ref8;\n return {\n style: {\n ...style,\n padding: 0,\n margin: 0,\n listStyle: 'none',\n display: expanded ? 'block' : 'none'\n }\n };\n },\n rootNodeChildren: {\n padding: 0,\n margin: 0,\n listStyle: 'none'\n }\n };\n};\nconst createStylingFromTheme = createStyling(getDefaultThemeStyling, {\n defaultBase16: solarized\n});\nexport default createStylingFromTheme;","// ES6 + inline style port of JSONViewer https://bitbucket.org/davevedder/react-json-viewer/\n// all credits and original code to the author\n// Dave Vedder http://www.eskimospy.com/\n// port by Daniele Zannotti http://www.github.com/dzannotti \n\nimport React, { useMemo } from 'react';\nimport JSONNode from './JSONNode';\nimport createStylingFromTheme from './createStylingFromTheme';\nimport { invertTheme } from 'react-base16-styling';\nconst identity = value => value;\nconst expandRootNode = (keyPath, data, level) => level === 0;\nconst defaultItemString = (type, data, itemType, itemString) => /*#__PURE__*/React.createElement(\"span\", null, itemType, \" \", itemString);\nconst defaultLabelRenderer = _ref => {\n let [label] = _ref;\n return /*#__PURE__*/React.createElement(\"span\", null, label, \":\");\n};\nconst noCustomNode = () => false;\nexport function JSONTree(_ref2) {\n let {\n data: value,\n theme,\n invertTheme: shouldInvertTheme,\n keyPath = ['root'],\n labelRenderer = defaultLabelRenderer,\n valueRenderer = identity,\n shouldExpandNodeInitially = expandRootNode,\n hideRoot = false,\n getItemString = defaultItemString,\n postprocessValue = identity,\n isCustomNode = noCustomNode,\n collectionLimit = 50,\n sortObjectKeys = false\n } = _ref2;\n const styling = useMemo(() => createStylingFromTheme(shouldInvertTheme ? invertTheme(theme) : theme), [theme, shouldInvertTheme]);\n return /*#__PURE__*/React.createElement(\"ul\", styling('tree'), /*#__PURE__*/React.createElement(JSONNode, {\n keyPath: hideRoot ? [] : keyPath,\n value: postprocessValue(value),\n isCustomNode: isCustomNode,\n styling: styling,\n labelRenderer: labelRenderer,\n valueRenderer: valueRenderer,\n shouldExpandNodeInitially: shouldExpandNodeInitially,\n hideRoot: hideRoot,\n getItemString: getItemString,\n postprocessValue: postprocessValue,\n collectionLimit: collectionLimit,\n sortObjectKeys: sortObjectKeys\n }));\n}","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { jupyterHighlightStyle } from '@jupyterlab/codemirror';\nimport { nullTranslator } from '@jupyterlab/translation';\nimport { InputGroup } from '@jupyterlab/ui-components';\nimport { tags } from '@lezer/highlight';\nimport { JSONExt } from '@lumino/coreutils';\nimport * as React from 'react';\nimport Highlighter from 'react-highlight-words';\nimport { JSONTree } from 'react-json-tree';\nimport { StyleModule } from 'style-mod';\n/**\n * Get the CodeMirror style for a given tag.\n */\nfunction getStyle(tag) {\n var _a;\n return (_a = jupyterHighlightStyle.style([tag])) !== null && _a !== void 0 ? _a : '';\n}\n/**\n * A component that renders JSON data as a collapsible tree.\n */\nexport class Component extends React.Component {\n constructor() {\n super(...arguments);\n this.state = { filter: '', value: '' };\n this.timer = 0;\n this.handleChange = (event) => {\n const { value } = event.target;\n this.setState({ value });\n window.clearTimeout(this.timer);\n this.timer = window.setTimeout(() => {\n this.setState({ filter: value });\n }, 300);\n };\n }\n componentDidMount() {\n StyleModule.mount(document, jupyterHighlightStyle.module);\n }\n render() {\n const translator = this.props.translator || nullTranslator;\n const trans = translator.load('jupyterlab');\n const { data, metadata, forwardedRef } = this.props;\n const root = metadata && metadata.root ? metadata.root : 'root';\n const keyPaths = this.state.filter\n ? filterPaths(data, this.state.filter, [root])\n : [root];\n return (React.createElement(\"div\", { className: \"container\", ref: forwardedRef },\n React.createElement(InputGroup, { className: \"filter\", type: \"text\", placeholder: trans.__('Filter…'), onChange: this.handleChange, value: this.state.value, rightIcon: \"ui-components:search\" }),\n React.createElement(JSONTree, { data: data, collectionLimit: 100, theme: {\n extend: theme,\n valueLabel: getStyle(tags.variableName),\n valueText: getStyle(tags.string),\n nestedNodeItemString: getStyle(tags.comment)\n }, invertTheme: false, keyPath: [root], getItemString: (type, data, itemType, itemString) => Array.isArray(data) ? (\n // Always display array type and the number of items i.e. \"[] 2 items\".\n React.createElement(\"span\", null,\n itemType,\n \" \",\n itemString)) : Object.keys(data).length === 0 ? (\n // Only display object type when it's empty i.e. \"{}\".\n React.createElement(\"span\", null, itemType)) : (null // Upstream typings don't accept null, but it should be ok\n ), labelRenderer: ([label, type]) => {\n return (React.createElement(\"span\", { className: getStyle(tags.keyword) },\n React.createElement(Highlighter, { searchWords: [this.state.filter], textToHighlight: `${label}`, highlightClassName: \"jp-mod-selected\" })));\n }, valueRenderer: raw => {\n let className = getStyle(tags.string);\n if (typeof raw === 'number') {\n className = getStyle(tags.number);\n }\n if (raw === 'true' || raw === 'false') {\n className = getStyle(tags.keyword);\n }\n return (React.createElement(\"span\", { className: className },\n React.createElement(Highlighter, { searchWords: [this.state.filter], textToHighlight: `${raw}`, highlightClassName: \"jp-mod-selected\" })));\n }, shouldExpandNodeInitially: (keyPath, data, level) => metadata && metadata.expanded\n ? true\n : keyPaths.join(',').includes(keyPath.join(',')) })));\n }\n}\n// Provide an invalid theme object (this is on purpose!) to invalidate the\n// react-json-tree's inline styles that override CodeMirror CSS classes\nconst theme = {\n scheme: 'jupyter',\n base00: 'invalid',\n base01: 'invalid',\n base02: 'invalid',\n base03: 'invalid',\n base04: 'invalid',\n base05: 'invalid',\n base06: 'invalid',\n base07: 'invalid',\n base08: 'invalid',\n base09: 'invalid',\n base0A: 'invalid',\n base0B: 'invalid',\n base0C: 'invalid',\n base0D: 'invalid',\n base0E: 'invalid',\n base0F: 'invalid',\n author: 'invalid'\n};\nfunction objectIncludes(data, query) {\n return JSON.stringify(data).includes(query);\n}\nfunction filterPaths(data, query, parent = ['root']) {\n if (JSONExt.isArray(data)) {\n return data.reduce((result, item, index) => {\n if (item && typeof item === 'object' && objectIncludes(item, query)) {\n return [\n ...result,\n [index, ...parent].join(','),\n ...filterPaths(item, query, [index, ...parent])\n ];\n }\n return result;\n }, []);\n }\n if (JSONExt.isObject(data)) {\n return Object.keys(data).reduce((result, key) => {\n const item = data[key];\n if (item &&\n typeof item === 'object' &&\n (key.includes(query) || objectIncludes(item, query))) {\n return [\n ...result,\n [key, ...parent].join(','),\n ...filterPaths(item, query, [key, ...parent])\n ];\n }\n return result;\n }, []);\n }\n return [];\n}\n//# sourceMappingURL=component.js.map","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.lumino_coreutils = {}));\n})(this, (function (exports) { 'use strict';\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for JSON-specific functions.\n */\n exports.JSONExt = void 0;\n (function (JSONExt) {\n /**\n * A shared frozen empty JSONObject\n */\n JSONExt.emptyObject = Object.freeze({});\n /**\n * A shared frozen empty JSONArray\n */\n JSONExt.emptyArray = Object.freeze([]);\n /**\n * Test whether a JSON value is a primitive.\n *\n * @param value - The JSON value of interest.\n *\n * @returns `true` if the value is a primitive,`false` otherwise.\n */\n function isPrimitive(value) {\n return (value === null ||\n typeof value === 'boolean' ||\n typeof value === 'number' ||\n typeof value === 'string');\n }\n JSONExt.isPrimitive = isPrimitive;\n function isArray(value) {\n return Array.isArray(value);\n }\n JSONExt.isArray = isArray;\n function isObject(value) {\n return !isPrimitive(value) && !isArray(value);\n }\n JSONExt.isObject = isObject;\n /**\n * Compare two JSON values for deep equality.\n *\n * @param first - The first JSON value of interest.\n *\n * @param second - The second JSON value of interest.\n *\n * @returns `true` if the values are equivalent, `false` otherwise.\n */\n function deepEqual(first, second) {\n // Check referential and primitive equality first.\n if (first === second) {\n return true;\n }\n // If one is a primitive, the `===` check ruled out the other.\n if (isPrimitive(first) || isPrimitive(second)) {\n return false;\n }\n // Test whether they are arrays.\n let a1 = isArray(first);\n let a2 = isArray(second);\n // Bail if the types are different.\n if (a1 !== a2) {\n return false;\n }\n // If they are both arrays, compare them.\n if (a1 && a2) {\n return deepArrayEqual(first, second);\n }\n // At this point, they must both be objects.\n return deepObjectEqual(first, second);\n }\n JSONExt.deepEqual = deepEqual;\n /**\n * Create a deep copy of a JSON value.\n *\n * @param value - The JSON value to copy.\n *\n * @returns A deep copy of the given JSON value.\n */\n function deepCopy(value) {\n // Do nothing for primitive values.\n if (isPrimitive(value)) {\n return value;\n }\n // Deep copy an array.\n if (isArray(value)) {\n return deepArrayCopy(value);\n }\n // Deep copy an object.\n return deepObjectCopy(value);\n }\n JSONExt.deepCopy = deepCopy;\n /**\n * Compare two JSON arrays for deep equality.\n */\n function deepArrayEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Test the arrays for equal length.\n if (first.length !== second.length) {\n return false;\n }\n // Compare the values for equality.\n for (let i = 0, n = first.length; i < n; ++i) {\n if (!deepEqual(first[i], second[i])) {\n return false;\n }\n }\n // At this point, the arrays are equal.\n return true;\n }\n /**\n * Compare two JSON objects for deep equality.\n */\n function deepObjectEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Check for the first object's keys in the second object.\n for (let key in first) {\n if (first[key] !== undefined && !(key in second)) {\n return false;\n }\n }\n // Check for the second object's keys in the first object.\n for (let key in second) {\n if (second[key] !== undefined && !(key in first)) {\n return false;\n }\n }\n // Compare the values for equality.\n for (let key in first) {\n // Get the values.\n let firstValue = first[key];\n let secondValue = second[key];\n // If both are undefined, ignore the key.\n if (firstValue === undefined && secondValue === undefined) {\n continue;\n }\n // If only one value is undefined, the objects are not equal.\n if (firstValue === undefined || secondValue === undefined) {\n return false;\n }\n // Compare the values.\n if (!deepEqual(firstValue, secondValue)) {\n return false;\n }\n }\n // At this point, the objects are equal.\n return true;\n }\n /**\n * Create a deep copy of a JSON array.\n */\n function deepArrayCopy(value) {\n let result = new Array(value.length);\n for (let i = 0, n = value.length; i < n; ++i) {\n result[i] = deepCopy(value[i]);\n }\n return result;\n }\n /**\n * Create a deep copy of a JSON object.\n */\n function deepObjectCopy(value) {\n let result = {};\n for (let key in value) {\n // Ignore undefined values.\n let subvalue = value[key];\n if (subvalue === undefined) {\n continue;\n }\n result[key] = deepCopy(subvalue);\n }\n return result;\n }\n })(exports.JSONExt || (exports.JSONExt = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * An object which stores MIME data for general application use.\n *\n * #### Notes\n * This class does not attempt to enforce \"correctness\" of MIME types\n * and their associated data. Since this class is designed to transfer\n * arbitrary data and objects within the same application, it assumes\n * that the user provides correct and accurate data.\n */\n class MimeData {\n constructor() {\n this._types = [];\n this._values = [];\n }\n /**\n * Get an array of the MIME types contained within the dataset.\n *\n * @returns A new array of the MIME types, in order of insertion.\n */\n types() {\n return this._types.slice();\n }\n /**\n * Test whether the dataset has an entry for the given type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns `true` if the dataset contains a value for the given\n * MIME type, `false` otherwise.\n */\n hasData(mime) {\n return this._types.indexOf(mime) !== -1;\n }\n /**\n * Get the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns The value for the given MIME type, or `undefined` if\n * the dataset does not contain a value for the type.\n */\n getData(mime) {\n let i = this._types.indexOf(mime);\n return i !== -1 ? this._values[i] : undefined;\n }\n /**\n * Set the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @param data - The data value for the given MIME type.\n *\n * #### Notes\n * This will overwrite any previous entry for the MIME type.\n */\n setData(mime, data) {\n this.clearData(mime);\n this._types.push(mime);\n this._values.push(data);\n }\n /**\n * Remove the data entry for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * #### Notes\n * This is a no-op if there is no entry for the given MIME type.\n */\n clearData(mime) {\n let i = this._types.indexOf(mime);\n if (i !== -1) {\n this._types.splice(i, 1);\n this._values.splice(i, 1);\n }\n }\n /**\n * Remove all data entries from the dataset.\n */\n clear() {\n this._types.length = 0;\n this._values.length = 0;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A class which wraps a promise into a delegate object.\n *\n * #### Notes\n * This class is useful when the logic to resolve or reject a promise\n * cannot be defined at the point where the promise is created.\n */\n class PromiseDelegate {\n /**\n * Construct a new promise delegate.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n /**\n * Resolve the wrapped promise with the given value.\n *\n * @param value - The value to use for resolving the promise.\n */\n resolve(value) {\n let resolve = this._resolve;\n resolve(value);\n }\n /**\n * Reject the wrapped promise with the given value.\n *\n * @reason - The reason for rejecting the promise.\n */\n reject(reason) {\n let reject = this._reject;\n reject(reason);\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A runtime object which captures compile-time type information.\n *\n * #### Notes\n * A token captures the compile-time type of an interface or class in\n * an object which can be used at runtime in a type-safe fashion.\n */\n class Token {\n /**\n * Construct a new token.\n *\n * @param name - A human readable name for the token.\n * @param description - Token purpose description for documentation.\n */\n constructor(name, description) {\n this.name = name;\n this.description = description !== null && description !== void 0 ? description : '';\n this._tokenStructuralPropertyT = null;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n // Fallback\n function fallbackRandomValues(buffer) {\n let value = 0;\n for (let i = 0, n = buffer.length; i < n; ++i) {\n if (i % 4 === 0) {\n value = (Math.random() * 0xffffffff) >>> 0;\n }\n buffer[i] = value & 0xff;\n value >>>= 8;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for random number related functionality.\n */\n exports.Random = void 0;\n (function (Random) {\n /**\n * A function which generates random bytes.\n *\n * @param buffer - The `Uint8Array` to fill with random bytes.\n *\n * #### Notes\n * A cryptographically strong random number generator will be used if\n * available. Otherwise, `Math.random` will be used as a fallback for\n * randomness.\n *\n * The following RNGs are supported, listed in order of precedence:\n * - `window.crypto.getRandomValues`\n * - `window.msCrypto.getRandomValues`\n * - `require('crypto').randomFillSync\n * - `require('crypto').randomBytes\n * - `Math.random`\n */\n Random.getRandomValues = (() => {\n // Look up the crypto module if available.\n const crypto = (typeof window !== 'undefined' && (window.crypto || window.msCrypto)) ||\n null;\n // Modern browsers and IE 11\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return function getRandomValues(buffer) {\n return crypto.getRandomValues(buffer);\n };\n }\n // Fallback\n return fallbackRandomValues;\n })();\n })(exports.Random || (exports.Random = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A function which creates a function that generates UUID v4 identifiers.\n *\n * @returns A new function that creates a UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n function uuid4Factory(getRandomValues) {\n // Create a 16 byte array to hold the random values.\n const bytes = new Uint8Array(16);\n // Create a look up table from bytes to hex strings.\n const lut = new Array(256);\n // Pad the single character hex digits with a leading zero.\n for (let i = 0; i < 16; ++i) {\n lut[i] = '0' + i.toString(16);\n }\n // Populate the rest of the hex digits.\n for (let i = 16; i < 256; ++i) {\n lut[i] = i.toString(16);\n }\n // Return a function which generates the UUID.\n return function uuid4() {\n // Get a new batch of random values.\n getRandomValues(bytes);\n // Set the UUID version number to 4.\n bytes[6] = 0x40 | (bytes[6] & 0x0f);\n // Set the clock sequence bit to the RFC spec.\n bytes[8] = 0x80 | (bytes[8] & 0x3f);\n // Assemble the UUID string.\n return (lut[bytes[0]] +\n lut[bytes[1]] +\n lut[bytes[2]] +\n lut[bytes[3]] +\n '-' +\n lut[bytes[4]] +\n lut[bytes[5]] +\n '-' +\n lut[bytes[6]] +\n lut[bytes[7]] +\n '-' +\n lut[bytes[8]] +\n lut[bytes[9]] +\n '-' +\n lut[bytes[10]] +\n lut[bytes[11]] +\n lut[bytes[12]] +\n lut[bytes[13]] +\n lut[bytes[14]] +\n lut[bytes[15]]);\n };\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for UUID related functionality.\n */\n exports.UUID = void 0;\n (function (UUID) {\n /**\n * A function which generates UUID v4 identifiers.\n *\n * @returns A new UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n UUID.uuid4 = uuid4Factory(exports.Random.getRandomValues);\n })(exports.UUID || (exports.UUID = {}));\n\n exports.MimeData = MimeData;\n exports.PromiseDelegate = PromiseDelegate;\n exports.Token = Token;\n\n}));\n//# sourceMappingURL=index.js.map\n","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.lumino_coreutils = {}));\n})(this, (function (exports) { 'use strict';\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for JSON-specific functions.\n */\n exports.JSONExt = void 0;\n (function (JSONExt) {\n /**\n * A shared frozen empty JSONObject\n */\n JSONExt.emptyObject = Object.freeze({});\n /**\n * A shared frozen empty JSONArray\n */\n JSONExt.emptyArray = Object.freeze([]);\n /**\n * Test whether a JSON value is a primitive.\n *\n * @param value - The JSON value of interest.\n *\n * @returns `true` if the value is a primitive,`false` otherwise.\n */\n function isPrimitive(value) {\n return (value === null ||\n typeof value === 'boolean' ||\n typeof value === 'number' ||\n typeof value === 'string');\n }\n JSONExt.isPrimitive = isPrimitive;\n function isArray(value) {\n return Array.isArray(value);\n }\n JSONExt.isArray = isArray;\n function isObject(value) {\n return !isPrimitive(value) && !isArray(value);\n }\n JSONExt.isObject = isObject;\n /**\n * Compare two JSON values for deep equality.\n *\n * @param first - The first JSON value of interest.\n *\n * @param second - The second JSON value of interest.\n *\n * @returns `true` if the values are equivalent, `false` otherwise.\n */\n function deepEqual(first, second) {\n // Check referential and primitive equality first.\n if (first === second) {\n return true;\n }\n // If one is a primitive, the `===` check ruled out the other.\n if (isPrimitive(first) || isPrimitive(second)) {\n return false;\n }\n // Test whether they are arrays.\n let a1 = isArray(first);\n let a2 = isArray(second);\n // Bail if the types are different.\n if (a1 !== a2) {\n return false;\n }\n // If they are both arrays, compare them.\n if (a1 && a2) {\n return deepArrayEqual(first, second);\n }\n // At this point, they must both be objects.\n return deepObjectEqual(first, second);\n }\n JSONExt.deepEqual = deepEqual;\n /**\n * Create a deep copy of a JSON value.\n *\n * @param value - The JSON value to copy.\n *\n * @returns A deep copy of the given JSON value.\n */\n function deepCopy(value) {\n // Do nothing for primitive values.\n if (isPrimitive(value)) {\n return value;\n }\n // Deep copy an array.\n if (isArray(value)) {\n return deepArrayCopy(value);\n }\n // Deep copy an object.\n return deepObjectCopy(value);\n }\n JSONExt.deepCopy = deepCopy;\n /**\n * Compare two JSON arrays for deep equality.\n */\n function deepArrayEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Test the arrays for equal length.\n if (first.length !== second.length) {\n return false;\n }\n // Compare the values for equality.\n for (let i = 0, n = first.length; i < n; ++i) {\n if (!deepEqual(first[i], second[i])) {\n return false;\n }\n }\n // At this point, the arrays are equal.\n return true;\n }\n /**\n * Compare two JSON objects for deep equality.\n */\n function deepObjectEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Check for the first object's keys in the second object.\n for (let key in first) {\n if (first[key] !== undefined && !(key in second)) {\n return false;\n }\n }\n // Check for the second object's keys in the first object.\n for (let key in second) {\n if (second[key] !== undefined && !(key in first)) {\n return false;\n }\n }\n // Compare the values for equality.\n for (let key in first) {\n // Get the values.\n let firstValue = first[key];\n let secondValue = second[key];\n // If both are undefined, ignore the key.\n if (firstValue === undefined && secondValue === undefined) {\n continue;\n }\n // If only one value is undefined, the objects are not equal.\n if (firstValue === undefined || secondValue === undefined) {\n return false;\n }\n // Compare the values.\n if (!deepEqual(firstValue, secondValue)) {\n return false;\n }\n }\n // At this point, the objects are equal.\n return true;\n }\n /**\n * Create a deep copy of a JSON array.\n */\n function deepArrayCopy(value) {\n let result = new Array(value.length);\n for (let i = 0, n = value.length; i < n; ++i) {\n result[i] = deepCopy(value[i]);\n }\n return result;\n }\n /**\n * Create a deep copy of a JSON object.\n */\n function deepObjectCopy(value) {\n let result = {};\n for (let key in value) {\n // Ignore undefined values.\n let subvalue = value[key];\n if (subvalue === undefined) {\n continue;\n }\n result[key] = deepCopy(subvalue);\n }\n return result;\n }\n })(exports.JSONExt || (exports.JSONExt = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * An object which stores MIME data for general application use.\n *\n * #### Notes\n * This class does not attempt to enforce \"correctness\" of MIME types\n * and their associated data. Since this class is designed to transfer\n * arbitrary data and objects within the same application, it assumes\n * that the user provides correct and accurate data.\n */\n class MimeData {\n constructor() {\n this._types = [];\n this._values = [];\n }\n /**\n * Get an array of the MIME types contained within the dataset.\n *\n * @returns A new array of the MIME types, in order of insertion.\n */\n types() {\n return this._types.slice();\n }\n /**\n * Test whether the dataset has an entry for the given type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns `true` if the dataset contains a value for the given\n * MIME type, `false` otherwise.\n */\n hasData(mime) {\n return this._types.indexOf(mime) !== -1;\n }\n /**\n * Get the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns The value for the given MIME type, or `undefined` if\n * the dataset does not contain a value for the type.\n */\n getData(mime) {\n let i = this._types.indexOf(mime);\n return i !== -1 ? this._values[i] : undefined;\n }\n /**\n * Set the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @param data - The data value for the given MIME type.\n *\n * #### Notes\n * This will overwrite any previous entry for the MIME type.\n */\n setData(mime, data) {\n this.clearData(mime);\n this._types.push(mime);\n this._values.push(data);\n }\n /**\n * Remove the data entry for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * #### Notes\n * This is a no-op if there is no entry for the given MIME type.\n */\n clearData(mime) {\n let i = this._types.indexOf(mime);\n if (i !== -1) {\n this._types.splice(i, 1);\n this._values.splice(i, 1);\n }\n }\n /**\n * Remove all data entries from the dataset.\n */\n clear() {\n this._types.length = 0;\n this._values.length = 0;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A class which wraps a promise into a delegate object.\n *\n * #### Notes\n * This class is useful when the logic to resolve or reject a promise\n * cannot be defined at the point where the promise is created.\n */\n class PromiseDelegate {\n /**\n * Construct a new promise delegate.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n /**\n * Resolve the wrapped promise with the given value.\n *\n * @param value - The value to use for resolving the promise.\n */\n resolve(value) {\n let resolve = this._resolve;\n resolve(value);\n }\n /**\n * Reject the wrapped promise with the given value.\n *\n * @reason - The reason for rejecting the promise.\n */\n reject(reason) {\n let reject = this._reject;\n reject(reason);\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A runtime object which captures compile-time type information.\n *\n * #### Notes\n * A token captures the compile-time type of an interface or class in\n * an object which can be used at runtime in a type-safe fashion.\n */\n class Token {\n /**\n * Construct a new token.\n *\n * @param name - A human readable name for the token.\n * @param description - Token purpose description for documentation.\n */\n constructor(name, description) {\n this.name = name;\n this.description = description !== null && description !== void 0 ? description : '';\n this._tokenStructuralPropertyT = null;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n // Fallback\n function fallbackRandomValues(buffer) {\n let value = 0;\n for (let i = 0, n = buffer.length; i < n; ++i) {\n if (i % 4 === 0) {\n value = (Math.random() * 0xffffffff) >>> 0;\n }\n buffer[i] = value & 0xff;\n value >>>= 8;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for random number related functionality.\n */\n exports.Random = void 0;\n (function (Random) {\n /**\n * A function which generates random bytes.\n *\n * @param buffer - The `Uint8Array` to fill with random bytes.\n *\n * #### Notes\n * A cryptographically strong random number generator will be used if\n * available. Otherwise, `Math.random` will be used as a fallback for\n * randomness.\n *\n * The following RNGs are supported, listed in order of precedence:\n * - `window.crypto.getRandomValues`\n * - `window.msCrypto.getRandomValues`\n * - `require('crypto').randomFillSync\n * - `require('crypto').randomBytes\n * - `Math.random`\n */\n Random.getRandomValues = (() => {\n // Look up the crypto module if available.\n const crypto = (typeof window !== 'undefined' && (window.crypto || window.msCrypto)) ||\n null;\n // Modern browsers and IE 11\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return function getRandomValues(buffer) {\n return crypto.getRandomValues(buffer);\n };\n }\n // Fallback\n return fallbackRandomValues;\n })();\n })(exports.Random || (exports.Random = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A function which creates a function that generates UUID v4 identifiers.\n *\n * @returns A new function that creates a UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n function uuid4Factory(getRandomValues) {\n // Create a 16 byte array to hold the random values.\n const bytes = new Uint8Array(16);\n // Create a look up table from bytes to hex strings.\n const lut = new Array(256);\n // Pad the single character hex digits with a leading zero.\n for (let i = 0; i < 16; ++i) {\n lut[i] = '0' + i.toString(16);\n }\n // Populate the rest of the hex digits.\n for (let i = 16; i < 256; ++i) {\n lut[i] = i.toString(16);\n }\n // Return a function which generates the UUID.\n return function uuid4() {\n // Get a new batch of random values.\n getRandomValues(bytes);\n // Set the UUID version number to 4.\n bytes[6] = 0x40 | (bytes[6] & 0x0f);\n // Set the clock sequence bit to the RFC spec.\n bytes[8] = 0x80 | (bytes[8] & 0x3f);\n // Assemble the UUID string.\n return (lut[bytes[0]] +\n lut[bytes[1]] +\n lut[bytes[2]] +\n lut[bytes[3]] +\n '-' +\n lut[bytes[4]] +\n lut[bytes[5]] +\n '-' +\n lut[bytes[6]] +\n lut[bytes[7]] +\n '-' +\n lut[bytes[8]] +\n lut[bytes[9]] +\n '-' +\n lut[bytes[10]] +\n lut[bytes[11]] +\n lut[bytes[12]] +\n lut[bytes[13]] +\n lut[bytes[14]] +\n lut[bytes[15]]);\n };\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for UUID related functionality.\n */\n exports.UUID = void 0;\n (function (UUID) {\n /**\n * A function which generates UUID v4 identifiers.\n *\n * @returns A new UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n UUID.uuid4 = uuid4Factory(exports.Random.getRandomValues);\n })(exports.UUID || (exports.UUID = {}));\n\n exports.MimeData = MimeData;\n exports.PromiseDelegate = PromiseDelegate;\n exports.Token = Token;\n\n}));\n//# sourceMappingURL=index.js.map\n","import { Annotation, StateEffect, EditorSelection, codePointAt, codePointSize, fromCodePoint, Facet, combineConfig, StateField, Prec, Text, MapMode, RangeValue, RangeSet, CharCategory } from '@codemirror/state';\nimport { Direction, logException, showTooltip, EditorView, ViewPlugin, getTooltip, Decoration, WidgetType, keymap } from '@codemirror/view';\nimport { syntaxTree, indentUnit } from '@codemirror/language';\n\n/**\nAn instance of this is passed to completion source functions.\n*/\nclass CompletionContext {\n /**\n Create a new completion context. (Mostly useful for testing\n completion sources—in the editor, the extension will create\n these for you.)\n */\n constructor(\n /**\n The editor state that the completion happens in.\n */\n state, \n /**\n The position at which the completion is happening.\n */\n pos, \n /**\n Indicates whether completion was activated explicitly, or\n implicitly by typing. The usual way to respond to this is to\n only return completions when either there is part of a\n completable entity before the cursor, or `explicit` is true.\n */\n explicit) {\n this.state = state;\n this.pos = pos;\n this.explicit = explicit;\n /**\n @internal\n */\n this.abortListeners = [];\n }\n /**\n Get the extent, content, and (if there is a token) type of the\n token before `this.pos`.\n */\n tokenBefore(types) {\n let token = syntaxTree(this.state).resolveInner(this.pos, -1);\n while (token && types.indexOf(token.name) < 0)\n token = token.parent;\n return token ? { from: token.from, to: this.pos,\n text: this.state.sliceDoc(token.from, this.pos),\n type: token.type } : null;\n }\n /**\n Get the match of the given expression directly before the\n cursor.\n */\n matchBefore(expr) {\n let line = this.state.doc.lineAt(this.pos);\n let start = Math.max(line.from, this.pos - 250);\n let str = line.text.slice(start - line.from, this.pos - line.from);\n let found = str.search(ensureAnchor(expr, false));\n return found < 0 ? null : { from: start + found, to: this.pos, text: str.slice(found) };\n }\n /**\n Yields true when the query has been aborted. Can be useful in\n asynchronous queries to avoid doing work that will be ignored.\n */\n get aborted() { return this.abortListeners == null; }\n /**\n Allows you to register abort handlers, which will be called when\n the query is\n [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).\n */\n addEventListener(type, listener) {\n if (type == \"abort\" && this.abortListeners)\n this.abortListeners.push(listener);\n }\n}\nfunction toSet(chars) {\n let flat = Object.keys(chars).join(\"\");\n let words = /\\w/.test(flat);\n if (words)\n flat = flat.replace(/\\w/g, \"\");\n return `[${words ? \"\\\\w\" : \"\"}${flat.replace(/[^\\w\\s]/g, \"\\\\$&\")}]`;\n}\nfunction prefixMatch(options) {\n let first = Object.create(null), rest = Object.create(null);\n for (let { label } of options) {\n first[label[0]] = true;\n for (let i = 1; i < label.length; i++)\n rest[label[i]] = true;\n }\n let source = toSet(first) + toSet(rest) + \"*$\";\n return [new RegExp(\"^\" + source), new RegExp(source)];\n}\n/**\nGiven a a fixed array of options, return an autocompleter that\ncompletes them.\n*/\nfunction completeFromList(list) {\n let options = list.map(o => typeof o == \"string\" ? { label: o } : o);\n let [validFor, match] = options.every(o => /^\\w+$/.test(o.label)) ? [/\\w*$/, /\\w+$/] : prefixMatch(options);\n return (context) => {\n let token = context.matchBefore(match);\n return token || context.explicit ? { from: token ? token.from : context.pos, options, validFor } : null;\n };\n}\n/**\nWrap the given completion source so that it will only fire when the\ncursor is in a syntax node with one of the given names.\n*/\nfunction ifIn(nodes, source) {\n return (context) => {\n for (let pos = syntaxTree(context.state).resolveInner(context.pos, -1); pos; pos = pos.parent) {\n if (nodes.indexOf(pos.name) > -1)\n return source(context);\n if (pos.type.isTop)\n break;\n }\n return null;\n };\n}\n/**\nWrap the given completion source so that it will not fire when the\ncursor is in a syntax node with one of the given names.\n*/\nfunction ifNotIn(nodes, source) {\n return (context) => {\n for (let pos = syntaxTree(context.state).resolveInner(context.pos, -1); pos; pos = pos.parent) {\n if (nodes.indexOf(pos.name) > -1)\n return null;\n if (pos.type.isTop)\n break;\n }\n return source(context);\n };\n}\nclass Option {\n constructor(completion, source, match, score) {\n this.completion = completion;\n this.source = source;\n this.match = match;\n this.score = score;\n }\n}\nfunction cur(state) { return state.selection.main.from; }\n// Make sure the given regexp has a $ at its end and, if `start` is\n// true, a ^ at its start.\nfunction ensureAnchor(expr, start) {\n var _a;\n let { source } = expr;\n let addStart = start && source[0] != \"^\", addEnd = source[source.length - 1] != \"$\";\n if (!addStart && !addEnd)\n return expr;\n return new RegExp(`${addStart ? \"^\" : \"\"}(?:${source})${addEnd ? \"$\" : \"\"}`, (_a = expr.flags) !== null && _a !== void 0 ? _a : (expr.ignoreCase ? \"i\" : \"\"));\n}\n/**\nThis annotation is added to transactions that are produced by\npicking a completion.\n*/\nconst pickedCompletion = /*@__PURE__*/Annotation.define();\n/**\nHelper function that returns a transaction spec which inserts a\ncompletion's text in the main selection range, and any other\nselection range that has the same text in front of it.\n*/\nfunction insertCompletionText(state, text, from, to) {\n let { main } = state.selection, fromOff = from - main.from, toOff = to - main.from;\n return Object.assign(Object.assign({}, state.changeByRange(range => {\n if (range != main && from != to &&\n state.sliceDoc(range.from + fromOff, range.from + toOff) != state.sliceDoc(from, to))\n return { range };\n return {\n changes: { from: range.from + fromOff, to: to == main.from ? range.to : range.from + toOff, insert: text },\n range: EditorSelection.cursor(range.from + fromOff + text.length)\n };\n })), { scrollIntoView: true, userEvent: \"input.complete\" });\n}\nconst SourceCache = /*@__PURE__*/new WeakMap();\nfunction asSource(source) {\n if (!Array.isArray(source))\n return source;\n let known = SourceCache.get(source);\n if (!known)\n SourceCache.set(source, known = completeFromList(source));\n return known;\n}\nconst startCompletionEffect = /*@__PURE__*/StateEffect.define();\nconst closeCompletionEffect = /*@__PURE__*/StateEffect.define();\n\n// A pattern matcher for fuzzy completion matching. Create an instance\n// once for a pattern, and then use that to match any number of\n// completions.\nclass FuzzyMatcher {\n constructor(pattern) {\n this.pattern = pattern;\n this.chars = [];\n this.folded = [];\n // Buffers reused by calls to `match` to track matched character\n // positions.\n this.any = [];\n this.precise = [];\n this.byWord = [];\n this.score = 0;\n this.matched = [];\n for (let p = 0; p < pattern.length;) {\n let char = codePointAt(pattern, p), size = codePointSize(char);\n this.chars.push(char);\n let part = pattern.slice(p, p + size), upper = part.toUpperCase();\n this.folded.push(codePointAt(upper == part ? part.toLowerCase() : upper, 0));\n p += size;\n }\n this.astral = pattern.length != this.chars.length;\n }\n ret(score, matched) {\n this.score = score;\n this.matched = matched;\n return true;\n }\n // Matches a given word (completion) against the pattern (input).\n // Will return a boolean indicating whether there was a match and,\n // on success, set `this.score` to the score, `this.matched` to an\n // array of `from, to` pairs indicating the matched parts of `word`.\n //\n // The score is a number that is more negative the worse the match\n // is. See `Penalty` above.\n match(word) {\n if (this.pattern.length == 0)\n return this.ret(-100 /* Penalty.NotFull */, []);\n if (word.length < this.pattern.length)\n return false;\n let { chars, folded, any, precise, byWord } = this;\n // For single-character queries, only match when they occur right\n // at the start\n if (chars.length == 1) {\n let first = codePointAt(word, 0), firstSize = codePointSize(first);\n let score = firstSize == word.length ? 0 : -100 /* Penalty.NotFull */;\n if (first == chars[0]) ;\n else if (first == folded[0])\n score += -200 /* Penalty.CaseFold */;\n else\n return false;\n return this.ret(score, [0, firstSize]);\n }\n let direct = word.indexOf(this.pattern);\n if (direct == 0)\n return this.ret(word.length == this.pattern.length ? 0 : -100 /* Penalty.NotFull */, [0, this.pattern.length]);\n let len = chars.length, anyTo = 0;\n if (direct < 0) {\n for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) {\n let next = codePointAt(word, i);\n if (next == chars[anyTo] || next == folded[anyTo])\n any[anyTo++] = i;\n i += codePointSize(next);\n }\n // No match, exit immediately\n if (anyTo < len)\n return false;\n }\n // This tracks the extent of the precise (non-folded, not\n // necessarily adjacent) match\n let preciseTo = 0;\n // Tracks whether there is a match that hits only characters that\n // appear to be starting words. `byWordFolded` is set to true when\n // a case folded character is encountered in such a match\n let byWordTo = 0, byWordFolded = false;\n // If we've found a partial adjacent match, these track its state\n let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1;\n let hasLower = /[a-z]/.test(word), wordAdjacent = true;\n // Go over the option's text, scanning for the various kinds of matches\n for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* Tp.NonWord */; i < e && byWordTo < len;) {\n let next = codePointAt(word, i);\n if (direct < 0) {\n if (preciseTo < len && next == chars[preciseTo])\n precise[preciseTo++] = i;\n if (adjacentTo < len) {\n if (next == chars[adjacentTo] || next == folded[adjacentTo]) {\n if (adjacentTo == 0)\n adjacentStart = i;\n adjacentEnd = i + 1;\n adjacentTo++;\n }\n else {\n adjacentTo = 0;\n }\n }\n }\n let ch, type = next < 0xff\n ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Tp.Lower */ : next >= 65 && next <= 90 ? 1 /* Tp.Upper */ : 0 /* Tp.NonWord */)\n : ((ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Tp.Upper */ : ch != ch.toUpperCase() ? 2 /* Tp.Lower */ : 0 /* Tp.NonWord */);\n if (!i || type == 1 /* Tp.Upper */ && hasLower || prevType == 0 /* Tp.NonWord */ && type != 0 /* Tp.NonWord */) {\n if (chars[byWordTo] == next || (folded[byWordTo] == next && (byWordFolded = true)))\n byWord[byWordTo++] = i;\n else if (byWord.length)\n wordAdjacent = false;\n }\n prevType = type;\n i += codePointSize(next);\n }\n if (byWordTo == len && byWord[0] == 0 && wordAdjacent)\n return this.result(-100 /* Penalty.ByWord */ + (byWordFolded ? -200 /* Penalty.CaseFold */ : 0), byWord, word);\n if (adjacentTo == len && adjacentStart == 0)\n return this.ret(-200 /* Penalty.CaseFold */ - word.length + (adjacentEnd == word.length ? 0 : -100 /* Penalty.NotFull */), [0, adjacentEnd]);\n if (direct > -1)\n return this.ret(-700 /* Penalty.NotStart */ - word.length, [direct, direct + this.pattern.length]);\n if (adjacentTo == len)\n return this.ret(-200 /* Penalty.CaseFold */ + -700 /* Penalty.NotStart */ - word.length, [adjacentStart, adjacentEnd]);\n if (byWordTo == len)\n return this.result(-100 /* Penalty.ByWord */ + (byWordFolded ? -200 /* Penalty.CaseFold */ : 0) + -700 /* Penalty.NotStart */ +\n (wordAdjacent ? 0 : -1100 /* Penalty.Gap */), byWord, word);\n return chars.length == 2 ? false\n : this.result((any[0] ? -700 /* Penalty.NotStart */ : 0) + -200 /* Penalty.CaseFold */ + -1100 /* Penalty.Gap */, any, word);\n }\n result(score, positions, word) {\n let result = [], i = 0;\n for (let pos of positions) {\n let to = pos + (this.astral ? codePointSize(codePointAt(word, pos)) : 1);\n if (i && result[i - 1] == pos)\n result[i - 1] = to;\n else {\n result[i++] = pos;\n result[i++] = to;\n }\n }\n return this.ret(score - word.length, result);\n }\n}\n\nconst completionConfig = /*@__PURE__*/Facet.define({\n combine(configs) {\n return combineConfig(configs, {\n activateOnTyping: true,\n selectOnOpen: true,\n override: null,\n closeOnBlur: true,\n maxRenderedOptions: 100,\n defaultKeymap: true,\n tooltipClass: () => \"\",\n optionClass: () => \"\",\n aboveCursor: false,\n icons: true,\n addToOptions: [],\n positionInfo: defaultPositionInfo,\n compareCompletions: (a, b) => a.label.localeCompare(b.label),\n interactionDelay: 75,\n updateSyncTime: 100\n }, {\n defaultKeymap: (a, b) => a && b,\n closeOnBlur: (a, b) => a && b,\n icons: (a, b) => a && b,\n tooltipClass: (a, b) => c => joinClass(a(c), b(c)),\n optionClass: (a, b) => c => joinClass(a(c), b(c)),\n addToOptions: (a, b) => a.concat(b)\n });\n }\n});\nfunction joinClass(a, b) {\n return a ? b ? a + \" \" + b : a : b;\n}\nfunction defaultPositionInfo(view, list, option, info, space, tooltip) {\n let rtl = view.textDirection == Direction.RTL, left = rtl, narrow = false;\n let side = \"top\", offset, maxWidth;\n let spaceLeft = list.left - space.left, spaceRight = space.right - list.right;\n let infoWidth = info.right - info.left, infoHeight = info.bottom - info.top;\n if (left && spaceLeft < Math.min(infoWidth, spaceRight))\n left = false;\n else if (!left && spaceRight < Math.min(infoWidth, spaceLeft))\n left = true;\n if (infoWidth <= (left ? spaceLeft : spaceRight)) {\n offset = Math.max(space.top, Math.min(option.top, space.bottom - infoHeight)) - list.top;\n maxWidth = Math.min(400 /* Info.Width */, left ? spaceLeft : spaceRight);\n }\n else {\n narrow = true;\n maxWidth = Math.min(400 /* Info.Width */, (rtl ? list.right : space.right - list.left) - 30 /* Info.Margin */);\n let spaceBelow = space.bottom - list.bottom;\n if (spaceBelow >= infoHeight || spaceBelow > list.top) { // Below the completion\n offset = option.bottom - list.top;\n }\n else { // Above it\n side = \"bottom\";\n offset = list.bottom - option.top;\n }\n }\n let scaleY = (list.bottom - list.top) / tooltip.offsetHeight;\n let scaleX = (list.right - list.left) / tooltip.offsetWidth;\n return {\n style: `${side}: ${offset / scaleY}px; max-width: ${maxWidth / scaleX}px`,\n class: \"cm-completionInfo-\" + (narrow ? (rtl ? \"left-narrow\" : \"right-narrow\") : left ? \"left\" : \"right\")\n };\n}\n\nfunction optionContent(config) {\n let content = config.addToOptions.slice();\n if (config.icons)\n content.push({\n render(completion) {\n let icon = document.createElement(\"div\");\n icon.classList.add(\"cm-completionIcon\");\n if (completion.type)\n icon.classList.add(...completion.type.split(/\\s+/g).map(cls => \"cm-completionIcon-\" + cls));\n icon.setAttribute(\"aria-hidden\", \"true\");\n return icon;\n },\n position: 20\n });\n content.push({\n render(completion, _s, _v, match) {\n let labelElt = document.createElement(\"span\");\n labelElt.className = \"cm-completionLabel\";\n let label = completion.displayLabel || completion.label, off = 0;\n for (let j = 0; j < match.length;) {\n let from = match[j++], to = match[j++];\n if (from > off)\n labelElt.appendChild(document.createTextNode(label.slice(off, from)));\n let span = labelElt.appendChild(document.createElement(\"span\"));\n span.appendChild(document.createTextNode(label.slice(from, to)));\n span.className = \"cm-completionMatchedText\";\n off = to;\n }\n if (off < label.length)\n labelElt.appendChild(document.createTextNode(label.slice(off)));\n return labelElt;\n },\n position: 50\n }, {\n render(completion) {\n if (!completion.detail)\n return null;\n let detailElt = document.createElement(\"span\");\n detailElt.className = \"cm-completionDetail\";\n detailElt.textContent = completion.detail;\n return detailElt;\n },\n position: 80\n });\n return content.sort((a, b) => a.position - b.position).map(a => a.render);\n}\nfunction rangeAroundSelected(total, selected, max) {\n if (total <= max)\n return { from: 0, to: total };\n if (selected < 0)\n selected = 0;\n if (selected <= (total >> 1)) {\n let off = Math.floor(selected / max);\n return { from: off * max, to: (off + 1) * max };\n }\n let off = Math.floor((total - selected) / max);\n return { from: total - (off + 1) * max, to: total - off * max };\n}\nclass CompletionTooltip {\n constructor(view, stateField, applyCompletion) {\n this.view = view;\n this.stateField = stateField;\n this.applyCompletion = applyCompletion;\n this.info = null;\n this.infoDestroy = null;\n this.placeInfoReq = {\n read: () => this.measureInfo(),\n write: (pos) => this.placeInfo(pos),\n key: this\n };\n this.space = null;\n this.currentClass = \"\";\n let cState = view.state.field(stateField);\n let { options, selected } = cState.open;\n let config = view.state.facet(completionConfig);\n this.optionContent = optionContent(config);\n this.optionClass = config.optionClass;\n this.tooltipClass = config.tooltipClass;\n this.range = rangeAroundSelected(options.length, selected, config.maxRenderedOptions);\n this.dom = document.createElement(\"div\");\n this.dom.className = \"cm-tooltip-autocomplete\";\n this.updateTooltipClass(view.state);\n this.dom.addEventListener(\"mousedown\", (e) => {\n let { options } = view.state.field(stateField).open;\n for (let dom = e.target, match; dom && dom != this.dom; dom = dom.parentNode) {\n if (dom.nodeName == \"LI\" && (match = /-(\\d+)$/.exec(dom.id)) && +match[1] < options.length) {\n this.applyCompletion(view, options[+match[1]]);\n e.preventDefault();\n return;\n }\n }\n });\n this.dom.addEventListener(\"focusout\", (e) => {\n let state = view.state.field(this.stateField, false);\n if (state && state.tooltip && view.state.facet(completionConfig).closeOnBlur &&\n e.relatedTarget != view.contentDOM)\n view.dispatch({ effects: closeCompletionEffect.of(null) });\n });\n this.showOptions(options, cState.id);\n }\n mount() { this.updateSel(); }\n showOptions(options, id) {\n if (this.list)\n this.list.remove();\n this.list = this.dom.appendChild(this.createListBox(options, id, this.range));\n this.list.addEventListener(\"scroll\", () => {\n if (this.info)\n this.view.requestMeasure(this.placeInfoReq);\n });\n }\n update(update) {\n var _a;\n let cState = update.state.field(this.stateField);\n let prevState = update.startState.field(this.stateField);\n this.updateTooltipClass(update.state);\n if (cState != prevState) {\n let { options, selected, disabled } = cState.open;\n if (!prevState.open || prevState.open.options != options) {\n this.range = rangeAroundSelected(options.length, selected, update.state.facet(completionConfig).maxRenderedOptions);\n this.showOptions(options, cState.id);\n }\n this.updateSel();\n if (disabled != ((_a = prevState.open) === null || _a === void 0 ? void 0 : _a.disabled))\n this.dom.classList.toggle(\"cm-tooltip-autocomplete-disabled\", !!disabled);\n }\n }\n updateTooltipClass(state) {\n let cls = this.tooltipClass(state);\n if (cls != this.currentClass) {\n for (let c of this.currentClass.split(\" \"))\n if (c)\n this.dom.classList.remove(c);\n for (let c of cls.split(\" \"))\n if (c)\n this.dom.classList.add(c);\n this.currentClass = cls;\n }\n }\n positioned(space) {\n this.space = space;\n if (this.info)\n this.view.requestMeasure(this.placeInfoReq);\n }\n updateSel() {\n let cState = this.view.state.field(this.stateField), open = cState.open;\n if (open.selected > -1 && open.selected < this.range.from || open.selected >= this.range.to) {\n this.range = rangeAroundSelected(open.options.length, open.selected, this.view.state.facet(completionConfig).maxRenderedOptions);\n this.showOptions(open.options, cState.id);\n }\n if (this.updateSelectedOption(open.selected)) {\n this.destroyInfo();\n let { completion } = open.options[open.selected];\n let { info } = completion;\n if (!info)\n return;\n let infoResult = typeof info === \"string\" ? document.createTextNode(info) : info(completion);\n if (!infoResult)\n return;\n if (\"then\" in infoResult) {\n infoResult.then(obj => {\n if (obj && this.view.state.field(this.stateField, false) == cState)\n this.addInfoPane(obj, completion);\n }).catch(e => logException(this.view.state, e, \"completion info\"));\n }\n else {\n this.addInfoPane(infoResult, completion);\n }\n }\n }\n addInfoPane(content, completion) {\n this.destroyInfo();\n let wrap = this.info = document.createElement(\"div\");\n wrap.className = \"cm-tooltip cm-completionInfo\";\n if (content.nodeType != null) {\n wrap.appendChild(content);\n this.infoDestroy = null;\n }\n else {\n let { dom, destroy } = content;\n wrap.appendChild(dom);\n this.infoDestroy = destroy || null;\n }\n this.dom.appendChild(wrap);\n this.view.requestMeasure(this.placeInfoReq);\n }\n updateSelectedOption(selected) {\n let set = null;\n for (let opt = this.list.firstChild, i = this.range.from; opt; opt = opt.nextSibling, i++) {\n if (opt.nodeName != \"LI\" || !opt.id) {\n i--; // A section header\n }\n else if (i == selected) {\n if (!opt.hasAttribute(\"aria-selected\")) {\n opt.setAttribute(\"aria-selected\", \"true\");\n set = opt;\n }\n }\n else {\n if (opt.hasAttribute(\"aria-selected\"))\n opt.removeAttribute(\"aria-selected\");\n }\n }\n if (set)\n scrollIntoView(this.list, set);\n return set;\n }\n measureInfo() {\n let sel = this.dom.querySelector(\"[aria-selected]\");\n if (!sel || !this.info)\n return null;\n let listRect = this.dom.getBoundingClientRect();\n let infoRect = this.info.getBoundingClientRect();\n let selRect = sel.getBoundingClientRect();\n let space = this.space;\n if (!space) {\n let win = this.dom.ownerDocument.defaultView || window;\n space = { left: 0, top: 0, right: win.innerWidth, bottom: win.innerHeight };\n }\n if (selRect.top > Math.min(space.bottom, listRect.bottom) - 10 ||\n selRect.bottom < Math.max(space.top, listRect.top) + 10)\n return null;\n return this.view.state.facet(completionConfig).positionInfo(this.view, listRect, selRect, infoRect, space, this.dom);\n }\n placeInfo(pos) {\n if (this.info) {\n if (pos) {\n if (pos.style)\n this.info.style.cssText = pos.style;\n this.info.className = \"cm-tooltip cm-completionInfo \" + (pos.class || \"\");\n }\n else {\n this.info.style.cssText = \"top: -1e6px\";\n }\n }\n }\n createListBox(options, id, range) {\n const ul = document.createElement(\"ul\");\n ul.id = id;\n ul.setAttribute(\"role\", \"listbox\");\n ul.setAttribute(\"aria-expanded\", \"true\");\n ul.setAttribute(\"aria-label\", this.view.state.phrase(\"Completions\"));\n let curSection = null;\n for (let i = range.from; i < range.to; i++) {\n let { completion, match } = options[i], { section } = completion;\n if (section) {\n let name = typeof section == \"string\" ? section : section.name;\n if (name != curSection && (i > range.from || range.from == 0)) {\n curSection = name;\n if (typeof section != \"string\" && section.header) {\n ul.appendChild(section.header(section));\n }\n else {\n let header = ul.appendChild(document.createElement(\"completion-section\"));\n header.textContent = name;\n }\n }\n }\n const li = ul.appendChild(document.createElement(\"li\"));\n li.id = id + \"-\" + i;\n li.setAttribute(\"role\", \"option\");\n let cls = this.optionClass(completion);\n if (cls)\n li.className = cls;\n for (let source of this.optionContent) {\n let node = source(completion, this.view.state, this.view, match);\n if (node)\n li.appendChild(node);\n }\n }\n if (range.from)\n ul.classList.add(\"cm-completionListIncompleteTop\");\n if (range.to < options.length)\n ul.classList.add(\"cm-completionListIncompleteBottom\");\n return ul;\n }\n destroyInfo() {\n if (this.info) {\n if (this.infoDestroy)\n this.infoDestroy();\n this.info.remove();\n this.info = null;\n }\n }\n destroy() {\n this.destroyInfo();\n }\n}\nfunction completionTooltip(stateField, applyCompletion) {\n return (view) => new CompletionTooltip(view, stateField, applyCompletion);\n}\nfunction scrollIntoView(container, element) {\n let parent = container.getBoundingClientRect();\n let self = element.getBoundingClientRect();\n let scaleY = parent.height / container.offsetHeight;\n if (self.top < parent.top)\n container.scrollTop -= (parent.top - self.top) / scaleY;\n else if (self.bottom > parent.bottom)\n container.scrollTop += (self.bottom - parent.bottom) / scaleY;\n}\n\n// Used to pick a preferred option when two options with the same\n// label occur in the result.\nfunction score(option) {\n return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) +\n (option.type ? 1 : 0);\n}\nfunction sortOptions(active, state) {\n let options = [];\n let sections = null;\n let addOption = (option) => {\n options.push(option);\n let { section } = option.completion;\n if (section) {\n if (!sections)\n sections = [];\n let name = typeof section == \"string\" ? section : section.name;\n if (!sections.some(s => s.name == name))\n sections.push(typeof section == \"string\" ? { name } : section);\n }\n };\n for (let a of active)\n if (a.hasResult()) {\n let getMatch = a.result.getMatch;\n if (a.result.filter === false) {\n for (let option of a.result.options) {\n addOption(new Option(option, a.source, getMatch ? getMatch(option) : [], 1e9 - options.length));\n }\n }\n else {\n let matcher = new FuzzyMatcher(state.sliceDoc(a.from, a.to));\n for (let option of a.result.options)\n if (matcher.match(option.label)) {\n let matched = !option.displayLabel ? matcher.matched : getMatch ? getMatch(option, matcher.matched) : [];\n addOption(new Option(option, a.source, matched, matcher.score + (option.boost || 0)));\n }\n }\n }\n if (sections) {\n let sectionOrder = Object.create(null), pos = 0;\n let cmp = (a, b) => { var _a, _b; return ((_a = a.rank) !== null && _a !== void 0 ? _a : 1e9) - ((_b = b.rank) !== null && _b !== void 0 ? _b : 1e9) || (a.name < b.name ? -1 : 1); };\n for (let s of sections.sort(cmp)) {\n pos -= 1e5;\n sectionOrder[s.name] = pos;\n }\n for (let option of options) {\n let { section } = option.completion;\n if (section)\n option.score += sectionOrder[typeof section == \"string\" ? section : section.name];\n }\n }\n let result = [], prev = null;\n let compare = state.facet(completionConfig).compareCompletions;\n for (let opt of options.sort((a, b) => (b.score - a.score) || compare(a.completion, b.completion))) {\n let cur = opt.completion;\n if (!prev || prev.label != cur.label || prev.detail != cur.detail ||\n (prev.type != null && cur.type != null && prev.type != cur.type) ||\n prev.apply != cur.apply || prev.boost != cur.boost)\n result.push(opt);\n else if (score(opt.completion) > score(prev))\n result[result.length - 1] = opt;\n prev = opt.completion;\n }\n return result;\n}\nclass CompletionDialog {\n constructor(options, attrs, tooltip, timestamp, selected, disabled) {\n this.options = options;\n this.attrs = attrs;\n this.tooltip = tooltip;\n this.timestamp = timestamp;\n this.selected = selected;\n this.disabled = disabled;\n }\n setSelected(selected, id) {\n return selected == this.selected || selected >= this.options.length ? this\n : new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected, this.disabled);\n }\n static build(active, state, id, prev, conf) {\n let options = sortOptions(active, state);\n if (!options.length) {\n return prev && active.some(a => a.state == 1 /* State.Pending */) ?\n new CompletionDialog(prev.options, prev.attrs, prev.tooltip, prev.timestamp, prev.selected, true) : null;\n }\n let selected = state.facet(completionConfig).selectOnOpen ? 0 : -1;\n if (prev && prev.selected != selected && prev.selected != -1) {\n let selectedValue = prev.options[prev.selected].completion;\n for (let i = 0; i < options.length; i++)\n if (options[i].completion == selectedValue) {\n selected = i;\n break;\n }\n }\n return new CompletionDialog(options, makeAttrs(id, selected), {\n pos: active.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8),\n create: createTooltip,\n above: conf.aboveCursor,\n }, prev ? prev.timestamp : Date.now(), selected, false);\n }\n map(changes) {\n return new CompletionDialog(this.options, this.attrs, Object.assign(Object.assign({}, this.tooltip), { pos: changes.mapPos(this.tooltip.pos) }), this.timestamp, this.selected, this.disabled);\n }\n}\nclass CompletionState {\n constructor(active, id, open) {\n this.active = active;\n this.id = id;\n this.open = open;\n }\n static start() {\n return new CompletionState(none, \"cm-ac-\" + Math.floor(Math.random() * 2e6).toString(36), null);\n }\n update(tr) {\n let { state } = tr, conf = state.facet(completionConfig);\n let sources = conf.override ||\n state.languageDataAt(\"autocomplete\", cur(state)).map(asSource);\n let active = sources.map(source => {\n let value = this.active.find(s => s.source == source) ||\n new ActiveSource(source, this.active.some(a => a.state != 0 /* State.Inactive */) ? 1 /* State.Pending */ : 0 /* State.Inactive */);\n return value.update(tr, conf);\n });\n if (active.length == this.active.length && active.every((a, i) => a == this.active[i]))\n active = this.active;\n let open = this.open;\n if (open && tr.docChanged)\n open = open.map(tr.changes);\n if (tr.selection || active.some(a => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) ||\n !sameResults(active, this.active))\n open = CompletionDialog.build(active, state, this.id, open, conf);\n else if (open && open.disabled && !active.some(a => a.state == 1 /* State.Pending */))\n open = null;\n if (!open && active.every(a => a.state != 1 /* State.Pending */) && active.some(a => a.hasResult()))\n active = active.map(a => a.hasResult() ? new ActiveSource(a.source, 0 /* State.Inactive */) : a);\n for (let effect of tr.effects)\n if (effect.is(setSelectedEffect))\n open = open && open.setSelected(effect.value, this.id);\n return active == this.active && open == this.open ? this : new CompletionState(active, this.id, open);\n }\n get tooltip() { return this.open ? this.open.tooltip : null; }\n get attrs() { return this.open ? this.open.attrs : baseAttrs; }\n}\nfunction sameResults(a, b) {\n if (a == b)\n return true;\n for (let iA = 0, iB = 0;;) {\n while (iA < a.length && !a[iA].hasResult)\n iA++;\n while (iB < b.length && !b[iB].hasResult)\n iB++;\n let endA = iA == a.length, endB = iB == b.length;\n if (endA || endB)\n return endA == endB;\n if (a[iA++].result != b[iB++].result)\n return false;\n }\n}\nconst baseAttrs = {\n \"aria-autocomplete\": \"list\"\n};\nfunction makeAttrs(id, selected) {\n let result = {\n \"aria-autocomplete\": \"list\",\n \"aria-haspopup\": \"listbox\",\n \"aria-controls\": id\n };\n if (selected > -1)\n result[\"aria-activedescendant\"] = id + \"-\" + selected;\n return result;\n}\nconst none = [];\nfunction getUserEvent(tr) {\n return tr.isUserEvent(\"input.type\") ? \"input\" : tr.isUserEvent(\"delete.backward\") ? \"delete\" : null;\n}\nclass ActiveSource {\n constructor(source, state, explicitPos = -1) {\n this.source = source;\n this.state = state;\n this.explicitPos = explicitPos;\n }\n hasResult() { return false; }\n update(tr, conf) {\n let event = getUserEvent(tr), value = this;\n if (event)\n value = value.handleUserEvent(tr, event, conf);\n else if (tr.docChanged)\n value = value.handleChange(tr);\n else if (tr.selection && value.state != 0 /* State.Inactive */)\n value = new ActiveSource(value.source, 0 /* State.Inactive */);\n for (let effect of tr.effects) {\n if (effect.is(startCompletionEffect))\n value = new ActiveSource(value.source, 1 /* State.Pending */, effect.value ? cur(tr.state) : -1);\n else if (effect.is(closeCompletionEffect))\n value = new ActiveSource(value.source, 0 /* State.Inactive */);\n else if (effect.is(setActiveEffect))\n for (let active of effect.value)\n if (active.source == value.source)\n value = active;\n }\n return value;\n }\n handleUserEvent(tr, type, conf) {\n return type == \"delete\" || !conf.activateOnTyping ? this.map(tr.changes) : new ActiveSource(this.source, 1 /* State.Pending */);\n }\n handleChange(tr) {\n return tr.changes.touchesRange(cur(tr.startState)) ? new ActiveSource(this.source, 0 /* State.Inactive */) : this.map(tr.changes);\n }\n map(changes) {\n return changes.empty || this.explicitPos < 0 ? this : new ActiveSource(this.source, this.state, changes.mapPos(this.explicitPos));\n }\n}\nclass ActiveResult extends ActiveSource {\n constructor(source, explicitPos, result, from, to) {\n super(source, 2 /* State.Result */, explicitPos);\n this.result = result;\n this.from = from;\n this.to = to;\n }\n hasResult() { return true; }\n handleUserEvent(tr, type, conf) {\n var _a;\n let from = tr.changes.mapPos(this.from), to = tr.changes.mapPos(this.to, 1);\n let pos = cur(tr.state);\n if ((this.explicitPos < 0 ? pos <= from : pos < this.from) ||\n pos > to ||\n type == \"delete\" && cur(tr.startState) == this.from)\n return new ActiveSource(this.source, type == \"input\" && conf.activateOnTyping ? 1 /* State.Pending */ : 0 /* State.Inactive */);\n let explicitPos = this.explicitPos < 0 ? -1 : tr.changes.mapPos(this.explicitPos), updated;\n if (checkValid(this.result.validFor, tr.state, from, to))\n return new ActiveResult(this.source, explicitPos, this.result, from, to);\n if (this.result.update &&\n (updated = this.result.update(this.result, from, to, new CompletionContext(tr.state, pos, explicitPos >= 0))))\n return new ActiveResult(this.source, explicitPos, updated, updated.from, (_a = updated.to) !== null && _a !== void 0 ? _a : cur(tr.state));\n return new ActiveSource(this.source, 1 /* State.Pending */, explicitPos);\n }\n handleChange(tr) {\n return tr.changes.touchesRange(this.from, this.to) ? new ActiveSource(this.source, 0 /* State.Inactive */) : this.map(tr.changes);\n }\n map(mapping) {\n return mapping.empty ? this :\n new ActiveResult(this.source, this.explicitPos < 0 ? -1 : mapping.mapPos(this.explicitPos), this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1));\n }\n}\nfunction checkValid(validFor, state, from, to) {\n if (!validFor)\n return false;\n let text = state.sliceDoc(from, to);\n return typeof validFor == \"function\" ? validFor(text, from, to, state) : ensureAnchor(validFor, true).test(text);\n}\nconst setActiveEffect = /*@__PURE__*/StateEffect.define({\n map(sources, mapping) { return sources.map(s => s.map(mapping)); }\n});\nconst setSelectedEffect = /*@__PURE__*/StateEffect.define();\nconst completionState = /*@__PURE__*/StateField.define({\n create() { return CompletionState.start(); },\n update(value, tr) { return value.update(tr); },\n provide: f => [\n showTooltip.from(f, val => val.tooltip),\n EditorView.contentAttributes.from(f, state => state.attrs)\n ]\n});\nfunction applyCompletion(view, option) {\n const apply = option.completion.apply || option.completion.label;\n let result = view.state.field(completionState).active.find(a => a.source == option.source);\n if (!(result instanceof ActiveResult))\n return false;\n if (typeof apply == \"string\")\n view.dispatch(Object.assign(Object.assign({}, insertCompletionText(view.state, apply, result.from, result.to)), { annotations: pickedCompletion.of(option.completion) }));\n else\n apply(view, option.completion, result.from, result.to);\n return true;\n}\nconst createTooltip = /*@__PURE__*/completionTooltip(completionState, applyCompletion);\n\n/**\nReturns a command that moves the completion selection forward or\nbackward by the given amount.\n*/\nfunction moveCompletionSelection(forward, by = \"option\") {\n return (view) => {\n let cState = view.state.field(completionState, false);\n if (!cState || !cState.open || cState.open.disabled ||\n Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay)\n return false;\n let step = 1, tooltip;\n if (by == \"page\" && (tooltip = getTooltip(view, cState.open.tooltip)))\n step = Math.max(2, Math.floor(tooltip.dom.offsetHeight /\n tooltip.dom.querySelector(\"li\").offsetHeight) - 1);\n let { length } = cState.open.options;\n let selected = cState.open.selected > -1 ? cState.open.selected + step * (forward ? 1 : -1) : forward ? 0 : length - 1;\n if (selected < 0)\n selected = by == \"page\" ? 0 : length - 1;\n else if (selected >= length)\n selected = by == \"page\" ? length - 1 : 0;\n view.dispatch({ effects: setSelectedEffect.of(selected) });\n return true;\n };\n}\n/**\nAccept the current completion.\n*/\nconst acceptCompletion = (view) => {\n let cState = view.state.field(completionState, false);\n if (view.state.readOnly || !cState || !cState.open || cState.open.selected < 0 || cState.open.disabled ||\n Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay)\n return false;\n return applyCompletion(view, cState.open.options[cState.open.selected]);\n};\n/**\nExplicitly start autocompletion.\n*/\nconst startCompletion = (view) => {\n let cState = view.state.field(completionState, false);\n if (!cState)\n return false;\n view.dispatch({ effects: startCompletionEffect.of(true) });\n return true;\n};\n/**\nClose the currently active completion.\n*/\nconst closeCompletion = (view) => {\n let cState = view.state.field(completionState, false);\n if (!cState || !cState.active.some(a => a.state != 0 /* State.Inactive */))\n return false;\n view.dispatch({ effects: closeCompletionEffect.of(null) });\n return true;\n};\nclass RunningQuery {\n constructor(active, context) {\n this.active = active;\n this.context = context;\n this.time = Date.now();\n this.updates = [];\n // Note that 'undefined' means 'not done yet', whereas 'null' means\n // 'query returned null'.\n this.done = undefined;\n }\n}\nconst MaxUpdateCount = 50, MinAbortTime = 1000;\nconst completionPlugin = /*@__PURE__*/ViewPlugin.fromClass(class {\n constructor(view) {\n this.view = view;\n this.debounceUpdate = -1;\n this.running = [];\n this.debounceAccept = -1;\n this.composing = 0 /* CompositionState.None */;\n for (let active of view.state.field(completionState).active)\n if (active.state == 1 /* State.Pending */)\n this.startQuery(active);\n }\n update(update) {\n let cState = update.state.field(completionState);\n if (!update.selectionSet && !update.docChanged && update.startState.field(completionState) == cState)\n return;\n let doesReset = update.transactions.some(tr => {\n return (tr.selection || tr.docChanged) && !getUserEvent(tr);\n });\n for (let i = 0; i < this.running.length; i++) {\n let query = this.running[i];\n if (doesReset ||\n query.updates.length + update.transactions.length > MaxUpdateCount && Date.now() - query.time > MinAbortTime) {\n for (let handler of query.context.abortListeners) {\n try {\n handler();\n }\n catch (e) {\n logException(this.view.state, e);\n }\n }\n query.context.abortListeners = null;\n this.running.splice(i--, 1);\n }\n else {\n query.updates.push(...update.transactions);\n }\n }\n if (this.debounceUpdate > -1)\n clearTimeout(this.debounceUpdate);\n this.debounceUpdate = cState.active.some(a => a.state == 1 /* State.Pending */ && !this.running.some(q => q.active.source == a.source))\n ? setTimeout(() => this.startUpdate(), 50) : -1;\n if (this.composing != 0 /* CompositionState.None */)\n for (let tr of update.transactions) {\n if (getUserEvent(tr) == \"input\")\n this.composing = 2 /* CompositionState.Changed */;\n else if (this.composing == 2 /* CompositionState.Changed */ && tr.selection)\n this.composing = 3 /* CompositionState.ChangedAndMoved */;\n }\n }\n startUpdate() {\n this.debounceUpdate = -1;\n let { state } = this.view, cState = state.field(completionState);\n for (let active of cState.active) {\n if (active.state == 1 /* State.Pending */ && !this.running.some(r => r.active.source == active.source))\n this.startQuery(active);\n }\n }\n startQuery(active) {\n let { state } = this.view, pos = cur(state);\n let context = new CompletionContext(state, pos, active.explicitPos == pos);\n let pending = new RunningQuery(active, context);\n this.running.push(pending);\n Promise.resolve(active.source(context)).then(result => {\n if (!pending.context.aborted) {\n pending.done = result || null;\n this.scheduleAccept();\n }\n }, err => {\n this.view.dispatch({ effects: closeCompletionEffect.of(null) });\n logException(this.view.state, err);\n });\n }\n scheduleAccept() {\n if (this.running.every(q => q.done !== undefined))\n this.accept();\n else if (this.debounceAccept < 0)\n this.debounceAccept = setTimeout(() => this.accept(), this.view.state.facet(completionConfig).updateSyncTime);\n }\n // For each finished query in this.running, try to create a result\n // or, if appropriate, restart the query.\n accept() {\n var _a;\n if (this.debounceAccept > -1)\n clearTimeout(this.debounceAccept);\n this.debounceAccept = -1;\n let updated = [];\n let conf = this.view.state.facet(completionConfig);\n for (let i = 0; i < this.running.length; i++) {\n let query = this.running[i];\n if (query.done === undefined)\n continue;\n this.running.splice(i--, 1);\n if (query.done) {\n let active = new ActiveResult(query.active.source, query.active.explicitPos, query.done, query.done.from, (_a = query.done.to) !== null && _a !== void 0 ? _a : cur(query.updates.length ? query.updates[0].startState : this.view.state));\n // Replay the transactions that happened since the start of\n // the request and see if that preserves the result\n for (let tr of query.updates)\n active = active.update(tr, conf);\n if (active.hasResult()) {\n updated.push(active);\n continue;\n }\n }\n let current = this.view.state.field(completionState).active.find(a => a.source == query.active.source);\n if (current && current.state == 1 /* State.Pending */) {\n if (query.done == null) {\n // Explicitly failed. Should clear the pending status if it\n // hasn't been re-set in the meantime.\n let active = new ActiveSource(query.active.source, 0 /* State.Inactive */);\n for (let tr of query.updates)\n active = active.update(tr, conf);\n if (active.state != 1 /* State.Pending */)\n updated.push(active);\n }\n else {\n // Cleared by subsequent transactions. Restart.\n this.startQuery(current);\n }\n }\n }\n if (updated.length)\n this.view.dispatch({ effects: setActiveEffect.of(updated) });\n }\n}, {\n eventHandlers: {\n blur(event) {\n let state = this.view.state.field(completionState, false);\n if (state && state.tooltip && this.view.state.facet(completionConfig).closeOnBlur) {\n let dialog = state.open && getTooltip(this.view, state.open.tooltip);\n if (!dialog || !dialog.dom.contains(event.relatedTarget))\n this.view.dispatch({ effects: closeCompletionEffect.of(null) });\n }\n },\n compositionstart() {\n this.composing = 1 /* CompositionState.Started */;\n },\n compositionend() {\n if (this.composing == 3 /* CompositionState.ChangedAndMoved */) {\n // Safari fires compositionend events synchronously, possibly\n // from inside an update, so dispatch asynchronously to avoid reentrancy\n setTimeout(() => this.view.dispatch({ effects: startCompletionEffect.of(false) }), 20);\n }\n this.composing = 0 /* CompositionState.None */;\n }\n }\n});\n\nconst baseTheme = /*@__PURE__*/EditorView.baseTheme({\n \".cm-tooltip.cm-tooltip-autocomplete\": {\n \"& > ul\": {\n fontFamily: \"monospace\",\n whiteSpace: \"nowrap\",\n overflow: \"hidden auto\",\n maxWidth_fallback: \"700px\",\n maxWidth: \"min(700px, 95vw)\",\n minWidth: \"250px\",\n maxHeight: \"10em\",\n height: \"100%\",\n listStyle: \"none\",\n margin: 0,\n padding: 0,\n \"& > li, & > completion-section\": {\n padding: \"1px 3px\",\n lineHeight: 1.2\n },\n \"& > li\": {\n overflowX: \"hidden\",\n textOverflow: \"ellipsis\",\n cursor: \"pointer\"\n },\n \"& > completion-section\": {\n display: \"list-item\",\n borderBottom: \"1px solid silver\",\n paddingLeft: \"0.5em\",\n opacity: 0.7\n }\n }\n },\n \"&light .cm-tooltip-autocomplete ul li[aria-selected]\": {\n background: \"#17c\",\n color: \"white\",\n },\n \"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]\": {\n background: \"#777\",\n },\n \"&dark .cm-tooltip-autocomplete ul li[aria-selected]\": {\n background: \"#347\",\n color: \"white\",\n },\n \"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]\": {\n background: \"#444\",\n },\n \".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after\": {\n content: '\"···\"',\n opacity: 0.5,\n display: \"block\",\n textAlign: \"center\"\n },\n \".cm-tooltip.cm-completionInfo\": {\n position: \"absolute\",\n padding: \"3px 9px\",\n width: \"max-content\",\n maxWidth: `${400 /* Info.Width */}px`,\n boxSizing: \"border-box\"\n },\n \".cm-completionInfo.cm-completionInfo-left\": { right: \"100%\" },\n \".cm-completionInfo.cm-completionInfo-right\": { left: \"100%\" },\n \".cm-completionInfo.cm-completionInfo-left-narrow\": { right: `${30 /* Info.Margin */}px` },\n \".cm-completionInfo.cm-completionInfo-right-narrow\": { left: `${30 /* Info.Margin */}px` },\n \"&light .cm-snippetField\": { backgroundColor: \"#00000022\" },\n \"&dark .cm-snippetField\": { backgroundColor: \"#ffffff22\" },\n \".cm-snippetFieldPosition\": {\n verticalAlign: \"text-top\",\n width: 0,\n height: \"1.15em\",\n display: \"inline-block\",\n margin: \"0 -0.7px -.7em\",\n borderLeft: \"1.4px dotted #888\"\n },\n \".cm-completionMatchedText\": {\n textDecoration: \"underline\"\n },\n \".cm-completionDetail\": {\n marginLeft: \"0.5em\",\n fontStyle: \"italic\"\n },\n \".cm-completionIcon\": {\n fontSize: \"90%\",\n width: \".8em\",\n display: \"inline-block\",\n textAlign: \"center\",\n paddingRight: \".6em\",\n opacity: \"0.6\",\n boxSizing: \"content-box\"\n },\n \".cm-completionIcon-function, .cm-completionIcon-method\": {\n \"&:after\": { content: \"'ƒ'\" }\n },\n \".cm-completionIcon-class\": {\n \"&:after\": { content: \"'○'\" }\n },\n \".cm-completionIcon-interface\": {\n \"&:after\": { content: \"'◌'\" }\n },\n \".cm-completionIcon-variable\": {\n \"&:after\": { content: \"'𝑥'\" }\n },\n \".cm-completionIcon-constant\": {\n \"&:after\": { content: \"'𝐶'\" }\n },\n \".cm-completionIcon-type\": {\n \"&:after\": { content: \"'𝑡'\" }\n },\n \".cm-completionIcon-enum\": {\n \"&:after\": { content: \"'∪'\" }\n },\n \".cm-completionIcon-property\": {\n \"&:after\": { content: \"'□'\" }\n },\n \".cm-completionIcon-keyword\": {\n \"&:after\": { content: \"'🔑\\uFE0E'\" } // Disable emoji rendering\n },\n \".cm-completionIcon-namespace\": {\n \"&:after\": { content: \"'▢'\" }\n },\n \".cm-completionIcon-text\": {\n \"&:after\": { content: \"'abc'\", fontSize: \"50%\", verticalAlign: \"middle\" }\n }\n});\n\nclass FieldPos {\n constructor(field, line, from, to) {\n this.field = field;\n this.line = line;\n this.from = from;\n this.to = to;\n }\n}\nclass FieldRange {\n constructor(field, from, to) {\n this.field = field;\n this.from = from;\n this.to = to;\n }\n map(changes) {\n let from = changes.mapPos(this.from, -1, MapMode.TrackDel);\n let to = changes.mapPos(this.to, 1, MapMode.TrackDel);\n return from == null || to == null ? null : new FieldRange(this.field, from, to);\n }\n}\nclass Snippet {\n constructor(lines, fieldPositions) {\n this.lines = lines;\n this.fieldPositions = fieldPositions;\n }\n instantiate(state, pos) {\n let text = [], lineStart = [pos];\n let lineObj = state.doc.lineAt(pos), baseIndent = /^\\s*/.exec(lineObj.text)[0];\n for (let line of this.lines) {\n if (text.length) {\n let indent = baseIndent, tabs = /^\\t*/.exec(line)[0].length;\n for (let i = 0; i < tabs; i++)\n indent += state.facet(indentUnit);\n lineStart.push(pos + indent.length - tabs);\n line = indent + line.slice(tabs);\n }\n text.push(line);\n pos += line.length + 1;\n }\n let ranges = this.fieldPositions.map(pos => new FieldRange(pos.field, lineStart[pos.line] + pos.from, lineStart[pos.line] + pos.to));\n return { text, ranges };\n }\n static parse(template) {\n let fields = [];\n let lines = [], positions = [], m;\n for (let line of template.split(/\\r\\n?|\\n/)) {\n while (m = /[#$]\\{(?:(\\d+)(?::([^}]*))?|([^}]*))\\}/.exec(line)) {\n let seq = m[1] ? +m[1] : null, name = m[2] || m[3] || \"\", found = -1;\n for (let i = 0; i < fields.length; i++) {\n if (seq != null ? fields[i].seq == seq : name ? fields[i].name == name : false)\n found = i;\n }\n if (found < 0) {\n let i = 0;\n while (i < fields.length && (seq == null || (fields[i].seq != null && fields[i].seq < seq)))\n i++;\n fields.splice(i, 0, { seq, name });\n found = i;\n for (let pos of positions)\n if (pos.field >= found)\n pos.field++;\n }\n positions.push(new FieldPos(found, lines.length, m.index, m.index + name.length));\n line = line.slice(0, m.index) + name + line.slice(m.index + m[0].length);\n }\n for (let esc; esc = /\\\\([{}])/.exec(line);) {\n line = line.slice(0, esc.index) + esc[1] + line.slice(esc.index + esc[0].length);\n for (let pos of positions)\n if (pos.line == lines.length && pos.from > esc.index) {\n pos.from--;\n pos.to--;\n }\n }\n lines.push(line);\n }\n return new Snippet(lines, positions);\n }\n}\nlet fieldMarker = /*@__PURE__*/Decoration.widget({ widget: /*@__PURE__*/new class extends WidgetType {\n toDOM() {\n let span = document.createElement(\"span\");\n span.className = \"cm-snippetFieldPosition\";\n return span;\n }\n ignoreEvent() { return false; }\n } });\nlet fieldRange = /*@__PURE__*/Decoration.mark({ class: \"cm-snippetField\" });\nclass ActiveSnippet {\n constructor(ranges, active) {\n this.ranges = ranges;\n this.active = active;\n this.deco = Decoration.set(ranges.map(r => (r.from == r.to ? fieldMarker : fieldRange).range(r.from, r.to)));\n }\n map(changes) {\n let ranges = [];\n for (let r of this.ranges) {\n let mapped = r.map(changes);\n if (!mapped)\n return null;\n ranges.push(mapped);\n }\n return new ActiveSnippet(ranges, this.active);\n }\n selectionInsideField(sel) {\n return sel.ranges.every(range => this.ranges.some(r => r.field == this.active && r.from <= range.from && r.to >= range.to));\n }\n}\nconst setActive = /*@__PURE__*/StateEffect.define({\n map(value, changes) { return value && value.map(changes); }\n});\nconst moveToField = /*@__PURE__*/StateEffect.define();\nconst snippetState = /*@__PURE__*/StateField.define({\n create() { return null; },\n update(value, tr) {\n for (let effect of tr.effects) {\n if (effect.is(setActive))\n return effect.value;\n if (effect.is(moveToField) && value)\n return new ActiveSnippet(value.ranges, effect.value);\n }\n if (value && tr.docChanged)\n value = value.map(tr.changes);\n if (value && tr.selection && !value.selectionInsideField(tr.selection))\n value = null;\n return value;\n },\n provide: f => EditorView.decorations.from(f, val => val ? val.deco : Decoration.none)\n});\nfunction fieldSelection(ranges, field) {\n return EditorSelection.create(ranges.filter(r => r.field == field).map(r => EditorSelection.range(r.from, r.to)));\n}\n/**\nConvert a snippet template to a function that can\n[apply](https://codemirror.net/6/docs/ref/#autocomplete.Completion.apply) it. Snippets are written\nusing syntax like this:\n\n \"for (let ${index} = 0; ${index} < ${end}; ${index}++) {\\n\\t${}\\n}\"\n\nEach `${}` placeholder (you may also use `#{}`) indicates a field\nthat the user can fill in. Its name, if any, will be the default\ncontent for the field.\n\nWhen the snippet is activated by calling the returned function,\nthe code is inserted at the given position. Newlines in the\ntemplate are indented by the indentation of the start line, plus\none [indent unit](https://codemirror.net/6/docs/ref/#language.indentUnit) per tab character after\nthe newline.\n\nOn activation, (all instances of) the first field are selected.\nThe user can move between fields with Tab and Shift-Tab as long as\nthe fields are active. Moving to the last field or moving the\ncursor out of the current field deactivates the fields.\n\nThe order of fields defaults to textual order, but you can add\nnumbers to placeholders (`${1}` or `${1:defaultText}`) to provide\na custom order.\n\nTo include a literal `{` or `}` in your template, put a backslash\nin front of it. This will be removed and the brace will not be\ninterpreted as indicating a placeholder.\n*/\nfunction snippet(template) {\n let snippet = Snippet.parse(template);\n return (editor, completion, from, to) => {\n let { text, ranges } = snippet.instantiate(editor.state, from);\n let spec = {\n changes: { from, to, insert: Text.of(text) },\n scrollIntoView: true,\n annotations: completion ? pickedCompletion.of(completion) : undefined\n };\n if (ranges.length)\n spec.selection = fieldSelection(ranges, 0);\n if (ranges.length > 1) {\n let active = new ActiveSnippet(ranges, 0);\n let effects = spec.effects = [setActive.of(active)];\n if (editor.state.field(snippetState, false) === undefined)\n effects.push(StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme]));\n }\n editor.dispatch(editor.state.update(spec));\n };\n}\nfunction moveField(dir) {\n return ({ state, dispatch }) => {\n let active = state.field(snippetState, false);\n if (!active || dir < 0 && active.active == 0)\n return false;\n let next = active.active + dir, last = dir > 0 && !active.ranges.some(r => r.field == next + dir);\n dispatch(state.update({\n selection: fieldSelection(active.ranges, next),\n effects: setActive.of(last ? null : new ActiveSnippet(active.ranges, next)),\n scrollIntoView: true\n }));\n return true;\n };\n}\n/**\nA command that clears the active snippet, if any.\n*/\nconst clearSnippet = ({ state, dispatch }) => {\n let active = state.field(snippetState, false);\n if (!active)\n return false;\n dispatch(state.update({ effects: setActive.of(null) }));\n return true;\n};\n/**\nMove to the next snippet field, if available.\n*/\nconst nextSnippetField = /*@__PURE__*/moveField(1);\n/**\nMove to the previous snippet field, if available.\n*/\nconst prevSnippetField = /*@__PURE__*/moveField(-1);\n/**\nCheck if there is an active snippet with a next field for\n`nextSnippetField` to move to.\n*/\nfunction hasNextSnippetField(state) {\n let active = state.field(snippetState, false);\n return !!(active && active.ranges.some(r => r.field == active.active + 1));\n}\n/**\nReturns true if there is an active snippet and a previous field\nfor `prevSnippetField` to move to.\n*/\nfunction hasPrevSnippetField(state) {\n let active = state.field(snippetState, false);\n return !!(active && active.active > 0);\n}\nconst defaultSnippetKeymap = [\n { key: \"Tab\", run: nextSnippetField, shift: prevSnippetField },\n { key: \"Escape\", run: clearSnippet }\n];\n/**\nA facet that can be used to configure the key bindings used by\nsnippets. The default binds Tab to\n[`nextSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.nextSnippetField), Shift-Tab to\n[`prevSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.prevSnippetField), and Escape\nto [`clearSnippet`](https://codemirror.net/6/docs/ref/#autocomplete.clearSnippet).\n*/\nconst snippetKeymap = /*@__PURE__*/Facet.define({\n combine(maps) { return maps.length ? maps[0] : defaultSnippetKeymap; }\n});\nconst addSnippetKeymap = /*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.compute([snippetKeymap], state => state.facet(snippetKeymap)));\n/**\nCreate a completion from a snippet. Returns an object with the\nproperties from `completion`, plus an `apply` function that\napplies the snippet.\n*/\nfunction snippetCompletion(template, completion) {\n return Object.assign(Object.assign({}, completion), { apply: snippet(template) });\n}\nconst snippetPointerHandler = /*@__PURE__*/EditorView.domEventHandlers({\n mousedown(event, view) {\n let active = view.state.field(snippetState, false), pos;\n if (!active || (pos = view.posAtCoords({ x: event.clientX, y: event.clientY })) == null)\n return false;\n let match = active.ranges.find(r => r.from <= pos && r.to >= pos);\n if (!match || match.field == active.active)\n return false;\n view.dispatch({\n selection: fieldSelection(active.ranges, match.field),\n effects: setActive.of(active.ranges.some(r => r.field > match.field)\n ? new ActiveSnippet(active.ranges, match.field) : null),\n scrollIntoView: true\n });\n return true;\n }\n});\n\nfunction wordRE(wordChars) {\n let escaped = wordChars.replace(/[\\]\\-\\\\]/g, \"\\\\$&\");\n try {\n return new RegExp(`[\\\\p{Alphabetic}\\\\p{Number}_${escaped}]+`, \"ug\");\n }\n catch (_a) {\n return new RegExp(`[\\w${escaped}]`, \"g\");\n }\n}\nfunction mapRE(re, f) {\n return new RegExp(f(re.source), re.unicode ? \"u\" : \"\");\n}\nconst wordCaches = /*@__PURE__*/Object.create(null);\nfunction wordCache(wordChars) {\n return wordCaches[wordChars] || (wordCaches[wordChars] = new WeakMap);\n}\nfunction storeWords(doc, wordRE, result, seen, ignoreAt) {\n for (let lines = doc.iterLines(), pos = 0; !lines.next().done;) {\n let { value } = lines, m;\n wordRE.lastIndex = 0;\n while (m = wordRE.exec(value)) {\n if (!seen[m[0]] && pos + m.index != ignoreAt) {\n result.push({ type: \"text\", label: m[0] });\n seen[m[0]] = true;\n if (result.length >= 2000 /* C.MaxList */)\n return;\n }\n }\n pos += value.length + 1;\n }\n}\nfunction collectWords(doc, cache, wordRE, to, ignoreAt) {\n let big = doc.length >= 1000 /* C.MinCacheLen */;\n let cached = big && cache.get(doc);\n if (cached)\n return cached;\n let result = [], seen = Object.create(null);\n if (doc.children) {\n let pos = 0;\n for (let ch of doc.children) {\n if (ch.length >= 1000 /* C.MinCacheLen */) {\n for (let c of collectWords(ch, cache, wordRE, to - pos, ignoreAt - pos)) {\n if (!seen[c.label]) {\n seen[c.label] = true;\n result.push(c);\n }\n }\n }\n else {\n storeWords(ch, wordRE, result, seen, ignoreAt - pos);\n }\n pos += ch.length + 1;\n }\n }\n else {\n storeWords(doc, wordRE, result, seen, ignoreAt);\n }\n if (big && result.length < 2000 /* C.MaxList */)\n cache.set(doc, result);\n return result;\n}\n/**\nA completion source that will scan the document for words (using a\n[character categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer)), and\nreturn those as completions.\n*/\nconst completeAnyWord = context => {\n let wordChars = context.state.languageDataAt(\"wordChars\", context.pos).join(\"\");\n let re = wordRE(wordChars);\n let token = context.matchBefore(mapRE(re, s => s + \"$\"));\n if (!token && !context.explicit)\n return null;\n let from = token ? token.from : context.pos;\n let options = collectWords(context.state.doc, wordCache(wordChars), re, 50000 /* C.Range */, from);\n return { from, options, validFor: mapRE(re, s => \"^\" + s) };\n};\n\nconst defaults = {\n brackets: [\"(\", \"[\", \"{\", \"'\", '\"'],\n before: \")]}:;>\",\n stringPrefixes: []\n};\nconst closeBracketEffect = /*@__PURE__*/StateEffect.define({\n map(value, mapping) {\n let mapped = mapping.mapPos(value, -1, MapMode.TrackAfter);\n return mapped == null ? undefined : mapped;\n }\n});\nconst closedBracket = /*@__PURE__*/new class extends RangeValue {\n};\nclosedBracket.startSide = 1;\nclosedBracket.endSide = -1;\nconst bracketState = /*@__PURE__*/StateField.define({\n create() { return RangeSet.empty; },\n update(value, tr) {\n if (tr.selection) {\n let line = tr.state.doc.lineAt(tr.selection.main.head);\n value = value.update({ filter: from => from >= line.from && from <= line.to });\n }\n value = value.map(tr.changes);\n for (let effect of tr.effects)\n if (effect.is(closeBracketEffect))\n value = value.update({ add: [closedBracket.range(effect.value, effect.value + 1)] });\n return value;\n }\n});\n/**\nExtension to enable bracket-closing behavior. When a closeable\nbracket is typed, its closing bracket is immediately inserted\nafter the cursor. When closing a bracket directly in front of a\nclosing bracket inserted by the extension, the cursor moves over\nthat bracket.\n*/\nfunction closeBrackets() {\n return [inputHandler, bracketState];\n}\nconst definedClosing = \"()[]{}<>\";\nfunction closing(ch) {\n for (let i = 0; i < definedClosing.length; i += 2)\n if (definedClosing.charCodeAt(i) == ch)\n return definedClosing.charAt(i + 1);\n return fromCodePoint(ch < 128 ? ch : ch + 1);\n}\nfunction config(state, pos) {\n return state.languageDataAt(\"closeBrackets\", pos)[0] || defaults;\n}\nconst android = typeof navigator == \"object\" && /*@__PURE__*//Android\\b/.test(navigator.userAgent);\nconst inputHandler = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, insert) => {\n if ((android ? view.composing : view.compositionStarted) || view.state.readOnly)\n return false;\n let sel = view.state.selection.main;\n if (insert.length > 2 || insert.length == 2 && codePointSize(codePointAt(insert, 0)) == 1 ||\n from != sel.from || to != sel.to)\n return false;\n let tr = insertBracket(view.state, insert);\n if (!tr)\n return false;\n view.dispatch(tr);\n return true;\n});\n/**\nCommand that implements deleting a pair of matching brackets when\nthe cursor is between them.\n*/\nconst deleteBracketPair = ({ state, dispatch }) => {\n if (state.readOnly)\n return false;\n let conf = config(state, state.selection.main.head);\n let tokens = conf.brackets || defaults.brackets;\n let dont = null, changes = state.changeByRange(range => {\n if (range.empty) {\n let before = prevChar(state.doc, range.head);\n for (let token of tokens) {\n if (token == before && nextChar(state.doc, range.head) == closing(codePointAt(token, 0)))\n return { changes: { from: range.head - token.length, to: range.head + token.length },\n range: EditorSelection.cursor(range.head - token.length) };\n }\n }\n return { range: dont = range };\n });\n if (!dont)\n dispatch(state.update(changes, { scrollIntoView: true, userEvent: \"delete.backward\" }));\n return !dont;\n};\n/**\nClose-brackets related key bindings. Binds Backspace to\n[`deleteBracketPair`](https://codemirror.net/6/docs/ref/#autocomplete.deleteBracketPair).\n*/\nconst closeBracketsKeymap = [\n { key: \"Backspace\", run: deleteBracketPair }\n];\n/**\nImplements the extension's behavior on text insertion. If the\ngiven string counts as a bracket in the language around the\nselection, and replacing the selection with it requires custom\nbehavior (inserting a closing version or skipping past a\npreviously-closed bracket), this function returns a transaction\nrepresenting that custom behavior. (You only need this if you want\nto programmatically insert brackets—the\n[`closeBrackets`](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) extension will\ntake care of running this for user input.)\n*/\nfunction insertBracket(state, bracket) {\n let conf = config(state, state.selection.main.head);\n let tokens = conf.brackets || defaults.brackets;\n for (let tok of tokens) {\n let closed = closing(codePointAt(tok, 0));\n if (bracket == tok)\n return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1, conf)\n : handleOpen(state, tok, closed, conf.before || defaults.before);\n if (bracket == closed && closedBracketAt(state, state.selection.main.from))\n return handleClose(state, tok, closed);\n }\n return null;\n}\nfunction closedBracketAt(state, pos) {\n let found = false;\n state.field(bracketState).between(0, state.doc.length, from => {\n if (from == pos)\n found = true;\n });\n return found;\n}\nfunction nextChar(doc, pos) {\n let next = doc.sliceString(pos, pos + 2);\n return next.slice(0, codePointSize(codePointAt(next, 0)));\n}\nfunction prevChar(doc, pos) {\n let prev = doc.sliceString(pos - 2, pos);\n return codePointSize(codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1);\n}\nfunction handleOpen(state, open, close, closeBefore) {\n let dont = null, changes = state.changeByRange(range => {\n if (!range.empty)\n return { changes: [{ insert: open, from: range.from }, { insert: close, from: range.to }],\n effects: closeBracketEffect.of(range.to + open.length),\n range: EditorSelection.range(range.anchor + open.length, range.head + open.length) };\n let next = nextChar(state.doc, range.head);\n if (!next || /\\s/.test(next) || closeBefore.indexOf(next) > -1)\n return { changes: { insert: open + close, from: range.head },\n effects: closeBracketEffect.of(range.head + open.length),\n range: EditorSelection.cursor(range.head + open.length) };\n return { range: dont = range };\n });\n return dont ? null : state.update(changes, {\n scrollIntoView: true,\n userEvent: \"input.type\"\n });\n}\nfunction handleClose(state, _open, close) {\n let dont = null, changes = state.changeByRange(range => {\n if (range.empty && nextChar(state.doc, range.head) == close)\n return { changes: { from: range.head, to: range.head + close.length, insert: close },\n range: EditorSelection.cursor(range.head + close.length) };\n return dont = { range };\n });\n return dont ? null : state.update(changes, {\n scrollIntoView: true,\n userEvent: \"input.type\"\n });\n}\n// Handles cases where the open and close token are the same, and\n// possibly triple quotes (as in `\"\"\"abc\"\"\"`-style quoting).\nfunction handleSame(state, token, allowTriple, config) {\n let stringPrefixes = config.stringPrefixes || defaults.stringPrefixes;\n let dont = null, changes = state.changeByRange(range => {\n if (!range.empty)\n return { changes: [{ insert: token, from: range.from }, { insert: token, from: range.to }],\n effects: closeBracketEffect.of(range.to + token.length),\n range: EditorSelection.range(range.anchor + token.length, range.head + token.length) };\n let pos = range.head, next = nextChar(state.doc, pos), start;\n if (next == token) {\n if (nodeStart(state, pos)) {\n return { changes: { insert: token + token, from: pos },\n effects: closeBracketEffect.of(pos + token.length),\n range: EditorSelection.cursor(pos + token.length) };\n }\n else if (closedBracketAt(state, pos)) {\n let isTriple = allowTriple && state.sliceDoc(pos, pos + token.length * 3) == token + token + token;\n let content = isTriple ? token + token + token : token;\n return { changes: { from: pos, to: pos + content.length, insert: content },\n range: EditorSelection.cursor(pos + content.length) };\n }\n }\n else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token &&\n (start = canStartStringAt(state, pos - 2 * token.length, stringPrefixes)) > -1 &&\n nodeStart(state, start)) {\n return { changes: { insert: token + token + token + token, from: pos },\n effects: closeBracketEffect.of(pos + token.length),\n range: EditorSelection.cursor(pos + token.length) };\n }\n else if (state.charCategorizer(pos)(next) != CharCategory.Word) {\n if (canStartStringAt(state, pos, stringPrefixes) > -1 && !probablyInString(state, pos, token, stringPrefixes))\n return { changes: { insert: token + token, from: pos },\n effects: closeBracketEffect.of(pos + token.length),\n range: EditorSelection.cursor(pos + token.length) };\n }\n return { range: dont = range };\n });\n return dont ? null : state.update(changes, {\n scrollIntoView: true,\n userEvent: \"input.type\"\n });\n}\nfunction nodeStart(state, pos) {\n let tree = syntaxTree(state).resolveInner(pos + 1);\n return tree.parent && tree.from == pos;\n}\nfunction probablyInString(state, pos, quoteToken, prefixes) {\n let node = syntaxTree(state).resolveInner(pos, -1);\n let maxPrefix = prefixes.reduce((m, p) => Math.max(m, p.length), 0);\n for (let i = 0; i < 5; i++) {\n let start = state.sliceDoc(node.from, Math.min(node.to, node.from + quoteToken.length + maxPrefix));\n let quotePos = start.indexOf(quoteToken);\n if (!quotePos || quotePos > -1 && prefixes.indexOf(start.slice(0, quotePos)) > -1) {\n let first = node.firstChild;\n while (first && first.from == node.from && first.to - first.from > quoteToken.length + quotePos) {\n if (state.sliceDoc(first.to - quoteToken.length, first.to) == quoteToken)\n return false;\n first = first.firstChild;\n }\n return true;\n }\n let parent = node.to == pos && node.parent;\n if (!parent)\n break;\n node = parent;\n }\n return false;\n}\nfunction canStartStringAt(state, pos, prefixes) {\n let charCat = state.charCategorizer(pos);\n if (charCat(state.sliceDoc(pos - 1, pos)) != CharCategory.Word)\n return pos;\n for (let prefix of prefixes) {\n let start = pos - prefix.length;\n if (state.sliceDoc(start, pos) == prefix && charCat(state.sliceDoc(start - 1, start)) != CharCategory.Word)\n return start;\n }\n return -1;\n}\n\n/**\nReturns an extension that enables autocompletion.\n*/\nfunction autocompletion(config = {}) {\n return [\n completionState,\n completionConfig.of(config),\n completionPlugin,\n completionKeymapExt,\n baseTheme\n ];\n}\n/**\nBasic keybindings for autocompletion.\n\n - Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)\n - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)\n - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`\n - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`\n - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, \"page\")`\n - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, \"page\")`\n - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)\n*/\nconst completionKeymap = [\n { key: \"Ctrl-Space\", run: startCompletion },\n { key: \"Escape\", run: closeCompletion },\n { key: \"ArrowDown\", run: /*@__PURE__*/moveCompletionSelection(true) },\n { key: \"ArrowUp\", run: /*@__PURE__*/moveCompletionSelection(false) },\n { key: \"PageDown\", run: /*@__PURE__*/moveCompletionSelection(true, \"page\") },\n { key: \"PageUp\", run: /*@__PURE__*/moveCompletionSelection(false, \"page\") },\n { key: \"Enter\", run: acceptCompletion }\n];\nconst completionKeymapExt = /*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.computeN([completionConfig], state => state.facet(completionConfig).defaultKeymap ? [completionKeymap] : []));\n/**\nGet the current completion status. When completions are available,\nthis will return `\"active\"`. When completions are pending (in the\nprocess of being queried), this returns `\"pending\"`. Otherwise, it\nreturns `null`.\n*/\nfunction completionStatus(state) {\n let cState = state.field(completionState, false);\n return cState && cState.active.some(a => a.state == 1 /* State.Pending */) ? \"pending\"\n : cState && cState.active.some(a => a.state != 0 /* State.Inactive */) ? \"active\" : null;\n}\nconst completionArrayCache = /*@__PURE__*/new WeakMap;\n/**\nReturns the available completions as an array.\n*/\nfunction currentCompletions(state) {\n var _a;\n let open = (_a = state.field(completionState, false)) === null || _a === void 0 ? void 0 : _a.open;\n if (!open || open.disabled)\n return [];\n let completions = completionArrayCache.get(open.options);\n if (!completions)\n completionArrayCache.set(open.options, completions = open.options.map(o => o.completion));\n return completions;\n}\n/**\nReturn the currently selected completion, if any.\n*/\nfunction selectedCompletion(state) {\n var _a;\n let open = (_a = state.field(completionState, false)) === null || _a === void 0 ? void 0 : _a.open;\n return open && !open.disabled && open.selected >= 0 ? open.options[open.selected].completion : null;\n}\n/**\nReturns the currently selected position in the active completion\nlist, or null if no completions are active.\n*/\nfunction selectedCompletionIndex(state) {\n var _a;\n let open = (_a = state.field(completionState, false)) === null || _a === void 0 ? void 0 : _a.open;\n return open && !open.disabled && open.selected >= 0 ? open.selected : null;\n}\n/**\nCreate an effect that can be attached to a transaction to change\nthe currently selected completion.\n*/\nfunction setSelectedCompletion(index) {\n return setSelectedEffect.of(index);\n}\n\nexport { CompletionContext, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, hasNextSnippetField, hasPrevSnippetField, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextSnippetField, pickedCompletion, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };\n","import { NodeProp, IterMode, Tree, TreeFragment, Parser, NodeType, NodeSet } from '@lezer/common';\nimport { StateEffect, StateField, Facet, EditorState, countColumn, combineConfig, RangeSet, RangeSetBuilder, Prec } from '@codemirror/state';\nimport { ViewPlugin, logException, EditorView, Decoration, WidgetType, gutter, GutterMarker } from '@codemirror/view';\nimport { tags, tagHighlighter, highlightTree, styleTags } from '@lezer/highlight';\nimport { StyleModule } from 'style-mod';\n\nvar _a;\n/**\nNode prop stored in a parser's top syntax node to provide the\nfacet that stores language-specific data for that language.\n*/\nconst languageDataProp = /*@__PURE__*/new NodeProp();\n/**\nHelper function to define a facet (to be added to the top syntax\nnode(s) for a language via\n[`languageDataProp`](https://codemirror.net/6/docs/ref/#language.languageDataProp)), that will be\nused to associate language data with the language. You\nprobably only need this when subclassing\n[`Language`](https://codemirror.net/6/docs/ref/#language.Language).\n*/\nfunction defineLanguageFacet(baseData) {\n return Facet.define({\n combine: baseData ? values => values.concat(baseData) : undefined\n });\n}\n/**\nSyntax node prop used to register sublanguages. Should be added to\nthe top level node type for the language.\n*/\nconst sublanguageProp = /*@__PURE__*/new NodeProp();\n/**\nA language object manages parsing and per-language\n[metadata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). Parse data is\nmanaged as a [Lezer](https://lezer.codemirror.net) tree. The class\ncan be used directly, via the [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage)\nsubclass for [Lezer](https://lezer.codemirror.net/) LR parsers, or\nvia the [`StreamLanguage`](https://codemirror.net/6/docs/ref/#language.StreamLanguage) subclass\nfor stream parsers.\n*/\nclass Language {\n /**\n Construct a language object. If you need to invoke this\n directly, first define a data facet with\n [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet), and then\n configure your parser to [attach](https://codemirror.net/6/docs/ref/#language.languageDataProp) it\n to the language's outer syntax node.\n */\n constructor(\n /**\n The [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) facet\n used for this language.\n */\n data, parser, extraExtensions = [], \n /**\n A language name.\n */\n name = \"\") {\n this.data = data;\n this.name = name;\n // Kludge to define EditorState.tree as a debugging helper,\n // without the EditorState package actually knowing about\n // languages and lezer trees.\n if (!EditorState.prototype.hasOwnProperty(\"tree\"))\n Object.defineProperty(EditorState.prototype, \"tree\", { get() { return syntaxTree(this); } });\n this.parser = parser;\n this.extension = [\n language.of(this),\n EditorState.languageData.of((state, pos, side) => {\n let top = topNodeAt(state, pos, side), data = top.type.prop(languageDataProp);\n if (!data)\n return [];\n let base = state.facet(data), sub = top.type.prop(sublanguageProp);\n if (sub) {\n let innerNode = top.resolve(pos - top.from, side);\n for (let sublang of sub)\n if (sublang.test(innerNode, state)) {\n let data = state.facet(sublang.facet);\n return sublang.type == \"replace\" ? data : data.concat(base);\n }\n }\n return base;\n })\n ].concat(extraExtensions);\n }\n /**\n Query whether this language is active at the given position.\n */\n isActiveAt(state, pos, side = -1) {\n return topNodeAt(state, pos, side).type.prop(languageDataProp) == this.data;\n }\n /**\n Find the document regions that were parsed using this language.\n The returned regions will _include_ any nested languages rooted\n in this language, when those exist.\n */\n findRegions(state) {\n let lang = state.facet(language);\n if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data)\n return [{ from: 0, to: state.doc.length }];\n if (!lang || !lang.allowsNesting)\n return [];\n let result = [];\n let explore = (tree, from) => {\n if (tree.prop(languageDataProp) == this.data) {\n result.push({ from, to: from + tree.length });\n return;\n }\n let mount = tree.prop(NodeProp.mounted);\n if (mount) {\n if (mount.tree.prop(languageDataProp) == this.data) {\n if (mount.overlay)\n for (let r of mount.overlay)\n result.push({ from: r.from + from, to: r.to + from });\n else\n result.push({ from: from, to: from + tree.length });\n return;\n }\n else if (mount.overlay) {\n let size = result.length;\n explore(mount.tree, mount.overlay[0].from + from);\n if (result.length > size)\n return;\n }\n }\n for (let i = 0; i < tree.children.length; i++) {\n let ch = tree.children[i];\n if (ch instanceof Tree)\n explore(ch, tree.positions[i] + from);\n }\n };\n explore(syntaxTree(state), 0);\n return result;\n }\n /**\n Indicates whether this language allows nested languages. The\n default implementation returns true.\n */\n get allowsNesting() { return true; }\n}\n/**\n@internal\n*/\nLanguage.setState = /*@__PURE__*/StateEffect.define();\nfunction topNodeAt(state, pos, side) {\n let topLang = state.facet(language), tree = syntaxTree(state).topNode;\n if (!topLang || topLang.allowsNesting) {\n for (let node = tree; node; node = node.enter(pos, side, IterMode.ExcludeBuffers))\n if (node.type.isTop)\n tree = node;\n }\n return tree;\n}\n/**\nA subclass of [`Language`](https://codemirror.net/6/docs/ref/#language.Language) for use with Lezer\n[LR parsers](https://lezer.codemirror.net/docs/ref#lr.LRParser)\nparsers.\n*/\nclass LRLanguage extends Language {\n constructor(data, parser, name) {\n super(data, parser, [], name);\n this.parser = parser;\n }\n /**\n Define a language from a parser.\n */\n static define(spec) {\n let data = defineLanguageFacet(spec.languageData);\n return new LRLanguage(data, spec.parser.configure({\n props: [languageDataProp.add(type => type.isTop ? data : undefined)]\n }), spec.name);\n }\n /**\n Create a new instance of this language with a reconfigured\n version of its parser and optionally a new name.\n */\n configure(options, name) {\n return new LRLanguage(this.data, this.parser.configure(options), name || this.name);\n }\n get allowsNesting() { return this.parser.hasWrappers(); }\n}\n/**\nGet the syntax tree for a state, which is the current (possibly\nincomplete) parse tree of the active\n[language](https://codemirror.net/6/docs/ref/#language.Language), or the empty tree if there is no\nlanguage available.\n*/\nfunction syntaxTree(state) {\n let field = state.field(Language.state, false);\n return field ? field.tree : Tree.empty;\n}\n/**\nTry to get a parse tree that spans at least up to `upto`. The\nmethod will do at most `timeout` milliseconds of work to parse\nup to that point if the tree isn't already available.\n*/\nfunction ensureSyntaxTree(state, upto, timeout = 50) {\n var _a;\n let parse = (_a = state.field(Language.state, false)) === null || _a === void 0 ? void 0 : _a.context;\n if (!parse)\n return null;\n let oldVieport = parse.viewport;\n parse.updateViewport({ from: 0, to: upto });\n let result = parse.isDone(upto) || parse.work(timeout, upto) ? parse.tree : null;\n parse.updateViewport(oldVieport);\n return result;\n}\n/**\nQueries whether there is a full syntax tree available up to the\ngiven document position. If there isn't, the background parse\nprocess _might_ still be working and update the tree further, but\nthere is no guarantee of that—the parser will [stop\nworking](https://codemirror.net/6/docs/ref/#language.syntaxParserRunning) when it has spent a\ncertain amount of time or has moved beyond the visible viewport.\nAlways returns false if no language has been enabled.\n*/\nfunction syntaxTreeAvailable(state, upto = state.doc.length) {\n var _a;\n return ((_a = state.field(Language.state, false)) === null || _a === void 0 ? void 0 : _a.context.isDone(upto)) || false;\n}\n/**\nMove parsing forward, and update the editor state afterwards to\nreflect the new tree. Will work for at most `timeout`\nmilliseconds. Returns true if the parser managed get to the given\nposition in that time.\n*/\nfunction forceParsing(view, upto = view.viewport.to, timeout = 100) {\n let success = ensureSyntaxTree(view.state, upto, timeout);\n if (success != syntaxTree(view.state))\n view.dispatch({});\n return !!success;\n}\n/**\nTells you whether the language parser is planning to do more\nparsing work (in a `requestIdleCallback` pseudo-thread) or has\nstopped running, either because it parsed the entire document,\nbecause it spent too much time and was cut off, or because there\nis no language parser enabled.\n*/\nfunction syntaxParserRunning(view) {\n var _a;\n return ((_a = view.plugin(parseWorker)) === null || _a === void 0 ? void 0 : _a.isWorking()) || false;\n}\n/**\nLezer-style\n[`Input`](https://lezer.codemirror.net/docs/ref#common.Input)\nobject for a [`Text`](https://codemirror.net/6/docs/ref/#state.Text) object.\n*/\nclass DocInput {\n /**\n Create an input object for the given document.\n */\n constructor(doc) {\n this.doc = doc;\n this.cursorPos = 0;\n this.string = \"\";\n this.cursor = doc.iter();\n }\n get length() { return this.doc.length; }\n syncTo(pos) {\n this.string = this.cursor.next(pos - this.cursorPos).value;\n this.cursorPos = pos + this.string.length;\n return this.cursorPos - this.string.length;\n }\n chunk(pos) {\n this.syncTo(pos);\n return this.string;\n }\n get lineChunks() { return true; }\n read(from, to) {\n let stringStart = this.cursorPos - this.string.length;\n if (from < stringStart || to >= this.cursorPos)\n return this.doc.sliceString(from, to);\n else\n return this.string.slice(from - stringStart, to - stringStart);\n }\n}\nlet currentContext = null;\n/**\nA parse context provided to parsers working on the editor content.\n*/\nclass ParseContext {\n constructor(parser, \n /**\n The current editor state.\n */\n state, \n /**\n Tree fragments that can be reused by incremental re-parses.\n */\n fragments = [], \n /**\n @internal\n */\n tree, \n /**\n @internal\n */\n treeLen, \n /**\n The current editor viewport (or some overapproximation\n thereof). Intended to be used for opportunistically avoiding\n work (in which case\n [`skipUntilInView`](https://codemirror.net/6/docs/ref/#language.ParseContext.skipUntilInView)\n should be called to make sure the parser is restarted when the\n skipped region becomes visible).\n */\n viewport, \n /**\n @internal\n */\n skipped, \n /**\n This is where skipping parsers can register a promise that,\n when resolved, will schedule a new parse. It is cleared when\n the parse worker picks up the promise. @internal\n */\n scheduleOn) {\n this.parser = parser;\n this.state = state;\n this.fragments = fragments;\n this.tree = tree;\n this.treeLen = treeLen;\n this.viewport = viewport;\n this.skipped = skipped;\n this.scheduleOn = scheduleOn;\n this.parse = null;\n /**\n @internal\n */\n this.tempSkipped = [];\n }\n /**\n @internal\n */\n static create(parser, state, viewport) {\n return new ParseContext(parser, state, [], Tree.empty, 0, viewport, [], null);\n }\n startParse() {\n return this.parser.startParse(new DocInput(this.state.doc), this.fragments);\n }\n /**\n @internal\n */\n work(until, upto) {\n if (upto != null && upto >= this.state.doc.length)\n upto = undefined;\n if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) {\n this.takeTree();\n return true;\n }\n return this.withContext(() => {\n var _a;\n if (typeof until == \"number\") {\n let endTime = Date.now() + until;\n until = () => Date.now() > endTime;\n }\n if (!this.parse)\n this.parse = this.startParse();\n if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) &&\n upto < this.state.doc.length)\n this.parse.stopAt(upto);\n for (;;) {\n let done = this.parse.advance();\n if (done) {\n this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null));\n this.treeLen = (_a = this.parse.stoppedAt) !== null && _a !== void 0 ? _a : this.state.doc.length;\n this.tree = done;\n this.parse = null;\n if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length))\n this.parse = this.startParse();\n else\n return true;\n }\n if (until())\n return false;\n }\n });\n }\n /**\n @internal\n */\n takeTree() {\n let pos, tree;\n if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) {\n if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos)\n this.parse.stopAt(pos);\n this.withContext(() => { while (!(tree = this.parse.advance())) { } });\n this.treeLen = pos;\n this.tree = tree;\n this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true));\n this.parse = null;\n }\n }\n withContext(f) {\n let prev = currentContext;\n currentContext = this;\n try {\n return f();\n }\n finally {\n currentContext = prev;\n }\n }\n withoutTempSkipped(fragments) {\n for (let r; r = this.tempSkipped.pop();)\n fragments = cutFragments(fragments, r.from, r.to);\n return fragments;\n }\n /**\n @internal\n */\n changes(changes, newState) {\n let { fragments, tree, treeLen, viewport, skipped } = this;\n this.takeTree();\n if (!changes.empty) {\n let ranges = [];\n changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB }));\n fragments = TreeFragment.applyChanges(fragments, ranges);\n tree = Tree.empty;\n treeLen = 0;\n viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) };\n if (this.skipped.length) {\n skipped = [];\n for (let r of this.skipped) {\n let from = changes.mapPos(r.from, 1), to = changes.mapPos(r.to, -1);\n if (from < to)\n skipped.push({ from, to });\n }\n }\n }\n return new ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn);\n }\n /**\n @internal\n */\n updateViewport(viewport) {\n if (this.viewport.from == viewport.from && this.viewport.to == viewport.to)\n return false;\n this.viewport = viewport;\n let startLen = this.skipped.length;\n for (let i = 0; i < this.skipped.length; i++) {\n let { from, to } = this.skipped[i];\n if (from < viewport.to && to > viewport.from) {\n this.fragments = cutFragments(this.fragments, from, to);\n this.skipped.splice(i--, 1);\n }\n }\n if (this.skipped.length >= startLen)\n return false;\n this.reset();\n return true;\n }\n /**\n @internal\n */\n reset() {\n if (this.parse) {\n this.takeTree();\n this.parse = null;\n }\n }\n /**\n Notify the parse scheduler that the given region was skipped\n because it wasn't in view, and the parse should be restarted\n when it comes into view.\n */\n skipUntilInView(from, to) {\n this.skipped.push({ from, to });\n }\n /**\n Returns a parser intended to be used as placeholder when\n asynchronously loading a nested parser. It'll skip its input and\n mark it as not-really-parsed, so that the next update will parse\n it again.\n \n When `until` is given, a reparse will be scheduled when that\n promise resolves.\n */\n static getSkippingParser(until) {\n return new class extends Parser {\n createParse(input, fragments, ranges) {\n let from = ranges[0].from, to = ranges[ranges.length - 1].to;\n let parser = {\n parsedPos: from,\n advance() {\n let cx = currentContext;\n if (cx) {\n for (let r of ranges)\n cx.tempSkipped.push(r);\n if (until)\n cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until;\n }\n this.parsedPos = to;\n return new Tree(NodeType.none, [], [], to - from);\n },\n stoppedAt: null,\n stopAt() { }\n };\n return parser;\n }\n };\n }\n /**\n @internal\n */\n isDone(upto) {\n upto = Math.min(upto, this.state.doc.length);\n let frags = this.fragments;\n return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto;\n }\n /**\n Get the context for the current parse, or `null` if no editor\n parse is in progress.\n */\n static get() { return currentContext; }\n}\nfunction cutFragments(fragments, from, to) {\n return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]);\n}\nclass LanguageState {\n constructor(\n // A mutable parse state that is used to preserve work done during\n // the lifetime of a state when moving to the next state.\n context) {\n this.context = context;\n this.tree = context.tree;\n }\n apply(tr) {\n if (!tr.docChanged && this.tree == this.context.tree)\n return this;\n let newCx = this.context.changes(tr.changes, tr.state);\n // If the previous parse wasn't done, go forward only up to its\n // end position or the end of the viewport, to avoid slowing down\n // state updates with parse work beyond the viewport.\n let upto = this.context.treeLen == tr.startState.doc.length ? undefined\n : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to);\n if (!newCx.work(20 /* Work.Apply */, upto))\n newCx.takeTree();\n return new LanguageState(newCx);\n }\n static init(state) {\n let vpTo = Math.min(3000 /* Work.InitViewport */, state.doc.length);\n let parseState = ParseContext.create(state.facet(language).parser, state, { from: 0, to: vpTo });\n if (!parseState.work(20 /* Work.Apply */, vpTo))\n parseState.takeTree();\n return new LanguageState(parseState);\n }\n}\nLanguage.state = /*@__PURE__*/StateField.define({\n create: LanguageState.init,\n update(value, tr) {\n for (let e of tr.effects)\n if (e.is(Language.setState))\n return e.value;\n if (tr.startState.facet(language) != tr.state.facet(language))\n return LanguageState.init(tr.state);\n return value.apply(tr);\n }\n});\nlet requestIdle = (callback) => {\n let timeout = setTimeout(() => callback(), 500 /* Work.MaxPause */);\n return () => clearTimeout(timeout);\n};\nif (typeof requestIdleCallback != \"undefined\")\n requestIdle = (callback) => {\n let idle = -1, timeout = setTimeout(() => {\n idle = requestIdleCallback(callback, { timeout: 500 /* Work.MaxPause */ - 100 /* Work.MinPause */ });\n }, 100 /* Work.MinPause */);\n return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle);\n };\nconst isInputPending = typeof navigator != \"undefined\" && ((_a = navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending)\n ? () => navigator.scheduling.isInputPending() : null;\nconst parseWorker = /*@__PURE__*/ViewPlugin.fromClass(class ParseWorker {\n constructor(view) {\n this.view = view;\n this.working = null;\n this.workScheduled = 0;\n // End of the current time chunk\n this.chunkEnd = -1;\n // Milliseconds of budget left for this chunk\n this.chunkBudget = -1;\n this.work = this.work.bind(this);\n this.scheduleWork();\n }\n update(update) {\n let cx = this.view.state.field(Language.state).context;\n if (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen)\n this.scheduleWork();\n if (update.docChanged || update.selectionSet) {\n if (this.view.hasFocus)\n this.chunkBudget += 50 /* Work.ChangeBonus */;\n this.scheduleWork();\n }\n this.checkAsyncSchedule(cx);\n }\n scheduleWork() {\n if (this.working)\n return;\n let { state } = this.view, field = state.field(Language.state);\n if (field.tree != field.context.tree || !field.context.isDone(state.doc.length))\n this.working = requestIdle(this.work);\n }\n work(deadline) {\n this.working = null;\n let now = Date.now();\n if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) { // Start a new chunk\n this.chunkEnd = now + 30000 /* Work.ChunkTime */;\n this.chunkBudget = 3000 /* Work.ChunkBudget */;\n }\n if (this.chunkBudget <= 0)\n return; // No more budget\n let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language.state);\n if (field.tree == field.context.tree && field.context.isDone(vpTo + 100000 /* Work.MaxParseAhead */))\n return;\n let endTime = Date.now() + Math.min(this.chunkBudget, 100 /* Work.Slice */, deadline && !isInputPending ? Math.max(25 /* Work.MinSlice */, deadline.timeRemaining() - 5) : 1e9);\n let viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1000;\n let done = field.context.work(() => {\n return isInputPending && isInputPending() || Date.now() > endTime;\n }, vpTo + (viewportFirst ? 0 : 100000 /* Work.MaxParseAhead */));\n this.chunkBudget -= Date.now() - now;\n if (done || this.chunkBudget <= 0) {\n field.context.takeTree();\n this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) });\n }\n if (this.chunkBudget > 0 && !(done && !viewportFirst))\n this.scheduleWork();\n this.checkAsyncSchedule(field.context);\n }\n checkAsyncSchedule(cx) {\n if (cx.scheduleOn) {\n this.workScheduled++;\n cx.scheduleOn\n .then(() => this.scheduleWork())\n .catch(err => logException(this.view.state, err))\n .then(() => this.workScheduled--);\n cx.scheduleOn = null;\n }\n }\n destroy() {\n if (this.working)\n this.working();\n }\n isWorking() {\n return !!(this.working || this.workScheduled > 0);\n }\n}, {\n eventHandlers: { focus() { this.scheduleWork(); } }\n});\n/**\nThe facet used to associate a language with an editor state. Used\nby `Language` object's `extension` property (so you don't need to\nmanually wrap your languages in this). Can be used to access the\ncurrent language on a state.\n*/\nconst language = /*@__PURE__*/Facet.define({\n combine(languages) { return languages.length ? languages[0] : null; },\n enables: language => [\n Language.state,\n parseWorker,\n EditorView.contentAttributes.compute([language], state => {\n let lang = state.facet(language);\n return lang && lang.name ? { \"data-language\": lang.name } : {};\n })\n ]\n});\n/**\nThis class bundles a [language](https://codemirror.net/6/docs/ref/#language.Language) with an\noptional set of supporting extensions. Language packages are\nencouraged to export a function that optionally takes a\nconfiguration object and returns a `LanguageSupport` instance, as\nthe main way for client code to use the package.\n*/\nclass LanguageSupport {\n /**\n Create a language support object.\n */\n constructor(\n /**\n The language object.\n */\n language, \n /**\n An optional set of supporting extensions. When nesting a\n language in another language, the outer language is encouraged\n to include the supporting extensions for its inner languages\n in its own set of support extensions.\n */\n support = []) {\n this.language = language;\n this.support = support;\n this.extension = [language, support];\n }\n}\n/**\nLanguage descriptions are used to store metadata about languages\nand to dynamically load them. Their main role is finding the\nappropriate language for a filename or dynamically loading nested\nparsers.\n*/\nclass LanguageDescription {\n constructor(\n /**\n The name of this language.\n */\n name, \n /**\n Alternative names for the mode (lowercased, includes `this.name`).\n */\n alias, \n /**\n File extensions associated with this language.\n */\n extensions, \n /**\n Optional filename pattern that should be associated with this\n language.\n */\n filename, loadFunc, \n /**\n If the language has been loaded, this will hold its value.\n */\n support = undefined) {\n this.name = name;\n this.alias = alias;\n this.extensions = extensions;\n this.filename = filename;\n this.loadFunc = loadFunc;\n this.support = support;\n this.loading = null;\n }\n /**\n Start loading the the language. Will return a promise that\n resolves to a [`LanguageSupport`](https://codemirror.net/6/docs/ref/#language.LanguageSupport)\n object when the language successfully loads.\n */\n load() {\n return this.loading || (this.loading = this.loadFunc().then(support => this.support = support, err => { this.loading = null; throw err; }));\n }\n /**\n Create a language description.\n */\n static of(spec) {\n let { load, support } = spec;\n if (!load) {\n if (!support)\n throw new RangeError(\"Must pass either 'load' or 'support' to LanguageDescription.of\");\n load = () => Promise.resolve(support);\n }\n return new LanguageDescription(spec.name, (spec.alias || []).concat(spec.name).map(s => s.toLowerCase()), spec.extensions || [], spec.filename, load, support);\n }\n /**\n Look for a language in the given array of descriptions that\n matches the filename. Will first match\n [`filename`](https://codemirror.net/6/docs/ref/#language.LanguageDescription.filename) patterns,\n and then [extensions](https://codemirror.net/6/docs/ref/#language.LanguageDescription.extensions),\n and return the first language that matches.\n */\n static matchFilename(descs, filename) {\n for (let d of descs)\n if (d.filename && d.filename.test(filename))\n return d;\n let ext = /\\.([^.]+)$/.exec(filename);\n if (ext)\n for (let d of descs)\n if (d.extensions.indexOf(ext[1]) > -1)\n return d;\n return null;\n }\n /**\n Look for a language whose name or alias matches the the given\n name (case-insensitively). If `fuzzy` is true, and no direct\n matchs is found, this'll also search for a language whose name\n or alias occurs in the string (for names shorter than three\n characters, only when surrounded by non-word characters).\n */\n static matchLanguageName(descs, name, fuzzy = true) {\n name = name.toLowerCase();\n for (let d of descs)\n if (d.alias.some(a => a == name))\n return d;\n if (fuzzy)\n for (let d of descs)\n for (let a of d.alias) {\n let found = name.indexOf(a);\n if (found > -1 && (a.length > 2 || !/\\w/.test(name[found - 1]) && !/\\w/.test(name[found + a.length])))\n return d;\n }\n return null;\n }\n}\n\n/**\nFacet that defines a way to provide a function that computes the\nappropriate indentation depth, as a column number (see\n[`indentString`](https://codemirror.net/6/docs/ref/#language.indentString)), at the start of a given\nline. A return value of `null` indicates no indentation can be\ndetermined, and the line should inherit the indentation of the one\nabove it. A return value of `undefined` defers to the next indent\nservice.\n*/\nconst indentService = /*@__PURE__*/Facet.define();\n/**\nFacet for overriding the unit by which indentation happens. Should\nbe a string consisting either entirely of the same whitespace\ncharacter. When not set, this defaults to 2 spaces.\n*/\nconst indentUnit = /*@__PURE__*/Facet.define({\n combine: values => {\n if (!values.length)\n return \" \";\n let unit = values[0];\n if (!unit || /\\S/.test(unit) || Array.from(unit).some(e => e != unit[0]))\n throw new Error(\"Invalid indent unit: \" + JSON.stringify(values[0]));\n return unit;\n }\n});\n/**\nReturn the _column width_ of an indent unit in the state.\nDetermined by the [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit)\nfacet, and [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) when that\ncontains tabs.\n*/\nfunction getIndentUnit(state) {\n let unit = state.facet(indentUnit);\n return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length;\n}\n/**\nCreate an indentation string that covers columns 0 to `cols`.\nWill use tabs for as much of the columns as possible when the\n[`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) facet contains\ntabs.\n*/\nfunction indentString(state, cols) {\n let result = \"\", ts = state.tabSize, ch = state.facet(indentUnit)[0];\n if (ch == \"\\t\") {\n while (cols >= ts) {\n result += \"\\t\";\n cols -= ts;\n }\n ch = \" \";\n }\n for (let i = 0; i < cols; i++)\n result += ch;\n return result;\n}\n/**\nGet the indentation, as a column number, at the given position.\nWill first consult any [indent services](https://codemirror.net/6/docs/ref/#language.indentService)\nthat are registered, and if none of those return an indentation,\nthis will check the syntax tree for the [indent node\nprop](https://codemirror.net/6/docs/ref/#language.indentNodeProp) and use that if found. Returns a\nnumber when an indentation could be determined, and null\notherwise.\n*/\nfunction getIndentation(context, pos) {\n if (context instanceof EditorState)\n context = new IndentContext(context);\n for (let service of context.state.facet(indentService)) {\n let result = service(context, pos);\n if (result !== undefined)\n return result;\n }\n let tree = syntaxTree(context.state);\n return tree.length >= pos ? syntaxIndentation(context, tree, pos) : null;\n}\n/**\nCreate a change set that auto-indents all lines touched by the\ngiven document range.\n*/\nfunction indentRange(state, from, to) {\n let updated = Object.create(null);\n let context = new IndentContext(state, { overrideIndentation: start => { var _a; return (_a = updated[start]) !== null && _a !== void 0 ? _a : -1; } });\n let changes = [];\n for (let pos = from; pos <= to;) {\n let line = state.doc.lineAt(pos);\n pos = line.to + 1;\n let indent = getIndentation(context, line.from);\n if (indent == null)\n continue;\n if (!/\\S/.test(line.text))\n indent = 0;\n let cur = /^\\s*/.exec(line.text)[0];\n let norm = indentString(state, indent);\n if (cur != norm) {\n updated[line.from] = indent;\n changes.push({ from: line.from, to: line.from + cur.length, insert: norm });\n }\n }\n return state.changes(changes);\n}\n/**\nIndentation contexts are used when calling [indentation\nservices](https://codemirror.net/6/docs/ref/#language.indentService). They provide helper utilities\nuseful in indentation logic, and can selectively override the\nindentation reported for some lines.\n*/\nclass IndentContext {\n /**\n Create an indent context.\n */\n constructor(\n /**\n The editor state.\n */\n state, \n /**\n @internal\n */\n options = {}) {\n this.state = state;\n this.options = options;\n this.unit = getIndentUnit(state);\n }\n /**\n Get a description of the line at the given position, taking\n [simulated line\n breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)\n into account. If there is such a break at `pos`, the `bias`\n argument determines whether the part of the line line before or\n after the break is used.\n */\n lineAt(pos, bias = 1) {\n let line = this.state.doc.lineAt(pos);\n let { simulateBreak, simulateDoubleBreak } = this.options;\n if (simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to) {\n if (simulateDoubleBreak && simulateBreak == pos)\n return { text: \"\", from: pos };\n else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos)\n return { text: line.text.slice(simulateBreak - line.from), from: simulateBreak };\n else\n return { text: line.text.slice(0, simulateBreak - line.from), from: line.from };\n }\n return line;\n }\n /**\n Get the text directly after `pos`, either the entire line\n or the next 100 characters, whichever is shorter.\n */\n textAfterPos(pos, bias = 1) {\n if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak)\n return \"\";\n let { text, from } = this.lineAt(pos, bias);\n return text.slice(pos - from, Math.min(text.length, pos + 100 - from));\n }\n /**\n Find the column for the given position.\n */\n column(pos, bias = 1) {\n let { text, from } = this.lineAt(pos, bias);\n let result = this.countColumn(text, pos - from);\n let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1;\n if (override > -1)\n result += override - this.countColumn(text, text.search(/\\S|$/));\n return result;\n }\n /**\n Find the column position (taking tabs into account) of the given\n position in the given string.\n */\n countColumn(line, pos = line.length) {\n return countColumn(line, this.state.tabSize, pos);\n }\n /**\n Find the indentation column of the line at the given point.\n */\n lineIndent(pos, bias = 1) {\n let { text, from } = this.lineAt(pos, bias);\n let override = this.options.overrideIndentation;\n if (override) {\n let overriden = override(from);\n if (overriden > -1)\n return overriden;\n }\n return this.countColumn(text, text.search(/\\S|$/));\n }\n /**\n Returns the [simulated line\n break](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)\n for this context, if any.\n */\n get simulatedBreak() {\n return this.options.simulateBreak || null;\n }\n}\n/**\nA syntax tree node prop used to associate indentation strategies\nwith node types. Such a strategy is a function from an indentation\ncontext to a column number (see also\n[`indentString`](https://codemirror.net/6/docs/ref/#language.indentString)) or null, where null\nindicates that no definitive indentation can be determined.\n*/\nconst indentNodeProp = /*@__PURE__*/new NodeProp();\n// Compute the indentation for a given position from the syntax tree.\nfunction syntaxIndentation(cx, ast, pos) {\n let stack = ast.resolveStack(pos);\n let inner = stack.node.enterUnfinishedNodesBefore(pos);\n if (inner != stack.node) {\n let add = [];\n for (let cur = inner; cur != stack.node; cur = cur.parent)\n add.push(cur);\n for (let i = add.length - 1; i >= 0; i--)\n stack = { node: add[i], next: stack };\n }\n return indentFor(stack, cx, pos);\n}\nfunction indentFor(stack, cx, pos) {\n for (let cur = stack; cur; cur = cur.next) {\n let strategy = indentStrategy(cur.node);\n if (strategy)\n return strategy(TreeIndentContext.create(cx, pos, cur));\n }\n return 0;\n}\nfunction ignoreClosed(cx) {\n return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak;\n}\nfunction indentStrategy(tree) {\n let strategy = tree.type.prop(indentNodeProp);\n if (strategy)\n return strategy;\n let first = tree.firstChild, close;\n if (first && (close = first.type.prop(NodeProp.closedBy))) {\n let last = tree.lastChild, closed = last && close.indexOf(last.name) > -1;\n return cx => delimitedStrategy(cx, true, 1, undefined, closed && !ignoreClosed(cx) ? last.from : undefined);\n }\n return tree.parent == null ? topIndent : null;\n}\nfunction topIndent() { return 0; }\n/**\nObjects of this type provide context information and helper\nmethods to indentation functions registered on syntax nodes.\n*/\nclass TreeIndentContext extends IndentContext {\n constructor(base, \n /**\n The position at which indentation is being computed.\n */\n pos, \n /**\n @internal\n */\n context) {\n super(base.state, base.options);\n this.base = base;\n this.pos = pos;\n this.context = context;\n }\n /**\n The syntax tree node to which the indentation strategy\n applies.\n */\n get node() { return this.context.node; }\n /**\n @internal\n */\n static create(base, pos, context) {\n return new TreeIndentContext(base, pos, context);\n }\n /**\n Get the text directly after `this.pos`, either the entire line\n or the next 100 characters, whichever is shorter.\n */\n get textAfter() {\n return this.textAfterPos(this.pos);\n }\n /**\n Get the indentation at the reference line for `this.node`, which\n is the line on which it starts, unless there is a node that is\n _not_ a parent of this node covering the start of that line. If\n so, the line at the start of that node is tried, again skipping\n on if it is covered by another such node.\n */\n get baseIndent() {\n return this.baseIndentFor(this.node);\n }\n /**\n Get the indentation for the reference line of the given node\n (see [`baseIndent`](https://codemirror.net/6/docs/ref/#language.TreeIndentContext.baseIndent)).\n */\n baseIndentFor(node) {\n let line = this.state.doc.lineAt(node.from);\n // Skip line starts that are covered by a sibling (or cousin, etc)\n for (;;) {\n let atBreak = node.resolve(line.from);\n while (atBreak.parent && atBreak.parent.from == atBreak.from)\n atBreak = atBreak.parent;\n if (isParent(atBreak, node))\n break;\n line = this.state.doc.lineAt(atBreak.from);\n }\n return this.lineIndent(line.from);\n }\n /**\n Continue looking for indentations in the node's parent nodes,\n and return the result of that.\n */\n continue() {\n return indentFor(this.context.next, this.base, this.pos);\n }\n}\nfunction isParent(parent, of) {\n for (let cur = of; cur; cur = cur.parent)\n if (parent == cur)\n return true;\n return false;\n}\n// Check whether a delimited node is aligned (meaning there are\n// non-skipped nodes on the same line as the opening delimiter). And\n// if so, return the opening token.\nfunction bracketedAligned(context) {\n let tree = context.node;\n let openToken = tree.childAfter(tree.from), last = tree.lastChild;\n if (!openToken)\n return null;\n let sim = context.options.simulateBreak;\n let openLine = context.state.doc.lineAt(openToken.from);\n let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim);\n for (let pos = openToken.to;;) {\n let next = tree.childAfter(pos);\n if (!next || next == last)\n return null;\n if (!next.type.isSkipped)\n return next.from < lineEnd ? openToken : null;\n pos = next.to;\n }\n}\n/**\nAn indentation strategy for delimited (usually bracketed) nodes.\nWill, by default, indent one unit more than the parent's base\nindent unless the line starts with a closing token. When `align`\nis true and there are non-skipped nodes on the node's opening\nline, the content of the node will be aligned with the end of the\nopening node, like this:\n\n foo(bar,\n baz)\n*/\nfunction delimitedIndent({ closing, align = true, units = 1 }) {\n return (context) => delimitedStrategy(context, align, units, closing);\n}\nfunction delimitedStrategy(context, align, units, closing, closedAt) {\n let after = context.textAfter, space = after.match(/^\\s*/)[0].length;\n let closed = closing && after.slice(space, space + closing.length) == closing || closedAt == context.pos + space;\n let aligned = align ? bracketedAligned(context) : null;\n if (aligned)\n return closed ? context.column(aligned.from) : context.column(aligned.to);\n return context.baseIndent + (closed ? 0 : context.unit * units);\n}\n/**\nAn indentation strategy that aligns a node's content to its base\nindentation.\n*/\nconst flatIndent = (context) => context.baseIndent;\n/**\nCreates an indentation strategy that, by default, indents\ncontinued lines one unit more than the node's base indentation.\nYou can provide `except` to prevent indentation of lines that\nmatch a pattern (for example `/^else\\b/` in `if`/`else`\nconstructs), and you can change the amount of units used with the\n`units` option.\n*/\nfunction continuedIndent({ except, units = 1 } = {}) {\n return (context) => {\n let matchExcept = except && except.test(context.textAfter);\n return context.baseIndent + (matchExcept ? 0 : units * context.unit);\n };\n}\nconst DontIndentBeyond = 200;\n/**\nEnables reindentation on input. When a language defines an\n`indentOnInput` field in its [language\ndata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt), which must hold a regular\nexpression, the line at the cursor will be reindented whenever new\ntext is typed and the input from the start of the line up to the\ncursor matches that regexp.\n\nTo avoid unneccesary reindents, it is recommended to start the\nregexp with `^` (usually followed by `\\s*`), and end it with `$`.\nFor example, `/^\\s*\\}$/` will reindent when a closing brace is\nadded at the start of a line.\n*/\nfunction indentOnInput() {\n return EditorState.transactionFilter.of(tr => {\n if (!tr.docChanged || !tr.isUserEvent(\"input.type\") && !tr.isUserEvent(\"input.complete\"))\n return tr;\n let rules = tr.startState.languageDataAt(\"indentOnInput\", tr.startState.selection.main.head);\n if (!rules.length)\n return tr;\n let doc = tr.newDoc, { head } = tr.newSelection.main, line = doc.lineAt(head);\n if (head > line.from + DontIndentBeyond)\n return tr;\n let lineStart = doc.sliceString(line.from, head);\n if (!rules.some(r => r.test(lineStart)))\n return tr;\n let { state } = tr, last = -1, changes = [];\n for (let { head } of state.selection.ranges) {\n let line = state.doc.lineAt(head);\n if (line.from == last)\n continue;\n last = line.from;\n let indent = getIndentation(state, line.from);\n if (indent == null)\n continue;\n let cur = /^\\s*/.exec(line.text)[0];\n let norm = indentString(state, indent);\n if (cur != norm)\n changes.push({ from: line.from, to: line.from + cur.length, insert: norm });\n }\n return changes.length ? [tr, { changes, sequential: true }] : tr;\n });\n}\n\n/**\nA facet that registers a code folding service. When called with\nthe extent of a line, such a function should return a foldable\nrange that starts on that line (but continues beyond it), if one\ncan be found.\n*/\nconst foldService = /*@__PURE__*/Facet.define();\n/**\nThis node prop is used to associate folding information with\nsyntax node types. Given a syntax node, it should check whether\nthat tree is foldable and return the range that can be collapsed\nwhen it is.\n*/\nconst foldNodeProp = /*@__PURE__*/new NodeProp();\n/**\n[Fold](https://codemirror.net/6/docs/ref/#language.foldNodeProp) function that folds everything but\nthe first and the last child of a syntax node. Useful for nodes\nthat start and end with delimiters.\n*/\nfunction foldInside(node) {\n let first = node.firstChild, last = node.lastChild;\n return first && first.to < last.from ? { from: first.to, to: last.type.isError ? node.to : last.from } : null;\n}\nfunction syntaxFolding(state, start, end) {\n let tree = syntaxTree(state);\n if (tree.length < end)\n return null;\n let stack = tree.resolveStack(end, 1);\n let found = null;\n for (let iter = stack; iter; iter = iter.next) {\n let cur = iter.node;\n if (cur.to <= end || cur.from > end)\n continue;\n if (found && cur.from < start)\n break;\n let prop = cur.type.prop(foldNodeProp);\n if (prop && (cur.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur))) {\n let value = prop(cur, state);\n if (value && value.from <= end && value.from >= start && value.to > end)\n found = value;\n }\n }\n return found;\n}\nfunction isUnfinished(node) {\n let ch = node.lastChild;\n return ch && ch.to == node.to && ch.type.isError;\n}\n/**\nCheck whether the given line is foldable. First asks any fold\nservices registered through\n[`foldService`](https://codemirror.net/6/docs/ref/#language.foldService), and if none of them return\na result, tries to query the [fold node\nprop](https://codemirror.net/6/docs/ref/#language.foldNodeProp) of syntax nodes that cover the end\nof the line.\n*/\nfunction foldable(state, lineStart, lineEnd) {\n for (let service of state.facet(foldService)) {\n let result = service(state, lineStart, lineEnd);\n if (result)\n return result;\n }\n return syntaxFolding(state, lineStart, lineEnd);\n}\nfunction mapRange(range, mapping) {\n let from = mapping.mapPos(range.from, 1), to = mapping.mapPos(range.to, -1);\n return from >= to ? undefined : { from, to };\n}\n/**\nState effect that can be attached to a transaction to fold the\ngiven range. (You probably only need this in exceptional\ncircumstances—usually you'll just want to let\n[`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode) and the [fold\ngutter](https://codemirror.net/6/docs/ref/#language.foldGutter) create the transactions.)\n*/\nconst foldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange });\n/**\nState effect that unfolds the given range (if it was folded).\n*/\nconst unfoldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange });\nfunction selectedLines(view) {\n let lines = [];\n for (let { head } of view.state.selection.ranges) {\n if (lines.some(l => l.from <= head && l.to >= head))\n continue;\n lines.push(view.lineBlockAt(head));\n }\n return lines;\n}\n/**\nThe state field that stores the folded ranges (as a [decoration\nset](https://codemirror.net/6/docs/ref/#view.DecorationSet)). Can be passed to\n[`EditorState.toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) and\n[`fromJSON`](https://codemirror.net/6/docs/ref/#state.EditorState^fromJSON) to serialize the fold\nstate.\n*/\nconst foldState = /*@__PURE__*/StateField.define({\n create() {\n return Decoration.none;\n },\n update(folded, tr) {\n folded = folded.map(tr.changes);\n for (let e of tr.effects) {\n if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to)) {\n let { preparePlaceholder } = tr.state.facet(foldConfig);\n let widget = !preparePlaceholder ? foldWidget :\n Decoration.replace({ widget: new PreparedFoldWidget(preparePlaceholder(tr.state, e.value)) });\n folded = folded.update({ add: [widget.range(e.value.from, e.value.to)] });\n }\n else if (e.is(unfoldEffect)) {\n folded = folded.update({ filter: (from, to) => e.value.from != from || e.value.to != to,\n filterFrom: e.value.from, filterTo: e.value.to });\n }\n }\n // Clear folded ranges that cover the selection head\n if (tr.selection) {\n let onSelection = false, { head } = tr.selection.main;\n folded.between(head, head, (a, b) => { if (a < head && b > head)\n onSelection = true; });\n if (onSelection)\n folded = folded.update({\n filterFrom: head,\n filterTo: head,\n filter: (a, b) => b <= head || a >= head\n });\n }\n return folded;\n },\n provide: f => EditorView.decorations.from(f),\n toJSON(folded, state) {\n let ranges = [];\n folded.between(0, state.doc.length, (from, to) => { ranges.push(from, to); });\n return ranges;\n },\n fromJSON(value) {\n if (!Array.isArray(value) || value.length % 2)\n throw new RangeError(\"Invalid JSON for fold state\");\n let ranges = [];\n for (let i = 0; i < value.length;) {\n let from = value[i++], to = value[i++];\n if (typeof from != \"number\" || typeof to != \"number\")\n throw new RangeError(\"Invalid JSON for fold state\");\n ranges.push(foldWidget.range(from, to));\n }\n return Decoration.set(ranges, true);\n }\n});\n/**\nGet a [range set](https://codemirror.net/6/docs/ref/#state.RangeSet) containing the folded ranges\nin the given state.\n*/\nfunction foldedRanges(state) {\n return state.field(foldState, false) || RangeSet.empty;\n}\nfunction findFold(state, from, to) {\n var _a;\n let found = null;\n (_a = state.field(foldState, false)) === null || _a === void 0 ? void 0 : _a.between(from, to, (from, to) => {\n if (!found || found.from > from)\n found = { from, to };\n });\n return found;\n}\nfunction foldExists(folded, from, to) {\n let found = false;\n folded.between(from, from, (a, b) => { if (a == from && b == to)\n found = true; });\n return found;\n}\nfunction maybeEnable(state, other) {\n return state.field(foldState, false) ? other : other.concat(StateEffect.appendConfig.of(codeFolding()));\n}\n/**\nFold the lines that are selected, if possible.\n*/\nconst foldCode = view => {\n for (let line of selectedLines(view)) {\n let range = foldable(view.state, line.from, line.to);\n if (range) {\n view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)]) });\n return true;\n }\n }\n return false;\n};\n/**\nUnfold folded ranges on selected lines.\n*/\nconst unfoldCode = view => {\n if (!view.state.field(foldState, false))\n return false;\n let effects = [];\n for (let line of selectedLines(view)) {\n let folded = findFold(view.state, line.from, line.to);\n if (folded)\n effects.push(unfoldEffect.of(folded), announceFold(view, folded, false));\n }\n if (effects.length)\n view.dispatch({ effects });\n return effects.length > 0;\n};\nfunction announceFold(view, range, fold = true) {\n let lineFrom = view.state.doc.lineAt(range.from).number, lineTo = view.state.doc.lineAt(range.to).number;\n return EditorView.announce.of(`${view.state.phrase(fold ? \"Folded lines\" : \"Unfolded lines\")} ${lineFrom} ${view.state.phrase(\"to\")} ${lineTo}.`);\n}\n/**\nFold all top-level foldable ranges. Note that, in most cases,\nfolding information will depend on the [syntax\ntree](https://codemirror.net/6/docs/ref/#language.syntaxTree), and folding everything may not work\nreliably when the document hasn't been fully parsed (either\nbecause the editor state was only just initialized, or because the\ndocument is so big that the parser decided not to parse it\nentirely).\n*/\nconst foldAll = view => {\n let { state } = view, effects = [];\n for (let pos = 0; pos < state.doc.length;) {\n let line = view.lineBlockAt(pos), range = foldable(state, line.from, line.to);\n if (range)\n effects.push(foldEffect.of(range));\n pos = (range ? view.lineBlockAt(range.to) : line).to + 1;\n }\n if (effects.length)\n view.dispatch({ effects: maybeEnable(view.state, effects) });\n return !!effects.length;\n};\n/**\nUnfold all folded code.\n*/\nconst unfoldAll = view => {\n let field = view.state.field(foldState, false);\n if (!field || !field.size)\n return false;\n let effects = [];\n field.between(0, view.state.doc.length, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });\n view.dispatch({ effects });\n return true;\n};\n// Find the foldable region containing the given line, if one exists\nfunction foldableContainer(view, lineBlock) {\n // Look backwards through line blocks until we find a foldable region that\n // intersects with the line\n for (let line = lineBlock;;) {\n let foldableRegion = foldable(view.state, line.from, line.to);\n if (foldableRegion && foldableRegion.to > lineBlock.from)\n return foldableRegion;\n if (!line.from)\n return null;\n line = view.lineBlockAt(line.from - 1);\n }\n}\n/**\nToggle folding at cursors. Unfolds if there is an existing fold\nstarting in that line, tries to find a foldable range around it\notherwise.\n*/\nconst toggleFold = (view) => {\n let effects = [];\n for (let line of selectedLines(view)) {\n let folded = findFold(view.state, line.from, line.to);\n if (folded) {\n effects.push(unfoldEffect.of(folded), announceFold(view, folded, false));\n }\n else {\n let foldRange = foldableContainer(view, line);\n if (foldRange)\n effects.push(foldEffect.of(foldRange), announceFold(view, foldRange));\n }\n }\n if (effects.length > 0)\n view.dispatch({ effects: maybeEnable(view.state, effects) });\n return !!effects.length;\n};\n/**\nDefault fold-related key bindings.\n\n - Ctrl-Shift-[ (Cmd-Alt-[ on macOS): [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode).\n - Ctrl-Shift-] (Cmd-Alt-] on macOS): [`unfoldCode`](https://codemirror.net/6/docs/ref/#language.unfoldCode).\n - Ctrl-Alt-[: [`foldAll`](https://codemirror.net/6/docs/ref/#language.foldAll).\n - Ctrl-Alt-]: [`unfoldAll`](https://codemirror.net/6/docs/ref/#language.unfoldAll).\n*/\nconst foldKeymap = [\n { key: \"Ctrl-Shift-[\", mac: \"Cmd-Alt-[\", run: foldCode },\n { key: \"Ctrl-Shift-]\", mac: \"Cmd-Alt-]\", run: unfoldCode },\n { key: \"Ctrl-Alt-[\", run: foldAll },\n { key: \"Ctrl-Alt-]\", run: unfoldAll }\n];\nconst defaultConfig = {\n placeholderDOM: null,\n preparePlaceholder: null,\n placeholderText: \"…\"\n};\nconst foldConfig = /*@__PURE__*/Facet.define({\n combine(values) { return combineConfig(values, defaultConfig); }\n});\n/**\nCreate an extension that configures code folding.\n*/\nfunction codeFolding(config) {\n let result = [foldState, baseTheme$1];\n if (config)\n result.push(foldConfig.of(config));\n return result;\n}\nfunction widgetToDOM(view, prepared) {\n let { state } = view, conf = state.facet(foldConfig);\n let onclick = (event) => {\n let line = view.lineBlockAt(view.posAtDOM(event.target));\n let folded = findFold(view.state, line.from, line.to);\n if (folded)\n view.dispatch({ effects: unfoldEffect.of(folded) });\n event.preventDefault();\n };\n if (conf.placeholderDOM)\n return conf.placeholderDOM(view, onclick, prepared);\n let element = document.createElement(\"span\");\n element.textContent = conf.placeholderText;\n element.setAttribute(\"aria-label\", state.phrase(\"folded code\"));\n element.title = state.phrase(\"unfold\");\n element.className = \"cm-foldPlaceholder\";\n element.onclick = onclick;\n return element;\n}\nconst foldWidget = /*@__PURE__*/Decoration.replace({ widget: /*@__PURE__*/new class extends WidgetType {\n toDOM(view) { return widgetToDOM(view, null); }\n } });\nclass PreparedFoldWidget extends WidgetType {\n constructor(value) {\n super();\n this.value = value;\n }\n eq(other) { return this.value == other.value; }\n toDOM(view) { return widgetToDOM(view, this.value); }\n}\nconst foldGutterDefaults = {\n openText: \"⌄\",\n closedText: \"›\",\n markerDOM: null,\n domEventHandlers: {},\n foldingChanged: () => false\n};\nclass FoldMarker extends GutterMarker {\n constructor(config, open) {\n super();\n this.config = config;\n this.open = open;\n }\n eq(other) { return this.config == other.config && this.open == other.open; }\n toDOM(view) {\n if (this.config.markerDOM)\n return this.config.markerDOM(this.open);\n let span = document.createElement(\"span\");\n span.textContent = this.open ? this.config.openText : this.config.closedText;\n span.title = view.state.phrase(this.open ? \"Fold line\" : \"Unfold line\");\n return span;\n }\n}\n/**\nCreate an extension that registers a fold gutter, which shows a\nfold status indicator before foldable lines (which can be clicked\nto fold or unfold the line).\n*/\nfunction foldGutter(config = {}) {\n let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config);\n let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false);\n let markers = ViewPlugin.fromClass(class {\n constructor(view) {\n this.from = view.viewport.from;\n this.markers = this.buildMarkers(view);\n }\n update(update) {\n if (update.docChanged || update.viewportChanged ||\n update.startState.facet(language) != update.state.facet(language) ||\n update.startState.field(foldState, false) != update.state.field(foldState, false) ||\n syntaxTree(update.startState) != syntaxTree(update.state) ||\n fullConfig.foldingChanged(update))\n this.markers = this.buildMarkers(update.view);\n }\n buildMarkers(view) {\n let builder = new RangeSetBuilder();\n for (let line of view.viewportLineBlocks) {\n let mark = findFold(view.state, line.from, line.to) ? canUnfold\n : foldable(view.state, line.from, line.to) ? canFold : null;\n if (mark)\n builder.add(line.from, line.from, mark);\n }\n return builder.finish();\n }\n });\n let { domEventHandlers } = fullConfig;\n return [\n markers,\n gutter({\n class: \"cm-foldGutter\",\n markers(view) { var _a; return ((_a = view.plugin(markers)) === null || _a === void 0 ? void 0 : _a.markers) || RangeSet.empty; },\n initialSpacer() {\n return new FoldMarker(fullConfig, false);\n },\n domEventHandlers: Object.assign(Object.assign({}, domEventHandlers), { click: (view, line, event) => {\n if (domEventHandlers.click && domEventHandlers.click(view, line, event))\n return true;\n let folded = findFold(view.state, line.from, line.to);\n if (folded) {\n view.dispatch({ effects: unfoldEffect.of(folded) });\n return true;\n }\n let range = foldable(view.state, line.from, line.to);\n if (range) {\n view.dispatch({ effects: foldEffect.of(range) });\n return true;\n }\n return false;\n } })\n }),\n codeFolding()\n ];\n}\nconst baseTheme$1 = /*@__PURE__*/EditorView.baseTheme({\n \".cm-foldPlaceholder\": {\n backgroundColor: \"#eee\",\n border: \"1px solid #ddd\",\n color: \"#888\",\n borderRadius: \".2em\",\n margin: \"0 1px\",\n padding: \"0 1px\",\n cursor: \"pointer\"\n },\n \".cm-foldGutter span\": {\n padding: \"0 1px\",\n cursor: \"pointer\"\n }\n});\n\n/**\nA highlight style associates CSS styles with higlighting\n[tags](https://lezer.codemirror.net/docs/ref#highlight.Tag).\n*/\nclass HighlightStyle {\n constructor(\n /**\n The tag styles used to create this highlight style.\n */\n specs, options) {\n this.specs = specs;\n let modSpec;\n function def(spec) {\n let cls = StyleModule.newName();\n (modSpec || (modSpec = Object.create(null)))[\".\" + cls] = spec;\n return cls;\n }\n const all = typeof options.all == \"string\" ? options.all : options.all ? def(options.all) : undefined;\n const scopeOpt = options.scope;\n this.scope = scopeOpt instanceof Language ? (type) => type.prop(languageDataProp) == scopeOpt.data\n : scopeOpt ? (type) => type == scopeOpt : undefined;\n this.style = tagHighlighter(specs.map(style => ({\n tag: style.tag,\n class: style.class || def(Object.assign({}, style, { tag: null }))\n })), {\n all,\n }).style;\n this.module = modSpec ? new StyleModule(modSpec) : null;\n this.themeType = options.themeType;\n }\n /**\n Create a highlighter style that associates the given styles to\n the given tags. The specs must be objects that hold a style tag\n or array of tags in their `tag` property, and either a single\n `class` property providing a static CSS class (for highlighter\n that rely on external styling), or a\n [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style\n set of CSS properties (which define the styling for those tags).\n \n The CSS rules created for a highlighter will be emitted in the\n order of the spec's properties. That means that for elements that\n have multiple tags associated with them, styles defined further\n down in the list will have a higher CSS precedence than styles\n defined earlier.\n */\n static define(specs, options) {\n return new HighlightStyle(specs, options || {});\n }\n}\nconst highlighterFacet = /*@__PURE__*/Facet.define();\nconst fallbackHighlighter = /*@__PURE__*/Facet.define({\n combine(values) { return values.length ? [values[0]] : null; }\n});\nfunction getHighlighters(state) {\n let main = state.facet(highlighterFacet);\n return main.length ? main : state.facet(fallbackHighlighter);\n}\n/**\nWrap a highlighter in an editor extension that uses it to apply\nsyntax highlighting to the editor content.\n\nWhen multiple (non-fallback) styles are provided, the styling\napplied is the union of the classes they emit.\n*/\nfunction syntaxHighlighting(highlighter, options) {\n let ext = [treeHighlighter], themeType;\n if (highlighter instanceof HighlightStyle) {\n if (highlighter.module)\n ext.push(EditorView.styleModule.of(highlighter.module));\n themeType = highlighter.themeType;\n }\n if (options === null || options === void 0 ? void 0 : options.fallback)\n ext.push(fallbackHighlighter.of(highlighter));\n else if (themeType)\n ext.push(highlighterFacet.computeN([EditorView.darkTheme], state => {\n return state.facet(EditorView.darkTheme) == (themeType == \"dark\") ? [highlighter] : [];\n }));\n else\n ext.push(highlighterFacet.of(highlighter));\n return ext;\n}\n/**\nReturns the CSS classes (if any) that the highlighters active in\nthe state would assign to the given style\n[tags](https://lezer.codemirror.net/docs/ref#highlight.Tag) and\n(optional) language\n[scope](https://codemirror.net/6/docs/ref/#language.HighlightStyle^define^options.scope).\n*/\nfunction highlightingFor(state, tags, scope) {\n let highlighters = getHighlighters(state);\n let result = null;\n if (highlighters)\n for (let highlighter of highlighters) {\n if (!highlighter.scope || scope && highlighter.scope(scope)) {\n let cls = highlighter.style(tags);\n if (cls)\n result = result ? result + \" \" + cls : cls;\n }\n }\n return result;\n}\nclass TreeHighlighter {\n constructor(view) {\n this.markCache = Object.create(null);\n this.tree = syntaxTree(view.state);\n this.decorations = this.buildDeco(view, getHighlighters(view.state));\n }\n update(update) {\n let tree = syntaxTree(update.state), highlighters = getHighlighters(update.state);\n let styleChange = highlighters != getHighlighters(update.startState);\n if (tree.length < update.view.viewport.to && !styleChange && tree.type == this.tree.type) {\n this.decorations = this.decorations.map(update.changes);\n }\n else if (tree != this.tree || update.viewportChanged || styleChange) {\n this.tree = tree;\n this.decorations = this.buildDeco(update.view, highlighters);\n }\n }\n buildDeco(view, highlighters) {\n if (!highlighters || !this.tree.length)\n return Decoration.none;\n let builder = new RangeSetBuilder();\n for (let { from, to } of view.visibleRanges) {\n highlightTree(this.tree, highlighters, (from, to, style) => {\n builder.add(from, to, this.markCache[style] || (this.markCache[style] = Decoration.mark({ class: style })));\n }, from, to);\n }\n return builder.finish();\n }\n}\nconst treeHighlighter = /*@__PURE__*/Prec.high(/*@__PURE__*/ViewPlugin.fromClass(TreeHighlighter, {\n decorations: v => v.decorations\n}));\n/**\nA default highlight style (works well with light themes).\n*/\nconst defaultHighlightStyle = /*@__PURE__*/HighlightStyle.define([\n { tag: tags.meta,\n color: \"#404740\" },\n { tag: tags.link,\n textDecoration: \"underline\" },\n { tag: tags.heading,\n textDecoration: \"underline\",\n fontWeight: \"bold\" },\n { tag: tags.emphasis,\n fontStyle: \"italic\" },\n { tag: tags.strong,\n fontWeight: \"bold\" },\n { tag: tags.strikethrough,\n textDecoration: \"line-through\" },\n { tag: tags.keyword,\n color: \"#708\" },\n { tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName],\n color: \"#219\" },\n { tag: [tags.literal, tags.inserted],\n color: \"#164\" },\n { tag: [tags.string, tags.deleted],\n color: \"#a11\" },\n { tag: [tags.regexp, tags.escape, /*@__PURE__*/tags.special(tags.string)],\n color: \"#e40\" },\n { tag: /*@__PURE__*/tags.definition(tags.variableName),\n color: \"#00f\" },\n { tag: /*@__PURE__*/tags.local(tags.variableName),\n color: \"#30a\" },\n { tag: [tags.typeName, tags.namespace],\n color: \"#085\" },\n { tag: tags.className,\n color: \"#167\" },\n { tag: [/*@__PURE__*/tags.special(tags.variableName), tags.macroName],\n color: \"#256\" },\n { tag: /*@__PURE__*/tags.definition(tags.propertyName),\n color: \"#00c\" },\n { tag: tags.comment,\n color: \"#940\" },\n { tag: tags.invalid,\n color: \"#f00\" }\n]);\n\nconst baseTheme = /*@__PURE__*/EditorView.baseTheme({\n \"&.cm-focused .cm-matchingBracket\": { backgroundColor: \"#328c8252\" },\n \"&.cm-focused .cm-nonmatchingBracket\": { backgroundColor: \"#bb555544\" }\n});\nconst DefaultScanDist = 10000, DefaultBrackets = \"()[]{}\";\nconst bracketMatchingConfig = /*@__PURE__*/Facet.define({\n combine(configs) {\n return combineConfig(configs, {\n afterCursor: true,\n brackets: DefaultBrackets,\n maxScanDistance: DefaultScanDist,\n renderMatch: defaultRenderMatch\n });\n }\n});\nconst matchingMark = /*@__PURE__*/Decoration.mark({ class: \"cm-matchingBracket\" }), nonmatchingMark = /*@__PURE__*/Decoration.mark({ class: \"cm-nonmatchingBracket\" });\nfunction defaultRenderMatch(match) {\n let decorations = [];\n let mark = match.matched ? matchingMark : nonmatchingMark;\n decorations.push(mark.range(match.start.from, match.start.to));\n if (match.end)\n decorations.push(mark.range(match.end.from, match.end.to));\n return decorations;\n}\nconst bracketMatchingState = /*@__PURE__*/StateField.define({\n create() { return Decoration.none; },\n update(deco, tr) {\n if (!tr.docChanged && !tr.selection)\n return deco;\n let decorations = [];\n let config = tr.state.facet(bracketMatchingConfig);\n for (let range of tr.state.selection.ranges) {\n if (!range.empty)\n continue;\n let match = matchBrackets(tr.state, range.head, -1, config)\n || (range.head > 0 && matchBrackets(tr.state, range.head - 1, 1, config))\n || (config.afterCursor &&\n (matchBrackets(tr.state, range.head, 1, config) ||\n (range.head < tr.state.doc.length && matchBrackets(tr.state, range.head + 1, -1, config))));\n if (match)\n decorations = decorations.concat(config.renderMatch(match, tr.state));\n }\n return Decoration.set(decorations, true);\n },\n provide: f => EditorView.decorations.from(f)\n});\nconst bracketMatchingUnique = [\n bracketMatchingState,\n baseTheme\n];\n/**\nCreate an extension that enables bracket matching. Whenever the\ncursor is next to a bracket, that bracket and the one it matches\nare highlighted. Or, when no matching bracket is found, another\nhighlighting style is used to indicate this.\n*/\nfunction bracketMatching(config = {}) {\n return [bracketMatchingConfig.of(config), bracketMatchingUnique];\n}\n/**\nWhen larger syntax nodes, such as HTML tags, are marked as\nopening/closing, it can be a bit messy to treat the whole node as\na matchable bracket. This node prop allows you to define, for such\na node, a ‘handle’—the part of the node that is highlighted, and\nthat the cursor must be on to activate highlighting in the first\nplace.\n*/\nconst bracketMatchingHandle = /*@__PURE__*/new NodeProp();\nfunction matchingNodes(node, dir, brackets) {\n let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy);\n if (byProp)\n return byProp;\n if (node.name.length == 1) {\n let index = brackets.indexOf(node.name);\n if (index > -1 && index % 2 == (dir < 0 ? 1 : 0))\n return [brackets[index + dir]];\n }\n return null;\n}\nfunction findHandle(node) {\n let hasHandle = node.type.prop(bracketMatchingHandle);\n return hasHandle ? hasHandle(node.node) : node;\n}\n/**\nFind the matching bracket for the token at `pos`, scanning\ndirection `dir`. Only the `brackets` and `maxScanDistance`\nproperties are used from `config`, if given. Returns null if no\nbracket was found at `pos`, or a match result otherwise.\n*/\nfunction matchBrackets(state, pos, dir, config = {}) {\n let maxScanDistance = config.maxScanDistance || DefaultScanDist, brackets = config.brackets || DefaultBrackets;\n let tree = syntaxTree(state), node = tree.resolveInner(pos, dir);\n for (let cur = node; cur; cur = cur.parent) {\n let matches = matchingNodes(cur.type, dir, brackets);\n if (matches && cur.from < cur.to) {\n let handle = findHandle(cur);\n if (handle && (dir > 0 ? pos >= handle.from && pos < handle.to : pos > handle.from && pos <= handle.to))\n return matchMarkedBrackets(state, pos, dir, cur, handle, matches, brackets);\n }\n }\n return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets);\n}\nfunction matchMarkedBrackets(_state, _pos, dir, token, handle, matching, brackets) {\n let parent = token.parent, firstToken = { from: handle.from, to: handle.to };\n let depth = 0, cursor = parent === null || parent === void 0 ? void 0 : parent.cursor();\n if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to)))\n do {\n if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) {\n if (depth == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) {\n let endHandle = findHandle(cursor);\n return { start: firstToken, end: endHandle ? { from: endHandle.from, to: endHandle.to } : undefined, matched: true };\n }\n else if (matchingNodes(cursor.type, dir, brackets)) {\n depth++;\n }\n else if (matchingNodes(cursor.type, -dir, brackets)) {\n if (depth == 0) {\n let endHandle = findHandle(cursor);\n return {\n start: firstToken,\n end: endHandle && endHandle.from < endHandle.to ? { from: endHandle.from, to: endHandle.to } : undefined,\n matched: false\n };\n }\n depth--;\n }\n }\n } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling());\n return { start: firstToken, matched: false };\n}\nfunction matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) {\n let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1);\n let bracket = brackets.indexOf(startCh);\n if (bracket < 0 || (bracket % 2 == 0) != (dir > 0))\n return null;\n let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos };\n let iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth = 0;\n for (let distance = 0; !(iter.next()).done && distance <= maxScanDistance;) {\n let text = iter.value;\n if (dir < 0)\n distance += text.length;\n let basePos = pos + distance * dir;\n for (let pos = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos != end; pos += dir) {\n let found = brackets.indexOf(text[pos]);\n if (found < 0 || tree.resolveInner(basePos + pos, 1).type != tokenType)\n continue;\n if ((found % 2 == 0) == (dir > 0)) {\n depth++;\n }\n else if (depth == 1) { // Closing\n return { start: startToken, end: { from: basePos + pos, to: basePos + pos + 1 }, matched: (found >> 1) == (bracket >> 1) };\n }\n else {\n depth--;\n }\n }\n if (dir > 0)\n distance += text.length;\n }\n return iter.done ? { start: startToken, matched: false } : null;\n}\n\n// Counts the column offset in a string, taking tabs into account.\n// Used mostly to find indentation.\nfunction countCol(string, end, tabSize, startIndex = 0, startValue = 0) {\n if (end == null) {\n end = string.search(/[^\\s\\u00a0]/);\n if (end == -1)\n end = string.length;\n }\n let n = startValue;\n for (let i = startIndex; i < end; i++) {\n if (string.charCodeAt(i) == 9)\n n += tabSize - (n % tabSize);\n else\n n++;\n }\n return n;\n}\n/**\nEncapsulates a single line of input. Given to stream syntax code,\nwhich uses it to tokenize the content.\n*/\nclass StringStream {\n /**\n Create a stream.\n */\n constructor(\n /**\n The line.\n */\n string, tabSize, \n /**\n The current indent unit size.\n */\n indentUnit, overrideIndent) {\n this.string = string;\n this.tabSize = tabSize;\n this.indentUnit = indentUnit;\n this.overrideIndent = overrideIndent;\n /**\n The current position on the line.\n */\n this.pos = 0;\n /**\n The start position of the current token.\n */\n this.start = 0;\n this.lastColumnPos = 0;\n this.lastColumnValue = 0;\n }\n /**\n True if we are at the end of the line.\n */\n eol() { return this.pos >= this.string.length; }\n /**\n True if we are at the start of the line.\n */\n sol() { return this.pos == 0; }\n /**\n Get the next code unit after the current position, or undefined\n if we're at the end of the line.\n */\n peek() { return this.string.charAt(this.pos) || undefined; }\n /**\n Read the next code unit and advance `this.pos`.\n */\n next() {\n if (this.pos < this.string.length)\n return this.string.charAt(this.pos++);\n }\n /**\n Match the next character against the given string, regular\n expression, or predicate. Consume and return it if it matches.\n */\n eat(match) {\n let ch = this.string.charAt(this.pos);\n let ok;\n if (typeof match == \"string\")\n ok = ch == match;\n else\n ok = ch && (match instanceof RegExp ? match.test(ch) : match(ch));\n if (ok) {\n ++this.pos;\n return ch;\n }\n }\n /**\n Continue matching characters that match the given string,\n regular expression, or predicate function. Return true if any\n characters were consumed.\n */\n eatWhile(match) {\n let start = this.pos;\n while (this.eat(match)) { }\n return this.pos > start;\n }\n /**\n Consume whitespace ahead of `this.pos`. Return true if any was\n found.\n */\n eatSpace() {\n let start = this.pos;\n while (/[\\s\\u00a0]/.test(this.string.charAt(this.pos)))\n ++this.pos;\n return this.pos > start;\n }\n /**\n Move to the end of the line.\n */\n skipToEnd() { this.pos = this.string.length; }\n /**\n Move to directly before the given character, if found on the\n current line.\n */\n skipTo(ch) {\n let found = this.string.indexOf(ch, this.pos);\n if (found > -1) {\n this.pos = found;\n return true;\n }\n }\n /**\n Move back `n` characters.\n */\n backUp(n) { this.pos -= n; }\n /**\n Get the column position at `this.pos`.\n */\n column() {\n if (this.lastColumnPos < this.start) {\n this.lastColumnValue = countCol(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);\n this.lastColumnPos = this.start;\n }\n return this.lastColumnValue;\n }\n /**\n Get the indentation column of the current line.\n */\n indentation() {\n var _a;\n return (_a = this.overrideIndent) !== null && _a !== void 0 ? _a : countCol(this.string, null, this.tabSize);\n }\n /**\n Match the input against the given string or regular expression\n (which should start with a `^`). Return true or the regexp match\n if it matches.\n \n Unless `consume` is set to `false`, this will move `this.pos`\n past the matched text.\n \n When matching a string `caseInsensitive` can be set to true to\n make the match case-insensitive.\n */\n match(pattern, consume, caseInsensitive) {\n if (typeof pattern == \"string\") {\n let cased = (str) => caseInsensitive ? str.toLowerCase() : str;\n let substr = this.string.substr(this.pos, pattern.length);\n if (cased(substr) == cased(pattern)) {\n if (consume !== false)\n this.pos += pattern.length;\n return true;\n }\n else\n return null;\n }\n else {\n let match = this.string.slice(this.pos).match(pattern);\n if (match && match.index > 0)\n return null;\n if (match && consume !== false)\n this.pos += match[0].length;\n return match;\n }\n }\n /**\n Get the current token.\n */\n current() { return this.string.slice(this.start, this.pos); }\n}\n\nfunction fullParser(spec) {\n return {\n name: spec.name || \"\",\n token: spec.token,\n blankLine: spec.blankLine || (() => { }),\n startState: spec.startState || (() => true),\n copyState: spec.copyState || defaultCopyState,\n indent: spec.indent || (() => null),\n languageData: spec.languageData || {},\n tokenTable: spec.tokenTable || noTokens\n };\n}\nfunction defaultCopyState(state) {\n if (typeof state != \"object\")\n return state;\n let newState = {};\n for (let prop in state) {\n let val = state[prop];\n newState[prop] = (val instanceof Array ? val.slice() : val);\n }\n return newState;\n}\nconst IndentedFrom = /*@__PURE__*/new WeakMap();\n/**\nA [language](https://codemirror.net/6/docs/ref/#language.Language) class based on a CodeMirror\n5-style [streaming parser](https://codemirror.net/6/docs/ref/#language.StreamParser).\n*/\nclass StreamLanguage extends Language {\n constructor(parser) {\n let data = defineLanguageFacet(parser.languageData);\n let p = fullParser(parser), self;\n let impl = new class extends Parser {\n createParse(input, fragments, ranges) {\n return new Parse(self, input, fragments, ranges);\n }\n };\n super(data, impl, [indentService.of((cx, pos) => this.getIndent(cx, pos))], parser.name);\n this.topNode = docID(data);\n self = this;\n this.streamParser = p;\n this.stateAfter = new NodeProp({ perNode: true });\n this.tokenTable = parser.tokenTable ? new TokenTable(p.tokenTable) : defaultTokenTable;\n }\n /**\n Define a stream language.\n */\n static define(spec) { return new StreamLanguage(spec); }\n getIndent(cx, pos) {\n let tree = syntaxTree(cx.state), at = tree.resolve(pos);\n while (at && at.type != this.topNode)\n at = at.parent;\n if (!at)\n return null;\n let from = undefined;\n let { overrideIndentation } = cx.options;\n if (overrideIndentation) {\n from = IndentedFrom.get(cx.state);\n if (from != null && from < pos - 1e4)\n from = undefined;\n }\n let start = findState(this, tree, 0, at.from, from !== null && from !== void 0 ? from : pos), statePos, state;\n if (start) {\n state = start.state;\n statePos = start.pos + 1;\n }\n else {\n state = this.streamParser.startState(cx.unit);\n statePos = 0;\n }\n if (pos - statePos > 10000 /* C.MaxIndentScanDist */)\n return null;\n while (statePos < pos) {\n let line = cx.state.doc.lineAt(statePos), end = Math.min(pos, line.to);\n if (line.length) {\n let indentation = overrideIndentation ? overrideIndentation(line.from) : -1;\n let stream = new StringStream(line.text, cx.state.tabSize, cx.unit, indentation < 0 ? undefined : indentation);\n while (stream.pos < end - line.from)\n readToken(this.streamParser.token, stream, state);\n }\n else {\n this.streamParser.blankLine(state, cx.unit);\n }\n if (end == pos)\n break;\n statePos = line.to + 1;\n }\n let line = cx.lineAt(pos);\n if (overrideIndentation && from == null)\n IndentedFrom.set(cx.state, line.from);\n return this.streamParser.indent(state, /^\\s*(.*)/.exec(line.text)[1], cx);\n }\n get allowsNesting() { return false; }\n}\nfunction findState(lang, tree, off, startPos, before) {\n let state = off >= startPos && off + tree.length <= before && tree.prop(lang.stateAfter);\n if (state)\n return { state: lang.streamParser.copyState(state), pos: off + tree.length };\n for (let i = tree.children.length - 1; i >= 0; i--) {\n let child = tree.children[i], pos = off + tree.positions[i];\n let found = child instanceof Tree && pos < before && findState(lang, child, pos, startPos, before);\n if (found)\n return found;\n }\n return null;\n}\nfunction cutTree(lang, tree, from, to, inside) {\n if (inside && from <= 0 && to >= tree.length)\n return tree;\n if (!inside && tree.type == lang.topNode)\n inside = true;\n for (let i = tree.children.length - 1; i >= 0; i--) {\n let pos = tree.positions[i], child = tree.children[i], inner;\n if (pos < to && child instanceof Tree) {\n if (!(inner = cutTree(lang, child, from - pos, to - pos, inside)))\n break;\n return !inside ? inner\n : new Tree(tree.type, tree.children.slice(0, i).concat(inner), tree.positions.slice(0, i + 1), pos + inner.length);\n }\n }\n return null;\n}\nfunction findStartInFragments(lang, fragments, startPos, editorState) {\n for (let f of fragments) {\n let from = f.from + (f.openStart ? 25 : 0), to = f.to - (f.openEnd ? 25 : 0);\n let found = from <= startPos && to > startPos && findState(lang, f.tree, 0 - f.offset, startPos, to), tree;\n if (found && (tree = cutTree(lang, f.tree, startPos + f.offset, found.pos + f.offset, false)))\n return { state: found.state, tree };\n }\n return { state: lang.streamParser.startState(editorState ? getIndentUnit(editorState) : 4), tree: Tree.empty };\n}\nclass Parse {\n constructor(lang, input, fragments, ranges) {\n this.lang = lang;\n this.input = input;\n this.fragments = fragments;\n this.ranges = ranges;\n this.stoppedAt = null;\n this.chunks = [];\n this.chunkPos = [];\n this.chunk = [];\n this.chunkReused = undefined;\n this.rangeIndex = 0;\n this.to = ranges[ranges.length - 1].to;\n let context = ParseContext.get(), from = ranges[0].from;\n let { state, tree } = findStartInFragments(lang, fragments, from, context === null || context === void 0 ? void 0 : context.state);\n this.state = state;\n this.parsedPos = this.chunkStart = from + tree.length;\n for (let i = 0; i < tree.children.length; i++) {\n this.chunks.push(tree.children[i]);\n this.chunkPos.push(tree.positions[i]);\n }\n if (context && this.parsedPos < context.viewport.from - 100000 /* C.MaxDistanceBeforeViewport */) {\n this.state = this.lang.streamParser.startState(getIndentUnit(context.state));\n context.skipUntilInView(this.parsedPos, context.viewport.from);\n this.parsedPos = context.viewport.from;\n }\n this.moveRangeIndex();\n }\n advance() {\n let context = ParseContext.get();\n let parseEnd = this.stoppedAt == null ? this.to : Math.min(this.to, this.stoppedAt);\n let end = Math.min(parseEnd, this.chunkStart + 2048 /* C.ChunkSize */);\n if (context)\n end = Math.min(end, context.viewport.to);\n while (this.parsedPos < end)\n this.parseLine(context);\n if (this.chunkStart < this.parsedPos)\n this.finishChunk();\n if (this.parsedPos >= parseEnd)\n return this.finish();\n if (context && this.parsedPos >= context.viewport.to) {\n context.skipUntilInView(this.parsedPos, parseEnd);\n return this.finish();\n }\n return null;\n }\n stopAt(pos) {\n this.stoppedAt = pos;\n }\n lineAfter(pos) {\n let chunk = this.input.chunk(pos);\n if (!this.input.lineChunks) {\n let eol = chunk.indexOf(\"\\n\");\n if (eol > -1)\n chunk = chunk.slice(0, eol);\n }\n else if (chunk == \"\\n\") {\n chunk = \"\";\n }\n return pos + chunk.length <= this.to ? chunk : chunk.slice(0, this.to - pos);\n }\n nextLine() {\n let from = this.parsedPos, line = this.lineAfter(from), end = from + line.length;\n for (let index = this.rangeIndex;;) {\n let rangeEnd = this.ranges[index].to;\n if (rangeEnd >= end)\n break;\n line = line.slice(0, rangeEnd - (end - line.length));\n index++;\n if (index == this.ranges.length)\n break;\n let rangeStart = this.ranges[index].from;\n let after = this.lineAfter(rangeStart);\n line += after;\n end = rangeStart + after.length;\n }\n return { line, end };\n }\n skipGapsTo(pos, offset, side) {\n for (;;) {\n let end = this.ranges[this.rangeIndex].to, offPos = pos + offset;\n if (side > 0 ? end > offPos : end >= offPos)\n break;\n let start = this.ranges[++this.rangeIndex].from;\n offset += start - end;\n }\n return offset;\n }\n moveRangeIndex() {\n while (this.ranges[this.rangeIndex].to < this.parsedPos)\n this.rangeIndex++;\n }\n emitToken(id, from, to, size, offset) {\n if (this.ranges.length > 1) {\n offset = this.skipGapsTo(from, offset, 1);\n from += offset;\n let len0 = this.chunk.length;\n offset = this.skipGapsTo(to, offset, -1);\n to += offset;\n size += this.chunk.length - len0;\n }\n this.chunk.push(id, from, to, size);\n return offset;\n }\n parseLine(context) {\n let { line, end } = this.nextLine(), offset = 0, { streamParser } = this.lang;\n let stream = new StringStream(line, context ? context.state.tabSize : 4, context ? getIndentUnit(context.state) : 2);\n if (stream.eol()) {\n streamParser.blankLine(this.state, stream.indentUnit);\n }\n else {\n while (!stream.eol()) {\n let token = readToken(streamParser.token, stream, this.state);\n if (token)\n offset = this.emitToken(this.lang.tokenTable.resolve(token), this.parsedPos + stream.start, this.parsedPos + stream.pos, 4, offset);\n if (stream.start > 10000 /* C.MaxLineLength */)\n break;\n }\n }\n this.parsedPos = end;\n this.moveRangeIndex();\n if (this.parsedPos < this.to)\n this.parsedPos++;\n }\n finishChunk() {\n let tree = Tree.build({\n buffer: this.chunk,\n start: this.chunkStart,\n length: this.parsedPos - this.chunkStart,\n nodeSet,\n topID: 0,\n maxBufferLength: 2048 /* C.ChunkSize */,\n reused: this.chunkReused\n });\n tree = new Tree(tree.type, tree.children, tree.positions, tree.length, [[this.lang.stateAfter, this.lang.streamParser.copyState(this.state)]]);\n this.chunks.push(tree);\n this.chunkPos.push(this.chunkStart - this.ranges[0].from);\n this.chunk = [];\n this.chunkReused = undefined;\n this.chunkStart = this.parsedPos;\n }\n finish() {\n return new Tree(this.lang.topNode, this.chunks, this.chunkPos, this.parsedPos - this.ranges[0].from).balance();\n }\n}\nfunction readToken(token, stream, state) {\n stream.start = stream.pos;\n for (let i = 0; i < 10; i++) {\n let result = token(stream, state);\n if (stream.pos > stream.start)\n return result;\n }\n throw new Error(\"Stream parser failed to advance stream.\");\n}\nconst noTokens = /*@__PURE__*/Object.create(null);\nconst typeArray = [NodeType.none];\nconst nodeSet = /*@__PURE__*/new NodeSet(typeArray);\nconst warned = [];\nconst defaultTable = /*@__PURE__*/Object.create(null);\nfor (let [legacyName, name] of [\n [\"variable\", \"variableName\"],\n [\"variable-2\", \"variableName.special\"],\n [\"string-2\", \"string.special\"],\n [\"def\", \"variableName.definition\"],\n [\"tag\", \"tagName\"],\n [\"attribute\", \"attributeName\"],\n [\"type\", \"typeName\"],\n [\"builtin\", \"variableName.standard\"],\n [\"qualifier\", \"modifier\"],\n [\"error\", \"invalid\"],\n [\"header\", \"heading\"],\n [\"property\", \"propertyName\"]\n])\n defaultTable[legacyName] = /*@__PURE__*/createTokenType(noTokens, name);\nclass TokenTable {\n constructor(extra) {\n this.extra = extra;\n this.table = Object.assign(Object.create(null), defaultTable);\n }\n resolve(tag) {\n return !tag ? 0 : this.table[tag] || (this.table[tag] = createTokenType(this.extra, tag));\n }\n}\nconst defaultTokenTable = /*@__PURE__*/new TokenTable(noTokens);\nfunction warnForPart(part, msg) {\n if (warned.indexOf(part) > -1)\n return;\n warned.push(part);\n console.warn(msg);\n}\nfunction createTokenType(extra, tagStr) {\n let tags$1 = [];\n for (let name of tagStr.split(\" \")) {\n let found = [];\n for (let part of name.split(\".\")) {\n let value = (extra[part] || tags[part]);\n if (!value) {\n warnForPart(part, `Unknown highlighting tag ${part}`);\n }\n else if (typeof value == \"function\") {\n if (!found.length)\n warnForPart(part, `Modifier ${part} used at start of tag`);\n else\n found = found.map(value);\n }\n else {\n if (found.length)\n warnForPart(part, `Tag ${part} used as modifier`);\n else\n found = Array.isArray(value) ? value : [value];\n }\n }\n for (let tag of found)\n tags$1.push(tag);\n }\n if (!tags$1.length)\n return 0;\n let name = tagStr.replace(/ /g, \"_\"), type = NodeType.define({\n id: typeArray.length,\n name,\n props: [styleTags({ [name]: tags$1 })]\n });\n typeArray.push(type);\n return type.id;\n}\nfunction docID(data) {\n let type = NodeType.define({ id: typeArray.length, name: \"Document\", props: [languageDataProp.add(() => data)], top: true });\n typeArray.push(type);\n return type;\n}\n\nexport { DocInput, HighlightStyle, IndentContext, LRLanguage, Language, LanguageDescription, LanguageSupport, ParseContext, StreamLanguage, StringStream, TreeIndentContext, bracketMatching, bracketMatchingHandle, codeFolding, continuedIndent, defaultHighlightStyle, defineLanguageFacet, delimitedIndent, ensureSyntaxTree, flatIndent, foldAll, foldCode, foldEffect, foldGutter, foldInside, foldKeymap, foldNodeProp, foldService, foldState, foldable, foldedRanges, forceParsing, getIndentUnit, getIndentation, highlightingFor, indentNodeProp, indentOnInput, indentRange, indentService, indentString, indentUnit, language, languageDataProp, matchBrackets, sublanguageProp, syntaxHighlighting, syntaxParserRunning, syntaxTree, syntaxTreeAvailable, toggleFold, unfoldAll, unfoldCode, unfoldEffect };\n","/**\nThe data structure for documents. @nonabstract\n*/\nclass Text {\n /**\n Get the line description around the given position.\n */\n lineAt(pos) {\n if (pos < 0 || pos > this.length)\n throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);\n return this.lineInner(pos, false, 1, 0);\n }\n /**\n Get the description for the given (1-based) line number.\n */\n line(n) {\n if (n < 1 || n > this.lines)\n throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`);\n return this.lineInner(n, true, 1, 0);\n }\n /**\n Replace a range of the text with the given content.\n */\n replace(from, to, text) {\n let parts = [];\n this.decompose(0, from, parts, 2 /* Open.To */);\n if (text.length)\n text.decompose(0, text.length, parts, 1 /* Open.From */ | 2 /* Open.To */);\n this.decompose(to, this.length, parts, 1 /* Open.From */);\n return TextNode.from(parts, this.length - (to - from) + text.length);\n }\n /**\n Append another document to this one.\n */\n append(other) {\n return this.replace(this.length, this.length, other);\n }\n /**\n Retrieve the text between the given points.\n */\n slice(from, to = this.length) {\n let parts = [];\n this.decompose(from, to, parts, 0);\n return TextNode.from(parts, to - from);\n }\n /**\n Test whether this text is equal to another instance.\n */\n eq(other) {\n if (other == this)\n return true;\n if (other.length != this.length || other.lines != this.lines)\n return false;\n let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1);\n let a = new RawTextCursor(this), b = new RawTextCursor(other);\n for (let skip = start, pos = start;;) {\n a.next(skip);\n b.next(skip);\n skip = 0;\n if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value)\n return false;\n pos += a.value.length;\n if (a.done || pos >= end)\n return true;\n }\n }\n /**\n Iterate over the text. When `dir` is `-1`, iteration happens\n from end to start. This will return lines and the breaks between\n them as separate strings.\n */\n iter(dir = 1) { return new RawTextCursor(this, dir); }\n /**\n Iterate over a range of the text. When `from` > `to`, the\n iterator will run in reverse.\n */\n iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); }\n /**\n Return a cursor that iterates over the given range of lines,\n _without_ returning the line breaks between, and yielding empty\n strings for empty lines.\n \n When `from` and `to` are given, they should be 1-based line numbers.\n */\n iterLines(from, to) {\n let inner;\n if (from == null) {\n inner = this.iter();\n }\n else {\n if (to == null)\n to = this.lines + 1;\n let start = this.line(from).from;\n inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to));\n }\n return new LineCursor(inner);\n }\n /**\n Return the document as a string, using newline characters to\n separate lines.\n */\n toString() { return this.sliceString(0); }\n /**\n Convert the document to an array of lines (which can be\n deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)).\n */\n toJSON() {\n let lines = [];\n this.flatten(lines);\n return lines;\n }\n /**\n @internal\n */\n constructor() { }\n /**\n Create a `Text` instance for the given array of lines.\n */\n static of(text) {\n if (text.length == 0)\n throw new RangeError(\"A document must have at least one line\");\n if (text.length == 1 && !text[0])\n return Text.empty;\n return text.length <= 32 /* Tree.Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, []));\n }\n}\n// Leaves store an array of line strings. There are always line breaks\n// between these strings. Leaves are limited in size and have to be\n// contained in TextNode instances for bigger documents.\nclass TextLeaf extends Text {\n constructor(text, length = textLength(text)) {\n super();\n this.text = text;\n this.length = length;\n }\n get lines() { return this.text.length; }\n get children() { return null; }\n lineInner(target, isLine, line, offset) {\n for (let i = 0;; i++) {\n let string = this.text[i], end = offset + string.length;\n if ((isLine ? line : end) >= target)\n return new Line(offset, end, line, string);\n offset = end + 1;\n line++;\n }\n }\n decompose(from, to, target, open) {\n let text = from <= 0 && to >= this.length ? this\n : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from));\n if (open & 1 /* Open.From */) {\n let prev = target.pop();\n let joined = appendText(text.text, prev.text.slice(), 0, text.length);\n if (joined.length <= 32 /* Tree.Branch */) {\n target.push(new TextLeaf(joined, prev.length + text.length));\n }\n else {\n let mid = joined.length >> 1;\n target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid)));\n }\n }\n else {\n target.push(text);\n }\n }\n replace(from, to, text) {\n if (!(text instanceof TextLeaf))\n return super.replace(from, to, text);\n let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to);\n let newLen = this.length + text.length - (to - from);\n if (lines.length <= 32 /* Tree.Branch */)\n return new TextLeaf(lines, newLen);\n return TextNode.from(TextLeaf.split(lines, []), newLen);\n }\n sliceString(from, to = this.length, lineSep = \"\\n\") {\n let result = \"\";\n for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) {\n let line = this.text[i], end = pos + line.length;\n if (pos > from && i)\n result += lineSep;\n if (from < end && to > pos)\n result += line.slice(Math.max(0, from - pos), to - pos);\n pos = end + 1;\n }\n return result;\n }\n flatten(target) {\n for (let line of this.text)\n target.push(line);\n }\n scanIdentical() { return 0; }\n static split(text, target) {\n let part = [], len = -1;\n for (let line of text) {\n part.push(line);\n len += line.length + 1;\n if (part.length == 32 /* Tree.Branch */) {\n target.push(new TextLeaf(part, len));\n part = [];\n len = -1;\n }\n }\n if (len > -1)\n target.push(new TextLeaf(part, len));\n return target;\n }\n}\n// Nodes provide the tree structure of the `Text` type. They store a\n// number of other nodes or leaves, taking care to balance themselves\n// on changes. There are implied line breaks _between_ the children of\n// a node (but not before the first or after the last child).\nclass TextNode extends Text {\n constructor(children, length) {\n super();\n this.children = children;\n this.length = length;\n this.lines = 0;\n for (let child of children)\n this.lines += child.lines;\n }\n lineInner(target, isLine, line, offset) {\n for (let i = 0;; i++) {\n let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1;\n if ((isLine ? endLine : end) >= target)\n return child.lineInner(target, isLine, line, offset);\n offset = end + 1;\n line = endLine + 1;\n }\n }\n decompose(from, to, target, open) {\n for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) {\n let child = this.children[i], end = pos + child.length;\n if (from <= end && to >= pos) {\n let childOpen = open & ((pos <= from ? 1 /* Open.From */ : 0) | (end >= to ? 2 /* Open.To */ : 0));\n if (pos >= from && end <= to && !childOpen)\n target.push(child);\n else\n child.decompose(from - pos, to - pos, target, childOpen);\n }\n pos = end + 1;\n }\n }\n replace(from, to, text) {\n if (text.lines < this.lines)\n for (let i = 0, pos = 0; i < this.children.length; i++) {\n let child = this.children[i], end = pos + child.length;\n // Fast path: if the change only affects one child and the\n // child's size remains in the acceptable range, only update\n // that child\n if (from >= pos && to <= end) {\n let updated = child.replace(from - pos, to - pos, text);\n let totalLines = this.lines - child.lines + updated.lines;\n if (updated.lines < (totalLines >> (5 /* Tree.BranchShift */ - 1)) &&\n updated.lines > (totalLines >> (5 /* Tree.BranchShift */ + 1))) {\n let copy = this.children.slice();\n copy[i] = updated;\n return new TextNode(copy, this.length - (to - from) + text.length);\n }\n return super.replace(pos, end, updated);\n }\n pos = end + 1;\n }\n return super.replace(from, to, text);\n }\n sliceString(from, to = this.length, lineSep = \"\\n\") {\n let result = \"\";\n for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) {\n let child = this.children[i], end = pos + child.length;\n if (pos > from && i)\n result += lineSep;\n if (from < end && to > pos)\n result += child.sliceString(from - pos, to - pos, lineSep);\n pos = end + 1;\n }\n return result;\n }\n flatten(target) {\n for (let child of this.children)\n child.flatten(target);\n }\n scanIdentical(other, dir) {\n if (!(other instanceof TextNode))\n return 0;\n let length = 0;\n let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length]\n : [this.children.length - 1, other.children.length - 1, -1, -1];\n for (;; iA += dir, iB += dir) {\n if (iA == eA || iB == eB)\n return length;\n let chA = this.children[iA], chB = other.children[iB];\n if (chA != chB)\n return length + chA.scanIdentical(chB, dir);\n length += chA.length + 1;\n }\n }\n static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) {\n let lines = 0;\n for (let ch of children)\n lines += ch.lines;\n if (lines < 32 /* Tree.Branch */) {\n let flat = [];\n for (let ch of children)\n ch.flatten(flat);\n return new TextLeaf(flat, length);\n }\n let chunk = Math.max(32 /* Tree.Branch */, lines >> 5 /* Tree.BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1;\n let chunked = [], currentLines = 0, currentLen = -1, currentChunk = [];\n function add(child) {\n let last;\n if (child.lines > maxChunk && child instanceof TextNode) {\n for (let node of child.children)\n add(node);\n }\n else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) {\n flush();\n chunked.push(child);\n }\n else if (child instanceof TextLeaf && currentLines &&\n (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf &&\n child.lines + last.lines <= 32 /* Tree.Branch */) {\n currentLines += child.lines;\n currentLen += child.length + 1;\n currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length);\n }\n else {\n if (currentLines + child.lines > chunk)\n flush();\n currentLines += child.lines;\n currentLen += child.length + 1;\n currentChunk.push(child);\n }\n }\n function flush() {\n if (currentLines == 0)\n return;\n chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen));\n currentLen = -1;\n currentLines = currentChunk.length = 0;\n }\n for (let child of children)\n add(child);\n flush();\n return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length);\n }\n}\nText.empty = /*@__PURE__*/new TextLeaf([\"\"], 0);\nfunction textLength(text) {\n let length = -1;\n for (let line of text)\n length += line.length + 1;\n return length;\n}\nfunction appendText(text, target, from = 0, to = 1e9) {\n for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) {\n let line = text[i], end = pos + line.length;\n if (end >= from) {\n if (end > to)\n line = line.slice(0, to - pos);\n if (pos < from)\n line = line.slice(from - pos);\n if (first) {\n target[target.length - 1] += line;\n first = false;\n }\n else\n target.push(line);\n }\n pos = end + 1;\n }\n return target;\n}\nfunction sliceText(text, from, to) {\n return appendText(text, [\"\"], from, to);\n}\nclass RawTextCursor {\n constructor(text, dir = 1) {\n this.dir = dir;\n this.done = false;\n this.lineBreak = false;\n this.value = \"\";\n this.nodes = [text];\n this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1];\n }\n nextInner(skip, dir) {\n this.done = this.lineBreak = false;\n for (;;) {\n let last = this.nodes.length - 1;\n let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1;\n let size = top instanceof TextLeaf ? top.text.length : top.children.length;\n if (offset == (dir > 0 ? size : 0)) {\n if (last == 0) {\n this.done = true;\n this.value = \"\";\n return this;\n }\n if (dir > 0)\n this.offsets[last - 1]++;\n this.nodes.pop();\n this.offsets.pop();\n }\n else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) {\n this.offsets[last] += dir;\n if (skip == 0) {\n this.lineBreak = true;\n this.value = \"\\n\";\n return this;\n }\n skip--;\n }\n else if (top instanceof TextLeaf) {\n // Move to the next string\n let next = top.text[offset + (dir < 0 ? -1 : 0)];\n this.offsets[last] += dir;\n if (next.length > Math.max(0, skip)) {\n this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip);\n return this;\n }\n skip -= next.length;\n }\n else {\n let next = top.children[offset + (dir < 0 ? -1 : 0)];\n if (skip > next.length) {\n skip -= next.length;\n this.offsets[last] += dir;\n }\n else {\n if (dir < 0)\n this.offsets[last]--;\n this.nodes.push(next);\n this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1);\n }\n }\n }\n }\n next(skip = 0) {\n if (skip < 0) {\n this.nextInner(-skip, (-this.dir));\n skip = this.value.length;\n }\n return this.nextInner(skip, this.dir);\n }\n}\nclass PartialTextCursor {\n constructor(text, start, end) {\n this.value = \"\";\n this.done = false;\n this.cursor = new RawTextCursor(text, start > end ? -1 : 1);\n this.pos = start > end ? text.length : 0;\n this.from = Math.min(start, end);\n this.to = Math.max(start, end);\n }\n nextInner(skip, dir) {\n if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) {\n this.value = \"\";\n this.done = true;\n return this;\n }\n skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos);\n let limit = dir < 0 ? this.pos - this.from : this.to - this.pos;\n if (skip > limit)\n skip = limit;\n limit -= skip;\n let { value } = this.cursor.next(skip);\n this.pos += (value.length + skip) * dir;\n this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit);\n this.done = !this.value;\n return this;\n }\n next(skip = 0) {\n if (skip < 0)\n skip = Math.max(skip, this.from - this.pos);\n else if (skip > 0)\n skip = Math.min(skip, this.to - this.pos);\n return this.nextInner(skip, this.cursor.dir);\n }\n get lineBreak() { return this.cursor.lineBreak && this.value != \"\"; }\n}\nclass LineCursor {\n constructor(inner) {\n this.inner = inner;\n this.afterBreak = true;\n this.value = \"\";\n this.done = false;\n }\n next(skip = 0) {\n let { done, lineBreak, value } = this.inner.next(skip);\n if (done) {\n this.done = true;\n this.value = \"\";\n }\n else if (lineBreak) {\n if (this.afterBreak) {\n this.value = \"\";\n }\n else {\n this.afterBreak = true;\n this.next();\n }\n }\n else {\n this.value = value;\n this.afterBreak = false;\n }\n return this;\n }\n get lineBreak() { return false; }\n}\nif (typeof Symbol != \"undefined\") {\n Text.prototype[Symbol.iterator] = function () { return this.iter(); };\n RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] =\n LineCursor.prototype[Symbol.iterator] = function () { return this; };\n}\n/**\nThis type describes a line in the document. It is created\non-demand when lines are [queried](https://codemirror.net/6/docs/ref/#state.Text.lineAt).\n*/\nclass Line {\n /**\n @internal\n */\n constructor(\n /**\n The position of the start of the line.\n */\n from, \n /**\n The position at the end of the line (_before_ the line break,\n or at the end of document for the last line).\n */\n to, \n /**\n This line's line number (1-based).\n */\n number, \n /**\n The line's content.\n */\n text) {\n this.from = from;\n this.to = to;\n this.number = number;\n this.text = text;\n }\n /**\n The length of the line (not including any line break after it).\n */\n get length() { return this.to - this.from; }\n}\n\n// Compressed representation of the Grapheme_Cluster_Break=Extend\n// information from\n// http://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakProperty.txt.\n// Each pair of elements represents a range, as an offet from the\n// previous range and a length. Numbers are in base-36, with the empty\n// string being a shorthand for 1.\nlet extend = /*@__PURE__*/\"lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4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2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o\".split(\",\").map(s => s ? parseInt(s, 36) : 1);\n// Convert offsets into absolute values\nfor (let i = 1; i < extend.length; i++)\n extend[i] += extend[i - 1];\nfunction isExtendingChar(code) {\n for (let i = 1; i < extend.length; i += 2)\n if (extend[i] > code)\n return extend[i - 1] <= code;\n return false;\n}\nfunction isRegionalIndicator(code) {\n return code >= 0x1F1E6 && code <= 0x1F1FF;\n}\nconst ZWJ = 0x200d;\n/**\nReturns a next grapheme cluster break _after_ (not equal to)\n`pos`, if `forward` is true, or before otherwise. Returns `pos`\nitself if no further cluster break is available in the string.\nMoves across surrogate pairs, extending characters (when\n`includeExtending` is true), characters joined with zero-width\njoiners, and flag emoji.\n*/\nfunction findClusterBreak(str, pos, forward = true, includeExtending = true) {\n return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending);\n}\nfunction nextClusterBreak(str, pos, includeExtending) {\n if (pos == str.length)\n return pos;\n // If pos is in the middle of a surrogate pair, move to its start\n if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1)))\n pos--;\n let prev = codePointAt(str, pos);\n pos += codePointSize(prev);\n while (pos < str.length) {\n let next = codePointAt(str, pos);\n if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) {\n pos += codePointSize(next);\n prev = next;\n }\n else if (isRegionalIndicator(next)) {\n let countBefore = 0, i = pos - 2;\n while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) {\n countBefore++;\n i -= 2;\n }\n if (countBefore % 2 == 0)\n break;\n else\n pos += 2;\n }\n else {\n break;\n }\n }\n return pos;\n}\nfunction prevClusterBreak(str, pos, includeExtending) {\n while (pos > 0) {\n let found = nextClusterBreak(str, pos - 2, includeExtending);\n if (found < pos)\n return found;\n pos--;\n }\n return 0;\n}\nfunction surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; }\nfunction surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; }\n/**\nFind the code point at the given position in a string (like the\n[`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt)\nstring method).\n*/\nfunction codePointAt(str, pos) {\n let code0 = str.charCodeAt(pos);\n if (!surrogateHigh(code0) || pos + 1 == str.length)\n return code0;\n let code1 = str.charCodeAt(pos + 1);\n if (!surrogateLow(code1))\n return code0;\n return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000;\n}\n/**\nGiven a Unicode codepoint, return the JavaScript string that\nrespresents it (like\n[`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)).\n*/\nfunction fromCodePoint(code) {\n if (code <= 0xffff)\n return String.fromCharCode(code);\n code -= 0x10000;\n return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00);\n}\n/**\nThe amount of positions a character takes up a JavaScript string.\n*/\nfunction codePointSize(code) { return code < 0x10000 ? 1 : 2; }\n\nconst DefaultSplit = /\\r\\n?|\\n/;\n/**\nDistinguishes different ways in which positions can be mapped.\n*/\nvar MapMode = /*@__PURE__*/(function (MapMode) {\n /**\n Map a position to a valid new position, even when its context\n was deleted.\n */\n MapMode[MapMode[\"Simple\"] = 0] = \"Simple\";\n /**\n Return null if deletion happens across the position.\n */\n MapMode[MapMode[\"TrackDel\"] = 1] = \"TrackDel\";\n /**\n Return null if the character _before_ the position is deleted.\n */\n MapMode[MapMode[\"TrackBefore\"] = 2] = \"TrackBefore\";\n /**\n Return null if the character _after_ the position is deleted.\n */\n MapMode[MapMode[\"TrackAfter\"] = 3] = \"TrackAfter\";\nreturn MapMode})(MapMode || (MapMode = {}));\n/**\nA change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet)\nthat doesn't store the inserted text. As such, it can't be\napplied, but is cheaper to store and manipulate.\n*/\nclass ChangeDesc {\n // Sections are encoded as pairs of integers. The first is the\n // length in the current document, and the second is -1 for\n // unaffected sections, and the length of the replacement content\n // otherwise. So an insertion would be (0, n>0), a deletion (n>0,\n // 0), and a replacement two positive numbers.\n /**\n @internal\n */\n constructor(\n /**\n @internal\n */\n sections) {\n this.sections = sections;\n }\n /**\n The length of the document before the change.\n */\n get length() {\n let result = 0;\n for (let i = 0; i < this.sections.length; i += 2)\n result += this.sections[i];\n return result;\n }\n /**\n The length of the document after the change.\n */\n get newLength() {\n let result = 0;\n for (let i = 0; i < this.sections.length; i += 2) {\n let ins = this.sections[i + 1];\n result += ins < 0 ? this.sections[i] : ins;\n }\n return result;\n }\n /**\n False when there are actual changes in this set.\n */\n get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; }\n /**\n Iterate over the unchanged parts left by these changes. `posA`\n provides the position of the range in the old document, `posB`\n the new position in the changed document.\n */\n iterGaps(f) {\n for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) {\n let len = this.sections[i++], ins = this.sections[i++];\n if (ins < 0) {\n f(posA, posB, len);\n posB += len;\n }\n else {\n posB += ins;\n }\n posA += len;\n }\n }\n /**\n Iterate over the ranges changed by these changes. (See\n [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a\n variant that also provides you with the inserted text.)\n `fromA`/`toA` provides the extent of the change in the starting\n document, `fromB`/`toB` the extent of the replacement in the\n changed document.\n \n When `individual` is true, adjacent changes (which are kept\n separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are\n reported separately.\n */\n iterChangedRanges(f, individual = false) {\n iterChanges(this, f, individual);\n }\n /**\n Get a description of the inverted form of these changes.\n */\n get invertedDesc() {\n let sections = [];\n for (let i = 0; i < this.sections.length;) {\n let len = this.sections[i++], ins = this.sections[i++];\n if (ins < 0)\n sections.push(len, ins);\n else\n sections.push(ins, len);\n }\n return new ChangeDesc(sections);\n }\n /**\n Compute the combined effect of applying another set of changes\n after this one. The length of the document after this set should\n match the length before `other`.\n */\n composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); }\n /**\n Map this description, which should start with the same document\n as `other`, over another set of changes, so that it can be\n applied after it. When `before` is true, map as if the changes\n in `other` happened before the ones in `this`.\n */\n mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); }\n mapPos(pos, assoc = -1, mode = MapMode.Simple) {\n let posA = 0, posB = 0;\n for (let i = 0; i < this.sections.length;) {\n let len = this.sections[i++], ins = this.sections[i++], endA = posA + len;\n if (ins < 0) {\n if (endA > pos)\n return posB + (pos - posA);\n posB += len;\n }\n else {\n if (mode != MapMode.Simple && endA >= pos &&\n (mode == MapMode.TrackDel && posA < pos && endA > pos ||\n mode == MapMode.TrackBefore && posA < pos ||\n mode == MapMode.TrackAfter && endA > pos))\n return null;\n if (endA > pos || endA == pos && assoc < 0 && !len)\n return pos == posA || assoc < 0 ? posB : posB + ins;\n posB += ins;\n }\n posA = endA;\n }\n if (pos > posA)\n throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);\n return posB;\n }\n /**\n Check whether these changes touch a given range. When one of the\n changes entirely covers the range, the string `\"cover\"` is\n returned.\n */\n touchesRange(from, to = from) {\n for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) {\n let len = this.sections[i++], ins = this.sections[i++], end = pos + len;\n if (ins >= 0 && pos <= to && end >= from)\n return pos < from && end > to ? \"cover\" : true;\n pos = end;\n }\n return false;\n }\n /**\n @internal\n */\n toString() {\n let result = \"\";\n for (let i = 0; i < this.sections.length;) {\n let len = this.sections[i++], ins = this.sections[i++];\n result += (result ? \" \" : \"\") + len + (ins >= 0 ? \":\" + ins : \"\");\n }\n return result;\n }\n /**\n Serialize this change desc to a JSON-representable value.\n */\n toJSON() { return this.sections; }\n /**\n Create a change desc from its JSON representation (as produced\n by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON).\n */\n static fromJSON(json) {\n if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != \"number\"))\n throw new RangeError(\"Invalid JSON representation of ChangeDesc\");\n return new ChangeDesc(json);\n }\n /**\n @internal\n */\n static create(sections) { return new ChangeDesc(sections); }\n}\n/**\nA change set represents a group of modifications to a document. It\nstores the document length, and can only be applied to documents\nwith exactly that length.\n*/\nclass ChangeSet extends ChangeDesc {\n constructor(sections, \n /**\n @internal\n */\n inserted) {\n super(sections);\n this.inserted = inserted;\n }\n /**\n Apply the changes to a document, returning the modified\n document.\n */\n apply(doc) {\n if (this.length != doc.length)\n throw new RangeError(\"Applying change set to a document with the wrong length\");\n iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false);\n return doc;\n }\n mapDesc(other, before = false) { return mapSet(this, other, before, true); }\n /**\n Given the document as it existed _before_ the changes, return a\n change set that represents the inverse of this set, which could\n be used to go from the document created by the changes back to\n the document as it existed before the changes.\n */\n invert(doc) {\n let sections = this.sections.slice(), inserted = [];\n for (let i = 0, pos = 0; i < sections.length; i += 2) {\n let len = sections[i], ins = sections[i + 1];\n if (ins >= 0) {\n sections[i] = ins;\n sections[i + 1] = len;\n let index = i >> 1;\n while (inserted.length < index)\n inserted.push(Text.empty);\n inserted.push(len ? doc.slice(pos, pos + len) : Text.empty);\n }\n pos += len;\n }\n return new ChangeSet(sections, inserted);\n }\n /**\n Combine two subsequent change sets into a single set. `other`\n must start in the document produced by `this`. If `this` goes\n `docA` → `docB` and `other` represents `docB` → `docC`, the\n returned value will represent the change `docA` → `docC`.\n */\n compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); }\n /**\n Given another change set starting in the same document, maps this\n change set over the other, producing a new change set that can be\n applied to the document produced by applying `other`. When\n `before` is `true`, order changes as if `this` comes before\n `other`, otherwise (the default) treat `other` as coming first.\n \n Given two changes `A` and `B`, `A.compose(B.map(A))` and\n `B.compose(A.map(B, true))` will produce the same document. This\n provides a basic form of [operational\n transformation](https://en.wikipedia.org/wiki/Operational_transformation),\n and can be used for collaborative editing.\n */\n map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); }\n /**\n Iterate over the changed ranges in the document, calling `f` for\n each, with the range in the original document (`fromA`-`toA`)\n and the range that replaces it in the new document\n (`fromB`-`toB`).\n \n When `individual` is true, adjacent changes are reported\n separately.\n */\n iterChanges(f, individual = false) {\n iterChanges(this, f, individual);\n }\n /**\n Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change\n set.\n */\n get desc() { return ChangeDesc.create(this.sections); }\n /**\n @internal\n */\n filter(ranges) {\n let resultSections = [], resultInserted = [], filteredSections = [];\n let iter = new SectionIter(this);\n done: for (let i = 0, pos = 0;;) {\n let next = i == ranges.length ? 1e9 : ranges[i++];\n while (pos < next || pos == next && iter.len == 0) {\n if (iter.done)\n break done;\n let len = Math.min(iter.len, next - pos);\n addSection(filteredSections, len, -1);\n let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0;\n addSection(resultSections, len, ins);\n if (ins > 0)\n addInsert(resultInserted, resultSections, iter.text);\n iter.forward(len);\n pos += len;\n }\n let end = ranges[i++];\n while (pos < end) {\n if (iter.done)\n break done;\n let len = Math.min(iter.len, end - pos);\n addSection(resultSections, len, -1);\n addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);\n iter.forward(len);\n pos += len;\n }\n }\n return { changes: new ChangeSet(resultSections, resultInserted),\n filtered: ChangeDesc.create(filteredSections) };\n }\n /**\n Serialize this change set to a JSON-representable value.\n */\n toJSON() {\n let parts = [];\n for (let i = 0; i < this.sections.length; i += 2) {\n let len = this.sections[i], ins = this.sections[i + 1];\n if (ins < 0)\n parts.push(len);\n else if (ins == 0)\n parts.push([len]);\n else\n parts.push([len].concat(this.inserted[i >> 1].toJSON()));\n }\n return parts;\n }\n /**\n Create a change set for the given changes, for a document of the\n given length, using `lineSep` as line separator.\n */\n static of(changes, length, lineSep) {\n let sections = [], inserted = [], pos = 0;\n let total = null;\n function flush(force = false) {\n if (!force && !sections.length)\n return;\n if (pos < length)\n addSection(sections, length - pos, -1);\n let set = new ChangeSet(sections, inserted);\n total = total ? total.compose(set.map(total)) : set;\n sections = [];\n inserted = [];\n pos = 0;\n }\n function process(spec) {\n if (Array.isArray(spec)) {\n for (let sub of spec)\n process(sub);\n }\n else if (spec instanceof ChangeSet) {\n if (spec.length != length)\n throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);\n flush();\n total = total ? total.compose(spec.map(total)) : spec;\n }\n else {\n let { from, to = from, insert } = spec;\n if (from > to || from < 0 || to > length)\n throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);\n let insText = !insert ? Text.empty : typeof insert == \"string\" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert;\n let insLen = insText.length;\n if (from == to && insLen == 0)\n return;\n if (from < pos)\n flush();\n if (from > pos)\n addSection(sections, from - pos, -1);\n addSection(sections, to - from, insLen);\n addInsert(inserted, sections, insText);\n pos = to;\n }\n }\n process(changes);\n flush(!total);\n return total;\n }\n /**\n Create an empty changeset of the given length.\n */\n static empty(length) {\n return new ChangeSet(length ? [length, -1] : [], []);\n }\n /**\n Create a changeset from its JSON representation (as produced by\n [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON).\n */\n static fromJSON(json) {\n if (!Array.isArray(json))\n throw new RangeError(\"Invalid JSON representation of ChangeSet\");\n let sections = [], inserted = [];\n for (let i = 0; i < json.length; i++) {\n let part = json[i];\n if (typeof part == \"number\") {\n sections.push(part, -1);\n }\n else if (!Array.isArray(part) || typeof part[0] != \"number\" || part.some((e, i) => i && typeof e != \"string\")) {\n throw new RangeError(\"Invalid JSON representation of ChangeSet\");\n }\n else if (part.length == 1) {\n sections.push(part[0], 0);\n }\n else {\n while (inserted.length < i)\n inserted.push(Text.empty);\n inserted[i] = Text.of(part.slice(1));\n sections.push(part[0], inserted[i].length);\n }\n }\n return new ChangeSet(sections, inserted);\n }\n /**\n @internal\n */\n static createSet(sections, inserted) {\n return new ChangeSet(sections, inserted);\n }\n}\nfunction addSection(sections, len, ins, forceJoin = false) {\n if (len == 0 && ins <= 0)\n return;\n let last = sections.length - 2;\n if (last >= 0 && ins <= 0 && ins == sections[last + 1])\n sections[last] += len;\n else if (len == 0 && sections[last] == 0)\n sections[last + 1] += ins;\n else if (forceJoin) {\n sections[last] += len;\n sections[last + 1] += ins;\n }\n else\n sections.push(len, ins);\n}\nfunction addInsert(values, sections, value) {\n if (value.length == 0)\n return;\n let index = (sections.length - 2) >> 1;\n if (index < values.length) {\n values[values.length - 1] = values[values.length - 1].append(value);\n }\n else {\n while (values.length < index)\n values.push(Text.empty);\n values.push(value);\n }\n}\nfunction iterChanges(desc, f, individual) {\n let inserted = desc.inserted;\n for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) {\n let len = desc.sections[i++], ins = desc.sections[i++];\n if (ins < 0) {\n posA += len;\n posB += len;\n }\n else {\n let endA = posA, endB = posB, text = Text.empty;\n for (;;) {\n endA += len;\n endB += ins;\n if (ins && inserted)\n text = text.append(inserted[(i - 2) >> 1]);\n if (individual || i == desc.sections.length || desc.sections[i + 1] < 0)\n break;\n len = desc.sections[i++];\n ins = desc.sections[i++];\n }\n f(posA, endA, posB, endB, text);\n posA = endA;\n posB = endB;\n }\n }\n}\nfunction mapSet(setA, setB, before, mkSet = false) {\n // Produce a copy of setA that applies to the document after setB\n // has been applied (assuming both start at the same document).\n let sections = [], insert = mkSet ? [] : null;\n let a = new SectionIter(setA), b = new SectionIter(setB);\n // Iterate over both sets in parallel. inserted tracks, for changes\n // in A that have to be processed piece-by-piece, whether their\n // content has been inserted already, and refers to the section\n // index.\n for (let inserted = -1;;) {\n if (a.ins == -1 && b.ins == -1) {\n // Move across ranges skipped by both sets.\n let len = Math.min(a.len, b.len);\n addSection(sections, len, -1);\n a.forward(len);\n b.forward(len);\n }\n else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) {\n // If there's a change in B that comes before the next change in\n // A (ordered by start pos, then len, then before flag), skip\n // that (and process any changes in A it covers).\n let len = b.len;\n addSection(sections, b.ins, -1);\n while (len) {\n let piece = Math.min(a.len, len);\n if (a.ins >= 0 && inserted < a.i && a.len <= piece) {\n addSection(sections, 0, a.ins);\n if (insert)\n addInsert(insert, sections, a.text);\n inserted = a.i;\n }\n a.forward(piece);\n len -= piece;\n }\n b.next();\n }\n else if (a.ins >= 0) {\n // Process the part of a change in A up to the start of the next\n // non-deletion change in B (if overlapping).\n let len = 0, left = a.len;\n while (left) {\n if (b.ins == -1) {\n let piece = Math.min(left, b.len);\n len += piece;\n left -= piece;\n b.forward(piece);\n }\n else if (b.ins == 0 && b.len < left) {\n left -= b.len;\n b.next();\n }\n else {\n break;\n }\n }\n addSection(sections, len, inserted < a.i ? a.ins : 0);\n if (insert && inserted < a.i)\n addInsert(insert, sections, a.text);\n inserted = a.i;\n a.forward(a.len - left);\n }\n else if (a.done && b.done) {\n return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);\n }\n else {\n throw new Error(\"Mismatched change set lengths\");\n }\n }\n}\nfunction composeSets(setA, setB, mkSet = false) {\n let sections = [];\n let insert = mkSet ? [] : null;\n let a = new SectionIter(setA), b = new SectionIter(setB);\n for (let open = false;;) {\n if (a.done && b.done) {\n return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);\n }\n else if (a.ins == 0) { // Deletion in A\n addSection(sections, a.len, 0, open);\n a.next();\n }\n else if (b.len == 0 && !b.done) { // Insertion in B\n addSection(sections, 0, b.ins, open);\n if (insert)\n addInsert(insert, sections, b.text);\n b.next();\n }\n else if (a.done || b.done) {\n throw new Error(\"Mismatched change set lengths\");\n }\n else {\n let len = Math.min(a.len2, b.len), sectionLen = sections.length;\n if (a.ins == -1) {\n let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins;\n addSection(sections, len, insB, open);\n if (insert && insB)\n addInsert(insert, sections, b.text);\n }\n else if (b.ins == -1) {\n addSection(sections, a.off ? 0 : a.len, len, open);\n if (insert)\n addInsert(insert, sections, a.textBit(len));\n }\n else {\n addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open);\n if (insert && !b.off)\n addInsert(insert, sections, b.text);\n }\n open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen);\n a.forward2(len);\n b.forward(len);\n }\n }\n}\nclass SectionIter {\n constructor(set) {\n this.set = set;\n this.i = 0;\n this.next();\n }\n next() {\n let { sections } = this.set;\n if (this.i < sections.length) {\n this.len = sections[this.i++];\n this.ins = sections[this.i++];\n }\n else {\n this.len = 0;\n this.ins = -2;\n }\n this.off = 0;\n }\n get done() { return this.ins == -2; }\n get len2() { return this.ins < 0 ? this.len : this.ins; }\n get text() {\n let { inserted } = this.set, index = (this.i - 2) >> 1;\n return index >= inserted.length ? Text.empty : inserted[index];\n }\n textBit(len) {\n let { inserted } = this.set, index = (this.i - 2) >> 1;\n return index >= inserted.length && !len ? Text.empty\n : inserted[index].slice(this.off, len == null ? undefined : this.off + len);\n }\n forward(len) {\n if (len == this.len)\n this.next();\n else {\n this.len -= len;\n this.off += len;\n }\n }\n forward2(len) {\n if (this.ins == -1)\n this.forward(len);\n else if (len == this.ins)\n this.next();\n else {\n this.ins -= len;\n this.off += len;\n }\n }\n}\n\n/**\nA single selection range. When\n[`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)\nis enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold\nmultiple ranges. By default, selections hold exactly one range.\n*/\nclass SelectionRange {\n constructor(\n /**\n The lower boundary of the range.\n */\n from, \n /**\n The upper boundary of the range.\n */\n to, flags) {\n this.from = from;\n this.to = to;\n this.flags = flags;\n }\n /**\n The anchor of the range—the side that doesn't move when you\n extend it.\n */\n get anchor() { return this.flags & 32 /* RangeFlag.Inverted */ ? this.to : this.from; }\n /**\n The head of the range, which is moved when the range is\n [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend).\n */\n get head() { return this.flags & 32 /* RangeFlag.Inverted */ ? this.from : this.to; }\n /**\n True when `anchor` and `head` are at the same position.\n */\n get empty() { return this.from == this.to; }\n /**\n If this is a cursor that is explicitly associated with the\n character on one of its sides, this returns the side. -1 means\n the character before its position, 1 the character after, and 0\n means no association.\n */\n get assoc() { return this.flags & 8 /* RangeFlag.AssocBefore */ ? -1 : this.flags & 16 /* RangeFlag.AssocAfter */ ? 1 : 0; }\n /**\n The bidirectional text level associated with this cursor, if\n any.\n */\n get bidiLevel() {\n let level = this.flags & 7 /* RangeFlag.BidiLevelMask */;\n return level == 7 ? null : level;\n }\n /**\n The goal column (stored vertical offset) associated with a\n cursor. This is used to preserve the vertical position when\n [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across\n lines of different length.\n */\n get goalColumn() {\n let value = this.flags >> 6 /* RangeFlag.GoalColumnOffset */;\n return value == 16777215 /* RangeFlag.NoGoalColumn */ ? undefined : value;\n }\n /**\n Map this range through a change, producing a valid range in the\n updated document.\n */\n map(change, assoc = -1) {\n let from, to;\n if (this.empty) {\n from = to = change.mapPos(this.from, assoc);\n }\n else {\n from = change.mapPos(this.from, 1);\n to = change.mapPos(this.to, -1);\n }\n return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags);\n }\n /**\n Extend this range to cover at least `from` to `to`.\n */\n extend(from, to = from) {\n if (from <= this.anchor && to >= this.anchor)\n return EditorSelection.range(from, to);\n let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to;\n return EditorSelection.range(this.anchor, head);\n }\n /**\n Compare this range to another range.\n */\n eq(other) {\n return this.anchor == other.anchor && this.head == other.head;\n }\n /**\n Return a JSON-serializable object representing the range.\n */\n toJSON() { return { anchor: this.anchor, head: this.head }; }\n /**\n Convert a JSON representation of a range to a `SelectionRange`\n instance.\n */\n static fromJSON(json) {\n if (!json || typeof json.anchor != \"number\" || typeof json.head != \"number\")\n throw new RangeError(\"Invalid JSON representation for SelectionRange\");\n return EditorSelection.range(json.anchor, json.head);\n }\n /**\n @internal\n */\n static create(from, to, flags) {\n return new SelectionRange(from, to, flags);\n }\n}\n/**\nAn editor selection holds one or more selection ranges.\n*/\nclass EditorSelection {\n constructor(\n /**\n The ranges in the selection, sorted by position. Ranges cannot\n overlap (but they may touch, if they aren't empty).\n */\n ranges, \n /**\n The index of the _main_ range in the selection (which is\n usually the range that was added last).\n */\n mainIndex) {\n this.ranges = ranges;\n this.mainIndex = mainIndex;\n }\n /**\n Map a selection through a change. Used to adjust the selection\n position for changes.\n */\n map(change, assoc = -1) {\n if (change.empty)\n return this;\n return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex);\n }\n /**\n Compare this selection to another selection.\n */\n eq(other) {\n if (this.ranges.length != other.ranges.length ||\n this.mainIndex != other.mainIndex)\n return false;\n for (let i = 0; i < this.ranges.length; i++)\n if (!this.ranges[i].eq(other.ranges[i]))\n return false;\n return true;\n }\n /**\n Get the primary selection range. Usually, you should make sure\n your code applies to _all_ ranges, by using methods like\n [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange).\n */\n get main() { return this.ranges[this.mainIndex]; }\n /**\n Make sure the selection only has one range. Returns a selection\n holding only the main range from this selection.\n */\n asSingle() {\n return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0);\n }\n /**\n Extend this selection with an extra range.\n */\n addRange(range, main = true) {\n return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1);\n }\n /**\n Replace a given range with another range, and then normalize the\n selection to merge and sort ranges if necessary.\n */\n replaceRange(range, which = this.mainIndex) {\n let ranges = this.ranges.slice();\n ranges[which] = range;\n return EditorSelection.create(ranges, this.mainIndex);\n }\n /**\n Convert this selection to an object that can be serialized to\n JSON.\n */\n toJSON() {\n return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex };\n }\n /**\n Create a selection from a JSON representation.\n */\n static fromJSON(json) {\n if (!json || !Array.isArray(json.ranges) || typeof json.main != \"number\" || json.main >= json.ranges.length)\n throw new RangeError(\"Invalid JSON representation for EditorSelection\");\n return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main);\n }\n /**\n Create a selection holding a single range.\n */\n static single(anchor, head = anchor) {\n return new EditorSelection([EditorSelection.range(anchor, head)], 0);\n }\n /**\n Sort and merge the given set of ranges, creating a valid\n selection.\n */\n static create(ranges, mainIndex = 0) {\n if (ranges.length == 0)\n throw new RangeError(\"A selection needs at least one range\");\n for (let pos = 0, i = 0; i < ranges.length; i++) {\n let range = ranges[i];\n if (range.empty ? range.from <= pos : range.from < pos)\n return EditorSelection.normalized(ranges.slice(), mainIndex);\n pos = range.to;\n }\n return new EditorSelection(ranges, mainIndex);\n }\n /**\n Create a cursor selection range at the given position. You can\n safely ignore the optional arguments in most situations.\n */\n static cursor(pos, assoc = 0, bidiLevel, goalColumn) {\n return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 8 /* RangeFlag.AssocBefore */ : 16 /* RangeFlag.AssocAfter */) |\n (bidiLevel == null ? 7 : Math.min(6, bidiLevel)) |\n ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215 /* RangeFlag.NoGoalColumn */) << 6 /* RangeFlag.GoalColumnOffset */));\n }\n /**\n Create a selection range.\n */\n static range(anchor, head, goalColumn, bidiLevel) {\n let flags = ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215 /* RangeFlag.NoGoalColumn */) << 6 /* RangeFlag.GoalColumnOffset */) |\n (bidiLevel == null ? 7 : Math.min(6, bidiLevel));\n return head < anchor ? SelectionRange.create(head, anchor, 32 /* RangeFlag.Inverted */ | 16 /* RangeFlag.AssocAfter */ | flags)\n : SelectionRange.create(anchor, head, (head > anchor ? 8 /* RangeFlag.AssocBefore */ : 0) | flags);\n }\n /**\n @internal\n */\n static normalized(ranges, mainIndex = 0) {\n let main = ranges[mainIndex];\n ranges.sort((a, b) => a.from - b.from);\n mainIndex = ranges.indexOf(main);\n for (let i = 1; i < ranges.length; i++) {\n let range = ranges[i], prev = ranges[i - 1];\n if (range.empty ? range.from <= prev.to : range.from < prev.to) {\n let from = prev.from, to = Math.max(range.to, prev.to);\n if (i <= mainIndex)\n mainIndex--;\n ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to));\n }\n }\n return new EditorSelection(ranges, mainIndex);\n }\n}\nfunction checkSelection(selection, docLength) {\n for (let range of selection.ranges)\n if (range.to > docLength)\n throw new RangeError(\"Selection points outside of document\");\n}\n\nlet nextID = 0;\n/**\nA facet is a labeled value that is associated with an editor\nstate. It takes inputs from any number of extensions, and combines\nthose into a single output value.\n\nExamples of uses of facets are the [tab\nsize](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize), [editor\nattributes](https://codemirror.net/6/docs/ref/#view.EditorView^editorAttributes), and [update\nlisteners](https://codemirror.net/6/docs/ref/#view.EditorView^updateListener).\n\nNote that `Facet` instances can be used anywhere where\n[`FacetReader`](https://codemirror.net/6/docs/ref/#state.FacetReader) is expected.\n*/\nclass Facet {\n constructor(\n /**\n @internal\n */\n combine, \n /**\n @internal\n */\n compareInput, \n /**\n @internal\n */\n compare, isStatic, enables) {\n this.combine = combine;\n this.compareInput = compareInput;\n this.compare = compare;\n this.isStatic = isStatic;\n /**\n @internal\n */\n this.id = nextID++;\n this.default = combine([]);\n this.extensions = typeof enables == \"function\" ? enables(this) : enables;\n }\n /**\n Returns a facet reader for this facet, which can be used to\n [read](https://codemirror.net/6/docs/ref/#state.EditorState.facet) it but not to define values for it.\n */\n get reader() { return this; }\n /**\n Define a new facet.\n */\n static define(config = {}) {\n return new Facet(config.combine || ((a) => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray : (a, b) => a === b), !!config.static, config.enables);\n }\n /**\n Returns an extension that adds the given value to this facet.\n */\n of(value) {\n return new FacetProvider([], this, 0 /* Provider.Static */, value);\n }\n /**\n Create an extension that computes a value for the facet from a\n state. You must take care to declare the parts of the state that\n this value depends on, since your function is only called again\n for a new state when one of those parts changed.\n \n In cases where your value depends only on a single field, you'll\n want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead.\n */\n compute(deps, get) {\n if (this.isStatic)\n throw new Error(\"Can't compute a static facet\");\n return new FacetProvider(deps, this, 1 /* Provider.Single */, get);\n }\n /**\n Create an extension that computes zero or more values for this\n facet from a state.\n */\n computeN(deps, get) {\n if (this.isStatic)\n throw new Error(\"Can't compute a static facet\");\n return new FacetProvider(deps, this, 2 /* Provider.Multi */, get);\n }\n from(field, get) {\n if (!get)\n get = x => x;\n return this.compute([field], state => get(state.field(field)));\n }\n}\nfunction sameArray(a, b) {\n return a == b || a.length == b.length && a.every((e, i) => e === b[i]);\n}\nclass FacetProvider {\n constructor(dependencies, facet, type, value) {\n this.dependencies = dependencies;\n this.facet = facet;\n this.type = type;\n this.value = value;\n this.id = nextID++;\n }\n dynamicSlot(addresses) {\n var _a;\n let getter = this.value;\n let compare = this.facet.compareInput;\n let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Provider.Multi */;\n let depDoc = false, depSel = false, depAddrs = [];\n for (let dep of this.dependencies) {\n if (dep == \"doc\")\n depDoc = true;\n else if (dep == \"selection\")\n depSel = true;\n else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0)\n depAddrs.push(addresses[dep.id]);\n }\n return {\n create(state) {\n state.values[idx] = getter(state);\n return 1 /* SlotStatus.Changed */;\n },\n update(state, tr) {\n if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || ensureAll(state, depAddrs)) {\n let newVal = getter(state);\n if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) {\n state.values[idx] = newVal;\n return 1 /* SlotStatus.Changed */;\n }\n }\n return 0;\n },\n reconfigure: (state, oldState) => {\n let newVal, oldAddr = oldState.config.address[id];\n if (oldAddr != null) {\n let oldVal = getAddr(oldState, oldAddr);\n if (this.dependencies.every(dep => {\n return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) :\n dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true;\n }) || (multi ? compareArray(newVal = getter(state), oldVal, compare) : compare(newVal = getter(state), oldVal))) {\n state.values[idx] = oldVal;\n return 0;\n }\n }\n else {\n newVal = getter(state);\n }\n state.values[idx] = newVal;\n return 1 /* SlotStatus.Changed */;\n }\n };\n }\n}\nfunction compareArray(a, b, compare) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!compare(a[i], b[i]))\n return false;\n return true;\n}\nfunction ensureAll(state, addrs) {\n let changed = false;\n for (let addr of addrs)\n if (ensureAddr(state, addr) & 1 /* SlotStatus.Changed */)\n changed = true;\n return changed;\n}\nfunction dynamicFacetSlot(addresses, facet, providers) {\n let providerAddrs = providers.map(p => addresses[p.id]);\n let providerTypes = providers.map(p => p.type);\n let dynamic = providerAddrs.filter(p => !(p & 1));\n let idx = addresses[facet.id] >> 1;\n function get(state) {\n let values = [];\n for (let i = 0; i < providerAddrs.length; i++) {\n let value = getAddr(state, providerAddrs[i]);\n if (providerTypes[i] == 2 /* Provider.Multi */)\n for (let val of value)\n values.push(val);\n else\n values.push(value);\n }\n return facet.combine(values);\n }\n return {\n create(state) {\n for (let addr of providerAddrs)\n ensureAddr(state, addr);\n state.values[idx] = get(state);\n return 1 /* SlotStatus.Changed */;\n },\n update(state, tr) {\n if (!ensureAll(state, dynamic))\n return 0;\n let value = get(state);\n if (facet.compare(value, state.values[idx]))\n return 0;\n state.values[idx] = value;\n return 1 /* SlotStatus.Changed */;\n },\n reconfigure(state, oldState) {\n let depChanged = ensureAll(state, providerAddrs);\n let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet);\n if (oldProviders && !depChanged && sameArray(providers, oldProviders)) {\n state.values[idx] = oldValue;\n return 0;\n }\n let value = get(state);\n if (facet.compare(value, oldValue)) {\n state.values[idx] = oldValue;\n return 0;\n }\n state.values[idx] = value;\n return 1 /* SlotStatus.Changed */;\n }\n };\n}\nconst initField = /*@__PURE__*/Facet.define({ static: true });\n/**\nFields can store additional information in an editor state, and\nkeep it in sync with the rest of the state.\n*/\nclass StateField {\n constructor(\n /**\n @internal\n */\n id, createF, updateF, compareF, \n /**\n @internal\n */\n spec) {\n this.id = id;\n this.createF = createF;\n this.updateF = updateF;\n this.compareF = compareF;\n this.spec = spec;\n /**\n @internal\n */\n this.provides = undefined;\n }\n /**\n Define a state field.\n */\n static define(config) {\n let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config);\n if (config.provide)\n field.provides = config.provide(field);\n return field;\n }\n create(state) {\n let init = state.facet(initField).find(i => i.field == this);\n return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state);\n }\n /**\n @internal\n */\n slot(addresses) {\n let idx = addresses[this.id] >> 1;\n return {\n create: (state) => {\n state.values[idx] = this.create(state);\n return 1 /* SlotStatus.Changed */;\n },\n update: (state, tr) => {\n let oldVal = state.values[idx];\n let value = this.updateF(oldVal, tr);\n if (this.compareF(oldVal, value))\n return 0;\n state.values[idx] = value;\n return 1 /* SlotStatus.Changed */;\n },\n reconfigure: (state, oldState) => {\n if (oldState.config.address[this.id] != null) {\n state.values[idx] = oldState.field(this);\n return 0;\n }\n state.values[idx] = this.create(state);\n return 1 /* SlotStatus.Changed */;\n }\n };\n }\n /**\n Returns an extension that enables this field and overrides the\n way it is initialized. Can be useful when you need to provide a\n non-default starting value for the field.\n */\n init(create) {\n return [this, initField.of({ field: this, create })];\n }\n /**\n State field instances can be used as\n [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a\n given state.\n */\n get extension() { return this; }\n}\nconst Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 };\nfunction prec(value) {\n return (ext) => new PrecExtension(ext, value);\n}\n/**\nBy default extensions are registered in the order they are found\nin the flattened form of nested array that was provided.\nIndividual extension values can be assigned a precedence to\noverride this. Extensions that do not have a precedence set get\nthe precedence of the nearest parent with a precedence, or\n[`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The\nfinal ordering of extensions is determined by first sorting by\nprecedence and then by order within each precedence.\n*/\nconst Prec = {\n /**\n The highest precedence level, for extensions that should end up\n near the start of the precedence ordering.\n */\n highest: /*@__PURE__*/prec(Prec_.highest),\n /**\n A higher-than-default precedence, for extensions that should\n come before those with default precedence.\n */\n high: /*@__PURE__*/prec(Prec_.high),\n /**\n The default precedence, which is also used for extensions\n without an explicit precedence.\n */\n default: /*@__PURE__*/prec(Prec_.default),\n /**\n A lower-than-default precedence.\n */\n low: /*@__PURE__*/prec(Prec_.low),\n /**\n The lowest precedence level. Meant for things that should end up\n near the end of the extension order.\n */\n lowest: /*@__PURE__*/prec(Prec_.lowest)\n};\nclass PrecExtension {\n constructor(inner, prec) {\n this.inner = inner;\n this.prec = prec;\n }\n}\n/**\nExtension compartments can be used to make a configuration\ndynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your\nconfiguration in a compartment, you can later\n[replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a\ntransaction.\n*/\nclass Compartment {\n /**\n Create an instance of this compartment to add to your [state\n configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).\n */\n of(ext) { return new CompartmentInstance(this, ext); }\n /**\n Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that\n reconfigures this compartment.\n */\n reconfigure(content) {\n return Compartment.reconfigure.of({ compartment: this, extension: content });\n }\n /**\n Get the current content of the compartment in the state, or\n `undefined` if it isn't present.\n */\n get(state) {\n return state.config.compartments.get(this);\n }\n}\nclass CompartmentInstance {\n constructor(compartment, inner) {\n this.compartment = compartment;\n this.inner = inner;\n }\n}\nclass Configuration {\n constructor(base, compartments, dynamicSlots, address, staticValues, facets) {\n this.base = base;\n this.compartments = compartments;\n this.dynamicSlots = dynamicSlots;\n this.address = address;\n this.staticValues = staticValues;\n this.facets = facets;\n this.statusTemplate = [];\n while (this.statusTemplate.length < dynamicSlots.length)\n this.statusTemplate.push(0 /* SlotStatus.Unresolved */);\n }\n staticFacet(facet) {\n let addr = this.address[facet.id];\n return addr == null ? facet.default : this.staticValues[addr >> 1];\n }\n static resolve(base, compartments, oldState) {\n let fields = [];\n let facets = Object.create(null);\n let newCompartments = new Map();\n for (let ext of flatten(base, compartments, newCompartments)) {\n if (ext instanceof StateField)\n fields.push(ext);\n else\n (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);\n }\n let address = Object.create(null);\n let staticValues = [];\n let dynamicSlots = [];\n for (let field of fields) {\n address[field.id] = dynamicSlots.length << 1;\n dynamicSlots.push(a => field.slot(a));\n }\n let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;\n for (let id in facets) {\n let providers = facets[id], facet = providers[0].facet;\n let oldProviders = oldFacets && oldFacets[id] || [];\n if (providers.every(p => p.type == 0 /* Provider.Static */)) {\n address[facet.id] = (staticValues.length << 1) | 1;\n if (sameArray(oldProviders, providers)) {\n staticValues.push(oldState.facet(facet));\n }\n else {\n let value = facet.combine(providers.map(p => p.value));\n staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);\n }\n }\n else {\n for (let p of providers) {\n if (p.type == 0 /* Provider.Static */) {\n address[p.id] = (staticValues.length << 1) | 1;\n staticValues.push(p.value);\n }\n else {\n address[p.id] = dynamicSlots.length << 1;\n dynamicSlots.push(a => p.dynamicSlot(a));\n }\n }\n address[facet.id] = dynamicSlots.length << 1;\n dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers));\n }\n }\n let dynamic = dynamicSlots.map(f => f(address));\n return new Configuration(base, newCompartments, dynamic, address, staticValues, facets);\n }\n}\nfunction flatten(extension, compartments, newCompartments) {\n let result = [[], [], [], [], []];\n let seen = new Map();\n function inner(ext, prec) {\n let known = seen.get(ext);\n if (known != null) {\n if (known <= prec)\n return;\n let found = result[known].indexOf(ext);\n if (found > -1)\n result[known].splice(found, 1);\n if (ext instanceof CompartmentInstance)\n newCompartments.delete(ext.compartment);\n }\n seen.set(ext, prec);\n if (Array.isArray(ext)) {\n for (let e of ext)\n inner(e, prec);\n }\n else if (ext instanceof CompartmentInstance) {\n if (newCompartments.has(ext.compartment))\n throw new RangeError(`Duplicate use of compartment in extensions`);\n let content = compartments.get(ext.compartment) || ext.inner;\n newCompartments.set(ext.compartment, content);\n inner(content, prec);\n }\n else if (ext instanceof PrecExtension) {\n inner(ext.inner, ext.prec);\n }\n else if (ext instanceof StateField) {\n result[prec].push(ext);\n if (ext.provides)\n inner(ext.provides, prec);\n }\n else if (ext instanceof FacetProvider) {\n result[prec].push(ext);\n if (ext.facet.extensions)\n inner(ext.facet.extensions, Prec_.default);\n }\n else {\n let content = ext.extension;\n if (!content)\n throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);\n inner(content, prec);\n }\n }\n inner(extension, Prec_.default);\n return result.reduce((a, b) => a.concat(b));\n}\nfunction ensureAddr(state, addr) {\n if (addr & 1)\n return 2 /* SlotStatus.Computed */;\n let idx = addr >> 1;\n let status = state.status[idx];\n if (status == 4 /* SlotStatus.Computing */)\n throw new Error(\"Cyclic dependency between fields and/or facets\");\n if (status & 2 /* SlotStatus.Computed */)\n return status;\n state.status[idx] = 4 /* SlotStatus.Computing */;\n let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);\n return state.status[idx] = 2 /* SlotStatus.Computed */ | changed;\n}\nfunction getAddr(state, addr) {\n return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];\n}\n\nconst languageData = /*@__PURE__*/Facet.define();\nconst allowMultipleSelections = /*@__PURE__*/Facet.define({\n combine: values => values.some(v => v),\n static: true\n});\nconst lineSeparator = /*@__PURE__*/Facet.define({\n combine: values => values.length ? values[0] : undefined,\n static: true\n});\nconst changeFilter = /*@__PURE__*/Facet.define();\nconst transactionFilter = /*@__PURE__*/Facet.define();\nconst transactionExtender = /*@__PURE__*/Facet.define();\nconst readOnly = /*@__PURE__*/Facet.define({\n combine: values => values.length ? values[0] : false\n});\n\n/**\nAnnotations are tagged values that are used to add metadata to\ntransactions in an extensible way. They should be used to model\nthings that effect the entire transaction (such as its [time\nstamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its\n[origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen\n_alongside_ the other changes made by the transaction, [state\neffects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate.\n*/\nclass Annotation {\n /**\n @internal\n */\n constructor(\n /**\n The annotation type.\n */\n type, \n /**\n The value of this annotation.\n */\n value) {\n this.type = type;\n this.value = value;\n }\n /**\n Define a new type of annotation.\n */\n static define() { return new AnnotationType(); }\n}\n/**\nMarker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation).\n*/\nclass AnnotationType {\n /**\n Create an instance of this annotation.\n */\n of(value) { return new Annotation(this, value); }\n}\n/**\nRepresentation of a type of state effect. Defined with\n[`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define).\n*/\nclass StateEffectType {\n /**\n @internal\n */\n constructor(\n // The `any` types in these function types are there to work\n // around TypeScript issue #37631, where the type guard on\n // `StateEffect.is` mysteriously stops working when these properly\n // have type `Value`.\n /**\n @internal\n */\n map) {\n this.map = map;\n }\n /**\n Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this\n type.\n */\n of(value) { return new StateEffect(this, value); }\n}\n/**\nState effects can be used to represent additional effects\nassociated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They\nare often useful to model changes to custom [state\nfields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in\ndocument or selection changes.\n*/\nclass StateEffect {\n /**\n @internal\n */\n constructor(\n /**\n @internal\n */\n type, \n /**\n The value of this effect.\n */\n value) {\n this.type = type;\n this.value = value;\n }\n /**\n Map this effect through a position mapping. Will return\n `undefined` when that ends up deleting the effect.\n */\n map(mapping) {\n let mapped = this.type.map(this.value, mapping);\n return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped);\n }\n /**\n Tells you whether this effect object is of a given\n [type](https://codemirror.net/6/docs/ref/#state.StateEffectType).\n */\n is(type) { return this.type == type; }\n /**\n Define a new effect type. The type parameter indicates the type\n of values that his effect holds. It should be a type that\n doesn't include `undefined`, since that is used in\n [mapping](https://codemirror.net/6/docs/ref/#state.StateEffect.map) to indicate that an effect is\n removed.\n */\n static define(spec = {}) {\n return new StateEffectType(spec.map || (v => v));\n }\n /**\n Map an array of effects through a change set.\n */\n static mapEffects(effects, mapping) {\n if (!effects.length)\n return effects;\n let result = [];\n for (let effect of effects) {\n let mapped = effect.map(mapping);\n if (mapped)\n result.push(mapped);\n }\n return result;\n }\n}\n/**\nThis effect can be used to reconfigure the root extensions of\nthe editor. Doing this will discard any extensions\n[appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset\nthe content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure)\ncompartments.\n*/\nStateEffect.reconfigure = /*@__PURE__*/StateEffect.define();\n/**\nAppend extensions to the top-level configuration of the editor.\n*/\nStateEffect.appendConfig = /*@__PURE__*/StateEffect.define();\n/**\nChanges to the editor state are grouped into transactions.\nTypically, a user action creates a single transaction, which may\ncontain any number of document changes, may change the selection,\nor have other effects. Create a transaction by calling\n[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update), or immediately\ndispatch one by calling\n[`EditorView.dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch).\n*/\nclass Transaction {\n constructor(\n /**\n The state from which the transaction starts.\n */\n startState, \n /**\n The document changes made by this transaction.\n */\n changes, \n /**\n The selection set by this transaction, or undefined if it\n doesn't explicitly set a selection.\n */\n selection, \n /**\n The effects added to the transaction.\n */\n effects, \n /**\n @internal\n */\n annotations, \n /**\n Whether the selection should be scrolled into view after this\n transaction is dispatched.\n */\n scrollIntoView) {\n this.startState = startState;\n this.changes = changes;\n this.selection = selection;\n this.effects = effects;\n this.annotations = annotations;\n this.scrollIntoView = scrollIntoView;\n /**\n @internal\n */\n this._doc = null;\n /**\n @internal\n */\n this._state = null;\n if (selection)\n checkSelection(selection, changes.newLength);\n if (!annotations.some((a) => a.type == Transaction.time))\n this.annotations = annotations.concat(Transaction.time.of(Date.now()));\n }\n /**\n @internal\n */\n static create(startState, changes, selection, effects, annotations, scrollIntoView) {\n return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView);\n }\n /**\n The new document produced by the transaction. Contrary to\n [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't\n force the entire new state to be computed right away, so it is\n recommended that [transaction\n filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter\n when they need to look at the new document.\n */\n get newDoc() {\n return this._doc || (this._doc = this.changes.apply(this.startState.doc));\n }\n /**\n The new selection produced by the transaction. If\n [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined,\n this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's\n current selection through the changes made by the transaction.\n */\n get newSelection() {\n return this.selection || this.startState.selection.map(this.changes);\n }\n /**\n The new state created by the transaction. Computed on demand\n (but retained for subsequent access), so it is recommended not to\n access it in [transaction\n filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible.\n */\n get state() {\n if (!this._state)\n this.startState.applyTransaction(this);\n return this._state;\n }\n /**\n Get the value of the given annotation type, if any.\n */\n annotation(type) {\n for (let ann of this.annotations)\n if (ann.type == type)\n return ann.value;\n return undefined;\n }\n /**\n Indicates whether the transaction changed the document.\n */\n get docChanged() { return !this.changes.empty; }\n /**\n Indicates whether this transaction reconfigures the state\n (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or\n with a top-level configuration\n [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure).\n */\n get reconfigured() { return this.startState.config != this.state.config; }\n /**\n Returns true if the transaction has a [user\n event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to\n or more specific than `event`. For example, if the transaction\n has `\"select.pointer\"` as user event, `\"select\"` and\n `\"select.pointer\"` will match it.\n */\n isUserEvent(event) {\n let e = this.annotation(Transaction.userEvent);\n return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == \".\"));\n }\n}\n/**\nAnnotation used to store transaction timestamps. Automatically\nadded to every transaction, holding `Date.now()`.\n*/\nTransaction.time = /*@__PURE__*/Annotation.define();\n/**\nAnnotation used to associate a transaction with a user interface\nevent. Holds a string identifying the event, using a\ndot-separated format to support attaching more specific\ninformation. The events used by the core libraries are:\n\n - `\"input\"` when content is entered\n - `\"input.type\"` for typed input\n - `\"input.type.compose\"` for composition\n - `\"input.paste\"` for pasted input\n - `\"input.drop\"` when adding content with drag-and-drop\n - `\"input.complete\"` when autocompleting\n - `\"delete\"` when the user deletes content\n - `\"delete.selection\"` when deleting the selection\n - `\"delete.forward\"` when deleting forward from the selection\n - `\"delete.backward\"` when deleting backward from the selection\n - `\"delete.cut\"` when cutting to the clipboard\n - `\"move\"` when content is moved\n - `\"move.drop\"` when content is moved within the editor through drag-and-drop\n - `\"select\"` when explicitly changing the selection\n - `\"select.pointer\"` when selecting with a mouse or other pointing device\n - `\"undo\"` and `\"redo\"` for history actions\n\nUse [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check\nwhether the annotation matches a given event.\n*/\nTransaction.userEvent = /*@__PURE__*/Annotation.define();\n/**\nAnnotation indicating whether a transaction should be added to\nthe undo history or not.\n*/\nTransaction.addToHistory = /*@__PURE__*/Annotation.define();\n/**\nAnnotation indicating (when present and true) that a transaction\nrepresents a change made by some other actor, not the user. This\nis used, for example, to tag other people's changes in\ncollaborative editing.\n*/\nTransaction.remote = /*@__PURE__*/Annotation.define();\nfunction joinRanges(a, b) {\n let result = [];\n for (let iA = 0, iB = 0;;) {\n let from, to;\n if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {\n from = a[iA++];\n to = a[iA++];\n }\n else if (iB < b.length) {\n from = b[iB++];\n to = b[iB++];\n }\n else\n return result;\n if (!result.length || result[result.length - 1] < from)\n result.push(from, to);\n else if (result[result.length - 1] < to)\n result[result.length - 1] = to;\n }\n}\nfunction mergeTransaction(a, b, sequential) {\n var _a;\n let mapForA, mapForB, changes;\n if (sequential) {\n mapForA = b.changes;\n mapForB = ChangeSet.empty(b.changes.length);\n changes = a.changes.compose(b.changes);\n }\n else {\n mapForA = b.changes.map(a.changes);\n mapForB = a.changes.mapDesc(b.changes, true);\n changes = a.changes.compose(mapForA);\n }\n return {\n changes,\n selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA),\n effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)),\n annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,\n scrollIntoView: a.scrollIntoView || b.scrollIntoView\n };\n}\nfunction resolveTransactionInner(state, spec, docSize) {\n let sel = spec.selection, annotations = asArray(spec.annotations);\n if (spec.userEvent)\n annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent));\n return {\n changes: spec.changes instanceof ChangeSet ? spec.changes\n : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)),\n selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),\n effects: asArray(spec.effects),\n annotations,\n scrollIntoView: !!spec.scrollIntoView\n };\n}\nfunction resolveTransaction(state, specs, filter) {\n let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length);\n if (specs.length && specs[0].filter === false)\n filter = false;\n for (let i = 1; i < specs.length; i++) {\n if (specs[i].filter === false)\n filter = false;\n let seq = !!specs[i].sequential;\n s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq);\n }\n let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);\n return extendTransaction(filter ? filterTransaction(tr) : tr);\n}\n// Finish a transaction by applying filters if necessary.\nfunction filterTransaction(tr) {\n let state = tr.startState;\n // Change filters\n let result = true;\n for (let filter of state.facet(changeFilter)) {\n let value = filter(tr);\n if (value === false) {\n result = false;\n break;\n }\n if (Array.isArray(value))\n result = result === true ? value : joinRanges(result, value);\n }\n if (result !== true) {\n let changes, back;\n if (result === false) {\n back = tr.changes.invertedDesc;\n changes = ChangeSet.empty(state.doc.length);\n }\n else {\n let filtered = tr.changes.filter(result);\n changes = filtered.changes;\n back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;\n }\n tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView);\n }\n // Transaction filters\n let filters = state.facet(transactionFilter);\n for (let i = filters.length - 1; i >= 0; i--) {\n let filtered = filters[i](tr);\n if (filtered instanceof Transaction)\n tr = filtered;\n else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction)\n tr = filtered[0];\n else\n tr = resolveTransaction(state, asArray(filtered), false);\n }\n return tr;\n}\nfunction extendTransaction(tr) {\n let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr;\n for (let i = extenders.length - 1; i >= 0; i--) {\n let extension = extenders[i](tr);\n if (extension && Object.keys(extension).length)\n spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true);\n }\n return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView);\n}\nconst none = [];\nfunction asArray(value) {\n return value == null ? none : Array.isArray(value) ? value : [value];\n}\n\n/**\nThe categories produced by a [character\ncategorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used\ndo things like selecting by word.\n*/\nvar CharCategory = /*@__PURE__*/(function (CharCategory) {\n /**\n Word characters.\n */\n CharCategory[CharCategory[\"Word\"] = 0] = \"Word\";\n /**\n Whitespace.\n */\n CharCategory[CharCategory[\"Space\"] = 1] = \"Space\";\n /**\n Anything else.\n */\n CharCategory[CharCategory[\"Other\"] = 2] = \"Other\";\nreturn CharCategory})(CharCategory || (CharCategory = {}));\nconst nonASCIISingleCaseWordChar = /[\\u00df\\u0587\\u0590-\\u05f4\\u0600-\\u06ff\\u3040-\\u309f\\u30a0-\\u30ff\\u3400-\\u4db5\\u4e00-\\u9fcc\\uac00-\\ud7af]/;\nlet wordChar;\ntry {\n wordChar = /*@__PURE__*/new RegExp(\"[\\\\p{Alphabetic}\\\\p{Number}_]\", \"u\");\n}\ncatch (_) { }\nfunction hasWordChar(str) {\n if (wordChar)\n return wordChar.test(str);\n for (let i = 0; i < str.length; i++) {\n let ch = str[i];\n if (/\\w/.test(ch) || ch > \"\\x80\" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)))\n return true;\n }\n return false;\n}\nfunction makeCategorizer(wordChars) {\n return (char) => {\n if (!/\\S/.test(char))\n return CharCategory.Space;\n if (hasWordChar(char))\n return CharCategory.Word;\n for (let i = 0; i < wordChars.length; i++)\n if (char.indexOf(wordChars[i]) > -1)\n return CharCategory.Word;\n return CharCategory.Other;\n };\n}\n\n/**\nThe editor state class is a persistent (immutable) data structure.\nTo update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a\n[transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state\ninstance, without modifying the original object.\n\nAs such, _never_ mutate properties of a state directly. That'll\njust break things.\n*/\nclass EditorState {\n constructor(\n /**\n @internal\n */\n config, \n /**\n The current document.\n */\n doc, \n /**\n The current selection.\n */\n selection, \n /**\n @internal\n */\n values, computeSlot, tr) {\n this.config = config;\n this.doc = doc;\n this.selection = selection;\n this.values = values;\n this.status = config.statusTemplate.slice();\n this.computeSlot = computeSlot;\n // Fill in the computed state immediately, so that further queries\n // for it made during the update return this state\n if (tr)\n tr._state = this;\n for (let i = 0; i < this.config.dynamicSlots.length; i++)\n ensureAddr(this, i << 1);\n this.computeSlot = null;\n }\n field(field, require = true) {\n let addr = this.config.address[field.id];\n if (addr == null) {\n if (require)\n throw new RangeError(\"Field is not present in this state\");\n return undefined;\n }\n ensureAddr(this, addr);\n return getAddr(this, addr);\n }\n /**\n Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this\n state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)\n can be passed. Unless\n [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the\n [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec\n are assumed to start in the _current_ document (not the document\n produced by previous specs), and its\n [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and\n [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer\n to the document created by its _own_ changes. The resulting\n transaction contains the combined effect of all the different\n specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later\n specs take precedence over earlier ones.\n */\n update(...specs) {\n return resolveTransaction(this, specs, true);\n }\n /**\n @internal\n */\n applyTransaction(tr) {\n let conf = this.config, { base, compartments } = conf;\n for (let effect of tr.effects) {\n if (effect.is(Compartment.reconfigure)) {\n if (conf) {\n compartments = new Map;\n conf.compartments.forEach((val, key) => compartments.set(key, val));\n conf = null;\n }\n compartments.set(effect.value.compartment, effect.value.extension);\n }\n else if (effect.is(StateEffect.reconfigure)) {\n conf = null;\n base = effect.value;\n }\n else if (effect.is(StateEffect.appendConfig)) {\n conf = null;\n base = asArray(base).concat(effect.value);\n }\n }\n let startValues;\n if (!conf) {\n conf = Configuration.resolve(base, compartments, this);\n let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null);\n startValues = intermediateState.values;\n }\n else {\n startValues = tr.startState.values.slice();\n }\n new EditorState(conf, tr.newDoc, tr.newSelection, startValues, (state, slot) => slot.update(state, tr), tr);\n }\n /**\n Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that\n replaces every selection range with the given content.\n */\n replaceSelection(text) {\n if (typeof text == \"string\")\n text = this.toText(text);\n return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text },\n range: EditorSelection.cursor(range.from + text.length) }));\n }\n /**\n Create a set of changes and a new selection by running the given\n function for each range in the active selection. The function\n can return an optional set of changes (in the coordinate space\n of the start document), plus an updated range (in the coordinate\n space of the document produced by the call's own changes). This\n method will merge all the changes and ranges into a single\n changeset and selection, and return it as a [transaction\n spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to\n [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update).\n */\n changeByRange(f) {\n let sel = this.selection;\n let result1 = f(sel.ranges[0]);\n let changes = this.changes(result1.changes), ranges = [result1.range];\n let effects = asArray(result1.effects);\n for (let i = 1; i < sel.ranges.length; i++) {\n let result = f(sel.ranges[i]);\n let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes);\n for (let j = 0; j < i; j++)\n ranges[j] = ranges[j].map(newMapped);\n let mapBy = changes.mapDesc(newChanges, true);\n ranges.push(result.range.map(mapBy));\n changes = changes.compose(newMapped);\n effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray(result.effects), mapBy));\n }\n return {\n changes,\n selection: EditorSelection.create(ranges, sel.mainIndex),\n effects\n };\n }\n /**\n Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change\n description, taking the state's document length and line\n separator into account.\n */\n changes(spec = []) {\n if (spec instanceof ChangeSet)\n return spec;\n return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator));\n }\n /**\n Using the state's [line\n separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a\n [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.\n */\n toText(string) {\n return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit));\n }\n /**\n Return the given range of the document as a string.\n */\n sliceDoc(from = 0, to = this.doc.length) {\n return this.doc.sliceString(from, to, this.lineBreak);\n }\n /**\n Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).\n */\n facet(facet) {\n let addr = this.config.address[facet.id];\n if (addr == null)\n return facet.default;\n ensureAddr(this, addr);\n return getAddr(this, addr);\n }\n /**\n Convert this state to a JSON-serializable object. When custom\n fields should be serialized, you can pass them in as an object\n mapping property names (in the resulting object, which should\n not use `doc` or `selection`) to fields.\n */\n toJSON(fields) {\n let result = {\n doc: this.sliceDoc(),\n selection: this.selection.toJSON()\n };\n if (fields)\n for (let prop in fields) {\n let value = fields[prop];\n if (value instanceof StateField && this.config.address[value.id] != null)\n result[prop] = value.spec.toJSON(this.field(fields[prop]), this);\n }\n return result;\n }\n /**\n Deserialize a state from its JSON representation. When custom\n fields should be deserialized, pass the same object you passed\n to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as\n third argument.\n */\n static fromJSON(json, config = {}, fields) {\n if (!json || typeof json.doc != \"string\")\n throw new RangeError(\"Invalid JSON representation for EditorState\");\n let fieldInit = [];\n if (fields)\n for (let prop in fields) {\n if (Object.prototype.hasOwnProperty.call(json, prop)) {\n let field = fields[prop], value = json[prop];\n fieldInit.push(field.init(state => field.spec.fromJSON(value, state)));\n }\n }\n return EditorState.create({\n doc: json.doc,\n selection: EditorSelection.fromJSON(json.selection),\n extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit\n });\n }\n /**\n Create a new state. You'll usually only need this when\n initializing an editor—updated states are created by applying\n transactions.\n */\n static create(config = {}) {\n let configuration = Configuration.resolve(config.extensions || [], new Map);\n let doc = config.doc instanceof Text ? config.doc\n : Text.of((config.doc || \"\").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit));\n let selection = !config.selection ? EditorSelection.single(0)\n : config.selection instanceof EditorSelection ? config.selection\n : EditorSelection.single(config.selection.anchor, config.selection.head);\n checkSelection(selection, doc.length);\n if (!configuration.staticFacet(allowMultipleSelections))\n selection = selection.asSingle();\n return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);\n }\n /**\n The size (in columns) of a tab in the document, determined by\n the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.\n */\n get tabSize() { return this.facet(EditorState.tabSize); }\n /**\n Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)\n string for this state.\n */\n get lineBreak() { return this.facet(EditorState.lineSeparator) || \"\\n\"; }\n /**\n Returns true when the editor is\n [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.\n */\n get readOnly() { return this.facet(readOnly); }\n /**\n Look up a translation for the given phrase (via the\n [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the\n original string if no translation is found.\n \n If additional arguments are passed, they will be inserted in\n place of markers like `$1` (for the first value) and `$2`, etc.\n A single `$` is equivalent to `$1`, and `$$` will produce a\n literal dollar sign.\n */\n phrase(phrase, ...insert) {\n for (let map of this.facet(EditorState.phrases))\n if (Object.prototype.hasOwnProperty.call(map, phrase)) {\n phrase = map[phrase];\n break;\n }\n if (insert.length)\n phrase = phrase.replace(/\\$(\\$|\\d*)/g, (m, i) => {\n if (i == \"$\")\n return \"$\";\n let n = +(i || 1);\n return !n || n > insert.length ? m : insert[n - 1];\n });\n return phrase;\n }\n /**\n Find the values for a given language data field, provided by the\n the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet.\n \n Examples of language data fields are...\n \n - [`\"commentTokens\"`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) for specifying\n comment syntax.\n - [`\"autocomplete\"`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.override)\n for providing language-specific completion sources.\n - [`\"wordChars\"`](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) for adding\n characters that should be considered part of words in this\n language.\n - [`\"closeBrackets\"`](https://codemirror.net/6/docs/ref/#autocomplete.CloseBracketConfig) controls\n bracket closing behavior.\n */\n languageDataAt(name, pos, side = -1) {\n let values = [];\n for (let provider of this.facet(languageData)) {\n for (let result of provider(this, pos, side)) {\n if (Object.prototype.hasOwnProperty.call(result, name))\n values.push(result[name]);\n }\n }\n return values;\n }\n /**\n Return a function that can categorize strings (expected to\n represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak))\n into one of:\n \n - Word (contains an alphanumeric character or a character\n explicitly listed in the local language's `\"wordChars\"`\n language data, which should be a string)\n - Space (contains only whitespace)\n - Other (anything else)\n */\n charCategorizer(at) {\n return makeCategorizer(this.languageDataAt(\"wordChars\", at).join(\"\"));\n }\n /**\n Find the word at the given position, meaning the range\n containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters\n around it. If no word characters are adjacent to the position,\n this returns null.\n */\n wordAt(pos) {\n let { text, from, length } = this.doc.lineAt(pos);\n let cat = this.charCategorizer(pos);\n let start = pos - from, end = pos - from;\n while (start > 0) {\n let prev = findClusterBreak(text, start, false);\n if (cat(text.slice(prev, start)) != CharCategory.Word)\n break;\n start = prev;\n }\n while (end < length) {\n let next = findClusterBreak(text, end);\n if (cat(text.slice(end, next)) != CharCategory.Word)\n break;\n end = next;\n }\n return start == end ? null : EditorSelection.range(start + from, end + from);\n }\n}\n/**\nA facet that, when enabled, causes the editor to allow multiple\nranges to be selected. Be careful though, because by default the\neditor relies on the native DOM selection, which cannot handle\nmultiple selections. An extension like\n[`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make\nsecondary selections visible to the user.\n*/\nEditorState.allowMultipleSelections = allowMultipleSelections;\n/**\nConfigures the tab size to use in this state. The first\n(highest-precedence) value of the facet is used. If no value is\ngiven, this defaults to 4.\n*/\nEditorState.tabSize = /*@__PURE__*/Facet.define({\n combine: values => values.length ? values[0] : 4\n});\n/**\nThe line separator to use. By default, any of `\"\\n\"`, `\"\\r\\n\"`\nand `\"\\r\"` is treated as a separator when splitting lines, and\nlines are joined with `\"\\n\"`.\n\nWhen you configure a value here, only that precise separator\nwill be used, allowing you to round-trip documents through the\neditor without normalizing line separators.\n*/\nEditorState.lineSeparator = lineSeparator;\n/**\nThis facet controls the value of the\n[`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is\nconsulted by commands and extensions that implement editing\nfunctionality to determine whether they should apply. It\ndefaults to false, but when its highest-precedence value is\n`true`, such functionality disables itself.\n\nNot to be confused with\n[`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which\ncontrols whether the editor's DOM is set to be editable (and\nthus focusable).\n*/\nEditorState.readOnly = readOnly;\n/**\nRegisters translation phrases. The\n[`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through\nall objects registered with this facet to find translations for\nits argument.\n*/\nEditorState.phrases = /*@__PURE__*/Facet.define({\n compare(a, b) {\n let kA = Object.keys(a), kB = Object.keys(b);\n return kA.length == kB.length && kA.every(k => a[k] == b[k]);\n }\n});\n/**\nA facet used to register [language\ndata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers.\n*/\nEditorState.languageData = languageData;\n/**\nFacet used to register change filters, which are called for each\ntransaction (unless explicitly\n[disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress\npart of the transaction's changes.\n\nSuch a function can return `true` to indicate that it doesn't\nwant to do anything, `false` to completely stop the changes in\nthe transaction, or a set of ranges in which changes should be\nsuppressed. Such ranges are represented as an array of numbers,\nwith each pair of two numbers indicating the start and end of a\nrange. So for example `[10, 20, 100, 110]` suppresses changes\nbetween 10 and 20, and between 100 and 110.\n*/\nEditorState.changeFilter = changeFilter;\n/**\nFacet used to register a hook that gets a chance to update or\nreplace transaction specs before they are applied. This will\nonly be applied for transactions that don't have\n[`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You\ncan either return a single transaction spec (possibly the input\ntransaction), or an array of specs (which will be combined in\nthe same way as the arguments to\n[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)).\n\nWhen possible, it is recommended to avoid accessing\n[`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter,\nsince it will force creation of a state that will then be\ndiscarded again, if the transaction is actually filtered.\n\n(This functionality should be used with care. Indiscriminately\nmodifying transaction is likely to break something or degrade\nthe user experience.)\n*/\nEditorState.transactionFilter = transactionFilter;\n/**\nThis is a more limited form of\n[`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter),\nwhich can only add\n[annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and\n[effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type\nof filter runs even if the transaction has disabled regular\n[filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable\nfor effects that don't need to touch the changes or selection,\nbut do want to process every transaction.\n\nExtenders run _after_ filters, when both are present.\n*/\nEditorState.transactionExtender = transactionExtender;\nCompartment.reconfigure = /*@__PURE__*/StateEffect.define();\n\n/**\nUtility function for combining behaviors to fill in a config\nobject from an array of provided configs. `defaults` should hold\ndefault values for all optional fields in `Config`.\n\nThe function will, by default, error\nwhen a field gets two values that aren't `===`-equal, but you can\nprovide combine functions per field to do something else.\n*/\nfunction combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that\ncombine = {}) {\n let result = {};\n for (let config of configs)\n for (let key of Object.keys(config)) {\n let value = config[key], current = result[key];\n if (current === undefined)\n result[key] = value;\n else if (current === value || value === undefined) ; // No conflict\n else if (Object.hasOwnProperty.call(combine, key))\n result[key] = combine[key](current, value);\n else\n throw new Error(\"Config merge conflict for field \" + key);\n }\n for (let key in defaults)\n if (result[key] === undefined)\n result[key] = defaults[key];\n return result;\n}\n\n/**\nEach range is associated with a value, which must inherit from\nthis class.\n*/\nclass RangeValue {\n /**\n Compare this value with another value. Used when comparing\n rangesets. The default implementation compares by identity.\n Unless you are only creating a fixed number of unique instances\n of your value type, it is a good idea to implement this\n properly.\n */\n eq(other) { return this == other; }\n /**\n Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.\n */\n range(from, to = from) { return Range.create(from, to, this); }\n}\nRangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;\nRangeValue.prototype.point = false;\nRangeValue.prototype.mapMode = MapMode.TrackDel;\n/**\nA range associates a value with a range of positions.\n*/\nclass Range {\n constructor(\n /**\n The range's start position.\n */\n from, \n /**\n Its end position.\n */\n to, \n /**\n The value associated with this range.\n */\n value) {\n this.from = from;\n this.to = to;\n this.value = value;\n }\n /**\n @internal\n */\n static create(from, to, value) {\n return new Range(from, to, value);\n }\n}\nfunction cmpRange(a, b) {\n return a.from - b.from || a.value.startSide - b.value.startSide;\n}\nclass Chunk {\n constructor(from, to, value, \n // Chunks are marked with the largest point that occurs\n // in them (or -1 for no points), so that scans that are\n // only interested in points (such as the\n // heightmap-related logic) can skip range-only chunks.\n maxPoint) {\n this.from = from;\n this.to = to;\n this.value = value;\n this.maxPoint = maxPoint;\n }\n get length() { return this.to[this.to.length - 1]; }\n // Find the index of the given position and side. Use the ranges'\n // `from` pos when `end == false`, `to` when `end == true`.\n findIndex(pos, side, end, startAt = 0) {\n let arr = end ? this.to : this.from;\n for (let lo = startAt, hi = arr.length;;) {\n if (lo == hi)\n return lo;\n let mid = (lo + hi) >> 1;\n let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side;\n if (mid == lo)\n return diff >= 0 ? lo : hi;\n if (diff >= 0)\n hi = mid;\n else\n lo = mid + 1;\n }\n }\n between(offset, from, to, f) {\n for (let i = this.findIndex(from, -1000000000 /* C.Far */, true), e = this.findIndex(to, 1000000000 /* C.Far */, false, i); i < e; i++)\n if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false)\n return false;\n }\n map(offset, changes) {\n let value = [], from = [], to = [], newPos = -1, maxPoint = -1;\n for (let i = 0; i < this.value.length; i++) {\n let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo;\n if (curFrom == curTo) {\n let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);\n if (mapped == null)\n continue;\n newFrom = newTo = mapped;\n if (val.startSide != val.endSide) {\n newTo = changes.mapPos(curFrom, val.endSide);\n if (newTo < newFrom)\n continue;\n }\n }\n else {\n newFrom = changes.mapPos(curFrom, val.startSide);\n newTo = changes.mapPos(curTo, val.endSide);\n if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0)\n continue;\n }\n if ((newTo - newFrom || val.endSide - val.startSide) < 0)\n continue;\n if (newPos < 0)\n newPos = newFrom;\n if (val.point)\n maxPoint = Math.max(maxPoint, newTo - newFrom);\n value.push(val);\n from.push(newFrom - newPos);\n to.push(newTo - newPos);\n }\n return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos };\n }\n}\n/**\nA range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#state.Range) in a\nway that makes them efficient to [map](https://codemirror.net/6/docs/ref/#state.RangeSet.map) and\n[update](https://codemirror.net/6/docs/ref/#state.RangeSet.update). This is an immutable data\nstructure.\n*/\nclass RangeSet {\n constructor(\n /**\n @internal\n */\n chunkPos, \n /**\n @internal\n */\n chunk, \n /**\n @internal\n */\n nextLayer, \n /**\n @internal\n */\n maxPoint) {\n this.chunkPos = chunkPos;\n this.chunk = chunk;\n this.nextLayer = nextLayer;\n this.maxPoint = maxPoint;\n }\n /**\n @internal\n */\n static create(chunkPos, chunk, nextLayer, maxPoint) {\n return new RangeSet(chunkPos, chunk, nextLayer, maxPoint);\n }\n /**\n @internal\n */\n get length() {\n let last = this.chunk.length - 1;\n return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);\n }\n /**\n The number of ranges in the set.\n */\n get size() {\n if (this.isEmpty)\n return 0;\n let size = this.nextLayer.size;\n for (let chunk of this.chunk)\n size += chunk.value.length;\n return size;\n }\n /**\n @internal\n */\n chunkEnd(index) {\n return this.chunkPos[index] + this.chunk[index].length;\n }\n /**\n Update the range set, optionally adding new ranges or filtering\n out existing ones.\n \n (Note: The type parameter is just there as a kludge to work\n around TypeScript variance issues that prevented `RangeSet`\n from being a subtype of `RangeSet` when `X` is a subtype of\n `Y`.)\n */\n update(updateSpec) {\n let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec;\n let filter = updateSpec.filter;\n if (add.length == 0 && !filter)\n return this;\n if (sort)\n add = add.slice().sort(cmpRange);\n if (this.isEmpty)\n return add.length ? RangeSet.of(add) : this;\n let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = [];\n let builder = new RangeSetBuilder();\n while (cur.value || i < add.length) {\n if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) {\n let range = add[i++];\n if (!builder.addInner(range.from, range.to, range.value))\n spill.push(range);\n }\n else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length &&\n (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) &&\n (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) &&\n builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) {\n cur.nextChunk();\n }\n else {\n if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) {\n if (!builder.addInner(cur.from, cur.to, cur.value))\n spill.push(Range.create(cur.from, cur.to, cur.value));\n }\n cur.next();\n }\n }\n return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty\n : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo }));\n }\n /**\n Map this range set through a set of changes, return the new set.\n */\n map(changes) {\n if (changes.empty || this.isEmpty)\n return this;\n let chunks = [], chunkPos = [], maxPoint = -1;\n for (let i = 0; i < this.chunk.length; i++) {\n let start = this.chunkPos[i], chunk = this.chunk[i];\n let touch = changes.touchesRange(start, start + chunk.length);\n if (touch === false) {\n maxPoint = Math.max(maxPoint, chunk.maxPoint);\n chunks.push(chunk);\n chunkPos.push(changes.mapPos(start));\n }\n else if (touch === true) {\n let { mapped, pos } = chunk.map(start, changes);\n if (mapped) {\n maxPoint = Math.max(maxPoint, mapped.maxPoint);\n chunks.push(mapped);\n chunkPos.push(pos);\n }\n }\n }\n let next = this.nextLayer.map(changes);\n return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint);\n }\n /**\n Iterate over the ranges that touch the region `from` to `to`,\n calling `f` for each. There is no guarantee that the ranges will\n be reported in any specific order. When the callback returns\n `false`, iteration stops.\n */\n between(from, to, f) {\n if (this.isEmpty)\n return;\n for (let i = 0; i < this.chunk.length; i++) {\n let start = this.chunkPos[i], chunk = this.chunk[i];\n if (to >= start && from <= start + chunk.length &&\n chunk.between(start, from - start, to - start, f) === false)\n return;\n }\n this.nextLayer.between(from, to, f);\n }\n /**\n Iterate over the ranges in this set, in order, including all\n ranges that end at or after `from`.\n */\n iter(from = 0) {\n return HeapCursor.from([this]).goto(from);\n }\n /**\n @internal\n */\n get isEmpty() { return this.nextLayer == this; }\n /**\n Iterate over the ranges in a collection of sets, in order,\n starting from `from`.\n */\n static iter(sets, from = 0) {\n return HeapCursor.from(sets).goto(from);\n }\n /**\n Iterate over two groups of sets, calling methods on `comparator`\n to notify it of possible differences.\n */\n static compare(oldSets, newSets, \n /**\n This indicates how the underlying data changed between these\n ranges, and is needed to synchronize the iteration.\n */\n textDiff, comparator, \n /**\n Can be used to ignore all non-point ranges, and points below\n the given size. When -1, all ranges are compared.\n */\n minPointSize = -1) {\n let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);\n let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);\n let sharedChunks = findSharedChunks(a, b, textDiff);\n let sideA = new SpanCursor(a, sharedChunks, minPointSize);\n let sideB = new SpanCursor(b, sharedChunks, minPointSize);\n textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator));\n if (textDiff.empty && textDiff.length == 0)\n compare(sideA, 0, sideB, 0, 0, comparator);\n }\n /**\n Compare the contents of two groups of range sets, returning true\n if they are equivalent in the given range.\n */\n static eq(oldSets, newSets, from = 0, to) {\n if (to == null)\n to = 1000000000 /* C.Far */ - 1;\n let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0);\n let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0);\n if (a.length != b.length)\n return false;\n if (!a.length)\n return true;\n let sharedChunks = findSharedChunks(a, b);\n let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from);\n for (;;) {\n if (sideA.to != sideB.to ||\n !sameValues(sideA.active, sideB.active) ||\n sideA.point && (!sideB.point || !sideA.point.eq(sideB.point)))\n return false;\n if (sideA.to > to)\n return true;\n sideA.next();\n sideB.next();\n }\n }\n /**\n Iterate over a group of range sets at the same time, notifying\n the iterator about the ranges covering every given piece of\n content. Returns the open count (see\n [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end\n of the iteration.\n */\n static spans(sets, from, to, iterator, \n /**\n When given and greater than -1, only points of at least this\n size are taken into account.\n */\n minPointSize = -1) {\n let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from;\n let openRanges = cursor.openStart;\n for (;;) {\n let curTo = Math.min(cursor.to, to);\n if (cursor.point) {\n let active = cursor.activeForPoint(cursor.to);\n let openCount = cursor.pointFrom < from ? active.length + 1 : Math.min(active.length, openRanges);\n iterator.point(pos, curTo, cursor.point, active, openCount, cursor.pointRank);\n openRanges = Math.min(cursor.openEnd(curTo), active.length);\n }\n else if (curTo > pos) {\n iterator.span(pos, curTo, cursor.active, openRanges);\n openRanges = cursor.openEnd(curTo);\n }\n if (cursor.to > to)\n return openRanges + (cursor.point && cursor.to > to ? 1 : 0);\n pos = cursor.to;\n cursor.next();\n }\n }\n /**\n Create a range set for the given range or array of ranges. By\n default, this expects the ranges to be _sorted_ (by start\n position and, if two start at the same position,\n `value.startSide`). You can pass `true` as second argument to\n cause the method to sort them.\n */\n static of(ranges, sort = false) {\n let build = new RangeSetBuilder();\n for (let range of ranges instanceof Range ? [ranges] : sort ? lazySort(ranges) : ranges)\n build.add(range.from, range.to, range.value);\n return build.finish();\n }\n}\n/**\nThe empty set of ranges.\n*/\nRangeSet.empty = /*@__PURE__*/new RangeSet([], [], null, -1);\nfunction lazySort(ranges) {\n if (ranges.length > 1)\n for (let prev = ranges[0], i = 1; i < ranges.length; i++) {\n let cur = ranges[i];\n if (cmpRange(prev, cur) > 0)\n return ranges.slice().sort(cmpRange);\n prev = cur;\n }\n return ranges;\n}\nRangeSet.empty.nextLayer = RangeSet.empty;\n/**\nA range set builder is a data structure that helps build up a\n[range set](https://codemirror.net/6/docs/ref/#state.RangeSet) directly, without first allocating\nan array of [`Range`](https://codemirror.net/6/docs/ref/#state.Range) objects.\n*/\nclass RangeSetBuilder {\n finishChunk(newArrays) {\n this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint));\n this.chunkPos.push(this.chunkStart);\n this.chunkStart = -1;\n this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint);\n this.maxPoint = -1;\n if (newArrays) {\n this.from = [];\n this.to = [];\n this.value = [];\n }\n }\n /**\n Create an empty builder.\n */\n constructor() {\n this.chunks = [];\n this.chunkPos = [];\n this.chunkStart = -1;\n this.last = null;\n this.lastFrom = -1000000000 /* C.Far */;\n this.lastTo = -1000000000 /* C.Far */;\n this.from = [];\n this.to = [];\n this.value = [];\n this.maxPoint = -1;\n this.setMaxPoint = -1;\n this.nextLayer = null;\n }\n /**\n Add a range. Ranges should be added in sorted (by `from` and\n `value.startSide`) order.\n */\n add(from, to, value) {\n if (!this.addInner(from, to, value))\n (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value);\n }\n /**\n @internal\n */\n addInner(from, to, value) {\n let diff = from - this.lastTo || value.startSide - this.last.endSide;\n if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0)\n throw new Error(\"Ranges must be added sorted by `from` position and `startSide`\");\n if (diff < 0)\n return false;\n if (this.from.length == 250 /* C.ChunkSize */)\n this.finishChunk(true);\n if (this.chunkStart < 0)\n this.chunkStart = from;\n this.from.push(from - this.chunkStart);\n this.to.push(to - this.chunkStart);\n this.last = value;\n this.lastFrom = from;\n this.lastTo = to;\n this.value.push(value);\n if (value.point)\n this.maxPoint = Math.max(this.maxPoint, to - from);\n return true;\n }\n /**\n @internal\n */\n addChunk(from, chunk) {\n if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0)\n return false;\n if (this.from.length)\n this.finishChunk(true);\n this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint);\n this.chunks.push(chunk);\n this.chunkPos.push(from);\n let last = chunk.value.length - 1;\n this.last = chunk.value[last];\n this.lastFrom = chunk.from[last] + from;\n this.lastTo = chunk.to[last] + from;\n return true;\n }\n /**\n Finish the range set. Returns the new set. The builder can't be\n used anymore after this has been called.\n */\n finish() { return this.finishInner(RangeSet.empty); }\n /**\n @internal\n */\n finishInner(next) {\n if (this.from.length)\n this.finishChunk(false);\n if (this.chunks.length == 0)\n return next;\n let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint);\n this.from = null; // Make sure further `add` calls produce errors\n return result;\n }\n}\nfunction findSharedChunks(a, b, textDiff) {\n let inA = new Map();\n for (let set of a)\n for (let i = 0; i < set.chunk.length; i++)\n if (set.chunk[i].maxPoint <= 0)\n inA.set(set.chunk[i], set.chunkPos[i]);\n let shared = new Set();\n for (let set of b)\n for (let i = 0; i < set.chunk.length; i++) {\n let known = inA.get(set.chunk[i]);\n if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] &&\n !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length)))\n shared.add(set.chunk[i]);\n }\n return shared;\n}\nclass LayerCursor {\n constructor(layer, skip, minPoint, rank = 0) {\n this.layer = layer;\n this.skip = skip;\n this.minPoint = minPoint;\n this.rank = rank;\n }\n get startSide() { return this.value ? this.value.startSide : 0; }\n get endSide() { return this.value ? this.value.endSide : 0; }\n goto(pos, side = -1000000000 /* C.Far */) {\n this.chunkIndex = this.rangeIndex = 0;\n this.gotoInner(pos, side, false);\n return this;\n }\n gotoInner(pos, side, forward) {\n while (this.chunkIndex < this.layer.chunk.length) {\n let next = this.layer.chunk[this.chunkIndex];\n if (!(this.skip && this.skip.has(next) ||\n this.layer.chunkEnd(this.chunkIndex) < pos ||\n next.maxPoint < this.minPoint))\n break;\n this.chunkIndex++;\n forward = false;\n }\n if (this.chunkIndex < this.layer.chunk.length) {\n let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true);\n if (!forward || this.rangeIndex < rangeIndex)\n this.setRangeIndex(rangeIndex);\n }\n this.next();\n }\n forward(pos, side) {\n if ((this.to - pos || this.endSide - side) < 0)\n this.gotoInner(pos, side, true);\n }\n next() {\n for (;;) {\n if (this.chunkIndex == this.layer.chunk.length) {\n this.from = this.to = 1000000000 /* C.Far */;\n this.value = null;\n break;\n }\n else {\n let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex];\n let from = chunkPos + chunk.from[this.rangeIndex];\n this.from = from;\n this.to = chunkPos + chunk.to[this.rangeIndex];\n this.value = chunk.value[this.rangeIndex];\n this.setRangeIndex(this.rangeIndex + 1);\n if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint)\n break;\n }\n }\n }\n setRangeIndex(index) {\n if (index == this.layer.chunk[this.chunkIndex].value.length) {\n this.chunkIndex++;\n if (this.skip) {\n while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex]))\n this.chunkIndex++;\n }\n this.rangeIndex = 0;\n }\n else {\n this.rangeIndex = index;\n }\n }\n nextChunk() {\n this.chunkIndex++;\n this.rangeIndex = 0;\n this.next();\n }\n compare(other) {\n return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank ||\n this.to - other.to || this.endSide - other.endSide;\n }\n}\nclass HeapCursor {\n constructor(heap) {\n this.heap = heap;\n }\n static from(sets, skip = null, minPoint = -1) {\n let heap = [];\n for (let i = 0; i < sets.length; i++) {\n for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) {\n if (cur.maxPoint >= minPoint)\n heap.push(new LayerCursor(cur, skip, minPoint, i));\n }\n }\n return heap.length == 1 ? heap[0] : new HeapCursor(heap);\n }\n get startSide() { return this.value ? this.value.startSide : 0; }\n goto(pos, side = -1000000000 /* C.Far */) {\n for (let cur of this.heap)\n cur.goto(pos, side);\n for (let i = this.heap.length >> 1; i >= 0; i--)\n heapBubble(this.heap, i);\n this.next();\n return this;\n }\n forward(pos, side) {\n for (let cur of this.heap)\n cur.forward(pos, side);\n for (let i = this.heap.length >> 1; i >= 0; i--)\n heapBubble(this.heap, i);\n if ((this.to - pos || this.value.endSide - side) < 0)\n this.next();\n }\n next() {\n if (this.heap.length == 0) {\n this.from = this.to = 1000000000 /* C.Far */;\n this.value = null;\n this.rank = -1;\n }\n else {\n let top = this.heap[0];\n this.from = top.from;\n this.to = top.to;\n this.value = top.value;\n this.rank = top.rank;\n if (top.value)\n top.next();\n heapBubble(this.heap, 0);\n }\n }\n}\nfunction heapBubble(heap, index) {\n for (let cur = heap[index];;) {\n let childIndex = (index << 1) + 1;\n if (childIndex >= heap.length)\n break;\n let child = heap[childIndex];\n if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) {\n child = heap[childIndex + 1];\n childIndex++;\n }\n if (cur.compare(child) < 0)\n break;\n heap[childIndex] = cur;\n heap[index] = child;\n index = childIndex;\n }\n}\nclass SpanCursor {\n constructor(sets, skip, minPoint) {\n this.minPoint = minPoint;\n this.active = [];\n this.activeTo = [];\n this.activeRank = [];\n this.minActive = -1;\n // A currently active point range, if any\n this.point = null;\n this.pointFrom = 0;\n this.pointRank = 0;\n this.to = -1000000000 /* C.Far */;\n this.endSide = 0;\n // The amount of open active ranges at the start of the iterator.\n // Not including points.\n this.openStart = -1;\n this.cursor = HeapCursor.from(sets, skip, minPoint);\n }\n goto(pos, side = -1000000000 /* C.Far */) {\n this.cursor.goto(pos, side);\n this.active.length = this.activeTo.length = this.activeRank.length = 0;\n this.minActive = -1;\n this.to = pos;\n this.endSide = side;\n this.openStart = -1;\n this.next();\n return this;\n }\n forward(pos, side) {\n while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0)\n this.removeActive(this.minActive);\n this.cursor.forward(pos, side);\n }\n removeActive(index) {\n remove(this.active, index);\n remove(this.activeTo, index);\n remove(this.activeRank, index);\n this.minActive = findMinIndex(this.active, this.activeTo);\n }\n addActive(trackOpen) {\n let i = 0, { value, to, rank } = this.cursor;\n while (i < this.activeRank.length && this.activeRank[i] <= rank)\n i++;\n insert(this.active, i, value);\n insert(this.activeTo, i, to);\n insert(this.activeRank, i, rank);\n if (trackOpen)\n insert(trackOpen, i, this.cursor.from);\n this.minActive = findMinIndex(this.active, this.activeTo);\n }\n // After calling this, if `this.point` != null, the next range is a\n // point. Otherwise, it's a regular range, covered by `this.active`.\n next() {\n let from = this.to, wasPoint = this.point;\n this.point = null;\n let trackOpen = this.openStart < 0 ? [] : null;\n for (;;) {\n let a = this.minActive;\n if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {\n if (this.activeTo[a] > from) {\n this.to = this.activeTo[a];\n this.endSide = this.active[a].endSide;\n break;\n }\n this.removeActive(a);\n if (trackOpen)\n remove(trackOpen, a);\n }\n else if (!this.cursor.value) {\n this.to = this.endSide = 1000000000 /* C.Far */;\n break;\n }\n else if (this.cursor.from > from) {\n this.to = this.cursor.from;\n this.endSide = this.cursor.startSide;\n break;\n }\n else {\n let nextVal = this.cursor.value;\n if (!nextVal.point) { // Opening a range\n this.addActive(trackOpen);\n this.cursor.next();\n }\n else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) {\n // Ignore any non-empty points that end precisely at the end of the prev point\n this.cursor.next();\n }\n else { // New point\n this.point = nextVal;\n this.pointFrom = this.cursor.from;\n this.pointRank = this.cursor.rank;\n this.to = this.cursor.to;\n this.endSide = nextVal.endSide;\n this.cursor.next();\n this.forward(this.to, this.endSide);\n break;\n }\n }\n }\n if (trackOpen) {\n this.openStart = 0;\n for (let i = trackOpen.length - 1; i >= 0 && trackOpen[i] < from; i--)\n this.openStart++;\n }\n }\n activeForPoint(to) {\n if (!this.active.length)\n return this.active;\n let active = [];\n for (let i = this.active.length - 1; i >= 0; i--) {\n if (this.activeRank[i] < this.pointRank)\n break;\n if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide)\n active.push(this.active[i]);\n }\n return active.reverse();\n }\n openEnd(to) {\n let open = 0;\n for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--)\n open++;\n return open;\n }\n}\nfunction compare(a, startA, b, startB, length, comparator) {\n a.goto(startA);\n b.goto(startB);\n let endB = startB + length;\n let pos = startB, dPos = startB - startA;\n for (;;) {\n let diff = (a.to + dPos) - b.to || a.endSide - b.endSide;\n let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB);\n if (a.point || b.point) {\n if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) &&\n sameValues(a.activeForPoint(a.to), b.activeForPoint(b.to))))\n comparator.comparePoint(pos, clipEnd, a.point, b.point);\n }\n else {\n if (clipEnd > pos && !sameValues(a.active, b.active))\n comparator.compareRange(pos, clipEnd, a.active, b.active);\n }\n if (end > endB)\n break;\n pos = end;\n if (diff <= 0)\n a.next();\n if (diff >= 0)\n b.next();\n }\n}\nfunction sameValues(a, b) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (a[i] != b[i] && !a[i].eq(b[i]))\n return false;\n return true;\n}\nfunction remove(array, index) {\n for (let i = index, e = array.length - 1; i < e; i++)\n array[i] = array[i + 1];\n array.pop();\n}\nfunction insert(array, index, value) {\n for (let i = array.length - 1; i >= index; i--)\n array[i + 1] = array[i];\n array[index] = value;\n}\nfunction findMinIndex(value, array) {\n let found = -1, foundPos = 1000000000 /* C.Far */;\n for (let i = 0; i < array.length; i++)\n if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) {\n found = i;\n foundPos = array[i];\n }\n return found;\n}\n\n/**\nCount the column position at the given offset into the string,\ntaking extending characters and tab size into account.\n*/\nfunction countColumn(string, tabSize, to = string.length) {\n let n = 0;\n for (let i = 0; i < to;) {\n if (string.charCodeAt(i) == 9) {\n n += tabSize - (n % tabSize);\n i++;\n }\n else {\n n++;\n i = findClusterBreak(string, i);\n }\n }\n return n;\n}\n/**\nFind the offset that corresponds to the given column position in a\nstring, taking extending characters and tab size into account. By\ndefault, the string length is returned when it is too short to\nreach the column. Pass `strict` true to make it return -1 in that\nsituation.\n*/\nfunction findColumn(string, col, tabSize, strict) {\n for (let i = 0, n = 0;;) {\n if (n >= col)\n return i;\n if (i == string.length)\n break;\n n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1;\n i = findClusterBreak(string, i);\n }\n return strict === true ? -1 : string.length;\n}\n\nexport { Annotation, AnnotationType, ChangeDesc, ChangeSet, CharCategory, Compartment, EditorSelection, EditorState, Facet, Line, MapMode, Prec, Range, RangeSet, RangeSetBuilder, RangeValue, SelectionRange, StateEffect, StateEffectType, StateField, Text, Transaction, codePointAt, codePointSize, combineConfig, countColumn, findClusterBreak, findColumn, fromCodePoint };\n","export var base = {\n 8: \"Backspace\",\n 9: \"Tab\",\n 10: \"Enter\",\n 12: \"NumLock\",\n 13: \"Enter\",\n 16: \"Shift\",\n 17: \"Control\",\n 18: \"Alt\",\n 20: \"CapsLock\",\n 27: \"Escape\",\n 32: \" \",\n 33: \"PageUp\",\n 34: \"PageDown\",\n 35: \"End\",\n 36: \"Home\",\n 37: \"ArrowLeft\",\n 38: \"ArrowUp\",\n 39: \"ArrowRight\",\n 40: \"ArrowDown\",\n 44: \"PrintScreen\",\n 45: \"Insert\",\n 46: \"Delete\",\n 59: \";\",\n 61: \"=\",\n 91: \"Meta\",\n 92: \"Meta\",\n 106: \"*\",\n 107: \"+\",\n 108: \",\",\n 109: \"-\",\n 110: \".\",\n 111: \"/\",\n 144: \"NumLock\",\n 145: \"ScrollLock\",\n 160: \"Shift\",\n 161: \"Shift\",\n 162: \"Control\",\n 163: \"Control\",\n 164: \"Alt\",\n 165: \"Alt\",\n 173: \"-\",\n 186: \";\",\n 187: \"=\",\n 188: \",\",\n 189: \"-\",\n 190: \".\",\n 191: \"/\",\n 192: \"`\",\n 219: \"[\",\n 220: \"\\\\\",\n 221: \"]\",\n 222: \"'\"\n}\n\nexport var shift = {\n 48: \")\",\n 49: \"!\",\n 50: \"@\",\n 51: \"#\",\n 52: \"$\",\n 53: \"%\",\n 54: \"^\",\n 55: \"&\",\n 56: \"*\",\n 57: \"(\",\n 59: \":\",\n 61: \"+\",\n 173: \"_\",\n 186: \":\",\n 187: \"+\",\n 188: \"<\",\n 189: \"_\",\n 190: \">\",\n 191: \"?\",\n 192: \"~\",\n 219: \"{\",\n 220: \"|\",\n 221: \"}\",\n 222: \"\\\"\"\n}\n\nvar mac = typeof navigator != \"undefined\" && /Mac/.test(navigator.platform)\nvar ie = typeof navigator != \"undefined\" && /MSIE \\d|Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(navigator.userAgent)\n\n// Fill in the digit keys\nfor (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i)\n\n// The function keys\nfor (var i = 1; i <= 24; i++) base[i + 111] = \"F\" + i\n\n// And the alphabetic keys\nfor (var i = 65; i <= 90; i++) {\n base[i] = String.fromCharCode(i + 32)\n shift[i] = String.fromCharCode(i)\n}\n\n// For each code that doesn't have a shift-equivalent, copy the base name\nfor (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]\n\nexport function keyName(event) {\n // On macOS, keys held with Shift and Cmd don't reflect the effect of Shift in `.key`.\n // On IE, shift effect is never included in `.key`.\n var ignoreKey = mac && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey ||\n ie && event.shiftKey && event.key && event.key.length == 1 ||\n event.key == \"Unidentified\"\n var name = (!ignoreKey && event.key) ||\n (event.shiftKey ? shift : base)[event.keyCode] ||\n event.key || \"Unidentified\"\n // Edge sometimes produces wrong names (Issue #3)\n if (name == \"Esc\") name = \"Escape\"\n if (name == \"Del\") name = \"Delete\"\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/\n if (name == \"Left\") name = \"ArrowLeft\"\n if (name == \"Up\") name = \"ArrowUp\"\n if (name == \"Right\") name = \"ArrowRight\"\n if (name == \"Down\") name = \"ArrowDown\"\n return name\n}\n","import { Text, RangeSet, MapMode, RangeValue, Facet, StateEffect, ChangeSet, EditorSelection, findClusterBreak, findColumn, CharCategory, Annotation, EditorState, Transaction, Prec, codePointAt, codePointSize, combineConfig, StateField, RangeSetBuilder, countColumn } from '@codemirror/state';\nimport { StyleModule } from 'style-mod';\nimport { keyName, base, shift } from 'w3c-keyname';\n\nfunction getSelection(root) {\n let target;\n // Browsers differ on whether shadow roots have a getSelection\n // method. If it exists, use that, otherwise, call it on the\n // document.\n if (root.nodeType == 11) { // Shadow root\n target = root.getSelection ? root : root.ownerDocument;\n }\n else {\n target = root;\n }\n return target.getSelection();\n}\nfunction contains(dom, node) {\n return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false;\n}\nfunction deepActiveElement(doc) {\n let elt = doc.activeElement;\n while (elt && elt.shadowRoot)\n elt = elt.shadowRoot.activeElement;\n return elt;\n}\nfunction hasSelection(dom, selection) {\n if (!selection.anchorNode)\n return false;\n try {\n // Firefox will raise 'permission denied' errors when accessing\n // properties of `sel.anchorNode` when it's in a generated CSS\n // element.\n return contains(dom, selection.anchorNode);\n }\n catch (_) {\n return false;\n }\n}\nfunction clientRectsFor(dom) {\n if (dom.nodeType == 3)\n return textRange(dom, 0, dom.nodeValue.length).getClientRects();\n else if (dom.nodeType == 1)\n return dom.getClientRects();\n else\n return [];\n}\n// Scans forward and backward through DOM positions equivalent to the\n// given one to see if the two are in the same place (i.e. after a\n// text node vs at the end of that text node)\nfunction isEquivalentPosition(node, off, targetNode, targetOff) {\n return targetNode ? (scanFor(node, off, targetNode, targetOff, -1) ||\n scanFor(node, off, targetNode, targetOff, 1)) : false;\n}\nfunction domIndex(node) {\n for (var index = 0;; index++) {\n node = node.previousSibling;\n if (!node)\n return index;\n }\n}\nfunction scanFor(node, off, targetNode, targetOff, dir) {\n for (;;) {\n if (node == targetNode && off == targetOff)\n return true;\n if (off == (dir < 0 ? 0 : maxOffset(node))) {\n if (node.nodeName == \"DIV\")\n return false;\n let parent = node.parentNode;\n if (!parent || parent.nodeType != 1)\n return false;\n off = domIndex(node) + (dir < 0 ? 0 : 1);\n node = parent;\n }\n else if (node.nodeType == 1) {\n node = node.childNodes[off + (dir < 0 ? -1 : 0)];\n if (node.nodeType == 1 && node.contentEditable == \"false\")\n return false;\n off = dir < 0 ? maxOffset(node) : 0;\n }\n else {\n return false;\n }\n }\n}\nfunction maxOffset(node) {\n return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;\n}\nfunction flattenRect(rect, left) {\n let x = left ? rect.left : rect.right;\n return { left: x, right: x, top: rect.top, bottom: rect.bottom };\n}\nfunction windowRect(win) {\n return { left: 0, right: win.innerWidth,\n top: 0, bottom: win.innerHeight };\n}\nfunction scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) {\n let doc = dom.ownerDocument, win = doc.defaultView || window;\n for (let cur = dom, stop = false; cur && !stop;) {\n if (cur.nodeType == 1) { // Element\n let bounding, top = cur == doc.body;\n let scaleX = 1, scaleY = 1;\n if (top) {\n bounding = windowRect(win);\n }\n else {\n if (/^(fixed|sticky)$/.test(getComputedStyle(cur).position))\n stop = true;\n if (cur.scrollHeight <= cur.clientHeight && cur.scrollWidth <= cur.clientWidth) {\n cur = cur.assignedSlot || cur.parentNode;\n continue;\n }\n let rect = cur.getBoundingClientRect();\n scaleX = rect.width / cur.offsetWidth;\n scaleY = rect.height / cur.offsetHeight;\n // Make sure scrollbar width isn't included in the rectangle\n bounding = { left: rect.left, right: rect.left + cur.clientWidth * scaleX,\n top: rect.top, bottom: rect.top + cur.clientHeight * scaleY };\n }\n let moveX = 0, moveY = 0;\n if (y == \"nearest\") {\n if (rect.top < bounding.top) {\n moveY = -(bounding.top - rect.top + yMargin);\n if (side > 0 && rect.bottom > bounding.bottom + moveY)\n moveY = rect.bottom - bounding.bottom + moveY + yMargin;\n }\n else if (rect.bottom > bounding.bottom) {\n moveY = rect.bottom - bounding.bottom + yMargin;\n if (side < 0 && (rect.top - moveY) < bounding.top)\n moveY = -(bounding.top + moveY - rect.top + yMargin);\n }\n }\n else {\n let rectHeight = rect.bottom - rect.top, boundingHeight = bounding.bottom - bounding.top;\n let targetTop = y == \"center\" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 :\n y == \"start\" || y == \"center\" && side < 0 ? rect.top - yMargin :\n rect.bottom - boundingHeight + yMargin;\n moveY = targetTop - bounding.top;\n }\n if (x == \"nearest\") {\n if (rect.left < bounding.left) {\n moveX = -(bounding.left - rect.left + xMargin);\n if (side > 0 && rect.right > bounding.right + moveX)\n moveX = rect.right - bounding.right + moveX + xMargin;\n }\n else if (rect.right > bounding.right) {\n moveX = rect.right - bounding.right + xMargin;\n if (side < 0 && rect.left < bounding.left + moveX)\n moveX = -(bounding.left + moveX - rect.left + xMargin);\n }\n }\n else {\n let targetLeft = x == \"center\" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 :\n (x == \"start\") == ltr ? rect.left - xMargin :\n rect.right - (bounding.right - bounding.left) + xMargin;\n moveX = targetLeft - bounding.left;\n }\n if (moveX || moveY) {\n if (top) {\n win.scrollBy(moveX, moveY);\n }\n else {\n let movedX = 0, movedY = 0;\n if (moveY) {\n let start = cur.scrollTop;\n cur.scrollTop += moveY / scaleY;\n movedY = (cur.scrollTop - start) * scaleY;\n }\n if (moveX) {\n let start = cur.scrollLeft;\n cur.scrollLeft += moveX / scaleX;\n movedX = (cur.scrollLeft - start) * scaleX;\n }\n rect = { left: rect.left - movedX, top: rect.top - movedY,\n right: rect.right - movedX, bottom: rect.bottom - movedY };\n if (movedX && Math.abs(movedX - moveX) < 1)\n x = \"nearest\";\n if (movedY && Math.abs(movedY - moveY) < 1)\n y = \"nearest\";\n }\n }\n if (top)\n break;\n cur = cur.assignedSlot || cur.parentNode;\n }\n else if (cur.nodeType == 11) { // A shadow root\n cur = cur.host;\n }\n else {\n break;\n }\n }\n}\nfunction scrollableParent(dom) {\n let doc = dom.ownerDocument;\n for (let cur = dom.parentNode; cur;) {\n if (cur == doc.body) {\n break;\n }\n else if (cur.nodeType == 1) {\n if (cur.scrollHeight > cur.clientHeight || cur.scrollWidth > cur.clientWidth)\n return cur;\n cur = cur.assignedSlot || cur.parentNode;\n }\n else if (cur.nodeType == 11) {\n cur = cur.host;\n }\n else {\n break;\n }\n }\n return null;\n}\nclass DOMSelectionState {\n constructor() {\n this.anchorNode = null;\n this.anchorOffset = 0;\n this.focusNode = null;\n this.focusOffset = 0;\n }\n eq(domSel) {\n return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset &&\n this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset;\n }\n setRange(range) {\n let { anchorNode, focusNode } = range;\n // Clip offsets to node size to avoid crashes when Safari reports bogus offsets (#1152)\n this.set(anchorNode, Math.min(range.anchorOffset, anchorNode ? maxOffset(anchorNode) : 0), focusNode, Math.min(range.focusOffset, focusNode ? maxOffset(focusNode) : 0));\n }\n set(anchorNode, anchorOffset, focusNode, focusOffset) {\n this.anchorNode = anchorNode;\n this.anchorOffset = anchorOffset;\n this.focusNode = focusNode;\n this.focusOffset = focusOffset;\n }\n}\nlet preventScrollSupported = null;\n// Feature-detects support for .focus({preventScroll: true}), and uses\n// a fallback kludge when not supported.\nfunction focusPreventScroll(dom) {\n if (dom.setActive)\n return dom.setActive(); // in IE\n if (preventScrollSupported)\n return dom.focus(preventScrollSupported);\n let stack = [];\n for (let cur = dom; cur; cur = cur.parentNode) {\n stack.push(cur, cur.scrollTop, cur.scrollLeft);\n if (cur == cur.ownerDocument)\n break;\n }\n dom.focus(preventScrollSupported == null ? {\n get preventScroll() {\n preventScrollSupported = { preventScroll: true };\n return true;\n }\n } : undefined);\n if (!preventScrollSupported) {\n preventScrollSupported = false;\n for (let i = 0; i < stack.length;) {\n let elt = stack[i++], top = stack[i++], left = stack[i++];\n if (elt.scrollTop != top)\n elt.scrollTop = top;\n if (elt.scrollLeft != left)\n elt.scrollLeft = left;\n }\n }\n}\nlet scratchRange;\nfunction textRange(node, from, to = from) {\n let range = scratchRange || (scratchRange = document.createRange());\n range.setEnd(node, to);\n range.setStart(node, from);\n return range;\n}\nfunction dispatchKey(elt, name, code) {\n let options = { key: name, code: name, keyCode: code, which: code, cancelable: true };\n let down = new KeyboardEvent(\"keydown\", options);\n down.synthetic = true;\n elt.dispatchEvent(down);\n let up = new KeyboardEvent(\"keyup\", options);\n up.synthetic = true;\n elt.dispatchEvent(up);\n return down.defaultPrevented || up.defaultPrevented;\n}\nfunction getRoot(node) {\n while (node) {\n if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host))\n return node;\n node = node.assignedSlot || node.parentNode;\n }\n return null;\n}\nfunction clearAttributes(node) {\n while (node.attributes.length)\n node.removeAttributeNode(node.attributes[0]);\n}\nfunction atElementStart(doc, selection) {\n let node = selection.focusNode, offset = selection.focusOffset;\n if (!node || selection.anchorNode != node || selection.anchorOffset != offset)\n return false;\n // Safari can report bogus offsets (#1152)\n offset = Math.min(offset, maxOffset(node));\n for (;;) {\n if (offset) {\n if (node.nodeType != 1)\n return false;\n let prev = node.childNodes[offset - 1];\n if (prev.contentEditable == \"false\")\n offset--;\n else {\n node = prev;\n offset = maxOffset(node);\n }\n }\n else if (node == doc) {\n return true;\n }\n else {\n offset = domIndex(node);\n node = node.parentNode;\n }\n }\n}\nfunction isScrolledToBottom(elt) {\n return elt.scrollTop > Math.max(1, elt.scrollHeight - elt.clientHeight - 4);\n}\n\nclass DOMPos {\n constructor(node, offset, precise = true) {\n this.node = node;\n this.offset = offset;\n this.precise = precise;\n }\n static before(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom), precise); }\n static after(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom) + 1, precise); }\n}\nconst noChildren = [];\nclass ContentView {\n constructor() {\n this.parent = null;\n this.dom = null;\n this.flags = 2 /* ViewFlag.NodeDirty */;\n }\n get overrideDOMText() { return null; }\n get posAtStart() {\n return this.parent ? this.parent.posBefore(this) : 0;\n }\n get posAtEnd() {\n return this.posAtStart + this.length;\n }\n posBefore(view) {\n let pos = this.posAtStart;\n for (let child of this.children) {\n if (child == view)\n return pos;\n pos += child.length + child.breakAfter;\n }\n throw new RangeError(\"Invalid child in posBefore\");\n }\n posAfter(view) {\n return this.posBefore(view) + view.length;\n }\n sync(view, track) {\n if (this.flags & 2 /* ViewFlag.NodeDirty */) {\n let parent = this.dom;\n let prev = null, next;\n for (let child of this.children) {\n if (child.flags & 7 /* ViewFlag.Dirty */) {\n if (!child.dom && (next = prev ? prev.nextSibling : parent.firstChild)) {\n let contentView = ContentView.get(next);\n if (!contentView || !contentView.parent && contentView.canReuseDOM(child))\n child.reuseDOM(next);\n }\n child.sync(view, track);\n child.flags &= ~7 /* ViewFlag.Dirty */;\n }\n next = prev ? prev.nextSibling : parent.firstChild;\n if (track && !track.written && track.node == parent && next != child.dom)\n track.written = true;\n if (child.dom.parentNode == parent) {\n while (next && next != child.dom)\n next = rm$1(next);\n }\n else {\n parent.insertBefore(child.dom, next);\n }\n prev = child.dom;\n }\n next = prev ? prev.nextSibling : parent.firstChild;\n if (next && track && track.node == parent)\n track.written = true;\n while (next)\n next = rm$1(next);\n }\n else if (this.flags & 1 /* ViewFlag.ChildDirty */) {\n for (let child of this.children)\n if (child.flags & 7 /* ViewFlag.Dirty */) {\n child.sync(view, track);\n child.flags &= ~7 /* ViewFlag.Dirty */;\n }\n }\n }\n reuseDOM(_dom) { }\n localPosFromDOM(node, offset) {\n let after;\n if (node == this.dom) {\n after = this.dom.childNodes[offset];\n }\n else {\n let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1;\n for (;;) {\n let parent = node.parentNode;\n if (parent == this.dom)\n break;\n if (bias == 0 && parent.firstChild != parent.lastChild) {\n if (node == parent.firstChild)\n bias = -1;\n else\n bias = 1;\n }\n node = parent;\n }\n if (bias < 0)\n after = node;\n else\n after = node.nextSibling;\n }\n if (after == this.dom.firstChild)\n return 0;\n while (after && !ContentView.get(after))\n after = after.nextSibling;\n if (!after)\n return this.length;\n for (let i = 0, pos = 0;; i++) {\n let child = this.children[i];\n if (child.dom == after)\n return pos;\n pos += child.length + child.breakAfter;\n }\n }\n domBoundsAround(from, to, offset = 0) {\n let fromI = -1, fromStart = -1, toI = -1, toEnd = -1;\n for (let i = 0, pos = offset, prevEnd = offset; i < this.children.length; i++) {\n let child = this.children[i], end = pos + child.length;\n if (pos < from && end > to)\n return child.domBoundsAround(from, to, pos);\n if (end >= from && fromI == -1) {\n fromI = i;\n fromStart = pos;\n }\n if (pos > to && child.dom.parentNode == this.dom) {\n toI = i;\n toEnd = prevEnd;\n break;\n }\n prevEnd = end;\n pos = end + child.breakAfter;\n }\n return { from: fromStart, to: toEnd < 0 ? offset + this.length : toEnd,\n startDOM: (fromI ? this.children[fromI - 1].dom.nextSibling : null) || this.dom.firstChild,\n endDOM: toI < this.children.length && toI >= 0 ? this.children[toI].dom : null };\n }\n markDirty(andParent = false) {\n this.flags |= 2 /* ViewFlag.NodeDirty */;\n this.markParentsDirty(andParent);\n }\n markParentsDirty(childList) {\n for (let parent = this.parent; parent; parent = parent.parent) {\n if (childList)\n parent.flags |= 2 /* ViewFlag.NodeDirty */;\n if (parent.flags & 1 /* ViewFlag.ChildDirty */)\n return;\n parent.flags |= 1 /* ViewFlag.ChildDirty */;\n childList = false;\n }\n }\n setParent(parent) {\n if (this.parent != parent) {\n this.parent = parent;\n if (this.flags & 7 /* ViewFlag.Dirty */)\n this.markParentsDirty(true);\n }\n }\n setDOM(dom) {\n if (this.dom == dom)\n return;\n if (this.dom)\n this.dom.cmView = null;\n this.dom = dom;\n dom.cmView = this;\n }\n get rootView() {\n for (let v = this;;) {\n let parent = v.parent;\n if (!parent)\n return v;\n v = parent;\n }\n }\n replaceChildren(from, to, children = noChildren) {\n this.markDirty();\n for (let i = from; i < to; i++) {\n let child = this.children[i];\n if (child.parent == this)\n child.destroy();\n }\n this.children.splice(from, to - from, ...children);\n for (let i = 0; i < children.length; i++)\n children[i].setParent(this);\n }\n ignoreMutation(_rec) { return false; }\n ignoreEvent(_event) { return false; }\n childCursor(pos = this.length) {\n return new ChildCursor(this.children, pos, this.children.length);\n }\n childPos(pos, bias = 1) {\n return this.childCursor().findPos(pos, bias);\n }\n toString() {\n let name = this.constructor.name.replace(\"View\", \"\");\n return name + (this.children.length ? \"(\" + this.children.join() + \")\" :\n this.length ? \"[\" + (name == \"Text\" ? this.text : this.length) + \"]\" : \"\") +\n (this.breakAfter ? \"#\" : \"\");\n }\n static get(node) { return node.cmView; }\n get isEditable() { return true; }\n get isWidget() { return false; }\n get isHidden() { return false; }\n merge(from, to, source, hasStart, openStart, openEnd) {\n return false;\n }\n become(other) { return false; }\n canReuseDOM(other) {\n return other.constructor == this.constructor && !((this.flags | other.flags) & 8 /* ViewFlag.Composition */);\n }\n // When this is a zero-length view with a side, this should return a\n // number <= 0 to indicate it is before its position, or a\n // number > 0 when after its position.\n getSide() { return 0; }\n destroy() {\n this.parent = null;\n }\n}\nContentView.prototype.breakAfter = 0;\n// Remove a DOM node and return its next sibling.\nfunction rm$1(dom) {\n let next = dom.nextSibling;\n dom.parentNode.removeChild(dom);\n return next;\n}\nclass ChildCursor {\n constructor(children, pos, i) {\n this.children = children;\n this.pos = pos;\n this.i = i;\n this.off = 0;\n }\n findPos(pos, bias = 1) {\n for (;;) {\n if (pos > this.pos || pos == this.pos &&\n (bias > 0 || this.i == 0 || this.children[this.i - 1].breakAfter)) {\n this.off = pos - this.pos;\n return this;\n }\n let next = this.children[--this.i];\n this.pos -= next.length + next.breakAfter;\n }\n }\n}\nfunction replaceRange(parent, fromI, fromOff, toI, toOff, insert, breakAtStart, openStart, openEnd) {\n let { children } = parent;\n let before = children.length ? children[fromI] : null;\n let last = insert.length ? insert[insert.length - 1] : null;\n let breakAtEnd = last ? last.breakAfter : breakAtStart;\n // Change within a single child\n if (fromI == toI && before && !breakAtStart && !breakAtEnd && insert.length < 2 &&\n before.merge(fromOff, toOff, insert.length ? last : null, fromOff == 0, openStart, openEnd))\n return;\n if (toI < children.length) {\n let after = children[toI];\n // Make sure the end of the child after the update is preserved in `after`\n if (after && (toOff < after.length || after.breakAfter && (last === null || last === void 0 ? void 0 : last.breakAfter))) {\n // If we're splitting a child, separate part of it to avoid that\n // being mangled when updating the child before the update.\n if (fromI == toI) {\n after = after.split(toOff);\n toOff = 0;\n }\n // If the element after the replacement should be merged with\n // the last replacing element, update `content`\n if (!breakAtEnd && last && after.merge(0, toOff, last, true, 0, openEnd)) {\n insert[insert.length - 1] = after;\n }\n else {\n // Remove the start of the after element, if necessary, and\n // add it to `content`.\n if (toOff || after.children.length && !after.children[0].length)\n after.merge(0, toOff, null, false, 0, openEnd);\n insert.push(after);\n }\n }\n else if (after === null || after === void 0 ? void 0 : after.breakAfter) {\n // The element at `toI` is entirely covered by this range.\n // Preserve its line break, if any.\n if (last)\n last.breakAfter = 1;\n else\n breakAtStart = 1;\n }\n // Since we've handled the next element from the current elements\n // now, make sure `toI` points after that.\n toI++;\n }\n if (before) {\n before.breakAfter = breakAtStart;\n if (fromOff > 0) {\n if (!breakAtStart && insert.length && before.merge(fromOff, before.length, insert[0], false, openStart, 0)) {\n before.breakAfter = insert.shift().breakAfter;\n }\n else if (fromOff < before.length || before.children.length && before.children[before.children.length - 1].length == 0) {\n before.merge(fromOff, before.length, null, false, openStart, 0);\n }\n fromI++;\n }\n }\n // Try to merge widgets on the boundaries of the replacement\n while (fromI < toI && insert.length) {\n if (children[toI - 1].become(insert[insert.length - 1])) {\n toI--;\n insert.pop();\n openEnd = insert.length ? 0 : openStart;\n }\n else if (children[fromI].become(insert[0])) {\n fromI++;\n insert.shift();\n openStart = insert.length ? 0 : openEnd;\n }\n else {\n break;\n }\n }\n if (!insert.length && fromI && toI < children.length && !children[fromI - 1].breakAfter &&\n children[toI].merge(0, 0, children[fromI - 1], false, openStart, openEnd))\n fromI--;\n if (fromI < toI || insert.length)\n parent.replaceChildren(fromI, toI, insert);\n}\nfunction mergeChildrenInto(parent, from, to, insert, openStart, openEnd) {\n let cur = parent.childCursor();\n let { i: toI, off: toOff } = cur.findPos(to, 1);\n let { i: fromI, off: fromOff } = cur.findPos(from, -1);\n let dLen = from - to;\n for (let view of insert)\n dLen += view.length;\n parent.length += dLen;\n replaceRange(parent, fromI, fromOff, toI, toOff, insert, 0, openStart, openEnd);\n}\n\nlet nav = typeof navigator != \"undefined\" ? navigator : { userAgent: \"\", vendor: \"\", platform: \"\" };\nlet doc = typeof document != \"undefined\" ? document : { documentElement: { style: {} } };\nconst ie_edge = /*@__PURE__*//Edge\\/(\\d+)/.exec(nav.userAgent);\nconst ie_upto10 = /*@__PURE__*//MSIE \\d/.test(nav.userAgent);\nconst ie_11up = /*@__PURE__*//Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(nav.userAgent);\nconst ie = !!(ie_upto10 || ie_11up || ie_edge);\nconst gecko = !ie && /*@__PURE__*//gecko\\/(\\d+)/i.test(nav.userAgent);\nconst chrome = !ie && /*@__PURE__*//Chrome\\/(\\d+)/.exec(nav.userAgent);\nconst webkit = \"webkitFontSmoothing\" in doc.documentElement.style;\nconst safari = !ie && /*@__PURE__*//Apple Computer/.test(nav.vendor);\nconst ios = safari && (/*@__PURE__*//Mobile\\/\\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2);\nvar browser = {\n mac: ios || /*@__PURE__*//Mac/.test(nav.platform),\n windows: /*@__PURE__*//Win/.test(nav.platform),\n linux: /*@__PURE__*//Linux|X11/.test(nav.platform),\n ie,\n ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0,\n gecko,\n gecko_version: gecko ? +(/*@__PURE__*//Firefox\\/(\\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,\n chrome: !!chrome,\n chrome_version: chrome ? +chrome[1] : 0,\n ios,\n android: /*@__PURE__*//Android\\b/.test(nav.userAgent),\n webkit,\n safari,\n webkit_version: webkit ? +(/*@__PURE__*//\\bAppleWebKit\\/(\\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0,\n tabSize: doc.documentElement.style.tabSize != null ? \"tab-size\" : \"-moz-tab-size\"\n};\n\nconst MaxJoinLen = 256;\nclass TextView extends ContentView {\n constructor(text) {\n super();\n this.text = text;\n }\n get length() { return this.text.length; }\n createDOM(textDOM) {\n this.setDOM(textDOM || document.createTextNode(this.text));\n }\n sync(view, track) {\n if (!this.dom)\n this.createDOM();\n if (this.dom.nodeValue != this.text) {\n if (track && track.node == this.dom)\n track.written = true;\n this.dom.nodeValue = this.text;\n }\n }\n reuseDOM(dom) {\n if (dom.nodeType == 3)\n this.createDOM(dom);\n }\n merge(from, to, source) {\n if ((this.flags & 8 /* ViewFlag.Composition */) ||\n source && (!(source instanceof TextView) ||\n this.length - (to - from) + source.length > MaxJoinLen ||\n (source.flags & 8 /* ViewFlag.Composition */)))\n return false;\n this.text = this.text.slice(0, from) + (source ? source.text : \"\") + this.text.slice(to);\n this.markDirty();\n return true;\n }\n split(from) {\n let result = new TextView(this.text.slice(from));\n this.text = this.text.slice(0, from);\n this.markDirty();\n result.flags |= this.flags & 8 /* ViewFlag.Composition */;\n return result;\n }\n localPosFromDOM(node, offset) {\n return node == this.dom ? offset : offset ? this.text.length : 0;\n }\n domAtPos(pos) { return new DOMPos(this.dom, pos); }\n domBoundsAround(_from, _to, offset) {\n return { from: offset, to: offset + this.length, startDOM: this.dom, endDOM: this.dom.nextSibling };\n }\n coordsAt(pos, side) {\n return textCoords(this.dom, pos, side);\n }\n}\nclass MarkView extends ContentView {\n constructor(mark, children = [], length = 0) {\n super();\n this.mark = mark;\n this.children = children;\n this.length = length;\n for (let ch of children)\n ch.setParent(this);\n }\n setAttrs(dom) {\n clearAttributes(dom);\n if (this.mark.class)\n dom.className = this.mark.class;\n if (this.mark.attrs)\n for (let name in this.mark.attrs)\n dom.setAttribute(name, this.mark.attrs[name]);\n return dom;\n }\n canReuseDOM(other) {\n return super.canReuseDOM(other) && !((this.flags | other.flags) & 8 /* ViewFlag.Composition */);\n }\n reuseDOM(node) {\n if (node.nodeName == this.mark.tagName.toUpperCase()) {\n this.setDOM(node);\n this.flags |= 4 /* ViewFlag.AttrsDirty */ | 2 /* ViewFlag.NodeDirty */;\n }\n }\n sync(view, track) {\n if (!this.dom)\n this.setDOM(this.setAttrs(document.createElement(this.mark.tagName)));\n else if (this.flags & 4 /* ViewFlag.AttrsDirty */)\n this.setAttrs(this.dom);\n super.sync(view, track);\n }\n merge(from, to, source, _hasStart, openStart, openEnd) {\n if (source && (!(source instanceof MarkView && source.mark.eq(this.mark)) ||\n (from && openStart <= 0) || (to < this.length && openEnd <= 0)))\n return false;\n mergeChildrenInto(this, from, to, source ? source.children : [], openStart - 1, openEnd - 1);\n this.markDirty();\n return true;\n }\n split(from) {\n let result = [], off = 0, detachFrom = -1, i = 0;\n for (let elt of this.children) {\n let end = off + elt.length;\n if (end > from)\n result.push(off < from ? elt.split(from - off) : elt);\n if (detachFrom < 0 && off >= from)\n detachFrom = i;\n off = end;\n i++;\n }\n let length = this.length - from;\n this.length = from;\n if (detachFrom > -1) {\n this.children.length = detachFrom;\n this.markDirty();\n }\n return new MarkView(this.mark, result, length);\n }\n domAtPos(pos) {\n return inlineDOMAtPos(this, pos);\n }\n coordsAt(pos, side) {\n return coordsInChildren(this, pos, side);\n }\n}\nfunction textCoords(text, pos, side) {\n let length = text.nodeValue.length;\n if (pos > length)\n pos = length;\n let from = pos, to = pos, flatten = 0;\n if (pos == 0 && side < 0 || pos == length && side >= 0) {\n if (!(browser.chrome || browser.gecko)) { // These browsers reliably return valid rectangles for empty ranges\n if (pos) {\n from--;\n flatten = 1;\n } // FIXME this is wrong in RTL text\n else if (to < length) {\n to++;\n flatten = -1;\n }\n }\n }\n else {\n if (side < 0)\n from--;\n else if (to < length)\n to++;\n }\n let rects = textRange(text, from, to).getClientRects();\n if (!rects.length)\n return null;\n let rect = rects[(flatten ? flatten < 0 : side >= 0) ? 0 : rects.length - 1];\n if (browser.safari && !flatten && rect.width == 0)\n rect = Array.prototype.find.call(rects, r => r.width) || rect;\n return flatten ? flattenRect(rect, flatten < 0) : rect || null;\n}\n// Also used for collapsed ranges that don't have a placeholder widget!\nclass WidgetView extends ContentView {\n static create(widget, length, side) {\n return new WidgetView(widget, length, side);\n }\n constructor(widget, length, side) {\n super();\n this.widget = widget;\n this.length = length;\n this.side = side;\n this.prevWidget = null;\n }\n split(from) {\n let result = WidgetView.create(this.widget, this.length - from, this.side);\n this.length -= from;\n return result;\n }\n sync(view) {\n if (!this.dom || !this.widget.updateDOM(this.dom, view)) {\n if (this.dom && this.prevWidget)\n this.prevWidget.destroy(this.dom);\n this.prevWidget = null;\n this.setDOM(this.widget.toDOM(view));\n this.dom.contentEditable = \"false\";\n }\n }\n getSide() { return this.side; }\n merge(from, to, source, hasStart, openStart, openEnd) {\n if (source && (!(source instanceof WidgetView) || !this.widget.compare(source.widget) ||\n from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))\n return false;\n this.length = from + (source ? source.length : 0) + (this.length - to);\n return true;\n }\n become(other) {\n if (other instanceof WidgetView && other.side == this.side &&\n this.widget.constructor == other.widget.constructor) {\n if (!this.widget.compare(other.widget))\n this.markDirty(true);\n if (this.dom && !this.prevWidget)\n this.prevWidget = this.widget;\n this.widget = other.widget;\n this.length = other.length;\n return true;\n }\n return false;\n }\n ignoreMutation() { return true; }\n ignoreEvent(event) { return this.widget.ignoreEvent(event); }\n get overrideDOMText() {\n if (this.length == 0)\n return Text.empty;\n let top = this;\n while (top.parent)\n top = top.parent;\n let { view } = top, text = view && view.state.doc, start = this.posAtStart;\n return text ? text.slice(start, start + this.length) : Text.empty;\n }\n domAtPos(pos) {\n return (this.length ? pos == 0 : this.side > 0)\n ? DOMPos.before(this.dom)\n : DOMPos.after(this.dom, pos == this.length);\n }\n domBoundsAround() { return null; }\n coordsAt(pos, side) {\n let custom = this.widget.coordsAt(this.dom, pos, side);\n if (custom)\n return custom;\n let rects = this.dom.getClientRects(), rect = null;\n if (!rects.length)\n return null;\n let fromBack = this.side ? this.side < 0 : pos > 0;\n for (let i = fromBack ? rects.length - 1 : 0;; i += (fromBack ? -1 : 1)) {\n rect = rects[i];\n if (pos > 0 ? i == 0 : i == rects.length - 1 || rect.top < rect.bottom)\n break;\n }\n return flattenRect(rect, !fromBack);\n }\n get isEditable() { return false; }\n get isWidget() { return true; }\n get isHidden() { return this.widget.isHidden; }\n destroy() {\n super.destroy();\n if (this.dom)\n this.widget.destroy(this.dom);\n }\n}\n// These are drawn around uneditable widgets to avoid a number of\n// browser bugs that show up when the cursor is directly next to\n// uneditable inline content.\nclass WidgetBufferView extends ContentView {\n constructor(side) {\n super();\n this.side = side;\n }\n get length() { return 0; }\n merge() { return false; }\n become(other) {\n return other instanceof WidgetBufferView && other.side == this.side;\n }\n split() { return new WidgetBufferView(this.side); }\n sync() {\n if (!this.dom) {\n let dom = document.createElement(\"img\");\n dom.className = \"cm-widgetBuffer\";\n dom.setAttribute(\"aria-hidden\", \"true\");\n this.setDOM(dom);\n }\n }\n getSide() { return this.side; }\n domAtPos(pos) { return this.side > 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom); }\n localPosFromDOM() { return 0; }\n domBoundsAround() { return null; }\n coordsAt(pos) {\n return this.dom.getBoundingClientRect();\n }\n get overrideDOMText() {\n return Text.empty;\n }\n get isHidden() { return true; }\n}\nTextView.prototype.children = WidgetView.prototype.children = WidgetBufferView.prototype.children = noChildren;\nfunction inlineDOMAtPos(parent, pos) {\n let dom = parent.dom, { children } = parent, i = 0;\n for (let off = 0; i < children.length; i++) {\n let child = children[i], end = off + child.length;\n if (end == off && child.getSide() <= 0)\n continue;\n if (pos > off && pos < end && child.dom.parentNode == dom)\n return child.domAtPos(pos - off);\n if (pos <= off)\n break;\n off = end;\n }\n for (let j = i; j > 0; j--) {\n let prev = children[j - 1];\n if (prev.dom.parentNode == dom)\n return prev.domAtPos(prev.length);\n }\n for (let j = i; j < children.length; j++) {\n let next = children[j];\n if (next.dom.parentNode == dom)\n return next.domAtPos(0);\n }\n return new DOMPos(dom, 0);\n}\n// Assumes `view`, if a mark view, has precisely 1 child.\nfunction joinInlineInto(parent, view, open) {\n let last, { children } = parent;\n if (open > 0 && view instanceof MarkView && children.length &&\n (last = children[children.length - 1]) instanceof MarkView && last.mark.eq(view.mark)) {\n joinInlineInto(last, view.children[0], open - 1);\n }\n else {\n children.push(view);\n view.setParent(parent);\n }\n parent.length += view.length;\n}\nfunction coordsInChildren(view, pos, side) {\n let before = null, beforePos = -1, after = null, afterPos = -1;\n function scan(view, pos) {\n for (let i = 0, off = 0; i < view.children.length && off <= pos; i++) {\n let child = view.children[i], end = off + child.length;\n if (end >= pos) {\n if (child.children.length) {\n scan(child, pos - off);\n }\n else if ((!after || after.isHidden && side > 0) &&\n (end > pos || off == end && child.getSide() > 0)) {\n after = child;\n afterPos = pos - off;\n }\n else if (off < pos || (off == end && child.getSide() < 0) && !child.isHidden) {\n before = child;\n beforePos = pos - off;\n }\n }\n off = end;\n }\n }\n scan(view, pos);\n let target = (side < 0 ? before : after) || before || after;\n if (target)\n return target.coordsAt(Math.max(0, target == before ? beforePos : afterPos), side);\n return fallbackRect(view);\n}\nfunction fallbackRect(view) {\n let last = view.dom.lastChild;\n if (!last)\n return view.dom.getBoundingClientRect();\n let rects = clientRectsFor(last);\n return rects[rects.length - 1] || null;\n}\n\nfunction combineAttrs(source, target) {\n for (let name in source) {\n if (name == \"class\" && target.class)\n target.class += \" \" + source.class;\n else if (name == \"style\" && target.style)\n target.style += \";\" + source.style;\n else\n target[name] = source[name];\n }\n return target;\n}\nconst noAttrs = /*@__PURE__*/Object.create(null);\nfunction attrsEq(a, b, ignore) {\n if (a == b)\n return true;\n if (!a)\n a = noAttrs;\n if (!b)\n b = noAttrs;\n let keysA = Object.keys(a), keysB = Object.keys(b);\n if (keysA.length - (ignore && keysA.indexOf(ignore) > -1 ? 1 : 0) !=\n keysB.length - (ignore && keysB.indexOf(ignore) > -1 ? 1 : 0))\n return false;\n for (let key of keysA) {\n if (key != ignore && (keysB.indexOf(key) == -1 || a[key] !== b[key]))\n return false;\n }\n return true;\n}\nfunction updateAttrs(dom, prev, attrs) {\n let changed = false;\n if (prev)\n for (let name in prev)\n if (!(attrs && name in attrs)) {\n changed = true;\n if (name == \"style\")\n dom.style.cssText = \"\";\n else\n dom.removeAttribute(name);\n }\n if (attrs)\n for (let name in attrs)\n if (!(prev && prev[name] == attrs[name])) {\n changed = true;\n if (name == \"style\")\n dom.style.cssText = attrs[name];\n else\n dom.setAttribute(name, attrs[name]);\n }\n return changed;\n}\nfunction getAttrs(dom) {\n let attrs = Object.create(null);\n for (let i = 0; i < dom.attributes.length; i++) {\n let attr = dom.attributes[i];\n attrs[attr.name] = attr.value;\n }\n return attrs;\n}\n\nclass LineView extends ContentView {\n constructor() {\n super(...arguments);\n this.children = [];\n this.length = 0;\n this.prevAttrs = undefined;\n this.attrs = null;\n this.breakAfter = 0;\n }\n // Consumes source\n merge(from, to, source, hasStart, openStart, openEnd) {\n if (source) {\n if (!(source instanceof LineView))\n return false;\n if (!this.dom)\n source.transferDOM(this); // Reuse source.dom when appropriate\n }\n if (hasStart)\n this.setDeco(source ? source.attrs : null);\n mergeChildrenInto(this, from, to, source ? source.children : [], openStart, openEnd);\n return true;\n }\n split(at) {\n let end = new LineView;\n end.breakAfter = this.breakAfter;\n if (this.length == 0)\n return end;\n let { i, off } = this.childPos(at);\n if (off) {\n end.append(this.children[i].split(off), 0);\n this.children[i].merge(off, this.children[i].length, null, false, 0, 0);\n i++;\n }\n for (let j = i; j < this.children.length; j++)\n end.append(this.children[j], 0);\n while (i > 0 && this.children[i - 1].length == 0)\n this.children[--i].destroy();\n this.children.length = i;\n this.markDirty();\n this.length = at;\n return end;\n }\n transferDOM(other) {\n if (!this.dom)\n return;\n this.markDirty();\n other.setDOM(this.dom);\n other.prevAttrs = this.prevAttrs === undefined ? this.attrs : this.prevAttrs;\n this.prevAttrs = undefined;\n this.dom = null;\n }\n setDeco(attrs) {\n if (!attrsEq(this.attrs, attrs)) {\n if (this.dom) {\n this.prevAttrs = this.attrs;\n this.markDirty();\n }\n this.attrs = attrs;\n }\n }\n append(child, openStart) {\n joinInlineInto(this, child, openStart);\n }\n // Only called when building a line view in ContentBuilder\n addLineDeco(deco) {\n let attrs = deco.spec.attributes, cls = deco.spec.class;\n if (attrs)\n this.attrs = combineAttrs(attrs, this.attrs || {});\n if (cls)\n this.attrs = combineAttrs({ class: cls }, this.attrs || {});\n }\n domAtPos(pos) {\n return inlineDOMAtPos(this, pos);\n }\n reuseDOM(node) {\n if (node.nodeName == \"DIV\") {\n this.setDOM(node);\n this.flags |= 4 /* ViewFlag.AttrsDirty */ | 2 /* ViewFlag.NodeDirty */;\n }\n }\n sync(view, track) {\n var _a;\n if (!this.dom) {\n this.setDOM(document.createElement(\"div\"));\n this.dom.className = \"cm-line\";\n this.prevAttrs = this.attrs ? null : undefined;\n }\n else if (this.flags & 4 /* ViewFlag.AttrsDirty */) {\n clearAttributes(this.dom);\n this.dom.className = \"cm-line\";\n this.prevAttrs = this.attrs ? null : undefined;\n }\n if (this.prevAttrs !== undefined) {\n updateAttrs(this.dom, this.prevAttrs, this.attrs);\n this.dom.classList.add(\"cm-line\");\n this.prevAttrs = undefined;\n }\n super.sync(view, track);\n let last = this.dom.lastChild;\n while (last && ContentView.get(last) instanceof MarkView)\n last = last.lastChild;\n if (!last || !this.length ||\n last.nodeName != \"BR\" && ((_a = ContentView.get(last)) === null || _a === void 0 ? void 0 : _a.isEditable) == false &&\n (!browser.ios || !this.children.some(ch => ch instanceof TextView))) {\n let hack = document.createElement(\"BR\");\n hack.cmIgnore = true;\n this.dom.appendChild(hack);\n }\n }\n measureTextSize() {\n if (this.children.length == 0 || this.length > 20)\n return null;\n let totalWidth = 0, textHeight;\n for (let child of this.children) {\n if (!(child instanceof TextView) || /[^ -~]/.test(child.text))\n return null;\n let rects = clientRectsFor(child.dom);\n if (rects.length != 1)\n return null;\n totalWidth += rects[0].width;\n textHeight = rects[0].height;\n }\n return !totalWidth ? null : {\n lineHeight: this.dom.getBoundingClientRect().height,\n charWidth: totalWidth / this.length,\n textHeight\n };\n }\n coordsAt(pos, side) {\n let rect = coordsInChildren(this, pos, side);\n // Correct rectangle height for empty lines when the returned\n // height is larger than the text height.\n if (!this.children.length && rect && this.parent) {\n let { heightOracle } = this.parent.view.viewState, height = rect.bottom - rect.top;\n if (Math.abs(height - heightOracle.lineHeight) < 2 && heightOracle.textHeight < height) {\n let dist = (height - heightOracle.textHeight) / 2;\n return { top: rect.top + dist, bottom: rect.bottom - dist, left: rect.left, right: rect.left };\n }\n }\n return rect;\n }\n become(_other) { return false; }\n covers() { return true; }\n static find(docView, pos) {\n for (let i = 0, off = 0; i < docView.children.length; i++) {\n let block = docView.children[i], end = off + block.length;\n if (end >= pos) {\n if (block instanceof LineView)\n return block;\n if (end > pos)\n break;\n }\n off = end + block.breakAfter;\n }\n return null;\n }\n}\nclass BlockWidgetView extends ContentView {\n constructor(widget, length, deco) {\n super();\n this.widget = widget;\n this.length = length;\n this.deco = deco;\n this.breakAfter = 0;\n this.prevWidget = null;\n }\n merge(from, to, source, _takeDeco, openStart, openEnd) {\n if (source && (!(source instanceof BlockWidgetView) || !this.widget.compare(source.widget) ||\n from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))\n return false;\n this.length = from + (source ? source.length : 0) + (this.length - to);\n return true;\n }\n domAtPos(pos) {\n return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length);\n }\n split(at) {\n let len = this.length - at;\n this.length = at;\n let end = new BlockWidgetView(this.widget, len, this.deco);\n end.breakAfter = this.breakAfter;\n return end;\n }\n get children() { return noChildren; }\n sync(view) {\n if (!this.dom || !this.widget.updateDOM(this.dom, view)) {\n if (this.dom && this.prevWidget)\n this.prevWidget.destroy(this.dom);\n this.prevWidget = null;\n this.setDOM(this.widget.toDOM(view));\n this.dom.contentEditable = \"false\";\n }\n }\n get overrideDOMText() {\n return this.parent ? this.parent.view.state.doc.slice(this.posAtStart, this.posAtEnd) : Text.empty;\n }\n domBoundsAround() { return null; }\n become(other) {\n if (other instanceof BlockWidgetView &&\n other.widget.constructor == this.widget.constructor) {\n if (!other.widget.compare(this.widget))\n this.markDirty(true);\n if (this.dom && !this.prevWidget)\n this.prevWidget = this.widget;\n this.widget = other.widget;\n this.length = other.length;\n this.deco = other.deco;\n this.breakAfter = other.breakAfter;\n return true;\n }\n return false;\n }\n ignoreMutation() { return true; }\n ignoreEvent(event) { return this.widget.ignoreEvent(event); }\n get isEditable() { return false; }\n get isWidget() { return true; }\n coordsAt(pos, side) {\n return this.widget.coordsAt(this.dom, pos, side);\n }\n destroy() {\n super.destroy();\n if (this.dom)\n this.widget.destroy(this.dom);\n }\n covers(side) {\n let { startSide, endSide } = this.deco;\n return startSide == endSide ? false : side < 0 ? startSide < 0 : endSide > 0;\n }\n}\n\n/**\nWidgets added to the content are described by subclasses of this\nclass. Using a description object like that makes it possible to\ndelay creating of the DOM structure for a widget until it is\nneeded, and to avoid redrawing widgets even if the decorations\nthat define them are recreated.\n*/\nclass WidgetType {\n /**\n Compare this instance to another instance of the same type.\n (TypeScript can't express this, but only instances of the same\n specific class will be passed to this method.) This is used to\n avoid redrawing widgets when they are replaced by a new\n decoration of the same type. The default implementation just\n returns `false`, which will cause new instances of the widget to\n always be redrawn.\n */\n eq(widget) { return false; }\n /**\n Update a DOM element created by a widget of the same type (but\n different, non-`eq` content) to reflect this widget. May return\n true to indicate that it could update, false to indicate it\n couldn't (in which case the widget will be redrawn). The default\n implementation just returns false.\n */\n updateDOM(dom, view) { return false; }\n /**\n @internal\n */\n compare(other) {\n return this == other || this.constructor == other.constructor && this.eq(other);\n }\n /**\n The estimated height this widget will have, to be used when\n estimating the height of content that hasn't been drawn. May\n return -1 to indicate you don't know. The default implementation\n returns -1.\n */\n get estimatedHeight() { return -1; }\n /**\n For inline widgets that are displayed inline (as opposed to\n `inline-block`) and introduce line breaks (through `
    ` tags\n or textual newlines), this must indicate the amount of line\n breaks they introduce. Defaults to 0.\n */\n get lineBreaks() { return 0; }\n /**\n Can be used to configure which kinds of events inside the widget\n should be ignored by the editor. The default is to ignore all\n events.\n */\n ignoreEvent(event) { return true; }\n /**\n Override the way screen coordinates for positions at/in the\n widget are found. `pos` will be the offset into the widget, and\n `side` the side of the position that is being queried—less than\n zero for before, greater than zero for after, and zero for\n directly at that position.\n */\n coordsAt(dom, pos, side) { return null; }\n /**\n @internal\n */\n get isHidden() { return false; }\n /**\n This is called when the an instance of the widget is removed\n from the editor view.\n */\n destroy(dom) { }\n}\n/**\nThe different types of blocks that can occur in an editor view.\n*/\nvar BlockType = /*@__PURE__*/(function (BlockType) {\n /**\n A line of text.\n */\n BlockType[BlockType[\"Text\"] = 0] = \"Text\";\n /**\n A block widget associated with the position after it.\n */\n BlockType[BlockType[\"WidgetBefore\"] = 1] = \"WidgetBefore\";\n /**\n A block widget associated with the position before it.\n */\n BlockType[BlockType[\"WidgetAfter\"] = 2] = \"WidgetAfter\";\n /**\n A block widget [replacing](https://codemirror.net/6/docs/ref/#view.Decoration^replace) a range of content.\n */\n BlockType[BlockType[\"WidgetRange\"] = 3] = \"WidgetRange\";\nreturn BlockType})(BlockType || (BlockType = {}));\n/**\nA decoration provides information on how to draw or style a piece\nof content. You'll usually use it wrapped in a\n[`Range`](https://codemirror.net/6/docs/ref/#state.Range), which adds a start and end position.\n@nonabstract\n*/\nclass Decoration extends RangeValue {\n constructor(\n /**\n @internal\n */\n startSide, \n /**\n @internal\n */\n endSide, \n /**\n @internal\n */\n widget, \n /**\n The config object used to create this decoration. You can\n include additional properties in there to store metadata about\n your decoration.\n */\n spec) {\n super();\n this.startSide = startSide;\n this.endSide = endSide;\n this.widget = widget;\n this.spec = spec;\n }\n /**\n @internal\n */\n get heightRelevant() { return false; }\n /**\n Create a mark decoration, which influences the styling of the\n content in its range. Nested mark decorations will cause nested\n DOM elements to be created. Nesting order is determined by\n precedence of the [facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), with\n the higher-precedence decorations creating the inner DOM nodes.\n Such elements are split on line boundaries and on the boundaries\n of lower-precedence decorations.\n */\n static mark(spec) {\n return new MarkDecoration(spec);\n }\n /**\n Create a widget decoration, which displays a DOM element at the\n given position.\n */\n static widget(spec) {\n let side = Math.max(-10000, Math.min(10000, spec.side || 0)), block = !!spec.block;\n side += (block && !spec.inlineOrder)\n ? (side > 0 ? 300000000 /* Side.BlockAfter */ : -400000000 /* Side.BlockBefore */)\n : (side > 0 ? 100000000 /* Side.InlineAfter */ : -100000000 /* Side.InlineBefore */);\n return new PointDecoration(spec, side, side, block, spec.widget || null, false);\n }\n /**\n Create a replace decoration which replaces the given range with\n a widget, or simply hides it.\n */\n static replace(spec) {\n let block = !!spec.block, startSide, endSide;\n if (spec.isBlockGap) {\n startSide = -500000000 /* Side.GapStart */;\n endSide = 400000000 /* Side.GapEnd */;\n }\n else {\n let { start, end } = getInclusive(spec, block);\n startSide = (start ? (block ? -300000000 /* Side.BlockIncStart */ : -1 /* Side.InlineIncStart */) : 500000000 /* Side.NonIncStart */) - 1;\n endSide = (end ? (block ? 200000000 /* Side.BlockIncEnd */ : 1 /* Side.InlineIncEnd */) : -600000000 /* Side.NonIncEnd */) + 1;\n }\n return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true);\n }\n /**\n Create a line decoration, which can add DOM attributes to the\n line starting at the given position.\n */\n static line(spec) {\n return new LineDecoration(spec);\n }\n /**\n Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given\n decorated range or ranges. If the ranges aren't already sorted,\n pass `true` for `sort` to make the library sort them for you.\n */\n static set(of, sort = false) {\n return RangeSet.of(of, sort);\n }\n /**\n @internal\n */\n hasHeight() { return this.widget ? this.widget.estimatedHeight > -1 : false; }\n}\n/**\nThe empty set of decorations.\n*/\nDecoration.none = RangeSet.empty;\nclass MarkDecoration extends Decoration {\n constructor(spec) {\n let { start, end } = getInclusive(spec);\n super(start ? -1 /* Side.InlineIncStart */ : 500000000 /* Side.NonIncStart */, end ? 1 /* Side.InlineIncEnd */ : -600000000 /* Side.NonIncEnd */, null, spec);\n this.tagName = spec.tagName || \"span\";\n this.class = spec.class || \"\";\n this.attrs = spec.attributes || null;\n }\n eq(other) {\n var _a, _b;\n return this == other ||\n other instanceof MarkDecoration &&\n this.tagName == other.tagName &&\n (this.class || ((_a = this.attrs) === null || _a === void 0 ? void 0 : _a.class)) == (other.class || ((_b = other.attrs) === null || _b === void 0 ? void 0 : _b.class)) &&\n attrsEq(this.attrs, other.attrs, \"class\");\n }\n range(from, to = from) {\n if (from >= to)\n throw new RangeError(\"Mark decorations may not be empty\");\n return super.range(from, to);\n }\n}\nMarkDecoration.prototype.point = false;\nclass LineDecoration extends Decoration {\n constructor(spec) {\n super(-200000000 /* Side.Line */, -200000000 /* Side.Line */, null, spec);\n }\n eq(other) {\n return other instanceof LineDecoration &&\n this.spec.class == other.spec.class &&\n attrsEq(this.spec.attributes, other.spec.attributes);\n }\n range(from, to = from) {\n if (to != from)\n throw new RangeError(\"Line decoration ranges must be zero-length\");\n return super.range(from, to);\n }\n}\nLineDecoration.prototype.mapMode = MapMode.TrackBefore;\nLineDecoration.prototype.point = true;\nclass PointDecoration extends Decoration {\n constructor(spec, startSide, endSide, block, widget, isReplace) {\n super(startSide, endSide, widget, spec);\n this.block = block;\n this.isReplace = isReplace;\n this.mapMode = !block ? MapMode.TrackDel : startSide <= 0 ? MapMode.TrackBefore : MapMode.TrackAfter;\n }\n // Only relevant when this.block == true\n get type() {\n return this.startSide != this.endSide ? BlockType.WidgetRange\n : this.startSide <= 0 ? BlockType.WidgetBefore : BlockType.WidgetAfter;\n }\n get heightRelevant() {\n return this.block || !!this.widget && (this.widget.estimatedHeight >= 5 || this.widget.lineBreaks > 0);\n }\n eq(other) {\n return other instanceof PointDecoration &&\n widgetsEq(this.widget, other.widget) &&\n this.block == other.block &&\n this.startSide == other.startSide && this.endSide == other.endSide;\n }\n range(from, to = from) {\n if (this.isReplace && (from > to || (from == to && this.startSide > 0 && this.endSide <= 0)))\n throw new RangeError(\"Invalid range for replacement decoration\");\n if (!this.isReplace && to != from)\n throw new RangeError(\"Widget decorations can only have zero-length ranges\");\n return super.range(from, to);\n }\n}\nPointDecoration.prototype.point = true;\nfunction getInclusive(spec, block = false) {\n let { inclusiveStart: start, inclusiveEnd: end } = spec;\n if (start == null)\n start = spec.inclusive;\n if (end == null)\n end = spec.inclusive;\n return { start: start !== null && start !== void 0 ? start : block, end: end !== null && end !== void 0 ? end : block };\n}\nfunction widgetsEq(a, b) {\n return a == b || !!(a && b && a.compare(b));\n}\nfunction addRange(from, to, ranges, margin = 0) {\n let last = ranges.length - 1;\n if (last >= 0 && ranges[last] + margin >= from)\n ranges[last] = Math.max(ranges[last], to);\n else\n ranges.push(from, to);\n}\n\nclass ContentBuilder {\n constructor(doc, pos, end, disallowBlockEffectsFor) {\n this.doc = doc;\n this.pos = pos;\n this.end = end;\n this.disallowBlockEffectsFor = disallowBlockEffectsFor;\n this.content = [];\n this.curLine = null;\n this.breakAtStart = 0;\n this.pendingBuffer = 0 /* Buf.No */;\n this.bufferMarks = [];\n // Set to false directly after a widget that covers the position after it\n this.atCursorPos = true;\n this.openStart = -1;\n this.openEnd = -1;\n this.text = \"\";\n this.textOff = 0;\n this.cursor = doc.iter();\n this.skip = pos;\n }\n posCovered() {\n if (this.content.length == 0)\n return !this.breakAtStart && this.doc.lineAt(this.pos).from != this.pos;\n let last = this.content[this.content.length - 1];\n return !(last.breakAfter || last instanceof BlockWidgetView && last.deco.endSide < 0);\n }\n getLine() {\n if (!this.curLine) {\n this.content.push(this.curLine = new LineView);\n this.atCursorPos = true;\n }\n return this.curLine;\n }\n flushBuffer(active = this.bufferMarks) {\n if (this.pendingBuffer) {\n this.curLine.append(wrapMarks(new WidgetBufferView(-1), active), active.length);\n this.pendingBuffer = 0 /* Buf.No */;\n }\n }\n addBlockWidget(view) {\n this.flushBuffer();\n this.curLine = null;\n this.content.push(view);\n }\n finish(openEnd) {\n if (this.pendingBuffer && openEnd <= this.bufferMarks.length)\n this.flushBuffer();\n else\n this.pendingBuffer = 0 /* Buf.No */;\n if (!this.posCovered() &&\n !(openEnd && this.content.length && this.content[this.content.length - 1] instanceof BlockWidgetView))\n this.getLine();\n }\n buildText(length, active, openStart) {\n while (length > 0) {\n if (this.textOff == this.text.length) {\n let { value, lineBreak, done } = this.cursor.next(this.skip);\n this.skip = 0;\n if (done)\n throw new Error(\"Ran out of text content when drawing inline views\");\n if (lineBreak) {\n if (!this.posCovered())\n this.getLine();\n if (this.content.length)\n this.content[this.content.length - 1].breakAfter = 1;\n else\n this.breakAtStart = 1;\n this.flushBuffer();\n this.curLine = null;\n this.atCursorPos = true;\n length--;\n continue;\n }\n else {\n this.text = value;\n this.textOff = 0;\n }\n }\n let take = Math.min(this.text.length - this.textOff, length, 512 /* T.Chunk */);\n this.flushBuffer(active.slice(active.length - openStart));\n this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff, this.textOff + take)), active), openStart);\n this.atCursorPos = true;\n this.textOff += take;\n length -= take;\n openStart = 0;\n }\n }\n span(from, to, active, openStart) {\n this.buildText(to - from, active, openStart);\n this.pos = to;\n if (this.openStart < 0)\n this.openStart = openStart;\n }\n point(from, to, deco, active, openStart, index) {\n if (this.disallowBlockEffectsFor[index] && deco instanceof PointDecoration) {\n if (deco.block)\n throw new RangeError(\"Block decorations may not be specified via plugins\");\n if (to > this.doc.lineAt(this.pos).to)\n throw new RangeError(\"Decorations that replace line breaks may not be specified via plugins\");\n }\n let len = to - from;\n if (deco instanceof PointDecoration) {\n if (deco.block) {\n if (deco.startSide > 0 && !this.posCovered())\n this.getLine();\n this.addBlockWidget(new BlockWidgetView(deco.widget || new NullWidget(\"div\"), len, deco));\n }\n else {\n let view = WidgetView.create(deco.widget || new NullWidget(\"span\"), len, len ? 0 : deco.startSide);\n let cursorBefore = this.atCursorPos && !view.isEditable && openStart <= active.length &&\n (from < to || deco.startSide > 0);\n let cursorAfter = !view.isEditable && (from < to || openStart > active.length || deco.startSide <= 0);\n let line = this.getLine();\n if (this.pendingBuffer == 2 /* Buf.IfCursor */ && !cursorBefore && !view.isEditable)\n this.pendingBuffer = 0 /* Buf.No */;\n this.flushBuffer(active);\n if (cursorBefore) {\n line.append(wrapMarks(new WidgetBufferView(1), active), openStart);\n openStart = active.length + Math.max(0, openStart - active.length);\n }\n line.append(wrapMarks(view, active), openStart);\n this.atCursorPos = cursorAfter;\n this.pendingBuffer = !cursorAfter ? 0 /* Buf.No */ : from < to || openStart > active.length ? 1 /* Buf.Yes */ : 2 /* Buf.IfCursor */;\n if (this.pendingBuffer)\n this.bufferMarks = active.slice();\n }\n }\n else if (this.doc.lineAt(this.pos).from == this.pos) { // Line decoration\n this.getLine().addLineDeco(deco);\n }\n if (len) {\n // Advance the iterator past the replaced content\n if (this.textOff + len <= this.text.length) {\n this.textOff += len;\n }\n else {\n this.skip += len - (this.text.length - this.textOff);\n this.text = \"\";\n this.textOff = 0;\n }\n this.pos = to;\n }\n if (this.openStart < 0)\n this.openStart = openStart;\n }\n static build(text, from, to, decorations, dynamicDecorationMap) {\n let builder = new ContentBuilder(text, from, to, dynamicDecorationMap);\n builder.openEnd = RangeSet.spans(decorations, from, to, builder);\n if (builder.openStart < 0)\n builder.openStart = builder.openEnd;\n builder.finish(builder.openEnd);\n return builder;\n }\n}\nfunction wrapMarks(view, active) {\n for (let mark of active)\n view = new MarkView(mark, [view], view.length);\n return view;\n}\nclass NullWidget extends WidgetType {\n constructor(tag) {\n super();\n this.tag = tag;\n }\n eq(other) { return other.tag == this.tag; }\n toDOM() { return document.createElement(this.tag); }\n updateDOM(elt) { return elt.nodeName.toLowerCase() == this.tag; }\n get isHidden() { return true; }\n}\n\nconst clickAddsSelectionRange = /*@__PURE__*/Facet.define();\nconst dragMovesSelection$1 = /*@__PURE__*/Facet.define();\nconst mouseSelectionStyle = /*@__PURE__*/Facet.define();\nconst exceptionSink = /*@__PURE__*/Facet.define();\nconst updateListener = /*@__PURE__*/Facet.define();\nconst inputHandler = /*@__PURE__*/Facet.define();\nconst focusChangeEffect = /*@__PURE__*/Facet.define();\nconst perLineTextDirection = /*@__PURE__*/Facet.define({\n combine: values => values.some(x => x)\n});\nconst nativeSelectionHidden = /*@__PURE__*/Facet.define({\n combine: values => values.some(x => x)\n});\nclass ScrollTarget {\n constructor(range, y = \"nearest\", x = \"nearest\", yMargin = 5, xMargin = 5, \n // This data structure is abused to also store precise scroll\n // snapshots, instead of a `scrollIntoView` request. When this\n // flag is `true`, `range` points at a position in the reference\n // line, `yMargin` holds the difference between the top of that\n // line and the top of the editor, and `xMargin` holds the\n // editor's `scrollLeft`.\n isSnapshot = false) {\n this.range = range;\n this.y = y;\n this.x = x;\n this.yMargin = yMargin;\n this.xMargin = xMargin;\n this.isSnapshot = isSnapshot;\n }\n map(changes) {\n return changes.empty ? this :\n new ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);\n }\n clip(state) {\n return this.range.to <= state.doc.length ? this :\n new ScrollTarget(EditorSelection.cursor(state.doc.length), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);\n }\n}\nconst scrollIntoView = /*@__PURE__*/StateEffect.define({ map: (t, ch) => t.map(ch) });\n/**\nLog or report an unhandled exception in client code. Should\nprobably only be used by extension code that allows client code to\nprovide functions, and calls those functions in a context where an\nexception can't be propagated to calling code in a reasonable way\n(for example when in an event handler).\n\nEither calls a handler registered with\n[`EditorView.exceptionSink`](https://codemirror.net/6/docs/ref/#view.EditorView^exceptionSink),\n`window.onerror`, if defined, or `console.error` (in which case\nit'll pass `context`, when given, as first argument).\n*/\nfunction logException(state, exception, context) {\n let handler = state.facet(exceptionSink);\n if (handler.length)\n handler[0](exception);\n else if (window.onerror)\n window.onerror(String(exception), context, undefined, undefined, exception);\n else if (context)\n console.error(context + \":\", exception);\n else\n console.error(exception);\n}\nconst editable = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : true });\nlet nextPluginID = 0;\nconst viewPlugin = /*@__PURE__*/Facet.define();\n/**\nView plugins associate stateful values with a view. They can\ninfluence the way the content is drawn, and are notified of things\nthat happen in the view.\n*/\nclass ViewPlugin {\n constructor(\n /**\n @internal\n */\n id, \n /**\n @internal\n */\n create, \n /**\n @internal\n */\n domEventHandlers, \n /**\n @internal\n */\n domEventObservers, buildExtensions) {\n this.id = id;\n this.create = create;\n this.domEventHandlers = domEventHandlers;\n this.domEventObservers = domEventObservers;\n this.extension = buildExtensions(this);\n }\n /**\n Define a plugin from a constructor function that creates the\n plugin's value, given an editor view.\n */\n static define(create, spec) {\n const { eventHandlers, eventObservers, provide, decorations: deco } = spec || {};\n return new ViewPlugin(nextPluginID++, create, eventHandlers, eventObservers, plugin => {\n let ext = [viewPlugin.of(plugin)];\n if (deco)\n ext.push(decorations.of(view => {\n let pluginInst = view.plugin(plugin);\n return pluginInst ? deco(pluginInst) : Decoration.none;\n }));\n if (provide)\n ext.push(provide(plugin));\n return ext;\n });\n }\n /**\n Create a plugin for a class whose constructor takes a single\n editor view as argument.\n */\n static fromClass(cls, spec) {\n return ViewPlugin.define(view => new cls(view), spec);\n }\n}\nclass PluginInstance {\n constructor(spec) {\n this.spec = spec;\n // When starting an update, all plugins have this field set to the\n // update object, indicating they need to be updated. When finished\n // updating, it is set to `false`. Retrieving a plugin that needs to\n // be updated with `view.plugin` forces an eager update.\n this.mustUpdate = null;\n // This is null when the plugin is initially created, but\n // initialized on the first update.\n this.value = null;\n }\n update(view) {\n if (!this.value) {\n if (this.spec) {\n try {\n this.value = this.spec.create(view);\n }\n catch (e) {\n logException(view.state, e, \"CodeMirror plugin crashed\");\n this.deactivate();\n }\n }\n }\n else if (this.mustUpdate) {\n let update = this.mustUpdate;\n this.mustUpdate = null;\n if (this.value.update) {\n try {\n this.value.update(update);\n }\n catch (e) {\n logException(update.state, e, \"CodeMirror plugin crashed\");\n if (this.value.destroy)\n try {\n this.value.destroy();\n }\n catch (_) { }\n this.deactivate();\n }\n }\n }\n return this;\n }\n destroy(view) {\n var _a;\n if ((_a = this.value) === null || _a === void 0 ? void 0 : _a.destroy) {\n try {\n this.value.destroy();\n }\n catch (e) {\n logException(view.state, e, \"CodeMirror plugin crashed\");\n }\n }\n }\n deactivate() {\n this.spec = this.value = null;\n }\n}\nconst editorAttributes = /*@__PURE__*/Facet.define();\nconst contentAttributes = /*@__PURE__*/Facet.define();\n// Provide decorations\nconst decorations = /*@__PURE__*/Facet.define();\nconst atomicRanges = /*@__PURE__*/Facet.define();\nconst bidiIsolatedRanges = /*@__PURE__*/Facet.define();\nfunction getIsolatedRanges(view, from, to) {\n let isolates = view.state.facet(bidiIsolatedRanges);\n if (!isolates.length)\n return isolates;\n let sets = isolates.map(i => i instanceof Function ? i(view) : i);\n let result = [];\n RangeSet.spans(sets, from, to, {\n point() { },\n span(from, to, active, open) {\n let level = result;\n for (let i = active.length - 1; i >= 0; i--, open--) {\n let iso = active[i].spec.bidiIsolate, update;\n if (iso == null)\n continue;\n if (open > 0 && level.length &&\n (update = level[level.length - 1]).to == from && update.direction == iso) {\n update.to = to;\n level = update.inner;\n }\n else {\n let add = { from, to, direction: iso, inner: [] };\n level.push(add);\n level = add.inner;\n }\n }\n }\n });\n return result;\n}\nconst scrollMargins = /*@__PURE__*/Facet.define();\nfunction getScrollMargins(view) {\n let left = 0, right = 0, top = 0, bottom = 0;\n for (let source of view.state.facet(scrollMargins)) {\n let m = source(view);\n if (m) {\n if (m.left != null)\n left = Math.max(left, m.left);\n if (m.right != null)\n right = Math.max(right, m.right);\n if (m.top != null)\n top = Math.max(top, m.top);\n if (m.bottom != null)\n bottom = Math.max(bottom, m.bottom);\n }\n }\n return { left, right, top, bottom };\n}\nconst styleModule = /*@__PURE__*/Facet.define();\nclass ChangedRange {\n constructor(fromA, toA, fromB, toB) {\n this.fromA = fromA;\n this.toA = toA;\n this.fromB = fromB;\n this.toB = toB;\n }\n join(other) {\n return new ChangedRange(Math.min(this.fromA, other.fromA), Math.max(this.toA, other.toA), Math.min(this.fromB, other.fromB), Math.max(this.toB, other.toB));\n }\n addToSet(set) {\n let i = set.length, me = this;\n for (; i > 0; i--) {\n let range = set[i - 1];\n if (range.fromA > me.toA)\n continue;\n if (range.toA < me.fromA)\n break;\n me = me.join(range);\n set.splice(i - 1, 1);\n }\n set.splice(i, 0, me);\n return set;\n }\n static extendWithRanges(diff, ranges) {\n if (ranges.length == 0)\n return diff;\n let result = [];\n for (let dI = 0, rI = 0, posA = 0, posB = 0;; dI++) {\n let next = dI == diff.length ? null : diff[dI], off = posA - posB;\n let end = next ? next.fromB : 1e9;\n while (rI < ranges.length && ranges[rI] < end) {\n let from = ranges[rI], to = ranges[rI + 1];\n let fromB = Math.max(posB, from), toB = Math.min(end, to);\n if (fromB <= toB)\n new ChangedRange(fromB + off, toB + off, fromB, toB).addToSet(result);\n if (to > end)\n break;\n else\n rI += 2;\n }\n if (!next)\n return result;\n new ChangedRange(next.fromA, next.toA, next.fromB, next.toB).addToSet(result);\n posA = next.toA;\n posB = next.toB;\n }\n }\n}\n/**\nView [plugins](https://codemirror.net/6/docs/ref/#view.ViewPlugin) are given instances of this\nclass, which describe what happened, whenever the view is updated.\n*/\nclass ViewUpdate {\n constructor(\n /**\n The editor view that the update is associated with.\n */\n view, \n /**\n The new editor state.\n */\n state, \n /**\n The transactions involved in the update. May be empty.\n */\n transactions) {\n this.view = view;\n this.state = state;\n this.transactions = transactions;\n /**\n @internal\n */\n this.flags = 0;\n this.startState = view.state;\n this.changes = ChangeSet.empty(this.startState.doc.length);\n for (let tr of transactions)\n this.changes = this.changes.compose(tr.changes);\n let changedRanges = [];\n this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB)));\n this.changedRanges = changedRanges;\n }\n /**\n @internal\n */\n static create(view, state, transactions) {\n return new ViewUpdate(view, state, transactions);\n }\n /**\n Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or\n [visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this\n update.\n */\n get viewportChanged() {\n return (this.flags & 4 /* UpdateFlag.Viewport */) > 0;\n }\n /**\n Indicates whether the height of a block element in the editor\n changed in this update.\n */\n get heightChanged() {\n return (this.flags & 2 /* UpdateFlag.Height */) > 0;\n }\n /**\n Returns true when the document was modified or the size of the\n editor, or elements within the editor, changed.\n */\n get geometryChanged() {\n return this.docChanged || (this.flags & (8 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */)) > 0;\n }\n /**\n True when this update indicates a focus change.\n */\n get focusChanged() {\n return (this.flags & 1 /* UpdateFlag.Focus */) > 0;\n }\n /**\n Whether the document changed in this update.\n */\n get docChanged() {\n return !this.changes.empty;\n }\n /**\n Whether the selection was explicitly set in this update.\n */\n get selectionSet() {\n return this.transactions.some(tr => tr.selection);\n }\n /**\n @internal\n */\n get empty() { return this.flags == 0 && this.transactions.length == 0; }\n}\n\n/**\nUsed to indicate [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).\n*/\nvar Direction = /*@__PURE__*/(function (Direction) {\n // (These are chosen to match the base levels, in bidi algorithm\n // terms, of spans in that direction.)\n /**\n Left-to-right.\n */\n Direction[Direction[\"LTR\"] = 0] = \"LTR\";\n /**\n Right-to-left.\n */\n Direction[Direction[\"RTL\"] = 1] = \"RTL\";\nreturn Direction})(Direction || (Direction = {}));\nconst LTR = Direction.LTR, RTL = Direction.RTL;\n// Decode a string with each type encoded as log2(type)\nfunction dec(str) {\n let result = [];\n for (let i = 0; i < str.length; i++)\n result.push(1 << +str[i]);\n return result;\n}\n// Character types for codepoints 0 to 0xf8\nconst LowTypes = /*@__PURE__*/dec(\"88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008\");\n// Character types for codepoints 0x600 to 0x6f9\nconst ArabicTypes = /*@__PURE__*/dec(\"4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333\");\nconst Brackets = /*@__PURE__*/Object.create(null), BracketStack = [];\n// There's a lot more in\n// https://www.unicode.org/Public/UCD/latest/ucd/BidiBrackets.txt,\n// which are left out to keep code size down.\nfor (let p of [\"()\", \"[]\", \"{}\"]) {\n let l = /*@__PURE__*/p.charCodeAt(0), r = /*@__PURE__*/p.charCodeAt(1);\n Brackets[l] = r;\n Brackets[r] = -l;\n}\nfunction charType(ch) {\n return ch <= 0xf7 ? LowTypes[ch] :\n 0x590 <= ch && ch <= 0x5f4 ? 2 /* T.R */ :\n 0x600 <= ch && ch <= 0x6f9 ? ArabicTypes[ch - 0x600] :\n 0x6ee <= ch && ch <= 0x8ac ? 4 /* T.AL */ :\n 0x2000 <= ch && ch <= 0x200b ? 256 /* T.NI */ :\n 0xfb50 <= ch && ch <= 0xfdff ? 4 /* T.AL */ :\n ch == 0x200c ? 256 /* T.NI */ : 1 /* T.L */;\n}\nconst BidiRE = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac\\ufb50-\\ufdff]/;\n/**\nRepresents a contiguous range of text that has a single direction\n(as in left-to-right or right-to-left).\n*/\nclass BidiSpan {\n /**\n The direction of this span.\n */\n get dir() { return this.level % 2 ? RTL : LTR; }\n /**\n @internal\n */\n constructor(\n /**\n The start of the span (relative to the start of the line).\n */\n from, \n /**\n The end of the span.\n */\n to, \n /**\n The [\"bidi\n level\"](https://unicode.org/reports/tr9/#Basic_Display_Algorithm)\n of the span (in this context, 0 means\n left-to-right, 1 means right-to-left, 2 means left-to-right\n number inside right-to-left text).\n */\n level) {\n this.from = from;\n this.to = to;\n this.level = level;\n }\n /**\n @internal\n */\n side(end, dir) { return (this.dir == dir) == end ? this.to : this.from; }\n /**\n @internal\n */\n static find(order, index, level, assoc) {\n let maybe = -1;\n for (let i = 0; i < order.length; i++) {\n let span = order[i];\n if (span.from <= index && span.to >= index) {\n if (span.level == level)\n return i;\n // When multiple spans match, if assoc != 0, take the one that\n // covers that side, otherwise take the one with the minimum\n // level.\n if (maybe < 0 || (assoc != 0 ? (assoc < 0 ? span.from < index : span.to > index) : order[maybe].level > span.level))\n maybe = i;\n }\n }\n if (maybe < 0)\n throw new RangeError(\"Index out of range\");\n return maybe;\n }\n}\nfunction isolatesEq(a, b) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++) {\n let iA = a[i], iB = b[i];\n if (iA.from != iB.from || iA.to != iB.to || iA.direction != iB.direction || !isolatesEq(iA.inner, iB.inner))\n return false;\n }\n return true;\n}\n// Reused array of character types\nconst types = [];\n// Fill in the character types (in `types`) from `from` to `to` and\n// apply W normalization rules.\nfunction computeCharTypes(line, rFrom, rTo, isolates, outerType) {\n for (let iI = 0; iI <= isolates.length; iI++) {\n let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;\n let prevType = iI ? 256 /* T.NI */ : outerType;\n // W1. Examine each non-spacing mark (NSM) in the level run, and\n // change the type of the NSM to the type of the previous\n // character. If the NSM is at the start of the level run, it will\n // get the type of sor.\n // W2. Search backwards from each instance of a European number\n // until the first strong type (R, L, AL, or sor) is found. If an\n // AL is found, change the type of the European number to Arabic\n // number.\n // W3. Change all ALs to R.\n // (Left after this: L, R, EN, AN, ET, CS, NI)\n for (let i = from, prev = prevType, prevStrong = prevType; i < to; i++) {\n let type = charType(line.charCodeAt(i));\n if (type == 512 /* T.NSM */)\n type = prev;\n else if (type == 8 /* T.EN */ && prevStrong == 4 /* T.AL */)\n type = 16 /* T.AN */;\n types[i] = type == 4 /* T.AL */ ? 2 /* T.R */ : type;\n if (type & 7 /* T.Strong */)\n prevStrong = type;\n prev = type;\n }\n // W5. A sequence of European terminators adjacent to European\n // numbers changes to all European numbers.\n // W6. Otherwise, separators and terminators change to Other\n // Neutral.\n // W7. Search backwards from each instance of a European number\n // until the first strong type (R, L, or sor) is found. If an L is\n // found, then change the type of the European number to L.\n // (Left after this: L, R, EN+AN, NI)\n for (let i = from, prev = prevType, prevStrong = prevType; i < to; i++) {\n let type = types[i];\n if (type == 128 /* T.CS */) {\n if (i < to - 1 && prev == types[i + 1] && (prev & 24 /* T.Num */))\n type = types[i] = prev;\n else\n types[i] = 256 /* T.NI */;\n }\n else if (type == 64 /* T.ET */) {\n let end = i + 1;\n while (end < to && types[end] == 64 /* T.ET */)\n end++;\n let replace = (i && prev == 8 /* T.EN */) || (end < rTo && types[end] == 8 /* T.EN */) ? (prevStrong == 1 /* T.L */ ? 1 /* T.L */ : 8 /* T.EN */) : 256 /* T.NI */;\n for (let j = i; j < end; j++)\n types[j] = replace;\n i = end - 1;\n }\n else if (type == 8 /* T.EN */ && prevStrong == 1 /* T.L */) {\n types[i] = 1 /* T.L */;\n }\n prev = type;\n if (type & 7 /* T.Strong */)\n prevStrong = type;\n }\n }\n}\n// Process brackets throughout a run sequence.\nfunction processBracketPairs(line, rFrom, rTo, isolates, outerType) {\n let oppositeType = outerType == 1 /* T.L */ ? 2 /* T.R */ : 1 /* T.L */;\n for (let iI = 0, sI = 0, context = 0; iI <= isolates.length; iI++) {\n let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;\n // N0. Process bracket pairs in an isolating run sequence\n // sequentially in the logical order of the text positions of the\n // opening paired brackets using the logic given below. Within this\n // scope, bidirectional types EN and AN are treated as R.\n for (let i = from, ch, br, type; i < to; i++) {\n // Keeps [startIndex, type, strongSeen] triples for each open\n // bracket on BracketStack.\n if (br = Brackets[ch = line.charCodeAt(i)]) {\n if (br < 0) { // Closing bracket\n for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {\n if (BracketStack[sJ + 1] == -br) {\n let flags = BracketStack[sJ + 2];\n let type = (flags & 2 /* Bracketed.EmbedInside */) ? outerType :\n !(flags & 4 /* Bracketed.OppositeInside */) ? 0 :\n (flags & 1 /* Bracketed.OppositeBefore */) ? oppositeType : outerType;\n if (type)\n types[i] = types[BracketStack[sJ]] = type;\n sI = sJ;\n break;\n }\n }\n }\n else if (BracketStack.length == 189 /* Bracketed.MaxDepth */) {\n break;\n }\n else {\n BracketStack[sI++] = i;\n BracketStack[sI++] = ch;\n BracketStack[sI++] = context;\n }\n }\n else if ((type = types[i]) == 2 /* T.R */ || type == 1 /* T.L */) {\n let embed = type == outerType;\n context = embed ? 0 : 1 /* Bracketed.OppositeBefore */;\n for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {\n let cur = BracketStack[sJ + 2];\n if (cur & 2 /* Bracketed.EmbedInside */)\n break;\n if (embed) {\n BracketStack[sJ + 2] |= 2 /* Bracketed.EmbedInside */;\n }\n else {\n if (cur & 4 /* Bracketed.OppositeInside */)\n break;\n BracketStack[sJ + 2] |= 4 /* Bracketed.OppositeInside */;\n }\n }\n }\n }\n }\n}\nfunction processNeutrals(rFrom, rTo, isolates, outerType) {\n for (let iI = 0, prev = outerType; iI <= isolates.length; iI++) {\n let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;\n // N1. A sequence of neutrals takes the direction of the\n // surrounding strong text if the text on both sides has the same\n // direction. European and Arabic numbers act as if they were R in\n // terms of their influence on neutrals. Start-of-level-run (sor)\n // and end-of-level-run (eor) are used at level run boundaries.\n // N2. Any remaining neutrals take the embedding direction.\n // (Left after this: L, R, EN+AN)\n for (let i = from; i < to;) {\n let type = types[i];\n if (type == 256 /* T.NI */) {\n let end = i + 1;\n for (;;) {\n if (end == to) {\n if (iI == isolates.length)\n break;\n end = isolates[iI++].to;\n to = iI < isolates.length ? isolates[iI].from : rTo;\n }\n else if (types[end] == 256 /* T.NI */) {\n end++;\n }\n else {\n break;\n }\n }\n let beforeL = prev == 1 /* T.L */;\n let afterL = (end < rTo ? types[end] : outerType) == 1 /* T.L */;\n let replace = beforeL == afterL ? (beforeL ? 1 /* T.L */ : 2 /* T.R */) : outerType;\n for (let j = end, jI = iI, fromJ = jI ? isolates[jI - 1].to : rFrom; j > i;) {\n if (j == fromJ) {\n j = isolates[--jI].from;\n fromJ = jI ? isolates[jI - 1].to : rFrom;\n }\n types[--j] = replace;\n }\n i = end;\n }\n else {\n prev = type;\n i++;\n }\n }\n }\n}\n// Find the contiguous ranges of character types in a given range, and\n// emit spans for them. Flip the order of the spans as appropriate\n// based on the level, and call through to compute the spans for\n// isolates at the proper point.\nfunction emitSpans(line, from, to, level, baseLevel, isolates, order) {\n let ourType = level % 2 ? 2 /* T.R */ : 1 /* T.L */;\n if ((level % 2) == (baseLevel % 2)) { // Same dir as base direction, don't flip\n for (let iCh = from, iI = 0; iCh < to;) {\n // Scan a section of characters in direction ourType, unless\n // there's another type of char right after iCh, in which case\n // we scan a section of other characters (which, if ourType ==\n // T.L, may contain both T.R and T.AN chars).\n let sameDir = true, isNum = false;\n if (iI == isolates.length || iCh < isolates[iI].from) {\n let next = types[iCh];\n if (next != ourType) {\n sameDir = false;\n isNum = next == 16 /* T.AN */;\n }\n }\n // Holds an array of isolates to pass to a recursive call if we\n // must recurse (to distinguish T.AN inside an RTL section in\n // LTR text), null if we can emit directly\n let recurse = !sameDir && ourType == 1 /* T.L */ ? [] : null;\n let localLevel = sameDir ? level : level + 1;\n let iScan = iCh;\n run: for (;;) {\n if (iI < isolates.length && iScan == isolates[iI].from) {\n if (isNum)\n break run;\n let iso = isolates[iI];\n // Scan ahead to verify that there is another char in this dir after the isolate(s)\n if (!sameDir)\n for (let upto = iso.to, jI = iI + 1;;) {\n if (upto == to)\n break run;\n if (jI < isolates.length && isolates[jI].from == upto)\n upto = isolates[jI++].to;\n else if (types[upto] == ourType)\n break run;\n else\n break;\n }\n iI++;\n if (recurse) {\n recurse.push(iso);\n }\n else {\n if (iso.from > iCh)\n order.push(new BidiSpan(iCh, iso.from, localLevel));\n let dirSwap = (iso.direction == LTR) != !(localLevel % 2);\n computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);\n iCh = iso.to;\n }\n iScan = iso.to;\n }\n else if (iScan == to || (sameDir ? types[iScan] != ourType : types[iScan] == ourType)) {\n break;\n }\n else {\n iScan++;\n }\n }\n if (recurse)\n emitSpans(line, iCh, iScan, level + 1, baseLevel, recurse, order);\n else if (iCh < iScan)\n order.push(new BidiSpan(iCh, iScan, localLevel));\n iCh = iScan;\n }\n }\n else {\n // Iterate in reverse to flip the span order. Same code again, but\n // going from the back of the section to the front\n for (let iCh = to, iI = isolates.length; iCh > from;) {\n let sameDir = true, isNum = false;\n if (!iI || iCh > isolates[iI - 1].to) {\n let next = types[iCh - 1];\n if (next != ourType) {\n sameDir = false;\n isNum = next == 16 /* T.AN */;\n }\n }\n let recurse = !sameDir && ourType == 1 /* T.L */ ? [] : null;\n let localLevel = sameDir ? level : level + 1;\n let iScan = iCh;\n run: for (;;) {\n if (iI && iScan == isolates[iI - 1].to) {\n if (isNum)\n break run;\n let iso = isolates[--iI];\n // Scan ahead to verify that there is another char in this dir after the isolate(s)\n if (!sameDir)\n for (let upto = iso.from, jI = iI;;) {\n if (upto == from)\n break run;\n if (jI && isolates[jI - 1].to == upto)\n upto = isolates[--jI].from;\n else if (types[upto - 1] == ourType)\n break run;\n else\n break;\n }\n if (recurse) {\n recurse.push(iso);\n }\n else {\n if (iso.to < iCh)\n order.push(new BidiSpan(iso.to, iCh, localLevel));\n let dirSwap = (iso.direction == LTR) != !(localLevel % 2);\n computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);\n iCh = iso.from;\n }\n iScan = iso.from;\n }\n else if (iScan == from || (sameDir ? types[iScan - 1] != ourType : types[iScan - 1] == ourType)) {\n break;\n }\n else {\n iScan--;\n }\n }\n if (recurse)\n emitSpans(line, iScan, iCh, level + 1, baseLevel, recurse, order);\n else if (iScan < iCh)\n order.push(new BidiSpan(iScan, iCh, localLevel));\n iCh = iScan;\n }\n }\n}\nfunction computeSectionOrder(line, level, baseLevel, isolates, from, to, order) {\n let outerType = (level % 2 ? 2 /* T.R */ : 1 /* T.L */);\n computeCharTypes(line, from, to, isolates, outerType);\n processBracketPairs(line, from, to, isolates, outerType);\n processNeutrals(from, to, isolates, outerType);\n emitSpans(line, from, to, level, baseLevel, isolates, order);\n}\nfunction computeOrder(line, direction, isolates) {\n if (!line)\n return [new BidiSpan(0, 0, direction == RTL ? 1 : 0)];\n if (direction == LTR && !isolates.length && !BidiRE.test(line))\n return trivialOrder(line.length);\n if (isolates.length)\n while (line.length > types.length)\n types[types.length] = 256 /* T.NI */; // Make sure types array has no gaps\n let order = [], level = direction == LTR ? 0 : 1;\n computeSectionOrder(line, level, level, isolates, 0, line.length, order);\n return order;\n}\nfunction trivialOrder(length) {\n return [new BidiSpan(0, length, 0)];\n}\nlet movedOver = \"\";\nfunction moveVisually(line, order, dir, start, forward) {\n var _a;\n let startIndex = start.head - line.from, spanI = -1;\n if (startIndex == 0) {\n if (!forward || !line.length)\n return null;\n if (order[0].level != dir) {\n startIndex = order[0].side(false, dir);\n spanI = 0;\n }\n }\n else if (startIndex == line.length) {\n if (forward)\n return null;\n let last = order[order.length - 1];\n if (last.level != dir) {\n startIndex = last.side(true, dir);\n spanI = order.length - 1;\n }\n }\n if (spanI < 0)\n spanI = BidiSpan.find(order, startIndex, (_a = start.bidiLevel) !== null && _a !== void 0 ? _a : -1, start.assoc);\n let span = order[spanI];\n // End of span. (But not end of line--that was checked for above.)\n if (startIndex == span.side(forward, dir)) {\n span = order[spanI += forward ? 1 : -1];\n startIndex = span.side(!forward, dir);\n }\n let indexForward = forward == (span.dir == dir);\n let nextIndex = findClusterBreak(line.text, startIndex, indexForward);\n movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex));\n if (nextIndex != span.side(forward, dir))\n return EditorSelection.cursor(nextIndex + line.from, indexForward ? -1 : 1, span.level);\n let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)];\n if (!nextSpan && span.level != dir)\n return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1, dir);\n if (nextSpan && nextSpan.level < span.level)\n return EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, forward ? 1 : -1, nextSpan.level);\n return EditorSelection.cursor(nextIndex + line.from, forward ? -1 : 1, span.level);\n}\n\nclass DocView extends ContentView {\n get length() { return this.view.state.doc.length; }\n constructor(view) {\n super();\n this.view = view;\n this.decorations = [];\n this.dynamicDecorationMap = [];\n this.domChanged = null;\n this.hasComposition = null;\n this.markedForComposition = new Set;\n // Track a minimum width for the editor. When measuring sizes in\n // measureVisibleLineHeights, this is updated to point at the width\n // of a given element and its extent in the document. When a change\n // happens in that range, these are reset. That way, once we've seen\n // a line/element of a given length, we keep the editor wide enough\n // to fit at least that element, until it is changed, at which point\n // we forget it again.\n this.minWidth = 0;\n this.minWidthFrom = 0;\n this.minWidthTo = 0;\n // Track whether the DOM selection was set in a lossy way, so that\n // we don't mess it up when reading it back it\n this.impreciseAnchor = null;\n this.impreciseHead = null;\n this.forceSelection = false;\n // Used by the resize observer to ignore resizes that we caused\n // ourselves\n this.lastUpdate = Date.now();\n this.setDOM(view.contentDOM);\n this.children = [new LineView];\n this.children[0].setParent(this);\n this.updateDeco();\n this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], 0, null);\n }\n // Update the document view to a given state.\n update(update) {\n var _a;\n let changedRanges = update.changedRanges;\n if (this.minWidth > 0 && changedRanges.length) {\n if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) {\n this.minWidth = this.minWidthFrom = this.minWidthTo = 0;\n }\n else {\n this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1);\n this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1);\n }\n }\n let readCompositionAt = -1;\n if (this.view.inputState.composing >= 0) {\n if ((_a = this.domChanged) === null || _a === void 0 ? void 0 : _a.newSel)\n readCompositionAt = this.domChanged.newSel.head;\n else if (!touchesComposition(update.changes, this.hasComposition) && !update.selectionSet)\n readCompositionAt = update.state.selection.main.head;\n }\n let composition = readCompositionAt > -1 ? findCompositionRange(this.view, update.changes, readCompositionAt) : null;\n this.domChanged = null;\n if (this.hasComposition) {\n this.markedForComposition.clear();\n let { from, to } = this.hasComposition;\n changedRanges = new ChangedRange(from, to, update.changes.mapPos(from, -1), update.changes.mapPos(to, 1))\n .addToSet(changedRanges.slice());\n }\n this.hasComposition = composition ? { from: composition.range.fromB, to: composition.range.toB } : null;\n // When the DOM nodes around the selection are moved to another\n // parent, Chrome sometimes reports a different selection through\n // getSelection than the one that it actually shows to the user.\n // This forces a selection update when lines are joined to work\n // around that. Issue #54\n if ((browser.ie || browser.chrome) && !composition && update &&\n update.state.doc.lines != update.startState.doc.lines)\n this.forceSelection = true;\n let prevDeco = this.decorations, deco = this.updateDeco();\n let decoDiff = findChangedDeco(prevDeco, deco, update.changes);\n changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff);\n if (!(this.flags & 7 /* ViewFlag.Dirty */) && changedRanges.length == 0) {\n return false;\n }\n else {\n this.updateInner(changedRanges, update.startState.doc.length, composition);\n if (update.transactions.length)\n this.lastUpdate = Date.now();\n return true;\n }\n }\n // Used by update and the constructor do perform the actual DOM\n // update\n updateInner(changes, oldLength, composition) {\n this.view.viewState.mustMeasureContent = true;\n this.updateChildren(changes, oldLength, composition);\n let { observer } = this.view;\n observer.ignore(() => {\n // Lock the height during redrawing, since Chrome sometimes\n // messes with the scroll position during DOM mutation (though\n // no relayout is triggered and I cannot imagine how it can\n // recompute the scroll position without a layout)\n this.dom.style.height = this.view.viewState.contentHeight / this.view.scaleY + \"px\";\n this.dom.style.flexBasis = this.minWidth ? this.minWidth + \"px\" : \"\";\n // Chrome will sometimes, when DOM mutations occur directly\n // around the selection, get confused and report a different\n // selection from the one it displays (issue #218). This tries\n // to detect that situation.\n let track = browser.chrome || browser.ios ? { node: observer.selectionRange.focusNode, written: false } : undefined;\n this.sync(this.view, track);\n this.flags &= ~7 /* ViewFlag.Dirty */;\n if (track && (track.written || observer.selectionRange.focusNode != track.node))\n this.forceSelection = true;\n this.dom.style.height = \"\";\n });\n this.markedForComposition.forEach(cView => cView.flags &= ~8 /* ViewFlag.Composition */);\n let gaps = [];\n if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length)\n for (let child of this.children)\n if (child instanceof BlockWidgetView && child.widget instanceof BlockGapWidget)\n gaps.push(child.dom);\n observer.updateGaps(gaps);\n }\n updateChildren(changes, oldLength, composition) {\n let ranges = composition ? composition.range.addToSet(changes.slice()) : changes;\n let cursor = this.childCursor(oldLength);\n for (let i = ranges.length - 1;; i--) {\n let next = i >= 0 ? ranges[i] : null;\n if (!next)\n break;\n let { fromA, toA, fromB, toB } = next, content, breakAtStart, openStart, openEnd;\n if (composition && composition.range.fromB < toB && composition.range.toB > fromB) {\n let before = ContentBuilder.build(this.view.state.doc, fromB, composition.range.fromB, this.decorations, this.dynamicDecorationMap);\n let after = ContentBuilder.build(this.view.state.doc, composition.range.toB, toB, this.decorations, this.dynamicDecorationMap);\n breakAtStart = before.breakAtStart;\n openStart = before.openStart;\n openEnd = after.openEnd;\n let compLine = this.compositionView(composition);\n if (after.breakAtStart) {\n compLine.breakAfter = 1;\n }\n else if (after.content.length &&\n compLine.merge(compLine.length, compLine.length, after.content[0], false, after.openStart, 0)) {\n compLine.breakAfter = after.content[0].breakAfter;\n after.content.shift();\n }\n if (before.content.length &&\n compLine.merge(0, 0, before.content[before.content.length - 1], true, 0, before.openEnd)) {\n before.content.pop();\n }\n content = before.content.concat(compLine).concat(after.content);\n }\n else {\n ({ content, breakAtStart, openStart, openEnd } =\n ContentBuilder.build(this.view.state.doc, fromB, toB, this.decorations, this.dynamicDecorationMap));\n }\n let { i: toI, off: toOff } = cursor.findPos(toA, 1);\n let { i: fromI, off: fromOff } = cursor.findPos(fromA, -1);\n replaceRange(this, fromI, fromOff, toI, toOff, content, breakAtStart, openStart, openEnd);\n }\n if (composition)\n this.fixCompositionDOM(composition);\n }\n compositionView(composition) {\n let cur = new TextView(composition.text.nodeValue);\n cur.flags |= 8 /* ViewFlag.Composition */;\n for (let { deco } of composition.marks)\n cur = new MarkView(deco, [cur], cur.length);\n let line = new LineView;\n line.append(cur, 0);\n return line;\n }\n fixCompositionDOM(composition) {\n let fix = (dom, cView) => {\n cView.flags |= 8 /* ViewFlag.Composition */ | (cView.children.some(c => c.flags & 7 /* ViewFlag.Dirty */) ? 1 /* ViewFlag.ChildDirty */ : 0);\n this.markedForComposition.add(cView);\n let prev = ContentView.get(dom);\n if (prev && prev != cView)\n prev.dom = null;\n cView.setDOM(dom);\n };\n let pos = this.childPos(composition.range.fromB, 1);\n let cView = this.children[pos.i];\n fix(composition.line, cView);\n for (let i = composition.marks.length - 1; i >= -1; i--) {\n pos = cView.childPos(pos.off, 1);\n cView = cView.children[pos.i];\n fix(i >= 0 ? composition.marks[i].node : composition.text, cView);\n }\n }\n // Sync the DOM selection to this.state.selection\n updateSelection(mustRead = false, fromPointer = false) {\n if (mustRead || !this.view.observer.selectionRange.focusNode)\n this.view.observer.readSelectionRange();\n let activeElt = this.view.root.activeElement, focused = activeElt == this.dom;\n let selectionNotFocus = !focused &&\n hasSelection(this.dom, this.view.observer.selectionRange) && !(activeElt && this.dom.contains(activeElt));\n if (!(focused || fromPointer || selectionNotFocus))\n return;\n let force = this.forceSelection;\n this.forceSelection = false;\n let main = this.view.state.selection.main;\n let anchor = this.moveToLine(this.domAtPos(main.anchor));\n let head = main.empty ? anchor : this.moveToLine(this.domAtPos(main.head));\n // Always reset on Firefox when next to an uneditable node to\n // avoid invisible cursor bugs (#111)\n if (browser.gecko && main.empty && !this.hasComposition && betweenUneditable(anchor)) {\n let dummy = document.createTextNode(\"\");\n this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null));\n anchor = head = new DOMPos(dummy, 0);\n force = true;\n }\n let domSel = this.view.observer.selectionRange;\n // If the selection is already here, or in an equivalent position, don't touch it\n if (force || !domSel.focusNode ||\n !isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) ||\n !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) {\n this.view.observer.ignore(() => {\n // Chrome Android will hide the virtual keyboard when tapping\n // inside an uneditable node, and not bring it back when we\n // move the cursor to its proper position. This tries to\n // restore the keyboard by cycling focus.\n if (browser.android && browser.chrome && this.dom.contains(domSel.focusNode) &&\n inUneditable(domSel.focusNode, this.dom)) {\n this.dom.blur();\n this.dom.focus({ preventScroll: true });\n }\n let rawSel = getSelection(this.view.root);\n if (!rawSel) ;\n else if (main.empty) {\n // Work around https://bugzilla.mozilla.org/show_bug.cgi?id=1612076\n if (browser.gecko) {\n let nextTo = nextToUneditable(anchor.node, anchor.offset);\n if (nextTo && nextTo != (1 /* NextTo.Before */ | 2 /* NextTo.After */)) {\n let text = nearbyTextNode(anchor.node, anchor.offset, nextTo == 1 /* NextTo.Before */ ? 1 : -1);\n if (text)\n anchor = new DOMPos(text.node, text.offset);\n }\n }\n rawSel.collapse(anchor.node, anchor.offset);\n if (main.bidiLevel != null && rawSel.caretBidiLevel !== undefined)\n rawSel.caretBidiLevel = main.bidiLevel;\n }\n else if (rawSel.extend) {\n // Selection.extend can be used to create an 'inverted' selection\n // (one where the focus is before the anchor), but not all\n // browsers support it yet.\n rawSel.collapse(anchor.node, anchor.offset);\n // Safari will ignore the call above when the editor is\n // hidden, and then raise an error on the call to extend\n // (#940).\n try {\n rawSel.extend(head.node, head.offset);\n }\n catch (_) { }\n }\n else {\n // Primitive (IE) way\n let range = document.createRange();\n if (main.anchor > main.head)\n [anchor, head] = [head, anchor];\n range.setEnd(head.node, head.offset);\n range.setStart(anchor.node, anchor.offset);\n rawSel.removeAllRanges();\n rawSel.addRange(range);\n }\n if (selectionNotFocus && this.view.root.activeElement == this.dom) {\n this.dom.blur();\n if (activeElt)\n activeElt.focus();\n }\n });\n this.view.observer.setSelectionRange(anchor, head);\n }\n this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset);\n this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset);\n }\n enforceCursorAssoc() {\n if (this.hasComposition)\n return;\n let { view } = this, cursor = view.state.selection.main;\n let sel = getSelection(view.root);\n let { anchorNode, anchorOffset } = view.observer.selectionRange;\n if (!sel || !cursor.empty || !cursor.assoc || !sel.modify)\n return;\n let line = LineView.find(this, cursor.head);\n if (!line)\n return;\n let lineStart = line.posAtStart;\n if (cursor.head == lineStart || cursor.head == lineStart + line.length)\n return;\n let before = this.coordsAt(cursor.head, -1), after = this.coordsAt(cursor.head, 1);\n if (!before || !after || before.bottom > after.top)\n return;\n let dom = this.domAtPos(cursor.head + cursor.assoc);\n sel.collapse(dom.node, dom.offset);\n sel.modify(\"move\", cursor.assoc < 0 ? \"forward\" : \"backward\", \"lineboundary\");\n // This can go wrong in corner cases like single-character lines,\n // so check and reset if necessary.\n view.observer.readSelectionRange();\n let newRange = view.observer.selectionRange;\n if (view.docView.posFromDOM(newRange.anchorNode, newRange.anchorOffset) != cursor.from)\n sel.collapse(anchorNode, anchorOffset);\n }\n // If a position is in/near a block widget, move it to a nearby text\n // line, since we don't want the cursor inside a block widget.\n moveToLine(pos) {\n // Block widgets will return positions before/after them, which\n // are thus directly in the document DOM element.\n let dom = this.dom, newPos;\n if (pos.node != dom)\n return pos;\n for (let i = pos.offset; !newPos && i < dom.childNodes.length; i++) {\n let view = ContentView.get(dom.childNodes[i]);\n if (view instanceof LineView)\n newPos = view.domAtPos(0);\n }\n for (let i = pos.offset - 1; !newPos && i >= 0; i--) {\n let view = ContentView.get(dom.childNodes[i]);\n if (view instanceof LineView)\n newPos = view.domAtPos(view.length);\n }\n return newPos ? new DOMPos(newPos.node, newPos.offset, true) : pos;\n }\n nearest(dom) {\n for (let cur = dom; cur;) {\n let domView = ContentView.get(cur);\n if (domView && domView.rootView == this)\n return domView;\n cur = cur.parentNode;\n }\n return null;\n }\n posFromDOM(node, offset) {\n let view = this.nearest(node);\n if (!view)\n throw new RangeError(\"Trying to find position for a DOM position outside of the document\");\n return view.localPosFromDOM(node, offset) + view.posAtStart;\n }\n domAtPos(pos) {\n let { i, off } = this.childCursor().findPos(pos, -1);\n for (; i < this.children.length - 1;) {\n let child = this.children[i];\n if (off < child.length || child instanceof LineView)\n break;\n i++;\n off = 0;\n }\n return this.children[i].domAtPos(off);\n }\n coordsAt(pos, side) {\n let best = null, bestPos = 0;\n for (let off = this.length, i = this.children.length - 1; i >= 0; i--) {\n let child = this.children[i], end = off - child.breakAfter, start = end - child.length;\n if (end < pos)\n break;\n if (start <= pos && (start < pos || child.covers(-1)) && (end > pos || child.covers(1)) &&\n (!best || child instanceof LineView && !(best instanceof LineView && side >= 0))) {\n best = child;\n bestPos = start;\n }\n off = start;\n }\n return best ? best.coordsAt(pos - bestPos, side) : null;\n }\n coordsForChar(pos) {\n let { i, off } = this.childPos(pos, 1), child = this.children[i];\n if (!(child instanceof LineView))\n return null;\n while (child.children.length) {\n let { i, off: childOff } = child.childPos(off, 1);\n for (;; i++) {\n if (i == child.children.length)\n return null;\n if ((child = child.children[i]).length)\n break;\n }\n off = childOff;\n }\n if (!(child instanceof TextView))\n return null;\n let end = findClusterBreak(child.text, off);\n if (end == off)\n return null;\n let rects = textRange(child.dom, off, end).getClientRects();\n for (let i = 0; i < rects.length; i++) {\n let rect = rects[i];\n if (i == rects.length - 1 || rect.top < rect.bottom && rect.left < rect.right)\n return rect;\n }\n return null;\n }\n measureVisibleLineHeights(viewport) {\n let result = [], { from, to } = viewport;\n let contentWidth = this.view.contentDOM.clientWidth;\n let isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1;\n let widest = -1, ltr = this.view.textDirection == Direction.LTR;\n for (let pos = 0, i = 0; i < this.children.length; i++) {\n let child = this.children[i], end = pos + child.length;\n if (end > to)\n break;\n if (pos >= from) {\n let childRect = child.dom.getBoundingClientRect();\n result.push(childRect.height);\n if (isWider) {\n let last = child.dom.lastChild;\n let rects = last ? clientRectsFor(last) : [];\n if (rects.length) {\n let rect = rects[rects.length - 1];\n let width = ltr ? rect.right - childRect.left : childRect.right - rect.left;\n if (width > widest) {\n widest = width;\n this.minWidth = contentWidth;\n this.minWidthFrom = pos;\n this.minWidthTo = end;\n }\n }\n }\n }\n pos = end + child.breakAfter;\n }\n return result;\n }\n textDirectionAt(pos) {\n let { i } = this.childPos(pos, 1);\n return getComputedStyle(this.children[i].dom).direction == \"rtl\" ? Direction.RTL : Direction.LTR;\n }\n measureTextSize() {\n for (let child of this.children) {\n if (child instanceof LineView) {\n let measure = child.measureTextSize();\n if (measure)\n return measure;\n }\n }\n // If no workable line exists, force a layout of a measurable element\n let dummy = document.createElement(\"div\"), lineHeight, charWidth, textHeight;\n dummy.className = \"cm-line\";\n dummy.style.width = \"99999px\";\n dummy.style.position = \"absolute\";\n dummy.textContent = \"abc def ghi jkl mno pqr stu\";\n this.view.observer.ignore(() => {\n this.dom.appendChild(dummy);\n let rect = clientRectsFor(dummy.firstChild)[0];\n lineHeight = dummy.getBoundingClientRect().height;\n charWidth = rect ? rect.width / 27 : 7;\n textHeight = rect ? rect.height : lineHeight;\n dummy.remove();\n });\n return { lineHeight, charWidth, textHeight };\n }\n childCursor(pos = this.length) {\n // Move back to start of last element when possible, so that\n // `ChildCursor.findPos` doesn't have to deal with the edge case\n // of being after the last element.\n let i = this.children.length;\n if (i)\n pos -= this.children[--i].length;\n return new ChildCursor(this.children, pos, i);\n }\n computeBlockGapDeco() {\n let deco = [], vs = this.view.viewState;\n for (let pos = 0, i = 0;; i++) {\n let next = i == vs.viewports.length ? null : vs.viewports[i];\n let end = next ? next.from - 1 : this.length;\n if (end > pos) {\n let height = (vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top) / this.view.scaleY;\n deco.push(Decoration.replace({\n widget: new BlockGapWidget(height),\n block: true,\n inclusive: true,\n isBlockGap: true,\n }).range(pos, end));\n }\n if (!next)\n break;\n pos = next.to + 1;\n }\n return Decoration.set(deco);\n }\n updateDeco() {\n let allDeco = this.view.state.facet(decorations).map((d, i) => {\n let dynamic = this.dynamicDecorationMap[i] = typeof d == \"function\";\n return dynamic ? d(this.view) : d;\n });\n for (let i = allDeco.length; i < allDeco.length + 3; i++)\n this.dynamicDecorationMap[i] = false;\n return this.decorations = [\n ...allDeco,\n this.computeBlockGapDeco(),\n this.view.viewState.lineGapDeco\n ];\n }\n scrollIntoView(target) {\n if (target.isSnapshot) {\n let ref = this.view.viewState.lineBlockAt(target.range.head);\n this.view.scrollDOM.scrollTop = ref.top - target.yMargin;\n this.view.scrollDOM.scrollLeft = target.xMargin;\n return;\n }\n let { range } = target;\n let rect = this.coordsAt(range.head, range.empty ? range.assoc : range.head > range.anchor ? -1 : 1), other;\n if (!rect)\n return;\n if (!range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1)))\n rect = { left: Math.min(rect.left, other.left), top: Math.min(rect.top, other.top),\n right: Math.max(rect.right, other.right), bottom: Math.max(rect.bottom, other.bottom) };\n let margins = getScrollMargins(this.view);\n let targetRect = {\n left: rect.left - margins.left, top: rect.top - margins.top,\n right: rect.right + margins.right, bottom: rect.bottom + margins.bottom\n };\n let { offsetWidth, offsetHeight } = this.view.scrollDOM;\n scrollRectIntoView(this.view.scrollDOM, targetRect, range.head < range.anchor ? -1 : 1, target.x, target.y, Math.max(Math.min(target.xMargin, offsetWidth), -offsetWidth), Math.max(Math.min(target.yMargin, offsetHeight), -offsetHeight), this.view.textDirection == Direction.LTR);\n }\n}\nfunction betweenUneditable(pos) {\n return pos.node.nodeType == 1 && pos.node.firstChild &&\n (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == \"false\") &&\n (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == \"false\");\n}\nclass BlockGapWidget extends WidgetType {\n constructor(height) {\n super();\n this.height = height;\n }\n toDOM() {\n let elt = document.createElement(\"div\");\n this.updateDOM(elt);\n return elt;\n }\n eq(other) { return other.height == this.height; }\n updateDOM(elt) {\n elt.style.height = this.height + \"px\";\n return true;\n }\n get estimatedHeight() { return this.height; }\n}\nfunction findCompositionNode(view, headPos) {\n let sel = view.observer.selectionRange;\n let textNode = sel.focusNode && nearbyTextNode(sel.focusNode, sel.focusOffset, 0);\n if (!textNode)\n return null;\n let from = headPos - textNode.offset;\n return { from, to: from + textNode.node.nodeValue.length, node: textNode.node };\n}\nfunction findCompositionRange(view, changes, headPos) {\n let found = findCompositionNode(view, headPos);\n if (!found)\n return null;\n let { node: textNode, from, to } = found, text = textNode.nodeValue;\n // Don't try to preserve multi-line compositions\n if (/[\\n\\r]/.test(text))\n return null;\n if (view.state.doc.sliceString(found.from, found.to) != text)\n return null;\n let inv = changes.invertedDesc;\n let range = new ChangedRange(inv.mapPos(from), inv.mapPos(to), from, to);\n let marks = [];\n for (let parent = textNode.parentNode;; parent = parent.parentNode) {\n let parentView = ContentView.get(parent);\n if (parentView instanceof MarkView)\n marks.push({ node: parent, deco: parentView.mark });\n else if (parentView instanceof LineView || parent.nodeName == \"DIV\" && parent.parentNode == view.contentDOM)\n return { range, text: textNode, marks, line: parent };\n else if (parent != view.contentDOM)\n marks.push({ node: parent, deco: new MarkDecoration({\n inclusive: true,\n attributes: getAttrs(parent),\n tagName: parent.tagName.toLowerCase()\n }) });\n else\n return null;\n }\n}\nfunction nearbyTextNode(startNode, startOffset, side) {\n if (side <= 0)\n for (let node = startNode, offset = startOffset;;) {\n if (node.nodeType == 3)\n return { node: node, offset: offset };\n if (node.nodeType == 1 && offset > 0) {\n node = node.childNodes[offset - 1];\n offset = maxOffset(node);\n }\n else {\n break;\n }\n }\n if (side >= 0)\n for (let node = startNode, offset = startOffset;;) {\n if (node.nodeType == 3)\n return { node: node, offset: offset };\n if (node.nodeType == 1 && offset < node.childNodes.length && side >= 0) {\n node = node.childNodes[offset];\n offset = 0;\n }\n else {\n break;\n }\n }\n return null;\n}\nfunction nextToUneditable(node, offset) {\n if (node.nodeType != 1)\n return 0;\n return (offset && node.childNodes[offset - 1].contentEditable == \"false\" ? 1 /* NextTo.Before */ : 0) |\n (offset < node.childNodes.length && node.childNodes[offset].contentEditable == \"false\" ? 2 /* NextTo.After */ : 0);\n}\nlet DecorationComparator$1 = class DecorationComparator {\n constructor() {\n this.changes = [];\n }\n compareRange(from, to) { addRange(from, to, this.changes); }\n comparePoint(from, to) { addRange(from, to, this.changes); }\n};\nfunction findChangedDeco(a, b, diff) {\n let comp = new DecorationComparator$1;\n RangeSet.compare(a, b, diff, comp);\n return comp.changes;\n}\nfunction inUneditable(node, inside) {\n for (let cur = node; cur && cur != inside; cur = cur.assignedSlot || cur.parentNode) {\n if (cur.nodeType == 1 && cur.contentEditable == 'false') {\n return true;\n }\n }\n return false;\n}\nfunction touchesComposition(changes, composition) {\n let touched = false;\n if (composition)\n changes.iterChangedRanges((from, to) => {\n if (from < composition.to && to > composition.from)\n touched = true;\n });\n return touched;\n}\n\nfunction groupAt(state, pos, bias = 1) {\n let categorize = state.charCategorizer(pos);\n let line = state.doc.lineAt(pos), linePos = pos - line.from;\n if (line.length == 0)\n return EditorSelection.cursor(pos);\n if (linePos == 0)\n bias = 1;\n else if (linePos == line.length)\n bias = -1;\n let from = linePos, to = linePos;\n if (bias < 0)\n from = findClusterBreak(line.text, linePos, false);\n else\n to = findClusterBreak(line.text, linePos);\n let cat = categorize(line.text.slice(from, to));\n while (from > 0) {\n let prev = findClusterBreak(line.text, from, false);\n if (categorize(line.text.slice(prev, from)) != cat)\n break;\n from = prev;\n }\n while (to < line.length) {\n let next = findClusterBreak(line.text, to);\n if (categorize(line.text.slice(to, next)) != cat)\n break;\n to = next;\n }\n return EditorSelection.range(from + line.from, to + line.from);\n}\n// Search the DOM for the {node, offset} position closest to the given\n// coordinates. Very inefficient and crude, but can usually be avoided\n// by calling caret(Position|Range)FromPoint instead.\nfunction getdx(x, rect) {\n return rect.left > x ? rect.left - x : Math.max(0, x - rect.right);\n}\nfunction getdy(y, rect) {\n return rect.top > y ? rect.top - y : Math.max(0, y - rect.bottom);\n}\nfunction yOverlap(a, b) {\n return a.top < b.bottom - 1 && a.bottom > b.top + 1;\n}\nfunction upTop(rect, top) {\n return top < rect.top ? { top, left: rect.left, right: rect.right, bottom: rect.bottom } : rect;\n}\nfunction upBot(rect, bottom) {\n return bottom > rect.bottom ? { top: rect.top, left: rect.left, right: rect.right, bottom } : rect;\n}\nfunction domPosAtCoords(parent, x, y) {\n let closest, closestRect, closestX, closestY, closestOverlap = false;\n let above, below, aboveRect, belowRect;\n for (let child = parent.firstChild; child; child = child.nextSibling) {\n let rects = clientRectsFor(child);\n for (let i = 0; i < rects.length; i++) {\n let rect = rects[i];\n if (closestRect && yOverlap(closestRect, rect))\n rect = upTop(upBot(rect, closestRect.bottom), closestRect.top);\n let dx = getdx(x, rect), dy = getdy(y, rect);\n if (dx == 0 && dy == 0)\n return child.nodeType == 3 ? domPosInText(child, x, y) : domPosAtCoords(child, x, y);\n if (!closest || closestY > dy || closestY == dy && closestX > dx) {\n closest = child;\n closestRect = rect;\n closestX = dx;\n closestY = dy;\n let side = dy ? (y < rect.top ? -1 : 1) : dx ? (x < rect.left ? -1 : 1) : 0;\n closestOverlap = !side || (side > 0 ? i < rects.length - 1 : i > 0);\n }\n if (dx == 0) {\n if (y > rect.bottom && (!aboveRect || aboveRect.bottom < rect.bottom)) {\n above = child;\n aboveRect = rect;\n }\n else if (y < rect.top && (!belowRect || belowRect.top > rect.top)) {\n below = child;\n belowRect = rect;\n }\n }\n else if (aboveRect && yOverlap(aboveRect, rect)) {\n aboveRect = upBot(aboveRect, rect.bottom);\n }\n else if (belowRect && yOverlap(belowRect, rect)) {\n belowRect = upTop(belowRect, rect.top);\n }\n }\n }\n if (aboveRect && aboveRect.bottom >= y) {\n closest = above;\n closestRect = aboveRect;\n }\n else if (belowRect && belowRect.top <= y) {\n closest = below;\n closestRect = belowRect;\n }\n if (!closest)\n return { node: parent, offset: 0 };\n let clipX = Math.max(closestRect.left, Math.min(closestRect.right, x));\n if (closest.nodeType == 3)\n return domPosInText(closest, clipX, y);\n if (closestOverlap && closest.contentEditable != \"false\")\n return domPosAtCoords(closest, clipX, y);\n let offset = Array.prototype.indexOf.call(parent.childNodes, closest) +\n (x >= (closestRect.left + closestRect.right) / 2 ? 1 : 0);\n return { node: parent, offset };\n}\nfunction domPosInText(node, x, y) {\n let len = node.nodeValue.length;\n let closestOffset = -1, closestDY = 1e9, generalSide = 0;\n for (let i = 0; i < len; i++) {\n let rects = textRange(node, i, i + 1).getClientRects();\n for (let j = 0; j < rects.length; j++) {\n let rect = rects[j];\n if (rect.top == rect.bottom)\n continue;\n if (!generalSide)\n generalSide = x - rect.left;\n let dy = (rect.top > y ? rect.top - y : y - rect.bottom) - 1;\n if (rect.left - 1 <= x && rect.right + 1 >= x && dy < closestDY) {\n let right = x >= (rect.left + rect.right) / 2, after = right;\n if (browser.chrome || browser.gecko) {\n // Check for RTL on browsers that support getting client\n // rects for empty ranges.\n let rectBefore = textRange(node, i).getBoundingClientRect();\n if (rectBefore.left == rect.right)\n after = !right;\n }\n if (dy <= 0)\n return { node, offset: i + (after ? 1 : 0) };\n closestOffset = i + (after ? 1 : 0);\n closestDY = dy;\n }\n }\n }\n return { node, offset: closestOffset > -1 ? closestOffset : generalSide > 0 ? node.nodeValue.length : 0 };\n}\nfunction posAtCoords(view, coords, precise, bias = -1) {\n var _a, _b;\n let content = view.contentDOM.getBoundingClientRect(), docTop = content.top + view.viewState.paddingTop;\n let block, { docHeight } = view.viewState;\n let { x, y } = coords, yOffset = y - docTop;\n if (yOffset < 0)\n return 0;\n if (yOffset > docHeight)\n return view.state.doc.length;\n // Scan for a text block near the queried y position\n for (let halfLine = view.viewState.heightOracle.textHeight / 2, bounced = false;;) {\n block = view.elementAtHeight(yOffset);\n if (block.type == BlockType.Text)\n break;\n for (;;) {\n // Move the y position out of this block\n yOffset = bias > 0 ? block.bottom + halfLine : block.top - halfLine;\n if (yOffset >= 0 && yOffset <= docHeight)\n break;\n // If the document consists entirely of replaced widgets, we\n // won't find a text block, so return 0\n if (bounced)\n return precise ? null : 0;\n bounced = true;\n bias = -bias;\n }\n }\n y = docTop + yOffset;\n let lineStart = block.from;\n // If this is outside of the rendered viewport, we can't determine a position\n if (lineStart < view.viewport.from)\n return view.viewport.from == 0 ? 0 : precise ? null : posAtCoordsImprecise(view, content, block, x, y);\n if (lineStart > view.viewport.to)\n return view.viewport.to == view.state.doc.length ? view.state.doc.length :\n precise ? null : posAtCoordsImprecise(view, content, block, x, y);\n // Prefer ShadowRootOrDocument.elementFromPoint if present, fall back to document if not\n let doc = view.dom.ownerDocument;\n let root = view.root.elementFromPoint ? view.root : doc;\n let element = root.elementFromPoint(x, y);\n if (element && !view.contentDOM.contains(element))\n element = null;\n // If the element is unexpected, clip x at the sides of the content area and try again\n if (!element) {\n x = Math.max(content.left + 1, Math.min(content.right - 1, x));\n element = root.elementFromPoint(x, y);\n if (element && !view.contentDOM.contains(element))\n element = null;\n }\n // There's visible editor content under the point, so we can try\n // using caret(Position|Range)FromPoint as a shortcut\n let node, offset = -1;\n if (element && ((_a = view.docView.nearest(element)) === null || _a === void 0 ? void 0 : _a.isEditable) != false) {\n if (doc.caretPositionFromPoint) {\n let pos = doc.caretPositionFromPoint(x, y);\n if (pos)\n ({ offsetNode: node, offset } = pos);\n }\n else if (doc.caretRangeFromPoint) {\n let range = doc.caretRangeFromPoint(x, y);\n if (range) {\n ({ startContainer: node, startOffset: offset } = range);\n if (!view.contentDOM.contains(node) ||\n browser.safari && isSuspiciousSafariCaretResult(node, offset, x) ||\n browser.chrome && isSuspiciousChromeCaretResult(node, offset, x))\n node = undefined;\n }\n }\n }\n // No luck, do our own (potentially expensive) search\n if (!node || !view.docView.dom.contains(node)) {\n let line = LineView.find(view.docView, lineStart);\n if (!line)\n return yOffset > block.top + block.height / 2 ? block.to : block.from;\n ({ node, offset } = domPosAtCoords(line.dom, x, y));\n }\n let nearest = view.docView.nearest(node);\n if (!nearest)\n return null;\n if (nearest.isWidget && ((_b = nearest.dom) === null || _b === void 0 ? void 0 : _b.nodeType) == 1) {\n let rect = nearest.dom.getBoundingClientRect();\n return coords.y < rect.top || coords.y <= rect.bottom && coords.x <= (rect.left + rect.right) / 2\n ? nearest.posAtStart : nearest.posAtEnd;\n }\n else {\n return nearest.localPosFromDOM(node, offset) + nearest.posAtStart;\n }\n}\nfunction posAtCoordsImprecise(view, contentRect, block, x, y) {\n let into = Math.round((x - contentRect.left) * view.defaultCharacterWidth);\n if (view.lineWrapping && block.height > view.defaultLineHeight * 1.5) {\n let textHeight = view.viewState.heightOracle.textHeight;\n let line = Math.floor((y - block.top - (view.defaultLineHeight - textHeight) * 0.5) / textHeight);\n into += line * view.viewState.heightOracle.lineLength;\n }\n let content = view.state.sliceDoc(block.from, block.to);\n return block.from + findColumn(content, into, view.state.tabSize);\n}\n// In case of a high line height, Safari's caretRangeFromPoint treats\n// the space between lines as belonging to the last character of the\n// line before. This is used to detect such a result so that it can be\n// ignored (issue #401).\nfunction isSuspiciousSafariCaretResult(node, offset, x) {\n let len;\n if (node.nodeType != 3 || offset != (len = node.nodeValue.length))\n return false;\n for (let next = node.nextSibling; next; next = next.nextSibling)\n if (next.nodeType != 1 || next.nodeName != \"BR\")\n return false;\n return textRange(node, len - 1, len).getBoundingClientRect().left > x;\n}\n// Chrome will move positions between lines to the start of the next line\nfunction isSuspiciousChromeCaretResult(node, offset, x) {\n if (offset != 0)\n return false;\n for (let cur = node;;) {\n let parent = cur.parentNode;\n if (!parent || parent.nodeType != 1 || parent.firstChild != cur)\n return false;\n if (parent.classList.contains(\"cm-line\"))\n break;\n cur = parent;\n }\n let rect = node.nodeType == 1 ? node.getBoundingClientRect()\n : textRange(node, 0, Math.max(node.nodeValue.length, 1)).getBoundingClientRect();\n return x - rect.left > 5;\n}\nfunction blockAt(view, pos) {\n let line = view.lineBlockAt(pos);\n if (Array.isArray(line.type))\n for (let l of line.type) {\n if (l.to > pos || l.to == pos && (l.to == line.to || l.type == BlockType.Text))\n return l;\n }\n return line;\n}\nfunction moveToLineBoundary(view, start, forward, includeWrap) {\n let line = blockAt(view, start.head);\n let coords = !includeWrap || line.type != BlockType.Text || !(view.lineWrapping || line.widgetLineBreaks) ? null\n : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head);\n if (coords) {\n let editorRect = view.dom.getBoundingClientRect();\n let direction = view.textDirectionAt(line.from);\n let pos = view.posAtCoords({ x: forward == (direction == Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1,\n y: (coords.top + coords.bottom) / 2 });\n if (pos != null)\n return EditorSelection.cursor(pos, forward ? -1 : 1);\n }\n return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1);\n}\nfunction moveByChar(view, start, forward, by) {\n let line = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line);\n let direction = view.textDirectionAt(line.from);\n for (let cur = start, check = null;;) {\n let next = moveVisually(line, spans, direction, cur, forward), char = movedOver;\n if (!next) {\n if (line.number == (forward ? view.state.doc.lines : 1))\n return cur;\n char = \"\\n\";\n line = view.state.doc.line(line.number + (forward ? 1 : -1));\n spans = view.bidiSpans(line);\n next = EditorSelection.cursor(forward ? line.from : line.to);\n }\n if (!check) {\n if (!by)\n return next;\n check = by(char);\n }\n else if (!check(char)) {\n return cur;\n }\n cur = next;\n }\n}\nfunction byGroup(view, pos, start) {\n let categorize = view.state.charCategorizer(pos);\n let cat = categorize(start);\n return (next) => {\n let nextCat = categorize(next);\n if (cat == CharCategory.Space)\n cat = nextCat;\n return cat == nextCat;\n };\n}\nfunction moveVertically(view, start, forward, distance) {\n let startPos = start.head, dir = forward ? 1 : -1;\n if (startPos == (forward ? view.state.doc.length : 0))\n return EditorSelection.cursor(startPos, start.assoc);\n let goal = start.goalColumn, startY;\n let rect = view.contentDOM.getBoundingClientRect();\n let startCoords = view.coordsAtPos(startPos, start.assoc || -1), docTop = view.documentTop;\n if (startCoords) {\n if (goal == null)\n goal = startCoords.left - rect.left;\n startY = dir < 0 ? startCoords.top : startCoords.bottom;\n }\n else {\n let line = view.viewState.lineBlockAt(startPos);\n if (goal == null)\n goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from));\n startY = (dir < 0 ? line.top : line.bottom) + docTop;\n }\n let resolvedGoal = rect.left + goal;\n let dist = distance !== null && distance !== void 0 ? distance : (view.viewState.heightOracle.textHeight >> 1);\n for (let extra = 0;; extra += 10) {\n let curY = startY + (dist + extra) * dir;\n let pos = posAtCoords(view, { x: resolvedGoal, y: curY }, false, dir);\n if (curY < rect.top || curY > rect.bottom || (dir < 0 ? pos < startPos : pos > startPos)) {\n let charRect = view.docView.coordsForChar(pos);\n let assoc = !charRect || curY < charRect.top ? -1 : 1;\n return EditorSelection.cursor(pos, assoc, undefined, goal);\n }\n }\n}\nfunction skipAtomicRanges(atoms, pos, bias) {\n for (;;) {\n let moved = 0;\n for (let set of atoms) {\n set.between(pos - 1, pos + 1, (from, to, value) => {\n if (pos > from && pos < to) {\n let side = moved || bias || (pos - from < to - pos ? -1 : 1);\n pos = side < 0 ? from : to;\n moved = side;\n }\n });\n }\n if (!moved)\n return pos;\n }\n}\nfunction skipAtoms(view, oldPos, pos) {\n let newPos = skipAtomicRanges(view.state.facet(atomicRanges).map(f => f(view)), pos.from, oldPos.head > pos.from ? -1 : 1);\n return newPos == pos.from ? pos : EditorSelection.cursor(newPos, newPos < pos.from ? 1 : -1);\n}\n\n// This will also be where dragging info and such goes\nclass InputState {\n setSelectionOrigin(origin) {\n this.lastSelectionOrigin = origin;\n this.lastSelectionTime = Date.now();\n }\n constructor(view) {\n this.view = view;\n this.lastKeyCode = 0;\n this.lastKeyTime = 0;\n this.lastTouchTime = 0;\n this.lastFocusTime = 0;\n this.lastScrollTop = 0;\n this.lastScrollLeft = 0;\n // On iOS, some keys need to have their default behavior happen\n // (after which we retroactively handle them and reset the DOM) to\n // avoid messing up the virtual keyboard state.\n this.pendingIOSKey = undefined;\n this.lastSelectionOrigin = null;\n this.lastSelectionTime = 0;\n this.lastEscPress = 0;\n this.lastContextMenu = 0;\n this.scrollHandlers = [];\n this.handlers = Object.create(null);\n // -1 means not in a composition. Otherwise, this counts the number\n // of changes made during the composition. The count is used to\n // avoid treating the start state of the composition, before any\n // changes have been made, as part of the composition.\n this.composing = -1;\n // Tracks whether the next change should be marked as starting the\n // composition (null means no composition, true means next is the\n // first, false means first has already been marked for this\n // composition)\n this.compositionFirstChange = null;\n // End time of the previous composition\n this.compositionEndedAt = 0;\n // Used in a kludge to detect when an Enter keypress should be\n // considered part of the composition on Safari, which fires events\n // in the wrong order\n this.compositionPendingKey = false;\n // Used to categorize changes as part of a composition, even when\n // the mutation events fire shortly after the compositionend event\n this.compositionPendingChange = false;\n this.mouseSelection = null;\n // When a drag from the editor is active, this points at the range\n // being dragged.\n this.draggedContent = null;\n this.handleEvent = this.handleEvent.bind(this);\n this.notifiedFocused = view.hasFocus;\n // On Safari adding an input event handler somehow prevents an\n // issue where the composition vanishes when you press enter.\n if (browser.safari)\n view.contentDOM.addEventListener(\"input\", () => null);\n if (browser.gecko)\n firefoxCopyCutHack(view.contentDOM.ownerDocument);\n }\n handleEvent(event) {\n if (!eventBelongsToEditor(this.view, event) || this.ignoreDuringComposition(event))\n return;\n if (event.type == \"keydown\" && this.keydown(event))\n return;\n this.runHandlers(event.type, event);\n }\n runHandlers(type, event) {\n let handlers = this.handlers[type];\n if (handlers) {\n for (let observer of handlers.observers)\n observer(this.view, event);\n for (let handler of handlers.handlers) {\n if (event.defaultPrevented)\n break;\n if (handler(this.view, event)) {\n event.preventDefault();\n break;\n }\n }\n }\n }\n ensureHandlers(plugins) {\n let handlers = computeHandlers(plugins), prev = this.handlers, dom = this.view.contentDOM;\n for (let type in handlers)\n if (type != \"scroll\") {\n let passive = !handlers[type].handlers.length;\n let exists = prev[type];\n if (exists && passive != !exists.handlers.length) {\n dom.removeEventListener(type, this.handleEvent);\n exists = null;\n }\n if (!exists)\n dom.addEventListener(type, this.handleEvent, { passive });\n }\n for (let type in prev)\n if (type != \"scroll\" && !handlers[type])\n dom.removeEventListener(type, this.handleEvent);\n this.handlers = handlers;\n }\n keydown(event) {\n // Must always run, even if a custom handler handled the event\n this.lastKeyCode = event.keyCode;\n this.lastKeyTime = Date.now();\n if (event.keyCode == 9 && Date.now() < this.lastEscPress + 2000)\n return true;\n if (event.keyCode != 27 && modifierCodes.indexOf(event.keyCode) < 0)\n this.view.inputState.lastEscPress = 0;\n // Chrome for Android usually doesn't fire proper key events, but\n // occasionally does, usually surrounded by a bunch of complicated\n // composition changes. When an enter or backspace key event is\n // seen, hold off on handling DOM events for a bit, and then\n // dispatch it.\n if (browser.android && browser.chrome && !event.synthetic &&\n (event.keyCode == 13 || event.keyCode == 8)) {\n this.view.observer.delayAndroidKey(event.key, event.keyCode);\n return true;\n }\n // Preventing the default behavior of Enter on iOS makes the\n // virtual keyboard get stuck in the wrong (lowercase)\n // state. So we let it go through, and then, in\n // applyDOMChange, notify key handlers of it and reset to\n // the state they produce.\n let pending;\n if (browser.ios && !event.synthetic && !event.altKey && !event.metaKey &&\n ((pending = PendingKeys.find(key => key.keyCode == event.keyCode)) && !event.ctrlKey ||\n EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey && !event.shiftKey)) {\n this.pendingIOSKey = pending || event;\n setTimeout(() => this.flushIOSKey(), 250);\n return true;\n }\n if (event.keyCode != 229)\n this.view.observer.forceFlush();\n return false;\n }\n flushIOSKey() {\n let key = this.pendingIOSKey;\n if (!key)\n return false;\n this.pendingIOSKey = undefined;\n return dispatchKey(this.view.contentDOM, key.key, key.keyCode);\n }\n ignoreDuringComposition(event) {\n if (!/^key/.test(event.type))\n return false;\n if (this.composing > 0)\n return true;\n // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.\n // On some input method editors (IMEs), the Enter key is used to\n // confirm character selection. On Safari, when Enter is pressed,\n // compositionend and keydown events are sometimes emitted in the\n // wrong order. The key event should still be ignored, even when\n // it happens after the compositionend event.\n if (browser.safari && !browser.ios && this.compositionPendingKey && Date.now() - this.compositionEndedAt < 100) {\n this.compositionPendingKey = false;\n return true;\n }\n return false;\n }\n startMouseSelection(mouseSelection) {\n if (this.mouseSelection)\n this.mouseSelection.destroy();\n this.mouseSelection = mouseSelection;\n }\n update(update) {\n if (this.mouseSelection)\n this.mouseSelection.update(update);\n if (this.draggedContent && update.docChanged)\n this.draggedContent = this.draggedContent.map(update.changes);\n if (update.transactions.length)\n this.lastKeyCode = this.lastSelectionTime = 0;\n }\n destroy() {\n if (this.mouseSelection)\n this.mouseSelection.destroy();\n }\n}\nfunction bindHandler(plugin, handler) {\n return (view, event) => {\n try {\n return handler.call(plugin, event, view);\n }\n catch (e) {\n logException(view.state, e);\n }\n };\n}\nfunction computeHandlers(plugins) {\n let result = Object.create(null);\n function record(type) {\n return result[type] || (result[type] = { observers: [], handlers: [] });\n }\n for (let plugin of plugins) {\n let spec = plugin.spec;\n if (spec && spec.domEventHandlers)\n for (let type in spec.domEventHandlers) {\n let f = spec.domEventHandlers[type];\n if (f)\n record(type).handlers.push(bindHandler(plugin.value, f));\n }\n if (spec && spec.domEventObservers)\n for (let type in spec.domEventObservers) {\n let f = spec.domEventObservers[type];\n if (f)\n record(type).observers.push(bindHandler(plugin.value, f));\n }\n }\n for (let type in handlers)\n record(type).handlers.push(handlers[type]);\n for (let type in observers)\n record(type).observers.push(observers[type]);\n return result;\n}\nconst PendingKeys = [\n { key: \"Backspace\", keyCode: 8, inputType: \"deleteContentBackward\" },\n { key: \"Enter\", keyCode: 13, inputType: \"insertParagraph\" },\n { key: \"Enter\", keyCode: 13, inputType: \"insertLineBreak\" },\n { key: \"Delete\", keyCode: 46, inputType: \"deleteContentForward\" }\n];\nconst EmacsyPendingKeys = \"dthko\";\n// Key codes for modifier keys\nconst modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225];\nconst dragScrollMargin = 6;\nfunction dragScrollSpeed(dist) {\n return Math.max(0, dist) * 0.7 + 8;\n}\nfunction dist(a, b) {\n return Math.max(Math.abs(a.clientX - b.clientX), Math.abs(a.clientY - b.clientY));\n}\nclass MouseSelection {\n constructor(view, startEvent, style, mustSelect) {\n this.view = view;\n this.startEvent = startEvent;\n this.style = style;\n this.mustSelect = mustSelect;\n this.scrollSpeed = { x: 0, y: 0 };\n this.scrolling = -1;\n this.lastEvent = startEvent;\n this.scrollParent = scrollableParent(view.contentDOM);\n this.atoms = view.state.facet(atomicRanges).map(f => f(view));\n let doc = view.contentDOM.ownerDocument;\n doc.addEventListener(\"mousemove\", this.move = this.move.bind(this));\n doc.addEventListener(\"mouseup\", this.up = this.up.bind(this));\n this.extend = startEvent.shiftKey;\n this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent);\n this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false;\n }\n start(event) {\n // When clicking outside of the selection, immediately apply the\n // effect of starting the selection\n if (this.dragging === false)\n this.select(event);\n }\n move(event) {\n var _a;\n if (event.buttons == 0)\n return this.destroy();\n if (this.dragging || this.dragging == null && dist(this.startEvent, event) < 10)\n return;\n this.select(this.lastEvent = event);\n let sx = 0, sy = 0;\n let rect = ((_a = this.scrollParent) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect())\n || { left: 0, top: 0, right: this.view.win.innerWidth, bottom: this.view.win.innerHeight };\n let margins = getScrollMargins(this.view);\n if (event.clientX - margins.left <= rect.left + dragScrollMargin)\n sx = -dragScrollSpeed(rect.left - event.clientX);\n else if (event.clientX + margins.right >= rect.right - dragScrollMargin)\n sx = dragScrollSpeed(event.clientX - rect.right);\n if (event.clientY - margins.top <= rect.top + dragScrollMargin)\n sy = -dragScrollSpeed(rect.top - event.clientY);\n else if (event.clientY + margins.bottom >= rect.bottom - dragScrollMargin)\n sy = dragScrollSpeed(event.clientY - rect.bottom);\n this.setScrollSpeed(sx, sy);\n }\n up(event) {\n if (this.dragging == null)\n this.select(this.lastEvent);\n if (!this.dragging)\n event.preventDefault();\n this.destroy();\n }\n destroy() {\n this.setScrollSpeed(0, 0);\n let doc = this.view.contentDOM.ownerDocument;\n doc.removeEventListener(\"mousemove\", this.move);\n doc.removeEventListener(\"mouseup\", this.up);\n this.view.inputState.mouseSelection = this.view.inputState.draggedContent = null;\n }\n setScrollSpeed(sx, sy) {\n this.scrollSpeed = { x: sx, y: sy };\n if (sx || sy) {\n if (this.scrolling < 0)\n this.scrolling = setInterval(() => this.scroll(), 50);\n }\n else if (this.scrolling > -1) {\n clearInterval(this.scrolling);\n this.scrolling = -1;\n }\n }\n scroll() {\n if (this.scrollParent) {\n this.scrollParent.scrollLeft += this.scrollSpeed.x;\n this.scrollParent.scrollTop += this.scrollSpeed.y;\n }\n else {\n this.view.win.scrollBy(this.scrollSpeed.x, this.scrollSpeed.y);\n }\n if (this.dragging === false)\n this.select(this.lastEvent);\n }\n skipAtoms(sel) {\n let ranges = null;\n for (let i = 0; i < sel.ranges.length; i++) {\n let range = sel.ranges[i], updated = null;\n if (range.empty) {\n let pos = skipAtomicRanges(this.atoms, range.from, 0);\n if (pos != range.from)\n updated = EditorSelection.cursor(pos, -1);\n }\n else {\n let from = skipAtomicRanges(this.atoms, range.from, -1);\n let to = skipAtomicRanges(this.atoms, range.to, 1);\n if (from != range.from || to != range.to)\n updated = EditorSelection.range(range.from == range.anchor ? from : to, range.from == range.head ? from : to);\n }\n if (updated) {\n if (!ranges)\n ranges = sel.ranges.slice();\n ranges[i] = updated;\n }\n }\n return ranges ? EditorSelection.create(ranges, sel.mainIndex) : sel;\n }\n select(event) {\n let { view } = this, selection = this.skipAtoms(this.style.get(event, this.extend, this.multiple));\n if (this.mustSelect || !selection.eq(view.state.selection) ||\n selection.main.assoc != view.state.selection.main.assoc && this.dragging === false)\n this.view.dispatch({\n selection,\n userEvent: \"select.pointer\"\n });\n this.mustSelect = false;\n }\n update(update) {\n if (this.style.update(update))\n setTimeout(() => this.select(this.lastEvent), 20);\n }\n}\nfunction addsSelectionRange(view, event) {\n let facet = view.state.facet(clickAddsSelectionRange);\n return facet.length ? facet[0](event) : browser.mac ? event.metaKey : event.ctrlKey;\n}\nfunction dragMovesSelection(view, event) {\n let facet = view.state.facet(dragMovesSelection$1);\n return facet.length ? facet[0](event) : browser.mac ? !event.altKey : !event.ctrlKey;\n}\nfunction isInPrimarySelection(view, event) {\n let { main } = view.state.selection;\n if (main.empty)\n return false;\n // On boundary clicks, check whether the coordinates are inside the\n // selection's client rectangles\n let sel = getSelection(view.root);\n if (!sel || sel.rangeCount == 0)\n return true;\n let rects = sel.getRangeAt(0).getClientRects();\n for (let i = 0; i < rects.length; i++) {\n let rect = rects[i];\n if (rect.left <= event.clientX && rect.right >= event.clientX &&\n rect.top <= event.clientY && rect.bottom >= event.clientY)\n return true;\n }\n return false;\n}\nfunction eventBelongsToEditor(view, event) {\n if (!event.bubbles)\n return true;\n if (event.defaultPrevented)\n return false;\n for (let node = event.target, cView; node != view.contentDOM; node = node.parentNode)\n if (!node || node.nodeType == 11 || ((cView = ContentView.get(node)) && cView.ignoreEvent(event)))\n return false;\n return true;\n}\nconst handlers = /*@__PURE__*/Object.create(null);\nconst observers = /*@__PURE__*/Object.create(null);\n// This is very crude, but unfortunately both these browsers _pretend_\n// that they have a clipboard API—all the objects and methods are\n// there, they just don't work, and they are hard to test.\nconst brokenClipboardAPI = (browser.ie && browser.ie_version < 15) ||\n (browser.ios && browser.webkit_version < 604);\nfunction capturePaste(view) {\n let parent = view.dom.parentNode;\n if (!parent)\n return;\n let target = parent.appendChild(document.createElement(\"textarea\"));\n target.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n target.focus();\n setTimeout(() => {\n view.focus();\n target.remove();\n doPaste(view, target.value);\n }, 50);\n}\nfunction doPaste(view, input) {\n let { state } = view, changes, i = 1, text = state.toText(input);\n let byLine = text.lines == state.selection.ranges.length;\n let linewise = lastLinewiseCopy != null && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy == text.toString();\n if (linewise) {\n let lastLine = -1;\n changes = state.changeByRange(range => {\n let line = state.doc.lineAt(range.from);\n if (line.from == lastLine)\n return { range };\n lastLine = line.from;\n let insert = state.toText((byLine ? text.line(i++).text : input) + state.lineBreak);\n return { changes: { from: line.from, insert },\n range: EditorSelection.cursor(range.from + insert.length) };\n });\n }\n else if (byLine) {\n changes = state.changeByRange(range => {\n let line = text.line(i++);\n return { changes: { from: range.from, to: range.to, insert: line.text },\n range: EditorSelection.cursor(range.from + line.length) };\n });\n }\n else {\n changes = state.replaceSelection(text);\n }\n view.dispatch(changes, {\n userEvent: \"input.paste\",\n scrollIntoView: true\n });\n}\nobservers.scroll = view => {\n view.inputState.lastScrollTop = view.scrollDOM.scrollTop;\n view.inputState.lastScrollLeft = view.scrollDOM.scrollLeft;\n};\nhandlers.keydown = (view, event) => {\n view.inputState.setSelectionOrigin(\"select\");\n if (event.keyCode == 27)\n view.inputState.lastEscPress = Date.now();\n return false;\n};\nobservers.touchstart = (view, e) => {\n view.inputState.lastTouchTime = Date.now();\n view.inputState.setSelectionOrigin(\"select.pointer\");\n};\nobservers.touchmove = view => {\n view.inputState.setSelectionOrigin(\"select.pointer\");\n};\nhandlers.mousedown = (view, event) => {\n view.observer.flush();\n if (view.inputState.lastTouchTime > Date.now() - 2000)\n return false; // Ignore touch interaction\n let style = null;\n for (let makeStyle of view.state.facet(mouseSelectionStyle)) {\n style = makeStyle(view, event);\n if (style)\n break;\n }\n if (!style && event.button == 0)\n style = basicMouseSelection(view, event);\n if (style) {\n let mustFocus = !view.hasFocus;\n view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus));\n if (mustFocus)\n view.observer.ignore(() => focusPreventScroll(view.contentDOM));\n let mouseSel = view.inputState.mouseSelection;\n if (mouseSel) {\n mouseSel.start(event);\n return mouseSel.dragging === false;\n }\n }\n return false;\n};\nfunction rangeForClick(view, pos, bias, type) {\n if (type == 1) { // Single click\n return EditorSelection.cursor(pos, bias);\n }\n else if (type == 2) { // Double click\n return groupAt(view.state, pos, bias);\n }\n else { // Triple click\n let visual = LineView.find(view.docView, pos), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos);\n let from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to;\n if (to < view.state.doc.length && to == line.to)\n to++;\n return EditorSelection.range(from, to);\n }\n}\nlet insideY = (y, rect) => y >= rect.top && y <= rect.bottom;\nlet inside = (x, y, rect) => insideY(y, rect) && x >= rect.left && x <= rect.right;\n// Try to determine, for the given coordinates, associated with the\n// given position, whether they are related to the element before or\n// the element after the position.\nfunction findPositionSide(view, pos, x, y) {\n let line = LineView.find(view.docView, pos);\n if (!line)\n return 1;\n let off = pos - line.posAtStart;\n // Line boundaries point into the line\n if (off == 0)\n return 1;\n if (off == line.length)\n return -1;\n // Positions on top of an element point at that element\n let before = line.coordsAt(off, -1);\n if (before && inside(x, y, before))\n return -1;\n let after = line.coordsAt(off, 1);\n if (after && inside(x, y, after))\n return 1;\n // This is probably a line wrap point. Pick before if the point is\n // beside it.\n return before && insideY(y, before) ? -1 : 1;\n}\nfunction queryPos(view, event) {\n let pos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);\n return { pos, bias: findPositionSide(view, pos, event.clientX, event.clientY) };\n}\nconst BadMouseDetail = browser.ie && browser.ie_version <= 11;\nlet lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0;\nfunction getClickType(event) {\n if (!BadMouseDetail)\n return event.detail;\n let last = lastMouseDown, lastTime = lastMouseDownTime;\n lastMouseDown = event;\n lastMouseDownTime = Date.now();\n return lastMouseDownCount = !last || (lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 &&\n Math.abs(last.clientY - event.clientY) < 2) ? (lastMouseDownCount + 1) % 3 : 1;\n}\nfunction basicMouseSelection(view, event) {\n let start = queryPos(view, event), type = getClickType(event);\n let startSel = view.state.selection;\n return {\n update(update) {\n if (update.docChanged) {\n start.pos = update.changes.mapPos(start.pos);\n startSel = startSel.map(update.changes);\n }\n },\n get(event, extend, multiple) {\n let cur = queryPos(view, event), removed;\n let range = rangeForClick(view, cur.pos, cur.bias, type);\n if (start.pos != cur.pos && !extend) {\n let startRange = rangeForClick(view, start.pos, start.bias, type);\n let from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to);\n range = from < range.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from);\n }\n if (extend)\n return startSel.replaceRange(startSel.main.extend(range.from, range.to));\n else if (multiple && type == 1 && startSel.ranges.length > 1 && (removed = removeRangeAround(startSel, cur.pos)))\n return removed;\n else if (multiple)\n return startSel.addRange(range);\n else\n return EditorSelection.create([range]);\n }\n };\n}\nfunction removeRangeAround(sel, pos) {\n for (let i = 0; i < sel.ranges.length; i++) {\n let { from, to } = sel.ranges[i];\n if (from <= pos && to >= pos)\n return EditorSelection.create(sel.ranges.slice(0, i).concat(sel.ranges.slice(i + 1)), sel.mainIndex == i ? 0 : sel.mainIndex - (sel.mainIndex > i ? 1 : 0));\n }\n return null;\n}\nhandlers.dragstart = (view, event) => {\n let { selection: { main: range } } = view.state;\n if (event.target.draggable) {\n let cView = view.docView.nearest(event.target);\n if (cView && cView.isWidget) {\n let from = cView.posAtStart, to = from + cView.length;\n if (from >= range.to || to <= range.from)\n range = EditorSelection.range(from, to);\n }\n }\n let { inputState } = view;\n if (inputState.mouseSelection)\n inputState.mouseSelection.dragging = true;\n inputState.draggedContent = range;\n if (event.dataTransfer) {\n event.dataTransfer.setData(\"Text\", view.state.sliceDoc(range.from, range.to));\n event.dataTransfer.effectAllowed = \"copyMove\";\n }\n return false;\n};\nhandlers.dragend = view => {\n view.inputState.draggedContent = null;\n return false;\n};\nfunction dropText(view, event, text, direct) {\n if (!text)\n return;\n let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);\n let { draggedContent } = view.inputState;\n let del = direct && draggedContent && dragMovesSelection(view, event)\n ? { from: draggedContent.from, to: draggedContent.to } : null;\n let ins = { from: dropPos, insert: text };\n let changes = view.state.changes(del ? [del, ins] : ins);\n view.focus();\n view.dispatch({\n changes,\n selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) },\n userEvent: del ? \"move.drop\" : \"input.drop\"\n });\n view.inputState.draggedContent = null;\n}\nhandlers.drop = (view, event) => {\n if (!event.dataTransfer)\n return false;\n if (view.state.readOnly)\n return true;\n let files = event.dataTransfer.files;\n if (files && files.length) { // For a file drop, read the file's text.\n let text = Array(files.length), read = 0;\n let finishFile = () => {\n if (++read == files.length)\n dropText(view, event, text.filter(s => s != null).join(view.state.lineBreak), false);\n };\n for (let i = 0; i < files.length; i++) {\n let reader = new FileReader;\n reader.onerror = finishFile;\n reader.onload = () => {\n if (!/[\\x00-\\x08\\x0e-\\x1f]{2}/.test(reader.result))\n text[i] = reader.result;\n finishFile();\n };\n reader.readAsText(files[i]);\n }\n return true;\n }\n else {\n let text = event.dataTransfer.getData(\"Text\");\n if (text) {\n dropText(view, event, text, true);\n return true;\n }\n }\n return false;\n};\nhandlers.paste = (view, event) => {\n if (view.state.readOnly)\n return true;\n view.observer.flush();\n let data = brokenClipboardAPI ? null : event.clipboardData;\n if (data) {\n doPaste(view, data.getData(\"text/plain\") || data.getData(\"text/uri-text\"));\n return true;\n }\n else {\n capturePaste(view);\n return false;\n }\n};\nfunction captureCopy(view, text) {\n // The extra wrapper is somehow necessary on IE/Edge to prevent the\n // content from being mangled when it is put onto the clipboard\n let parent = view.dom.parentNode;\n if (!parent)\n return;\n let target = parent.appendChild(document.createElement(\"textarea\"));\n target.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n target.value = text;\n target.focus();\n target.selectionEnd = text.length;\n target.selectionStart = 0;\n setTimeout(() => {\n target.remove();\n view.focus();\n }, 50);\n}\nfunction copiedRange(state) {\n let content = [], ranges = [], linewise = false;\n for (let range of state.selection.ranges)\n if (!range.empty) {\n content.push(state.sliceDoc(range.from, range.to));\n ranges.push(range);\n }\n if (!content.length) {\n // Nothing selected, do a line-wise copy\n let upto = -1;\n for (let { from } of state.selection.ranges) {\n let line = state.doc.lineAt(from);\n if (line.number > upto) {\n content.push(line.text);\n ranges.push({ from: line.from, to: Math.min(state.doc.length, line.to + 1) });\n }\n upto = line.number;\n }\n linewise = true;\n }\n return { text: content.join(state.lineBreak), ranges, linewise };\n}\nlet lastLinewiseCopy = null;\nhandlers.copy = handlers.cut = (view, event) => {\n let { text, ranges, linewise } = copiedRange(view.state);\n if (!text && !linewise)\n return false;\n lastLinewiseCopy = linewise ? text : null;\n if (event.type == \"cut\" && !view.state.readOnly)\n view.dispatch({\n changes: ranges,\n scrollIntoView: true,\n userEvent: \"delete.cut\"\n });\n let data = brokenClipboardAPI ? null : event.clipboardData;\n if (data) {\n data.clearData();\n data.setData(\"text/plain\", text);\n return true;\n }\n else {\n captureCopy(view, text);\n return false;\n }\n};\nconst isFocusChange = /*@__PURE__*/Annotation.define();\nfunction focusChangeTransaction(state, focus) {\n let effects = [];\n for (let getEffect of state.facet(focusChangeEffect)) {\n let effect = getEffect(state, focus);\n if (effect)\n effects.push(effect);\n }\n return effects ? state.update({ effects, annotations: isFocusChange.of(true) }) : null;\n}\nfunction updateForFocusChange(view) {\n setTimeout(() => {\n let focus = view.hasFocus;\n if (focus != view.inputState.notifiedFocused) {\n let tr = focusChangeTransaction(view.state, focus);\n if (tr)\n view.dispatch(tr);\n else\n view.update([]);\n }\n }, 10);\n}\nobservers.focus = view => {\n view.inputState.lastFocusTime = Date.now();\n // When focusing reset the scroll position, move it back to where it was\n if (!view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft)) {\n view.scrollDOM.scrollTop = view.inputState.lastScrollTop;\n view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft;\n }\n updateForFocusChange(view);\n};\nobservers.blur = view => {\n view.observer.clearSelectionRange();\n updateForFocusChange(view);\n};\nobservers.compositionstart = observers.compositionupdate = view => {\n if (view.inputState.compositionFirstChange == null)\n view.inputState.compositionFirstChange = true;\n if (view.inputState.composing < 0) {\n // FIXME possibly set a timeout to clear it again on Android\n view.inputState.composing = 0;\n }\n};\nobservers.compositionend = view => {\n view.inputState.composing = -1;\n view.inputState.compositionEndedAt = Date.now();\n view.inputState.compositionPendingKey = true;\n view.inputState.compositionPendingChange = view.observer.pendingRecords().length > 0;\n view.inputState.compositionFirstChange = null;\n if (browser.chrome && browser.android) {\n // Delay flushing for a bit on Android because it'll often fire a\n // bunch of contradictory changes in a row at end of compositon\n view.observer.flushSoon();\n }\n else if (view.inputState.compositionPendingChange) {\n // If we found pending records, schedule a flush.\n Promise.resolve().then(() => view.observer.flush());\n }\n else {\n // Otherwise, make sure that, if no changes come in soon, the\n // composition view is cleared.\n setTimeout(() => {\n if (view.inputState.composing < 0 && view.docView.hasComposition)\n view.update([]);\n }, 50);\n }\n};\nobservers.contextmenu = view => {\n view.inputState.lastContextMenu = Date.now();\n};\nhandlers.beforeinput = (view, event) => {\n var _a;\n // Because Chrome Android doesn't fire useful key events, use\n // beforeinput to detect backspace (and possibly enter and delete,\n // but those usually don't even seem to fire beforeinput events at\n // the moment) and fake a key event for it.\n //\n // (preventDefault on beforeinput, though supported in the spec,\n // seems to do nothing at all on Chrome).\n let pending;\n if (browser.chrome && browser.android && (pending = PendingKeys.find(key => key.inputType == event.inputType))) {\n view.observer.delayAndroidKey(pending.key, pending.keyCode);\n if (pending.key == \"Backspace\" || pending.key == \"Delete\") {\n let startViewHeight = ((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0;\n setTimeout(() => {\n var _a;\n // Backspacing near uneditable nodes on Chrome Android sometimes\n // closes the virtual keyboard. This tries to crudely detect\n // that and refocus to get it back.\n if ((((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0) > startViewHeight + 10 && view.hasFocus) {\n view.contentDOM.blur();\n view.focus();\n }\n }, 100);\n }\n }\n return false;\n};\nconst appliedFirefoxHack = /*@__PURE__*/new Set;\n// In Firefox, when cut/copy handlers are added to the document, that\n// somehow avoids a bug where those events aren't fired when the\n// selection is empty. See https://github.com/codemirror/dev/issues/1082\n// and https://bugzilla.mozilla.org/show_bug.cgi?id=995961\nfunction firefoxCopyCutHack(doc) {\n if (!appliedFirefoxHack.has(doc)) {\n appliedFirefoxHack.add(doc);\n doc.addEventListener(\"copy\", () => { });\n doc.addEventListener(\"cut\", () => { });\n }\n}\n\nconst wrappingWhiteSpace = [\"pre-wrap\", \"normal\", \"pre-line\", \"break-spaces\"];\nclass HeightOracle {\n constructor(lineWrapping) {\n this.lineWrapping = lineWrapping;\n this.doc = Text.empty;\n this.heightSamples = {};\n this.lineHeight = 14; // The height of an entire line (line-height)\n this.charWidth = 7;\n this.textHeight = 14; // The height of the actual font (font-size)\n this.lineLength = 30;\n // Used to track, during updateHeight, if any actual heights changed\n this.heightChanged = false;\n }\n heightForGap(from, to) {\n let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1;\n if (this.lineWrapping)\n lines += Math.max(0, Math.ceil(((to - from) - (lines * this.lineLength * 0.5)) / this.lineLength));\n return this.lineHeight * lines;\n }\n heightForLine(length) {\n if (!this.lineWrapping)\n return this.lineHeight;\n let lines = 1 + Math.max(0, Math.ceil((length - this.lineLength) / (this.lineLength - 5)));\n return lines * this.lineHeight;\n }\n setDoc(doc) { this.doc = doc; return this; }\n mustRefreshForWrapping(whiteSpace) {\n return (wrappingWhiteSpace.indexOf(whiteSpace) > -1) != this.lineWrapping;\n }\n mustRefreshForHeights(lineHeights) {\n let newHeight = false;\n for (let i = 0; i < lineHeights.length; i++) {\n let h = lineHeights[i];\n if (h < 0) {\n i++;\n }\n else if (!this.heightSamples[Math.floor(h * 10)]) { // Round to .1 pixels\n newHeight = true;\n this.heightSamples[Math.floor(h * 10)] = true;\n }\n }\n return newHeight;\n }\n refresh(whiteSpace, lineHeight, charWidth, textHeight, lineLength, knownHeights) {\n let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1;\n let changed = Math.round(lineHeight) != Math.round(this.lineHeight) || this.lineWrapping != lineWrapping;\n this.lineWrapping = lineWrapping;\n this.lineHeight = lineHeight;\n this.charWidth = charWidth;\n this.textHeight = textHeight;\n this.lineLength = lineLength;\n if (changed) {\n this.heightSamples = {};\n for (let i = 0; i < knownHeights.length; i++) {\n let h = knownHeights[i];\n if (h < 0)\n i++;\n else\n this.heightSamples[Math.floor(h * 10)] = true;\n }\n }\n return changed;\n }\n}\n// This object is used by `updateHeight` to make DOM measurements\n// arrive at the right nides. The `heights` array is a sequence of\n// block heights, starting from position `from`.\nclass MeasuredHeights {\n constructor(from, heights) {\n this.from = from;\n this.heights = heights;\n this.index = 0;\n }\n get more() { return this.index < this.heights.length; }\n}\n/**\nRecord used to represent information about a block-level element\nin the editor view.\n*/\nclass BlockInfo {\n /**\n @internal\n */\n constructor(\n /**\n The start of the element in the document.\n */\n from, \n /**\n The length of the element.\n */\n length, \n /**\n The top position of the element (relative to the top of the\n document).\n */\n top, \n /**\n Its height.\n */\n height, \n /**\n @internal Weird packed field that holds an array of children\n for composite blocks, a decoration for block widgets, and a\n number indicating the amount of widget-create line breaks for\n text blocks.\n */\n _content) {\n this.from = from;\n this.length = length;\n this.top = top;\n this.height = height;\n this._content = _content;\n }\n /**\n The type of element this is. When querying lines, this may be\n an array of all the blocks that make up the line.\n */\n get type() {\n return typeof this._content == \"number\" ? BlockType.Text :\n Array.isArray(this._content) ? this._content : this._content.type;\n }\n /**\n The end of the element as a document position.\n */\n get to() { return this.from + this.length; }\n /**\n The bottom position of the element.\n */\n get bottom() { return this.top + this.height; }\n /**\n If this is a widget block, this will return the widget\n associated with it.\n */\n get widget() {\n return this._content instanceof PointDecoration ? this._content.widget : null;\n }\n /**\n If this is a textblock, this holds the number of line breaks\n that appear in widgets inside the block.\n */\n get widgetLineBreaks() {\n return typeof this._content == \"number\" ? this._content : 0;\n }\n /**\n @internal\n */\n join(other) {\n let content = (Array.isArray(this._content) ? this._content : [this])\n .concat(Array.isArray(other._content) ? other._content : [other]);\n return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, content);\n }\n}\nvar QueryType = /*@__PURE__*/(function (QueryType) {\n QueryType[QueryType[\"ByPos\"] = 0] = \"ByPos\";\n QueryType[QueryType[\"ByHeight\"] = 1] = \"ByHeight\";\n QueryType[QueryType[\"ByPosNoHeight\"] = 2] = \"ByPosNoHeight\";\nreturn QueryType})(QueryType || (QueryType = {}));\nconst Epsilon = 1e-3;\nclass HeightMap {\n constructor(length, // The number of characters covered\n height, // Height of this part of the document\n flags = 2 /* Flag.Outdated */) {\n this.length = length;\n this.height = height;\n this.flags = flags;\n }\n get outdated() { return (this.flags & 2 /* Flag.Outdated */) > 0; }\n set outdated(value) { this.flags = (value ? 2 /* Flag.Outdated */ : 0) | (this.flags & ~2 /* Flag.Outdated */); }\n setHeight(oracle, height) {\n if (this.height != height) {\n if (Math.abs(this.height - height) > Epsilon)\n oracle.heightChanged = true;\n this.height = height;\n }\n }\n // Base case is to replace a leaf node, which simply builds a tree\n // from the new nodes and returns that (HeightMapBranch and\n // HeightMapGap override this to actually use from/to)\n replace(_from, _to, nodes) {\n return HeightMap.of(nodes);\n }\n // Again, these are base cases, and are overridden for branch and gap nodes.\n decomposeLeft(_to, result) { result.push(this); }\n decomposeRight(_from, result) { result.push(this); }\n applyChanges(decorations, oldDoc, oracle, changes) {\n let me = this, doc = oracle.doc;\n for (let i = changes.length - 1; i >= 0; i--) {\n let { fromA, toA, fromB, toB } = changes[i];\n let start = me.lineAt(fromA, QueryType.ByPosNoHeight, oracle.setDoc(oldDoc), 0, 0);\n let end = start.to >= toA ? start : me.lineAt(toA, QueryType.ByPosNoHeight, oracle, 0, 0);\n toB += end.to - toA;\n toA = end.to;\n while (i > 0 && start.from <= changes[i - 1].toA) {\n fromA = changes[i - 1].fromA;\n fromB = changes[i - 1].fromB;\n i--;\n if (fromA < start.from)\n start = me.lineAt(fromA, QueryType.ByPosNoHeight, oracle, 0, 0);\n }\n fromB += start.from - fromA;\n fromA = start.from;\n let nodes = NodeBuilder.build(oracle.setDoc(doc), decorations, fromB, toB);\n me = me.replace(fromA, toA, nodes);\n }\n return me.updateHeight(oracle, 0);\n }\n static empty() { return new HeightMapText(0, 0); }\n // nodes uses null values to indicate the position of line breaks.\n // There are never line breaks at the start or end of the array, or\n // two line breaks next to each other, and the array isn't allowed\n // to be empty (same restrictions as return value from the builder).\n static of(nodes) {\n if (nodes.length == 1)\n return nodes[0];\n let i = 0, j = nodes.length, before = 0, after = 0;\n for (;;) {\n if (i == j) {\n if (before > after * 2) {\n let split = nodes[i - 1];\n if (split.break)\n nodes.splice(--i, 1, split.left, null, split.right);\n else\n nodes.splice(--i, 1, split.left, split.right);\n j += 1 + split.break;\n before -= split.size;\n }\n else if (after > before * 2) {\n let split = nodes[j];\n if (split.break)\n nodes.splice(j, 1, split.left, null, split.right);\n else\n nodes.splice(j, 1, split.left, split.right);\n j += 2 + split.break;\n after -= split.size;\n }\n else {\n break;\n }\n }\n else if (before < after) {\n let next = nodes[i++];\n if (next)\n before += next.size;\n }\n else {\n let next = nodes[--j];\n if (next)\n after += next.size;\n }\n }\n let brk = 0;\n if (nodes[i - 1] == null) {\n brk = 1;\n i--;\n }\n else if (nodes[i] == null) {\n brk = 1;\n j++;\n }\n return new HeightMapBranch(HeightMap.of(nodes.slice(0, i)), brk, HeightMap.of(nodes.slice(j)));\n }\n}\nHeightMap.prototype.size = 1;\nclass HeightMapBlock extends HeightMap {\n constructor(length, height, deco) {\n super(length, height);\n this.deco = deco;\n }\n blockAt(_height, _oracle, top, offset) {\n return new BlockInfo(offset, this.length, top, this.height, this.deco || 0);\n }\n lineAt(_value, _type, oracle, top, offset) {\n return this.blockAt(0, oracle, top, offset);\n }\n forEachLine(from, to, oracle, top, offset, f) {\n if (from <= offset + this.length && to >= offset)\n f(this.blockAt(0, oracle, top, offset));\n }\n updateHeight(oracle, offset = 0, _force = false, measured) {\n if (measured && measured.from <= offset && measured.more)\n this.setHeight(oracle, measured.heights[measured.index++]);\n this.outdated = false;\n return this;\n }\n toString() { return `block(${this.length})`; }\n}\nclass HeightMapText extends HeightMapBlock {\n constructor(length, height) {\n super(length, height, null);\n this.collapsed = 0; // Amount of collapsed content in the line\n this.widgetHeight = 0; // Maximum inline widget height\n this.breaks = 0; // Number of widget-introduced line breaks on the line\n }\n blockAt(_height, _oracle, top, offset) {\n return new BlockInfo(offset, this.length, top, this.height, this.breaks);\n }\n replace(_from, _to, nodes) {\n let node = nodes[0];\n if (nodes.length == 1 && (node instanceof HeightMapText || node instanceof HeightMapGap && (node.flags & 4 /* Flag.SingleLine */)) &&\n Math.abs(this.length - node.length) < 10) {\n if (node instanceof HeightMapGap)\n node = new HeightMapText(node.length, this.height);\n else\n node.height = this.height;\n if (!this.outdated)\n node.outdated = false;\n return node;\n }\n else {\n return HeightMap.of(nodes);\n }\n }\n updateHeight(oracle, offset = 0, force = false, measured) {\n if (measured && measured.from <= offset && measured.more)\n this.setHeight(oracle, measured.heights[measured.index++]);\n else if (force || this.outdated)\n this.setHeight(oracle, Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed)) +\n this.breaks * oracle.lineHeight);\n this.outdated = false;\n return this;\n }\n toString() {\n return `line(${this.length}${this.collapsed ? -this.collapsed : \"\"}${this.widgetHeight ? \":\" + this.widgetHeight : \"\"})`;\n }\n}\nclass HeightMapGap extends HeightMap {\n constructor(length) { super(length, 0); }\n heightMetrics(oracle, offset) {\n let firstLine = oracle.doc.lineAt(offset).number, lastLine = oracle.doc.lineAt(offset + this.length).number;\n let lines = lastLine - firstLine + 1;\n let perLine, perChar = 0;\n if (oracle.lineWrapping) {\n let totalPerLine = Math.min(this.height, oracle.lineHeight * lines);\n perLine = totalPerLine / lines;\n if (this.length > lines + 1)\n perChar = (this.height - totalPerLine) / (this.length - lines - 1);\n }\n else {\n perLine = this.height / lines;\n }\n return { firstLine, lastLine, perLine, perChar };\n }\n blockAt(height, oracle, top, offset) {\n let { firstLine, lastLine, perLine, perChar } = this.heightMetrics(oracle, offset);\n if (oracle.lineWrapping) {\n let guess = offset + Math.round(Math.max(0, Math.min(1, (height - top) / this.height)) * this.length);\n let line = oracle.doc.lineAt(guess), lineHeight = perLine + line.length * perChar;\n let lineTop = Math.max(top, height - lineHeight / 2);\n return new BlockInfo(line.from, line.length, lineTop, lineHeight, 0);\n }\n else {\n let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top) / perLine)));\n let { from, length } = oracle.doc.line(firstLine + line);\n return new BlockInfo(from, length, top + perLine * line, perLine, 0);\n }\n }\n lineAt(value, type, oracle, top, offset) {\n if (type == QueryType.ByHeight)\n return this.blockAt(value, oracle, top, offset);\n if (type == QueryType.ByPosNoHeight) {\n let { from, to } = oracle.doc.lineAt(value);\n return new BlockInfo(from, to - from, 0, 0, 0);\n }\n let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);\n let line = oracle.doc.lineAt(value), lineHeight = perLine + line.length * perChar;\n let linesAbove = line.number - firstLine;\n let lineTop = top + perLine * linesAbove + perChar * (line.from - offset - linesAbove);\n return new BlockInfo(line.from, line.length, Math.max(top, Math.min(lineTop, top + this.height - lineHeight)), lineHeight, 0);\n }\n forEachLine(from, to, oracle, top, offset, f) {\n from = Math.max(from, offset);\n to = Math.min(to, offset + this.length);\n let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);\n for (let pos = from, lineTop = top; pos <= to;) {\n let line = oracle.doc.lineAt(pos);\n if (pos == from) {\n let linesAbove = line.number - firstLine;\n lineTop += perLine * linesAbove + perChar * (from - offset - linesAbove);\n }\n let lineHeight = perLine + perChar * line.length;\n f(new BlockInfo(line.from, line.length, lineTop, lineHeight, 0));\n lineTop += lineHeight;\n pos = line.to + 1;\n }\n }\n replace(from, to, nodes) {\n let after = this.length - to;\n if (after > 0) {\n let last = nodes[nodes.length - 1];\n if (last instanceof HeightMapGap)\n nodes[nodes.length - 1] = new HeightMapGap(last.length + after);\n else\n nodes.push(null, new HeightMapGap(after - 1));\n }\n if (from > 0) {\n let first = nodes[0];\n if (first instanceof HeightMapGap)\n nodes[0] = new HeightMapGap(from + first.length);\n else\n nodes.unshift(new HeightMapGap(from - 1), null);\n }\n return HeightMap.of(nodes);\n }\n decomposeLeft(to, result) {\n result.push(new HeightMapGap(to - 1), null);\n }\n decomposeRight(from, result) {\n result.push(null, new HeightMapGap(this.length - from - 1));\n }\n updateHeight(oracle, offset = 0, force = false, measured) {\n let end = offset + this.length;\n if (measured && measured.from <= offset + this.length && measured.more) {\n // Fill in part of this gap with measured lines. We know there\n // can't be widgets or collapsed ranges in those lines, because\n // they would already have been added to the heightmap (gaps\n // only contain plain text).\n let nodes = [], pos = Math.max(offset, measured.from), singleHeight = -1;\n if (measured.from > offset)\n nodes.push(new HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset));\n while (pos <= end && measured.more) {\n let len = oracle.doc.lineAt(pos).length;\n if (nodes.length)\n nodes.push(null);\n let height = measured.heights[measured.index++];\n if (singleHeight == -1)\n singleHeight = height;\n else if (Math.abs(height - singleHeight) >= Epsilon)\n singleHeight = -2;\n let line = new HeightMapText(len, height);\n line.outdated = false;\n nodes.push(line);\n pos += len + 1;\n }\n if (pos <= end)\n nodes.push(null, new HeightMapGap(end - pos).updateHeight(oracle, pos));\n let result = HeightMap.of(nodes);\n if (singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon ||\n Math.abs(singleHeight - this.heightMetrics(oracle, offset).perLine) >= Epsilon)\n oracle.heightChanged = true;\n return result;\n }\n else if (force || this.outdated) {\n this.setHeight(oracle, oracle.heightForGap(offset, offset + this.length));\n this.outdated = false;\n }\n return this;\n }\n toString() { return `gap(${this.length})`; }\n}\nclass HeightMapBranch extends HeightMap {\n constructor(left, brk, right) {\n super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 /* Flag.Outdated */ : 0));\n this.left = left;\n this.right = right;\n this.size = left.size + right.size;\n }\n get break() { return this.flags & 1 /* Flag.Break */; }\n blockAt(height, oracle, top, offset) {\n let mid = top + this.left.height;\n return height < mid ? this.left.blockAt(height, oracle, top, offset)\n : this.right.blockAt(height, oracle, mid, offset + this.left.length + this.break);\n }\n lineAt(value, type, oracle, top, offset) {\n let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break;\n let left = type == QueryType.ByHeight ? value < rightTop : value < rightOffset;\n let base = left ? this.left.lineAt(value, type, oracle, top, offset)\n : this.right.lineAt(value, type, oracle, rightTop, rightOffset);\n if (this.break || (left ? base.to < rightOffset : base.from > rightOffset))\n return base;\n let subQuery = type == QueryType.ByPosNoHeight ? QueryType.ByPosNoHeight : QueryType.ByPos;\n if (left)\n return base.join(this.right.lineAt(rightOffset, subQuery, oracle, rightTop, rightOffset));\n else\n return this.left.lineAt(rightOffset, subQuery, oracle, top, offset).join(base);\n }\n forEachLine(from, to, oracle, top, offset, f) {\n let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break;\n if (this.break) {\n if (from < rightOffset)\n this.left.forEachLine(from, to, oracle, top, offset, f);\n if (to >= rightOffset)\n this.right.forEachLine(from, to, oracle, rightTop, rightOffset, f);\n }\n else {\n let mid = this.lineAt(rightOffset, QueryType.ByPos, oracle, top, offset);\n if (from < mid.from)\n this.left.forEachLine(from, mid.from - 1, oracle, top, offset, f);\n if (mid.to >= from && mid.from <= to)\n f(mid);\n if (to > mid.to)\n this.right.forEachLine(mid.to + 1, to, oracle, rightTop, rightOffset, f);\n }\n }\n replace(from, to, nodes) {\n let rightStart = this.left.length + this.break;\n if (to < rightStart)\n return this.balanced(this.left.replace(from, to, nodes), this.right);\n if (from > this.left.length)\n return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes));\n let result = [];\n if (from > 0)\n this.decomposeLeft(from, result);\n let left = result.length;\n for (let node of nodes)\n result.push(node);\n if (from > 0)\n mergeGaps(result, left - 1);\n if (to < this.length) {\n let right = result.length;\n this.decomposeRight(to, result);\n mergeGaps(result, right);\n }\n return HeightMap.of(result);\n }\n decomposeLeft(to, result) {\n let left = this.left.length;\n if (to <= left)\n return this.left.decomposeLeft(to, result);\n result.push(this.left);\n if (this.break) {\n left++;\n if (to >= left)\n result.push(null);\n }\n if (to > left)\n this.right.decomposeLeft(to - left, result);\n }\n decomposeRight(from, result) {\n let left = this.left.length, right = left + this.break;\n if (from >= right)\n return this.right.decomposeRight(from - right, result);\n if (from < left)\n this.left.decomposeRight(from, result);\n if (this.break && from < right)\n result.push(null);\n result.push(this.right);\n }\n balanced(left, right) {\n if (left.size > 2 * right.size || right.size > 2 * left.size)\n return HeightMap.of(this.break ? [left, null, right] : [left, right]);\n this.left = left;\n this.right = right;\n this.height = left.height + right.height;\n this.outdated = left.outdated || right.outdated;\n this.size = left.size + right.size;\n this.length = left.length + this.break + right.length;\n return this;\n }\n updateHeight(oracle, offset = 0, force = false, measured) {\n let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null;\n if (measured && measured.from <= offset + left.length && measured.more)\n rebalance = left = left.updateHeight(oracle, offset, force, measured);\n else\n left.updateHeight(oracle, offset, force);\n if (measured && measured.from <= rightStart + right.length && measured.more)\n rebalance = right = right.updateHeight(oracle, rightStart, force, measured);\n else\n right.updateHeight(oracle, rightStart, force);\n if (rebalance)\n return this.balanced(left, right);\n this.height = this.left.height + this.right.height;\n this.outdated = false;\n return this;\n }\n toString() { return this.left + (this.break ? \" \" : \"-\") + this.right; }\n}\nfunction mergeGaps(nodes, around) {\n let before, after;\n if (nodes[around] == null &&\n (before = nodes[around - 1]) instanceof HeightMapGap &&\n (after = nodes[around + 1]) instanceof HeightMapGap)\n nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length));\n}\nconst relevantWidgetHeight = 5;\nclass NodeBuilder {\n constructor(pos, oracle) {\n this.pos = pos;\n this.oracle = oracle;\n this.nodes = [];\n this.lineStart = -1;\n this.lineEnd = -1;\n this.covering = null;\n this.writtenTo = pos;\n }\n get isCovered() {\n return this.covering && this.nodes[this.nodes.length - 1] == this.covering;\n }\n span(_from, to) {\n if (this.lineStart > -1) {\n let end = Math.min(to, this.lineEnd), last = this.nodes[this.nodes.length - 1];\n if (last instanceof HeightMapText)\n last.length += end - this.pos;\n else if (end > this.pos || !this.isCovered)\n this.nodes.push(new HeightMapText(end - this.pos, -1));\n this.writtenTo = end;\n if (to > end) {\n this.nodes.push(null);\n this.writtenTo++;\n this.lineStart = -1;\n }\n }\n this.pos = to;\n }\n point(from, to, deco) {\n if (from < to || deco.heightRelevant) {\n let height = deco.widget ? deco.widget.estimatedHeight : 0;\n let breaks = deco.widget ? deco.widget.lineBreaks : 0;\n if (height < 0)\n height = this.oracle.lineHeight;\n let len = to - from;\n if (deco.block) {\n this.addBlock(new HeightMapBlock(len, height, deco));\n }\n else if (len || breaks || height >= relevantWidgetHeight) {\n this.addLineDeco(height, breaks, len);\n }\n }\n else if (to > from) {\n this.span(from, to);\n }\n if (this.lineEnd > -1 && this.lineEnd < this.pos)\n this.lineEnd = this.oracle.doc.lineAt(this.pos).to;\n }\n enterLine() {\n if (this.lineStart > -1)\n return;\n let { from, to } = this.oracle.doc.lineAt(this.pos);\n this.lineStart = from;\n this.lineEnd = to;\n if (this.writtenTo < from) {\n if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null)\n this.nodes.push(this.blankContent(this.writtenTo, from - 1));\n this.nodes.push(null);\n }\n if (this.pos > from)\n this.nodes.push(new HeightMapText(this.pos - from, -1));\n this.writtenTo = this.pos;\n }\n blankContent(from, to) {\n let gap = new HeightMapGap(to - from);\n if (this.oracle.doc.lineAt(from).to == to)\n gap.flags |= 4 /* Flag.SingleLine */;\n return gap;\n }\n ensureLine() {\n this.enterLine();\n let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null;\n if (last instanceof HeightMapText)\n return last;\n let line = new HeightMapText(0, -1);\n this.nodes.push(line);\n return line;\n }\n addBlock(block) {\n this.enterLine();\n let deco = block.deco;\n if (deco && deco.startSide > 0 && !this.isCovered)\n this.ensureLine();\n this.nodes.push(block);\n this.writtenTo = this.pos = this.pos + block.length;\n if (deco && deco.endSide > 0)\n this.covering = block;\n }\n addLineDeco(height, breaks, length) {\n let line = this.ensureLine();\n line.length += length;\n line.collapsed += length;\n line.widgetHeight = Math.max(line.widgetHeight, height);\n line.breaks += breaks;\n this.writtenTo = this.pos = this.pos + length;\n }\n finish(from) {\n let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1];\n if (this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered)\n this.nodes.push(new HeightMapText(0, -1));\n else if (this.writtenTo < this.pos || last == null)\n this.nodes.push(this.blankContent(this.writtenTo, this.pos));\n let pos = from;\n for (let node of this.nodes) {\n if (node instanceof HeightMapText)\n node.updateHeight(this.oracle, pos);\n pos += node ? node.length : 1;\n }\n return this.nodes;\n }\n // Always called with a region that on both sides either stretches\n // to a line break or the end of the document.\n // The returned array uses null to indicate line breaks, but never\n // starts or ends in a line break, or has multiple line breaks next\n // to each other.\n static build(oracle, decorations, from, to) {\n let builder = new NodeBuilder(from, oracle);\n RangeSet.spans(decorations, from, to, builder, 0);\n return builder.finish(from);\n }\n}\nfunction heightRelevantDecoChanges(a, b, diff) {\n let comp = new DecorationComparator;\n RangeSet.compare(a, b, diff, comp, 0);\n return comp.changes;\n}\nclass DecorationComparator {\n constructor() {\n this.changes = [];\n }\n compareRange() { }\n comparePoint(from, to, a, b) {\n if (from < to || a && a.heightRelevant || b && b.heightRelevant)\n addRange(from, to, this.changes, 5);\n }\n}\n\nfunction visiblePixelRange(dom, paddingTop) {\n let rect = dom.getBoundingClientRect();\n let doc = dom.ownerDocument, win = doc.defaultView || window;\n let left = Math.max(0, rect.left), right = Math.min(win.innerWidth, rect.right);\n let top = Math.max(0, rect.top), bottom = Math.min(win.innerHeight, rect.bottom);\n for (let parent = dom.parentNode; parent && parent != doc.body;) {\n if (parent.nodeType == 1) {\n let elt = parent;\n let style = window.getComputedStyle(elt);\n if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) &&\n style.overflow != \"visible\") {\n let parentRect = elt.getBoundingClientRect();\n left = Math.max(left, parentRect.left);\n right = Math.min(right, parentRect.right);\n top = Math.max(top, parentRect.top);\n bottom = parent == dom.parentNode ? parentRect.bottom : Math.min(bottom, parentRect.bottom);\n }\n parent = style.position == \"absolute\" || style.position == \"fixed\" ? elt.offsetParent : elt.parentNode;\n }\n else if (parent.nodeType == 11) { // Shadow root\n parent = parent.host;\n }\n else {\n break;\n }\n }\n return { left: left - rect.left, right: Math.max(left, right) - rect.left,\n top: top - (rect.top + paddingTop), bottom: Math.max(top, bottom) - (rect.top + paddingTop) };\n}\nfunction fullPixelRange(dom, paddingTop) {\n let rect = dom.getBoundingClientRect();\n return { left: 0, right: rect.right - rect.left,\n top: paddingTop, bottom: rect.bottom - (rect.top + paddingTop) };\n}\n// Line gaps are placeholder widgets used to hide pieces of overlong\n// lines within the viewport, as a kludge to keep the editor\n// responsive when a ridiculously long line is loaded into it.\nclass LineGap {\n constructor(from, to, size) {\n this.from = from;\n this.to = to;\n this.size = size;\n }\n static same(a, b) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++) {\n let gA = a[i], gB = b[i];\n if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size)\n return false;\n }\n return true;\n }\n draw(viewState, wrapping) {\n return Decoration.replace({\n widget: new LineGapWidget(this.size * (wrapping ? viewState.scaleY : viewState.scaleX), wrapping)\n }).range(this.from, this.to);\n }\n}\nclass LineGapWidget extends WidgetType {\n constructor(size, vertical) {\n super();\n this.size = size;\n this.vertical = vertical;\n }\n eq(other) { return other.size == this.size && other.vertical == this.vertical; }\n toDOM() {\n let elt = document.createElement(\"div\");\n if (this.vertical) {\n elt.style.height = this.size + \"px\";\n }\n else {\n elt.style.width = this.size + \"px\";\n elt.style.height = \"2px\";\n elt.style.display = \"inline-block\";\n }\n return elt;\n }\n get estimatedHeight() { return this.vertical ? this.size : -1; }\n}\nclass ViewState {\n constructor(state) {\n this.state = state;\n // These are contentDOM-local coordinates\n this.pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 };\n this.inView = true;\n this.paddingTop = 0; // Padding above the document, scaled\n this.paddingBottom = 0; // Padding below the document, scaled\n this.contentDOMWidth = 0; // contentDOM.getBoundingClientRect().width\n this.contentDOMHeight = 0; // contentDOM.getBoundingClientRect().height\n this.editorHeight = 0; // scrollDOM.clientHeight, unscaled\n this.editorWidth = 0; // scrollDOM.clientWidth, unscaled\n this.scrollTop = 0; // Last seen scrollDOM.scrollTop, scaled\n this.scrolledToBottom = true;\n // The CSS-transformation scale of the editor (transformed size /\n // concrete size)\n this.scaleX = 1;\n this.scaleY = 1;\n // The vertical position (document-relative) to which to anchor the\n // scroll position. -1 means anchor to the end of the document.\n this.scrollAnchorPos = 0;\n // The height at the anchor position. Set by the DOM update phase.\n // -1 means no height available.\n this.scrollAnchorHeight = -1;\n // See VP.MaxDOMHeight\n this.scaler = IdScaler;\n this.scrollTarget = null;\n // Briefly set to true when printing, to disable viewport limiting\n this.printing = false;\n // Flag set when editor content was redrawn, so that the next\n // measure stage knows it must read DOM layout\n this.mustMeasureContent = true;\n this.defaultTextDirection = Direction.LTR;\n this.visibleRanges = [];\n // Cursor 'assoc' is only significant when the cursor is on a line\n // wrap point, where it must stick to the character that it is\n // associated with. Since browsers don't provide a reasonable\n // interface to set or query this, when a selection is set that\n // might cause this to be significant, this flag is set. The next\n // measure phase will check whether the cursor is on a line-wrapping\n // boundary and, if so, reset it to make sure it is positioned in\n // the right place.\n this.mustEnforceCursorAssoc = false;\n let guessWrapping = state.facet(contentAttributes).some(v => typeof v != \"function\" && v.class == \"cm-lineWrapping\");\n this.heightOracle = new HeightOracle(guessWrapping);\n this.stateDeco = state.facet(decorations).filter(d => typeof d != \"function\");\n this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]);\n this.viewport = this.getViewport(0, null);\n this.updateViewportLines();\n this.updateForViewport();\n this.lineGaps = this.ensureLineGaps([]);\n this.lineGapDeco = Decoration.set(this.lineGaps.map(gap => gap.draw(this, false)));\n this.computeVisibleRanges();\n }\n updateForViewport() {\n let viewports = [this.viewport], { main } = this.state.selection;\n for (let i = 0; i <= 1; i++) {\n let pos = i ? main.head : main.anchor;\n if (!viewports.some(({ from, to }) => pos >= from && pos <= to)) {\n let { from, to } = this.lineBlockAt(pos);\n viewports.push(new Viewport(from, to));\n }\n }\n this.viewports = viewports.sort((a, b) => a.from - b.from);\n this.scaler = this.heightMap.height <= 7000000 /* VP.MaxDOMHeight */ ? IdScaler :\n new BigScaler(this.heightOracle, this.heightMap, this.viewports);\n }\n updateViewportLines() {\n this.viewportLines = [];\n this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.heightOracle.setDoc(this.state.doc), 0, 0, block => {\n this.viewportLines.push(this.scaler.scale == 1 ? block : scaleBlock(block, this.scaler));\n });\n }\n update(update, scrollTarget = null) {\n this.state = update.state;\n let prevDeco = this.stateDeco;\n this.stateDeco = this.state.facet(decorations).filter(d => typeof d != \"function\");\n let contentChanges = update.changedRanges;\n let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length)));\n let prevHeight = this.heightMap.height;\n let scrollAnchor = this.scrolledToBottom ? null : this.scrollAnchorAt(this.scrollTop);\n this.heightMap = this.heightMap.applyChanges(this.stateDeco, update.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges);\n if (this.heightMap.height != prevHeight)\n update.flags |= 2 /* UpdateFlag.Height */;\n if (scrollAnchor) {\n this.scrollAnchorPos = update.changes.mapPos(scrollAnchor.from, -1);\n this.scrollAnchorHeight = scrollAnchor.top;\n }\n else {\n this.scrollAnchorPos = -1;\n this.scrollAnchorHeight = this.heightMap.height;\n }\n let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport;\n if (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) ||\n !this.viewportIsAppropriate(viewport))\n viewport = this.getViewport(0, scrollTarget);\n let updateLines = !update.changes.empty || (update.flags & 2 /* UpdateFlag.Height */) ||\n viewport.from != this.viewport.from || viewport.to != this.viewport.to;\n this.viewport = viewport;\n this.updateForViewport();\n if (updateLines)\n this.updateViewportLines();\n if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1))\n this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes)));\n update.flags |= this.computeVisibleRanges();\n if (scrollTarget)\n this.scrollTarget = scrollTarget;\n if (!this.mustEnforceCursorAssoc && update.selectionSet && update.view.lineWrapping &&\n update.state.selection.main.empty && update.state.selection.main.assoc &&\n !update.state.facet(nativeSelectionHidden))\n this.mustEnforceCursorAssoc = true;\n }\n measure(view) {\n let dom = view.contentDOM, style = window.getComputedStyle(dom);\n let oracle = this.heightOracle;\n let whiteSpace = style.whiteSpace;\n this.defaultTextDirection = style.direction == \"rtl\" ? Direction.RTL : Direction.LTR;\n let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace);\n let domRect = dom.getBoundingClientRect();\n let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != domRect.height;\n this.contentDOMHeight = domRect.height;\n this.mustMeasureContent = false;\n let result = 0, bias = 0;\n if (domRect.width && domRect.height) {\n let scaleX = domRect.width / dom.offsetWidth;\n let scaleY = domRect.height / dom.offsetHeight;\n if (scaleX > 0.995 && scaleX < 1.005 || !isFinite(scaleX) || Math.abs(domRect.width - dom.offsetWidth) < 1)\n scaleX = 1;\n if (scaleY > 0.995 && scaleY < 1.005 || !isFinite(scaleY) || Math.abs(domRect.height - dom.offsetHeight) < 1)\n scaleY = 1;\n if (this.scaleX != scaleX || this.scaleY != scaleY) {\n this.scaleX = scaleX;\n this.scaleY = scaleY;\n result |= 8 /* UpdateFlag.Geometry */;\n refresh = measureContent = true;\n }\n }\n // Vertical padding\n let paddingTop = (parseInt(style.paddingTop) || 0) * this.scaleY;\n let paddingBottom = (parseInt(style.paddingBottom) || 0) * this.scaleY;\n if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) {\n this.paddingTop = paddingTop;\n this.paddingBottom = paddingBottom;\n result |= 8 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */;\n }\n if (this.editorWidth != view.scrollDOM.clientWidth) {\n if (oracle.lineWrapping)\n measureContent = true;\n this.editorWidth = view.scrollDOM.clientWidth;\n result |= 8 /* UpdateFlag.Geometry */;\n }\n let scrollTop = view.scrollDOM.scrollTop * this.scaleY;\n if (this.scrollTop != scrollTop) {\n this.scrollAnchorHeight = -1;\n this.scrollTop = scrollTop;\n }\n this.scrolledToBottom = isScrolledToBottom(view.scrollDOM);\n // Pixel viewport\n let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop);\n let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom;\n this.pixelViewport = pixelViewport;\n let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left;\n if (inView != this.inView) {\n this.inView = inView;\n if (inView)\n measureContent = true;\n }\n if (!this.inView && !this.scrollTarget)\n return 0;\n let contentWidth = domRect.width;\n if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) {\n this.contentDOMWidth = domRect.width;\n this.editorHeight = view.scrollDOM.clientHeight;\n result |= 8 /* UpdateFlag.Geometry */;\n }\n if (measureContent) {\n let lineHeights = view.docView.measureVisibleLineHeights(this.viewport);\n if (oracle.mustRefreshForHeights(lineHeights))\n refresh = true;\n if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) {\n let { lineHeight, charWidth, textHeight } = view.docView.measureTextSize();\n refresh = lineHeight > 0 && oracle.refresh(whiteSpace, lineHeight, charWidth, textHeight, contentWidth / charWidth, lineHeights);\n if (refresh) {\n view.docView.minWidth = 0;\n result |= 8 /* UpdateFlag.Geometry */;\n }\n }\n if (dTop > 0 && dBottom > 0)\n bias = Math.max(dTop, dBottom);\n else if (dTop < 0 && dBottom < 0)\n bias = Math.min(dTop, dBottom);\n oracle.heightChanged = false;\n for (let vp of this.viewports) {\n let heights = vp.from == this.viewport.from ? lineHeights : view.docView.measureVisibleLineHeights(vp);\n this.heightMap = (refresh ? HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle, [new ChangedRange(0, 0, 0, view.state.doc.length)]) : this.heightMap).updateHeight(oracle, 0, refresh, new MeasuredHeights(vp.from, heights));\n }\n if (oracle.heightChanged)\n result |= 2 /* UpdateFlag.Height */;\n }\n let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) ||\n this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from ||\n this.scrollTarget.range.head > this.viewport.to);\n if (viewportChange)\n this.viewport = this.getViewport(bias, this.scrollTarget);\n this.updateForViewport();\n if ((result & 2 /* UpdateFlag.Height */) || viewportChange)\n this.updateViewportLines();\n if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1))\n this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view));\n result |= this.computeVisibleRanges();\n if (this.mustEnforceCursorAssoc) {\n this.mustEnforceCursorAssoc = false;\n // This is done in the read stage, because moving the selection\n // to a line end is going to trigger a layout anyway, so it\n // can't be a pure write. It should be rare that it does any\n // writing.\n view.docView.enforceCursorAssoc();\n }\n return result;\n }\n get visibleTop() { return this.scaler.fromDOM(this.pixelViewport.top); }\n get visibleBottom() { return this.scaler.fromDOM(this.pixelViewport.bottom); }\n getViewport(bias, scrollTarget) {\n // This will divide VP.Margin between the top and the\n // bottom, depending on the bias (the change in viewport position\n // since the last update). It'll hold a number between 0 and 1\n let marginTop = 0.5 - Math.max(-0.5, Math.min(0.5, bias / 1000 /* VP.Margin */ / 2));\n let map = this.heightMap, oracle = this.heightOracle;\n let { visibleTop, visibleBottom } = this;\n let viewport = new Viewport(map.lineAt(visibleTop - marginTop * 1000 /* VP.Margin */, QueryType.ByHeight, oracle, 0, 0).from, map.lineAt(visibleBottom + (1 - marginTop) * 1000 /* VP.Margin */, QueryType.ByHeight, oracle, 0, 0).to);\n // If scrollTarget is given, make sure the viewport includes that position\n if (scrollTarget) {\n let { head } = scrollTarget.range;\n if (head < viewport.from || head > viewport.to) {\n let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top);\n let block = map.lineAt(head, QueryType.ByPos, oracle, 0, 0), topPos;\n if (scrollTarget.y == \"center\")\n topPos = (block.top + block.bottom) / 2 - viewHeight / 2;\n else if (scrollTarget.y == \"start\" || scrollTarget.y == \"nearest\" && head < viewport.from)\n topPos = block.top;\n else\n topPos = block.bottom - viewHeight;\n viewport = new Viewport(map.lineAt(topPos - 1000 /* VP.Margin */ / 2, QueryType.ByHeight, oracle, 0, 0).from, map.lineAt(topPos + viewHeight + 1000 /* VP.Margin */ / 2, QueryType.ByHeight, oracle, 0, 0).to);\n }\n }\n return viewport;\n }\n mapViewport(viewport, changes) {\n let from = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1);\n return new Viewport(this.heightMap.lineAt(from, QueryType.ByPos, this.heightOracle, 0, 0).from, this.heightMap.lineAt(to, QueryType.ByPos, this.heightOracle, 0, 0).to);\n }\n // Checks if a given viewport covers the visible part of the\n // document and not too much beyond that.\n viewportIsAppropriate({ from, to }, bias = 0) {\n if (!this.inView)\n return true;\n let { top } = this.heightMap.lineAt(from, QueryType.ByPos, this.heightOracle, 0, 0);\n let { bottom } = this.heightMap.lineAt(to, QueryType.ByPos, this.heightOracle, 0, 0);\n let { visibleTop, visibleBottom } = this;\n return (from == 0 || top <= visibleTop - Math.max(10 /* VP.MinCoverMargin */, Math.min(-bias, 250 /* VP.MaxCoverMargin */))) &&\n (to == this.state.doc.length ||\n bottom >= visibleBottom + Math.max(10 /* VP.MinCoverMargin */, Math.min(bias, 250 /* VP.MaxCoverMargin */))) &&\n (top > visibleTop - 2 * 1000 /* VP.Margin */ && bottom < visibleBottom + 2 * 1000 /* VP.Margin */);\n }\n mapLineGaps(gaps, changes) {\n if (!gaps.length || changes.empty)\n return gaps;\n let mapped = [];\n for (let gap of gaps)\n if (!changes.touchesRange(gap.from, gap.to))\n mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size));\n return mapped;\n }\n // Computes positions in the viewport where the start or end of a\n // line should be hidden, trying to reuse existing line gaps when\n // appropriate to avoid unneccesary redraws.\n // Uses crude character-counting for the positioning and sizing,\n // since actual DOM coordinates aren't always available and\n // predictable. Relies on generous margins (see LG.Margin) to hide\n // the artifacts this might produce from the user.\n ensureLineGaps(current, mayMeasure) {\n let wrapping = this.heightOracle.lineWrapping;\n let margin = wrapping ? 10000 /* LG.MarginWrap */ : 2000 /* LG.Margin */, halfMargin = margin >> 1, doubleMargin = margin << 1;\n // The non-wrapping logic won't work at all in predominantly right-to-left text.\n if (this.defaultTextDirection != Direction.LTR && !wrapping)\n return [];\n let gaps = [];\n let addGap = (from, to, line, structure) => {\n if (to - from < halfMargin)\n return;\n let sel = this.state.selection.main, avoid = [sel.from];\n if (!sel.empty)\n avoid.push(sel.to);\n for (let pos of avoid) {\n if (pos > from && pos < to) {\n addGap(from, pos - 10 /* LG.SelectionMargin */, line, structure);\n addGap(pos + 10 /* LG.SelectionMargin */, to, line, structure);\n return;\n }\n }\n let gap = find(current, gap => gap.from >= line.from && gap.to <= line.to &&\n Math.abs(gap.from - from) < halfMargin && Math.abs(gap.to - to) < halfMargin &&\n !avoid.some(pos => gap.from < pos && gap.to > pos));\n if (!gap) {\n // When scrolling down, snap gap ends to line starts to avoid shifts in wrapping\n if (to < line.to && mayMeasure && wrapping &&\n mayMeasure.visibleRanges.some(r => r.from <= to && r.to >= to)) {\n let lineStart = mayMeasure.moveToLineBoundary(EditorSelection.cursor(to), false, true).head;\n if (lineStart > from)\n to = lineStart;\n }\n gap = new LineGap(from, to, this.gapSize(line, from, to, structure));\n }\n gaps.push(gap);\n };\n for (let line of this.viewportLines) {\n if (line.length < doubleMargin)\n continue;\n let structure = lineStructure(line.from, line.to, this.stateDeco);\n if (structure.total < doubleMargin)\n continue;\n let target = this.scrollTarget ? this.scrollTarget.range.head : null;\n let viewFrom, viewTo;\n if (wrapping) {\n let marginHeight = (margin / this.heightOracle.lineLength) * this.heightOracle.lineHeight;\n let top, bot;\n if (target != null) {\n let targetFrac = findFraction(structure, target);\n let spaceFrac = ((this.visibleBottom - this.visibleTop) / 2 + marginHeight) / line.height;\n top = targetFrac - spaceFrac;\n bot = targetFrac + spaceFrac;\n }\n else {\n top = (this.visibleTop - line.top - marginHeight) / line.height;\n bot = (this.visibleBottom - line.top + marginHeight) / line.height;\n }\n viewFrom = findPosition(structure, top);\n viewTo = findPosition(structure, bot);\n }\n else {\n let totalWidth = structure.total * this.heightOracle.charWidth;\n let marginWidth = margin * this.heightOracle.charWidth;\n let left, right;\n if (target != null) {\n let targetFrac = findFraction(structure, target);\n let spaceFrac = ((this.pixelViewport.right - this.pixelViewport.left) / 2 + marginWidth) / totalWidth;\n left = targetFrac - spaceFrac;\n right = targetFrac + spaceFrac;\n }\n else {\n left = (this.pixelViewport.left - marginWidth) / totalWidth;\n right = (this.pixelViewport.right + marginWidth) / totalWidth;\n }\n viewFrom = findPosition(structure, left);\n viewTo = findPosition(structure, right);\n }\n if (viewFrom > line.from)\n addGap(line.from, viewFrom, line, structure);\n if (viewTo < line.to)\n addGap(viewTo, line.to, line, structure);\n }\n return gaps;\n }\n gapSize(line, from, to, structure) {\n let fraction = findFraction(structure, to) - findFraction(structure, from);\n if (this.heightOracle.lineWrapping) {\n return line.height * fraction;\n }\n else {\n return structure.total * this.heightOracle.charWidth * fraction;\n }\n }\n updateLineGaps(gaps) {\n if (!LineGap.same(gaps, this.lineGaps)) {\n this.lineGaps = gaps;\n this.lineGapDeco = Decoration.set(gaps.map(gap => gap.draw(this, this.heightOracle.lineWrapping)));\n }\n }\n computeVisibleRanges() {\n let deco = this.stateDeco;\n if (this.lineGaps.length)\n deco = deco.concat(this.lineGapDeco);\n let ranges = [];\n RangeSet.spans(deco, this.viewport.from, this.viewport.to, {\n span(from, to) { ranges.push({ from, to }); },\n point() { }\n }, 20);\n let changed = ranges.length != this.visibleRanges.length ||\n this.visibleRanges.some((r, i) => r.from != ranges[i].from || r.to != ranges[i].to);\n this.visibleRanges = ranges;\n return changed ? 4 /* UpdateFlag.Viewport */ : 0;\n }\n lineBlockAt(pos) {\n return (pos >= this.viewport.from && pos <= this.viewport.to && this.viewportLines.find(b => b.from <= pos && b.to >= pos)) ||\n scaleBlock(this.heightMap.lineAt(pos, QueryType.ByPos, this.heightOracle, 0, 0), this.scaler);\n }\n lineBlockAtHeight(height) {\n return scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType.ByHeight, this.heightOracle, 0, 0), this.scaler);\n }\n scrollAnchorAt(scrollTop) {\n let block = this.lineBlockAtHeight(scrollTop + 8);\n return block.from >= this.viewport.from || this.viewportLines[0].top - scrollTop > 200 ? block : this.viewportLines[0];\n }\n elementAtHeight(height) {\n return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.heightOracle, 0, 0), this.scaler);\n }\n get docHeight() {\n return this.scaler.toDOM(this.heightMap.height);\n }\n get contentHeight() {\n return this.docHeight + this.paddingTop + this.paddingBottom;\n }\n}\nclass Viewport {\n constructor(from, to) {\n this.from = from;\n this.to = to;\n }\n}\nfunction lineStructure(from, to, stateDeco) {\n let ranges = [], pos = from, total = 0;\n RangeSet.spans(stateDeco, from, to, {\n span() { },\n point(from, to) {\n if (from > pos) {\n ranges.push({ from: pos, to: from });\n total += from - pos;\n }\n pos = to;\n }\n }, 20); // We're only interested in collapsed ranges of a significant size\n if (pos < to) {\n ranges.push({ from: pos, to });\n total += to - pos;\n }\n return { total, ranges };\n}\nfunction findPosition({ total, ranges }, ratio) {\n if (ratio <= 0)\n return ranges[0].from;\n if (ratio >= 1)\n return ranges[ranges.length - 1].to;\n let dist = Math.floor(total * ratio);\n for (let i = 0;; i++) {\n let { from, to } = ranges[i], size = to - from;\n if (dist <= size)\n return from + dist;\n dist -= size;\n }\n}\nfunction findFraction(structure, pos) {\n let counted = 0;\n for (let { from, to } of structure.ranges) {\n if (pos <= to) {\n counted += pos - from;\n break;\n }\n counted += to - from;\n }\n return counted / structure.total;\n}\nfunction find(array, f) {\n for (let val of array)\n if (f(val))\n return val;\n return undefined;\n}\n// Don't scale when the document height is within the range of what\n// the DOM can handle.\nconst IdScaler = {\n toDOM(n) { return n; },\n fromDOM(n) { return n; },\n scale: 1\n};\n// When the height is too big (> VP.MaxDOMHeight), scale down the\n// regions outside the viewports so that the total height is\n// VP.MaxDOMHeight.\nclass BigScaler {\n constructor(oracle, heightMap, viewports) {\n let vpHeight = 0, base = 0, domBase = 0;\n this.viewports = viewports.map(({ from, to }) => {\n let top = heightMap.lineAt(from, QueryType.ByPos, oracle, 0, 0).top;\n let bottom = heightMap.lineAt(to, QueryType.ByPos, oracle, 0, 0).bottom;\n vpHeight += bottom - top;\n return { from, to, top, bottom, domTop: 0, domBottom: 0 };\n });\n this.scale = (7000000 /* VP.MaxDOMHeight */ - vpHeight) / (heightMap.height - vpHeight);\n for (let obj of this.viewports) {\n obj.domTop = domBase + (obj.top - base) * this.scale;\n domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top);\n base = obj.bottom;\n }\n }\n toDOM(n) {\n for (let i = 0, base = 0, domBase = 0;; i++) {\n let vp = i < this.viewports.length ? this.viewports[i] : null;\n if (!vp || n < vp.top)\n return domBase + (n - base) * this.scale;\n if (n <= vp.bottom)\n return vp.domTop + (n - vp.top);\n base = vp.bottom;\n domBase = vp.domBottom;\n }\n }\n fromDOM(n) {\n for (let i = 0, base = 0, domBase = 0;; i++) {\n let vp = i < this.viewports.length ? this.viewports[i] : null;\n if (!vp || n < vp.domTop)\n return base + (n - domBase) / this.scale;\n if (n <= vp.domBottom)\n return vp.top + (n - vp.domTop);\n base = vp.bottom;\n domBase = vp.domBottom;\n }\n }\n}\nfunction scaleBlock(block, scaler) {\n if (scaler.scale == 1)\n return block;\n let bTop = scaler.toDOM(block.top), bBottom = scaler.toDOM(block.bottom);\n return new BlockInfo(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block._content) ? block._content.map(b => scaleBlock(b, scaler)) : block._content);\n}\n\nconst theme = /*@__PURE__*/Facet.define({ combine: strs => strs.join(\" \") });\nconst darkTheme = /*@__PURE__*/Facet.define({ combine: values => values.indexOf(true) > -1 });\nconst baseThemeID = /*@__PURE__*/StyleModule.newName(), baseLightID = /*@__PURE__*/StyleModule.newName(), baseDarkID = /*@__PURE__*/StyleModule.newName();\nconst lightDarkIDs = { \"&light\": \".\" + baseLightID, \"&dark\": \".\" + baseDarkID };\nfunction buildTheme(main, spec, scopes) {\n return new StyleModule(spec, {\n finish(sel) {\n return /&/.test(sel) ? sel.replace(/&\\w*/, m => {\n if (m == \"&\")\n return main;\n if (!scopes || !scopes[m])\n throw new RangeError(`Unsupported selector: ${m}`);\n return scopes[m];\n }) : main + \" \" + sel;\n }\n });\n}\nconst baseTheme$1 = /*@__PURE__*/buildTheme(\".\" + baseThemeID, {\n \"&\": {\n position: \"relative !important\",\n boxSizing: \"border-box\",\n \"&.cm-focused\": {\n // Provide a simple default outline to make sure a focused\n // editor is visually distinct. Can't leave the default behavior\n // because that will apply to the content element, which is\n // inside the scrollable container and doesn't include the\n // gutters. We also can't use an 'auto' outline, since those\n // are, for some reason, drawn behind the element content, which\n // will cause things like the active line background to cover\n // the outline (#297).\n outline: \"1px dotted #212121\"\n },\n display: \"flex !important\",\n flexDirection: \"column\"\n },\n \".cm-scroller\": {\n display: \"flex !important\",\n alignItems: \"flex-start !important\",\n fontFamily: \"monospace\",\n lineHeight: 1.4,\n height: \"100%\",\n overflowX: \"auto\",\n position: \"relative\",\n zIndex: 0\n },\n \".cm-content\": {\n margin: 0,\n flexGrow: 2,\n flexShrink: 0,\n display: \"block\",\n whiteSpace: \"pre\",\n wordWrap: \"normal\",\n boxSizing: \"border-box\",\n minHeight: \"100%\",\n padding: \"4px 0\",\n outline: \"none\",\n \"&[contenteditable=true]\": {\n WebkitUserModify: \"read-write-plaintext-only\",\n }\n },\n \".cm-lineWrapping\": {\n whiteSpace_fallback: \"pre-wrap\",\n whiteSpace: \"break-spaces\",\n wordBreak: \"break-word\",\n overflowWrap: \"anywhere\",\n flexShrink: 1\n },\n \"&light .cm-content\": { caretColor: \"black\" },\n \"&dark .cm-content\": { caretColor: \"white\" },\n \".cm-line\": {\n display: \"block\",\n padding: \"0 2px 0 6px\"\n },\n \".cm-layer\": {\n position: \"absolute\",\n left: 0,\n top: 0,\n contain: \"size style\",\n \"& > *\": {\n position: \"absolute\"\n }\n },\n \"&light .cm-selectionBackground\": {\n background: \"#d9d9d9\"\n },\n \"&dark .cm-selectionBackground\": {\n background: \"#222\"\n },\n \"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground\": {\n background: \"#d7d4f0\"\n },\n \"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground\": {\n background: \"#233\"\n },\n \".cm-cursorLayer\": {\n pointerEvents: \"none\"\n },\n \"&.cm-focused > .cm-scroller > .cm-cursorLayer\": {\n animation: \"steps(1) cm-blink 1.2s infinite\"\n },\n // Two animations defined so that we can switch between them to\n // restart the animation without forcing another style\n // recomputation.\n \"@keyframes cm-blink\": { \"0%\": {}, \"50%\": { opacity: 0 }, \"100%\": {} },\n \"@keyframes cm-blink2\": { \"0%\": {}, \"50%\": { opacity: 0 }, \"100%\": {} },\n \".cm-cursor, .cm-dropCursor\": {\n borderLeft: \"1.2px solid black\",\n marginLeft: \"-0.6px\",\n pointerEvents: \"none\",\n },\n \".cm-cursor\": {\n display: \"none\"\n },\n \"&dark .cm-cursor\": {\n borderLeftColor: \"#444\"\n },\n \".cm-dropCursor\": {\n position: \"absolute\"\n },\n \"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor\": {\n display: \"block\"\n },\n \"&light .cm-activeLine\": { backgroundColor: \"#cceeff44\" },\n \"&dark .cm-activeLine\": { backgroundColor: \"#99eeff33\" },\n \"&light .cm-specialChar\": { color: \"red\" },\n \"&dark .cm-specialChar\": { color: \"#f78\" },\n \".cm-gutters\": {\n flexShrink: 0,\n display: \"flex\",\n height: \"100%\",\n boxSizing: \"border-box\",\n insetInlineStart: 0,\n zIndex: 200\n },\n \"&light .cm-gutters\": {\n backgroundColor: \"#f5f5f5\",\n color: \"#6c6c6c\",\n borderRight: \"1px solid #ddd\"\n },\n \"&dark .cm-gutters\": {\n backgroundColor: \"#333338\",\n color: \"#ccc\"\n },\n \".cm-gutter\": {\n display: \"flex !important\",\n flexDirection: \"column\",\n flexShrink: 0,\n boxSizing: \"border-box\",\n minHeight: \"100%\",\n overflow: \"hidden\"\n },\n \".cm-gutterElement\": {\n boxSizing: \"border-box\"\n },\n \".cm-lineNumbers .cm-gutterElement\": {\n padding: \"0 3px 0 5px\",\n minWidth: \"20px\",\n textAlign: \"right\",\n whiteSpace: \"nowrap\"\n },\n \"&light .cm-activeLineGutter\": {\n backgroundColor: \"#e2f2ff\"\n },\n \"&dark .cm-activeLineGutter\": {\n backgroundColor: \"#222227\"\n },\n \".cm-panels\": {\n boxSizing: \"border-box\",\n position: \"sticky\",\n left: 0,\n right: 0\n },\n \"&light .cm-panels\": {\n backgroundColor: \"#f5f5f5\",\n color: \"black\"\n },\n \"&light .cm-panels-top\": {\n borderBottom: \"1px solid #ddd\"\n },\n \"&light .cm-panels-bottom\": {\n borderTop: \"1px solid #ddd\"\n },\n \"&dark .cm-panels\": {\n backgroundColor: \"#333338\",\n color: \"white\"\n },\n \".cm-tab\": {\n display: \"inline-block\",\n overflow: \"hidden\",\n verticalAlign: \"bottom\"\n },\n \".cm-widgetBuffer\": {\n verticalAlign: \"text-top\",\n height: \"1em\",\n width: 0,\n display: \"inline\"\n },\n \".cm-placeholder\": {\n color: \"#888\",\n display: \"inline-block\",\n verticalAlign: \"top\",\n },\n \".cm-highlightSpace:before\": {\n content: \"attr(data-display)\",\n position: \"absolute\",\n pointerEvents: \"none\",\n color: \"#888\"\n },\n \".cm-highlightTab\": {\n backgroundImage: `url('data:image/svg+xml,')`,\n backgroundSize: \"auto 100%\",\n backgroundPosition: \"right 90%\",\n backgroundRepeat: \"no-repeat\"\n },\n \".cm-trailingSpace\": {\n backgroundColor: \"#ff332255\"\n },\n \".cm-button\": {\n verticalAlign: \"middle\",\n color: \"inherit\",\n fontSize: \"70%\",\n padding: \".2em 1em\",\n borderRadius: \"1px\"\n },\n \"&light .cm-button\": {\n backgroundImage: \"linear-gradient(#eff1f5, #d9d9df)\",\n border: \"1px solid #888\",\n \"&:active\": {\n backgroundImage: \"linear-gradient(#b4b4b4, #d0d3d6)\"\n }\n },\n \"&dark .cm-button\": {\n backgroundImage: \"linear-gradient(#393939, #111)\",\n border: \"1px solid #888\",\n \"&:active\": {\n backgroundImage: \"linear-gradient(#111, #333)\"\n }\n },\n \".cm-textfield\": {\n verticalAlign: \"middle\",\n color: \"inherit\",\n fontSize: \"70%\",\n border: \"1px solid silver\",\n padding: \".2em .5em\"\n },\n \"&light .cm-textfield\": {\n backgroundColor: \"white\"\n },\n \"&dark .cm-textfield\": {\n border: \"1px solid #555\",\n backgroundColor: \"inherit\"\n }\n}, lightDarkIDs);\n\nconst LineBreakPlaceholder = \"\\uffff\";\nclass DOMReader {\n constructor(points, state) {\n this.points = points;\n this.text = \"\";\n this.lineSeparator = state.facet(EditorState.lineSeparator);\n }\n append(text) {\n this.text += text;\n }\n lineBreak() {\n this.text += LineBreakPlaceholder;\n }\n readRange(start, end) {\n if (!start)\n return this;\n let parent = start.parentNode;\n for (let cur = start;;) {\n this.findPointBefore(parent, cur);\n let oldLen = this.text.length;\n this.readNode(cur);\n let next = cur.nextSibling;\n if (next == end)\n break;\n let view = ContentView.get(cur), nextView = ContentView.get(next);\n if (view && nextView ? view.breakAfter :\n (view ? view.breakAfter : isBlockElement(cur)) ||\n (isBlockElement(next) && (cur.nodeName != \"BR\" || cur.cmIgnore) && this.text.length > oldLen))\n this.lineBreak();\n cur = next;\n }\n this.findPointBefore(parent, end);\n return this;\n }\n readTextNode(node) {\n let text = node.nodeValue;\n for (let point of this.points)\n if (point.node == node)\n point.pos = this.text.length + Math.min(point.offset, text.length);\n for (let off = 0, re = this.lineSeparator ? null : /\\r\\n?|\\n/g;;) {\n let nextBreak = -1, breakSize = 1, m;\n if (this.lineSeparator) {\n nextBreak = text.indexOf(this.lineSeparator, off);\n breakSize = this.lineSeparator.length;\n }\n else if (m = re.exec(text)) {\n nextBreak = m.index;\n breakSize = m[0].length;\n }\n this.append(text.slice(off, nextBreak < 0 ? text.length : nextBreak));\n if (nextBreak < 0)\n break;\n this.lineBreak();\n if (breakSize > 1)\n for (let point of this.points)\n if (point.node == node && point.pos > this.text.length)\n point.pos -= breakSize - 1;\n off = nextBreak + breakSize;\n }\n }\n readNode(node) {\n if (node.cmIgnore)\n return;\n let view = ContentView.get(node);\n let fromView = view && view.overrideDOMText;\n if (fromView != null) {\n this.findPointInside(node, fromView.length);\n for (let i = fromView.iter(); !i.next().done;) {\n if (i.lineBreak)\n this.lineBreak();\n else\n this.append(i.value);\n }\n }\n else if (node.nodeType == 3) {\n this.readTextNode(node);\n }\n else if (node.nodeName == \"BR\") {\n if (node.nextSibling)\n this.lineBreak();\n }\n else if (node.nodeType == 1) {\n this.readRange(node.firstChild, null);\n }\n }\n findPointBefore(node, next) {\n for (let point of this.points)\n if (point.node == node && node.childNodes[point.offset] == next)\n point.pos = this.text.length;\n }\n findPointInside(node, length) {\n for (let point of this.points)\n if (node.nodeType == 3 ? point.node == node : node.contains(point.node))\n point.pos = this.text.length + (isAtEnd(node, point.node, point.offset) ? length : 0);\n }\n}\nfunction isAtEnd(parent, node, offset) {\n for (;;) {\n if (!node || offset < maxOffset(node))\n return false;\n if (node == parent)\n return true;\n offset = domIndex(node) + 1;\n node = node.parentNode;\n }\n}\nfunction isBlockElement(node) {\n return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\\d|SECTION|PRE)$/.test(node.nodeName);\n}\nclass DOMPoint {\n constructor(node, offset) {\n this.node = node;\n this.offset = offset;\n this.pos = -1;\n }\n}\n\nclass DOMChange {\n constructor(view, start, end, typeOver) {\n this.typeOver = typeOver;\n this.bounds = null;\n this.text = \"\";\n let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView;\n if (view.state.readOnly && start > -1) {\n // Ignore changes when the editor is read-only\n this.newSel = null;\n }\n else if (start > -1 && (this.bounds = view.docView.domBoundsAround(start, end, 0))) {\n let selPoints = iHead || iAnchor ? [] : selectionPoints(view);\n let reader = new DOMReader(selPoints, view.state);\n reader.readRange(this.bounds.startDOM, this.bounds.endDOM);\n this.text = reader.text;\n this.newSel = selectionFromPoints(selPoints, this.bounds.from);\n }\n else {\n let domSel = view.observer.selectionRange;\n let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset ||\n !contains(view.contentDOM, domSel.focusNode)\n ? view.state.selection.main.head\n : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset);\n let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset ||\n !contains(view.contentDOM, domSel.anchorNode)\n ? view.state.selection.main.anchor\n : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset);\n this.newSel = EditorSelection.single(anchor, head);\n }\n }\n}\nfunction applyDOMChange(view, domChange) {\n let change;\n let { newSel } = domChange, sel = view.state.selection.main;\n let lastKey = view.inputState.lastKeyTime > Date.now() - 100 ? view.inputState.lastKeyCode : -1;\n if (domChange.bounds) {\n let { from, to } = domChange.bounds;\n let preferredPos = sel.from, preferredSide = null;\n // Prefer anchoring to end when Backspace is pressed (or, on\n // Android, when something was deleted)\n if (lastKey === 8 || browser.android && domChange.text.length < to - from) {\n preferredPos = sel.to;\n preferredSide = \"end\";\n }\n let diff = findDiff(view.state.doc.sliceString(from, to, LineBreakPlaceholder), domChange.text, preferredPos - from, preferredSide);\n if (diff) {\n // Chrome inserts two newlines when pressing shift-enter at the\n // end of a line. DomChange drops one of those.\n if (browser.chrome && lastKey == 13 &&\n diff.toB == diff.from + 2 && domChange.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder)\n diff.toB--;\n change = { from: from + diff.from, to: from + diff.toA,\n insert: Text.of(domChange.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder)) };\n }\n }\n else if (newSel && (!view.hasFocus && view.state.facet(editable) || newSel.main.eq(sel))) {\n newSel = null;\n }\n if (!change && !newSel)\n return false;\n if (!change && domChange.typeOver && !sel.empty && newSel && newSel.main.empty) {\n // Heuristic to notice typing over a selected character\n change = { from: sel.from, to: sel.to, insert: view.state.doc.slice(sel.from, sel.to) };\n }\n else if (change && change.from >= sel.from && change.to <= sel.to &&\n (change.from != sel.from || change.to != sel.to) &&\n (sel.to - sel.from) - (change.to - change.from) <= 4) {\n // If the change is inside the selection and covers most of it,\n // assume it is a selection replace (with identical characters at\n // the start/end not included in the diff)\n change = {\n from: sel.from, to: sel.to,\n insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to))\n };\n }\n else if ((browser.mac || browser.android) && change && change.from == change.to && change.from == sel.head - 1 &&\n /^\\. ?$/.test(change.insert.toString()) && view.contentDOM.getAttribute(\"autocorrect\") == \"off\") {\n // Detect insert-period-on-double-space Mac and Android behavior,\n // and transform it into a regular space insert.\n if (newSel && change.insert.length == 2)\n newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);\n change = { from: sel.from, to: sel.to, insert: Text.of([\" \"]) };\n }\n else if (browser.chrome && change && change.from == change.to && change.from == sel.head &&\n change.insert.toString() == \"\\n \" && view.lineWrapping) {\n // In Chrome, if you insert a space at the start of a wrapped\n // line, it will actually insert a newline and a space, causing a\n // bogus new line to be created in CodeMirror (#968)\n if (newSel)\n newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);\n change = { from: sel.from, to: sel.to, insert: Text.of([\" \"]) };\n }\n if (change) {\n if (browser.ios && view.inputState.flushIOSKey())\n return true;\n // Android browsers don't fire reasonable key events for enter,\n // backspace, or delete. So this detects changes that look like\n // they're caused by those keys, and reinterprets them as key\n // events. (Some of these keys are also handled by beforeinput\n // events and the pendingAndroidKey mechanism, but that's not\n // reliable in all situations.)\n if (browser.android &&\n ((change.from == sel.from && change.to == sel.to &&\n change.insert.length == 1 && change.insert.lines == 2 &&\n dispatchKey(view.contentDOM, \"Enter\", 13)) ||\n ((change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 ||\n lastKey == 8 && change.insert.length < change.to - change.from && change.to > sel.head) &&\n dispatchKey(view.contentDOM, \"Backspace\", 8)) ||\n (change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 &&\n dispatchKey(view.contentDOM, \"Delete\", 46))))\n return true;\n let text = change.insert.toString();\n if (view.inputState.composing >= 0)\n view.inputState.composing++;\n let defaultTr;\n let defaultInsert = () => defaultTr || (defaultTr = applyDefaultInsert(view, change, newSel));\n if (!view.state.facet(inputHandler).some(h => h(view, change.from, change.to, text, defaultInsert)))\n view.dispatch(defaultInsert());\n return true;\n }\n else if (newSel && !newSel.main.eq(sel)) {\n let scrollIntoView = false, userEvent = \"select\";\n if (view.inputState.lastSelectionTime > Date.now() - 50) {\n if (view.inputState.lastSelectionOrigin == \"select\")\n scrollIntoView = true;\n userEvent = view.inputState.lastSelectionOrigin;\n }\n view.dispatch({ selection: newSel, scrollIntoView, userEvent });\n return true;\n }\n else {\n return false;\n }\n}\nfunction applyDefaultInsert(view, change, newSel) {\n let tr, startState = view.state, sel = startState.selection.main;\n if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 &&\n (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) &&\n view.inputState.composing < 0) {\n let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : \"\";\n let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : \"\";\n tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, undefined, view.state.lineBreak) + after));\n }\n else {\n let changes = startState.changes(change);\n let mainSel = newSel && newSel.main.to <= changes.newLength ? newSel.main : undefined;\n // Try to apply a composition change to all cursors\n if (startState.selection.ranges.length > 1 && view.inputState.composing >= 0 &&\n change.to <= sel.to && change.to >= sel.to - 10) {\n let replaced = view.state.sliceDoc(change.from, change.to);\n let compositionRange, composition = newSel && findCompositionNode(view, newSel.main.head);\n if (composition) {\n let dLen = change.insert.length - (change.to - change.from);\n compositionRange = { from: composition.from, to: composition.to - dLen };\n }\n else {\n compositionRange = view.state.doc.lineAt(sel.head);\n }\n let offset = sel.to - change.to, size = sel.to - sel.from;\n tr = startState.changeByRange(range => {\n if (range.from == sel.from && range.to == sel.to)\n return { changes, range: mainSel || range.map(changes) };\n let to = range.to - offset, from = to - replaced.length;\n if (range.to - range.from != size || view.state.sliceDoc(from, to) != replaced ||\n // Unfortunately, there's no way to make multiple\n // changes in the same node work without aborting\n // composition, so cursors in the composition range are\n // ignored.\n range.to >= compositionRange.from && range.from <= compositionRange.to)\n return { range };\n let rangeChanges = startState.changes({ from, to, insert: change.insert }), selOff = range.to - sel.to;\n return {\n changes: rangeChanges,\n range: !mainSel ? range.map(rangeChanges) :\n EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff))\n };\n });\n }\n else {\n tr = {\n changes,\n selection: mainSel && startState.selection.replaceRange(mainSel)\n };\n }\n }\n let userEvent = \"input.type\";\n if (view.composing ||\n view.inputState.compositionPendingChange && view.inputState.compositionEndedAt > Date.now() - 50) {\n view.inputState.compositionPendingChange = false;\n userEvent += \".compose\";\n if (view.inputState.compositionFirstChange) {\n userEvent += \".start\";\n view.inputState.compositionFirstChange = false;\n }\n }\n return startState.update(tr, { userEvent, scrollIntoView: true });\n}\nfunction findDiff(a, b, preferredPos, preferredSide) {\n let minLen = Math.min(a.length, b.length);\n let from = 0;\n while (from < minLen && a.charCodeAt(from) == b.charCodeAt(from))\n from++;\n if (from == minLen && a.length == b.length)\n return null;\n let toA = a.length, toB = b.length;\n while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1)) {\n toA--;\n toB--;\n }\n if (preferredSide == \"end\") {\n let adjust = Math.max(0, from - Math.min(toA, toB));\n preferredPos -= toA + adjust - from;\n }\n if (toA < from && a.length < b.length) {\n let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0;\n from -= move;\n toB = from + (toB - toA);\n toA = from;\n }\n else if (toB < from) {\n let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0;\n from -= move;\n toA = from + (toA - toB);\n toB = from;\n }\n return { from, toA, toB };\n}\nfunction selectionPoints(view) {\n let result = [];\n if (view.root.activeElement != view.contentDOM)\n return result;\n let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange;\n if (anchorNode) {\n result.push(new DOMPoint(anchorNode, anchorOffset));\n if (focusNode != anchorNode || focusOffset != anchorOffset)\n result.push(new DOMPoint(focusNode, focusOffset));\n }\n return result;\n}\nfunction selectionFromPoints(points, base) {\n if (points.length == 0)\n return null;\n let anchor = points[0].pos, head = points.length == 2 ? points[1].pos : anchor;\n return anchor > -1 && head > -1 ? EditorSelection.single(anchor + base, head + base) : null;\n}\n\nconst observeOptions = {\n childList: true,\n characterData: true,\n subtree: true,\n attributes: true,\n characterDataOldValue: true\n};\n// IE11 has very broken mutation observers, so we also listen to\n// DOMCharacterDataModified there\nconst useCharData = browser.ie && browser.ie_version <= 11;\nclass DOMObserver {\n constructor(view) {\n this.view = view;\n this.active = false;\n // The known selection. Kept in our own object, as opposed to just\n // directly accessing the selection because:\n // - Safari doesn't report the right selection in shadow DOM\n // - Reading from the selection forces a DOM layout\n // - This way, we can ignore selectionchange events if we have\n // already seen the 'new' selection\n this.selectionRange = new DOMSelectionState;\n // Set when a selection change is detected, cleared on flush\n this.selectionChanged = false;\n this.delayedFlush = -1;\n this.resizeTimeout = -1;\n this.queue = [];\n this.delayedAndroidKey = null;\n this.flushingAndroidKey = -1;\n this.lastChange = 0;\n this.scrollTargets = [];\n this.intersection = null;\n this.resizeScroll = null;\n this.intersecting = false;\n this.gapIntersection = null;\n this.gaps = [];\n // Timeout for scheduling check of the parents that need scroll handlers\n this.parentCheck = -1;\n this.dom = view.contentDOM;\n this.observer = new MutationObserver(mutations => {\n for (let mut of mutations)\n this.queue.push(mut);\n // IE11 will sometimes (on typing over a selection or\n // backspacing out a single character text node) call the\n // observer callback before actually updating the DOM.\n //\n // Unrelatedly, iOS Safari will, when ending a composition,\n // sometimes first clear it, deliver the mutations, and then\n // reinsert the finished text. CodeMirror's handling of the\n // deletion will prevent the reinsertion from happening,\n // breaking composition.\n if ((browser.ie && browser.ie_version <= 11 || browser.ios && view.composing) &&\n mutations.some(m => m.type == \"childList\" && m.removedNodes.length ||\n m.type == \"characterData\" && m.oldValue.length > m.target.nodeValue.length))\n this.flushSoon();\n else\n this.flush();\n });\n if (useCharData)\n this.onCharData = (event) => {\n this.queue.push({ target: event.target,\n type: \"characterData\",\n oldValue: event.prevValue });\n this.flushSoon();\n };\n this.onSelectionChange = this.onSelectionChange.bind(this);\n this.onResize = this.onResize.bind(this);\n this.onPrint = this.onPrint.bind(this);\n this.onScroll = this.onScroll.bind(this);\n if (typeof ResizeObserver == \"function\") {\n this.resizeScroll = new ResizeObserver(() => {\n var _a;\n if (((_a = this.view.docView) === null || _a === void 0 ? void 0 : _a.lastUpdate) < Date.now() - 75)\n this.onResize();\n });\n this.resizeScroll.observe(view.scrollDOM);\n }\n this.addWindowListeners(this.win = view.win);\n this.start();\n if (typeof IntersectionObserver == \"function\") {\n this.intersection = new IntersectionObserver(entries => {\n if (this.parentCheck < 0)\n this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1000);\n if (entries.length > 0 && (entries[entries.length - 1].intersectionRatio > 0) != this.intersecting) {\n this.intersecting = !this.intersecting;\n if (this.intersecting != this.view.inView)\n this.onScrollChanged(document.createEvent(\"Event\"));\n }\n }, { threshold: [0, .001] });\n this.intersection.observe(this.dom);\n this.gapIntersection = new IntersectionObserver(entries => {\n if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0)\n this.onScrollChanged(document.createEvent(\"Event\"));\n }, {});\n }\n this.listenForScroll();\n this.readSelectionRange();\n }\n onScrollChanged(e) {\n this.view.inputState.runHandlers(\"scroll\", e);\n if (this.intersecting)\n this.view.measure();\n }\n onScroll(e) {\n if (this.intersecting)\n this.flush(false);\n this.onScrollChanged(e);\n }\n onResize() {\n if (this.resizeTimeout < 0)\n this.resizeTimeout = setTimeout(() => {\n this.resizeTimeout = -1;\n this.view.requestMeasure();\n }, 50);\n }\n onPrint() {\n this.view.viewState.printing = true;\n this.view.measure();\n setTimeout(() => {\n this.view.viewState.printing = false;\n this.view.requestMeasure();\n }, 500);\n }\n updateGaps(gaps) {\n if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i) => g != gaps[i]))) {\n this.gapIntersection.disconnect();\n for (let gap of gaps)\n this.gapIntersection.observe(gap);\n this.gaps = gaps;\n }\n }\n onSelectionChange(event) {\n let wasChanged = this.selectionChanged;\n if (!this.readSelectionRange() || this.delayedAndroidKey)\n return;\n let { view } = this, sel = this.selectionRange;\n if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(view.dom, sel))\n return;\n let context = sel.anchorNode && view.docView.nearest(sel.anchorNode);\n if (context && context.ignoreEvent(event)) {\n if (!wasChanged)\n this.selectionChanged = false;\n return;\n }\n // Deletions on IE11 fire their events in the wrong order, giving\n // us a selection change event before the DOM changes are\n // reported.\n // Chrome Android has a similar issue when backspacing out a\n // selection (#645).\n if ((browser.ie && browser.ie_version <= 11 || browser.android && browser.chrome) && !view.state.selection.main.empty &&\n // (Selection.isCollapsed isn't reliable on IE)\n sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))\n this.flushSoon();\n else\n this.flush(false);\n }\n readSelectionRange() {\n let { view } = this;\n // The Selection object is broken in shadow roots in Safari. See\n // https://github.com/codemirror/dev/issues/414\n let range = browser.safari && view.root.nodeType == 11 &&\n deepActiveElement(this.dom.ownerDocument) == this.dom &&\n safariSelectionRangeHack(this.view) || getSelection(view.root);\n if (!range || this.selectionRange.eq(range))\n return false;\n let local = hasSelection(this.dom, range);\n // Detect the situation where the browser has, on focus, moved the\n // selection to the start of the content element. Reset it to the\n // position from the editor state.\n if (local && !this.selectionChanged &&\n view.inputState.lastFocusTime > Date.now() - 200 &&\n view.inputState.lastTouchTime < Date.now() - 300 &&\n atElementStart(this.dom, range)) {\n this.view.inputState.lastFocusTime = 0;\n view.docView.updateSelection();\n return false;\n }\n this.selectionRange.setRange(range);\n if (local)\n this.selectionChanged = true;\n return true;\n }\n setSelectionRange(anchor, head) {\n this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset);\n this.selectionChanged = false;\n }\n clearSelectionRange() {\n this.selectionRange.set(null, 0, null, 0);\n }\n listenForScroll() {\n this.parentCheck = -1;\n let i = 0, changed = null;\n for (let dom = this.dom; dom;) {\n if (dom.nodeType == 1) {\n if (!changed && i < this.scrollTargets.length && this.scrollTargets[i] == dom)\n i++;\n else if (!changed)\n changed = this.scrollTargets.slice(0, i);\n if (changed)\n changed.push(dom);\n dom = dom.assignedSlot || dom.parentNode;\n }\n else if (dom.nodeType == 11) { // Shadow root\n dom = dom.host;\n }\n else {\n break;\n }\n }\n if (i < this.scrollTargets.length && !changed)\n changed = this.scrollTargets.slice(0, i);\n if (changed) {\n for (let dom of this.scrollTargets)\n dom.removeEventListener(\"scroll\", this.onScroll);\n for (let dom of this.scrollTargets = changed)\n dom.addEventListener(\"scroll\", this.onScroll);\n }\n }\n ignore(f) {\n if (!this.active)\n return f();\n try {\n this.stop();\n return f();\n }\n finally {\n this.start();\n this.clear();\n }\n }\n start() {\n if (this.active)\n return;\n this.observer.observe(this.dom, observeOptions);\n if (useCharData)\n this.dom.addEventListener(\"DOMCharacterDataModified\", this.onCharData);\n this.active = true;\n }\n stop() {\n if (!this.active)\n return;\n this.active = false;\n this.observer.disconnect();\n if (useCharData)\n this.dom.removeEventListener(\"DOMCharacterDataModified\", this.onCharData);\n }\n // Throw away any pending changes\n clear() {\n this.processRecords();\n this.queue.length = 0;\n this.selectionChanged = false;\n }\n // Chrome Android, especially in combination with GBoard, not only\n // doesn't reliably fire regular key events, but also often\n // surrounds the effect of enter or backspace with a bunch of\n // composition events that, when interrupted, cause text duplication\n // or other kinds of corruption. This hack makes the editor back off\n // from handling DOM changes for a moment when such a key is\n // detected (via beforeinput or keydown), and then tries to flush\n // them or, if that has no effect, dispatches the given key.\n delayAndroidKey(key, keyCode) {\n var _a;\n if (!this.delayedAndroidKey) {\n let flush = () => {\n let key = this.delayedAndroidKey;\n if (key) {\n this.clearDelayedAndroidKey();\n this.view.inputState.lastKeyCode = key.keyCode;\n this.view.inputState.lastKeyTime = Date.now();\n let flushed = this.flush();\n if (!flushed && key.force)\n dispatchKey(this.dom, key.key, key.keyCode);\n }\n };\n this.flushingAndroidKey = this.view.win.requestAnimationFrame(flush);\n }\n // Since backspace beforeinput is sometimes signalled spuriously,\n // Enter always takes precedence.\n if (!this.delayedAndroidKey || key == \"Enter\")\n this.delayedAndroidKey = {\n key, keyCode,\n // Only run the key handler when no changes are detected if\n // this isn't coming right after another change, in which case\n // it is probably part of a weird chain of updates, and should\n // be ignored if it returns the DOM to its previous state.\n force: this.lastChange < Date.now() - 50 || !!((_a = this.delayedAndroidKey) === null || _a === void 0 ? void 0 : _a.force)\n };\n }\n clearDelayedAndroidKey() {\n this.win.cancelAnimationFrame(this.flushingAndroidKey);\n this.delayedAndroidKey = null;\n this.flushingAndroidKey = -1;\n }\n flushSoon() {\n if (this.delayedFlush < 0)\n this.delayedFlush = this.view.win.requestAnimationFrame(() => { this.delayedFlush = -1; this.flush(); });\n }\n forceFlush() {\n if (this.delayedFlush >= 0) {\n this.view.win.cancelAnimationFrame(this.delayedFlush);\n this.delayedFlush = -1;\n }\n this.flush();\n }\n pendingRecords() {\n for (let mut of this.observer.takeRecords())\n this.queue.push(mut);\n return this.queue;\n }\n processRecords() {\n let records = this.pendingRecords();\n if (records.length)\n this.queue = [];\n let from = -1, to = -1, typeOver = false;\n for (let record of records) {\n let range = this.readMutation(record);\n if (!range)\n continue;\n if (range.typeOver)\n typeOver = true;\n if (from == -1) {\n ({ from, to } = range);\n }\n else {\n from = Math.min(range.from, from);\n to = Math.max(range.to, to);\n }\n }\n return { from, to, typeOver };\n }\n readChange() {\n let { from, to, typeOver } = this.processRecords();\n let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange);\n if (from < 0 && !newSel)\n return null;\n if (from > -1)\n this.lastChange = Date.now();\n this.view.inputState.lastFocusTime = 0;\n this.selectionChanged = false;\n let change = new DOMChange(this.view, from, to, typeOver);\n this.view.docView.domChanged = { newSel: change.newSel ? change.newSel.main : null };\n return change;\n }\n // Apply pending changes, if any\n flush(readSelection = true) {\n // Completely hold off flushing when pending keys are set—the code\n // managing those will make sure processRecords is called and the\n // view is resynchronized after\n if (this.delayedFlush >= 0 || this.delayedAndroidKey)\n return false;\n if (readSelection)\n this.readSelectionRange();\n let domChange = this.readChange();\n if (!domChange) {\n this.view.requestMeasure();\n return false;\n }\n let startState = this.view.state;\n let handled = applyDOMChange(this.view, domChange);\n // The view wasn't updated\n if (this.view.state == startState)\n this.view.update([]);\n return handled;\n }\n readMutation(rec) {\n let cView = this.view.docView.nearest(rec.target);\n if (!cView || cView.ignoreMutation(rec))\n return null;\n cView.markDirty(rec.type == \"attributes\");\n if (rec.type == \"attributes\")\n cView.flags |= 4 /* ViewFlag.AttrsDirty */;\n if (rec.type == \"childList\") {\n let childBefore = findChild(cView, rec.previousSibling || rec.target.previousSibling, -1);\n let childAfter = findChild(cView, rec.nextSibling || rec.target.nextSibling, 1);\n return { from: childBefore ? cView.posAfter(childBefore) : cView.posAtStart,\n to: childAfter ? cView.posBefore(childAfter) : cView.posAtEnd, typeOver: false };\n }\n else if (rec.type == \"characterData\") {\n return { from: cView.posAtStart, to: cView.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue };\n }\n else {\n return null;\n }\n }\n setWindow(win) {\n if (win != this.win) {\n this.removeWindowListeners(this.win);\n this.win = win;\n this.addWindowListeners(this.win);\n }\n }\n addWindowListeners(win) {\n win.addEventListener(\"resize\", this.onResize);\n win.addEventListener(\"beforeprint\", this.onPrint);\n win.addEventListener(\"scroll\", this.onScroll);\n win.document.addEventListener(\"selectionchange\", this.onSelectionChange);\n }\n removeWindowListeners(win) {\n win.removeEventListener(\"scroll\", this.onScroll);\n win.removeEventListener(\"resize\", this.onResize);\n win.removeEventListener(\"beforeprint\", this.onPrint);\n win.document.removeEventListener(\"selectionchange\", this.onSelectionChange);\n }\n destroy() {\n var _a, _b, _c;\n this.stop();\n (_a = this.intersection) === null || _a === void 0 ? void 0 : _a.disconnect();\n (_b = this.gapIntersection) === null || _b === void 0 ? void 0 : _b.disconnect();\n (_c = this.resizeScroll) === null || _c === void 0 ? void 0 : _c.disconnect();\n for (let dom of this.scrollTargets)\n dom.removeEventListener(\"scroll\", this.onScroll);\n this.removeWindowListeners(this.win);\n clearTimeout(this.parentCheck);\n clearTimeout(this.resizeTimeout);\n this.win.cancelAnimationFrame(this.delayedFlush);\n this.win.cancelAnimationFrame(this.flushingAndroidKey);\n }\n}\nfunction findChild(cView, dom, dir) {\n while (dom) {\n let curView = ContentView.get(dom);\n if (curView && curView.parent == cView)\n return curView;\n let parent = dom.parentNode;\n dom = parent != cView.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling;\n }\n return null;\n}\n// Used to work around a Safari Selection/shadow DOM bug (#414)\nfunction safariSelectionRangeHack(view) {\n let found = null;\n // Because Safari (at least in 2018-2021) doesn't provide regular\n // access to the selection inside a shadowroot, we have to perform a\n // ridiculous hack to get at it—using `execCommand` to trigger a\n // `beforeInput` event so that we can read the target range from the\n // event.\n function read(event) {\n event.preventDefault();\n event.stopImmediatePropagation();\n found = event.getTargetRanges()[0];\n }\n view.contentDOM.addEventListener(\"beforeinput\", read, true);\n view.dom.ownerDocument.execCommand(\"indent\");\n view.contentDOM.removeEventListener(\"beforeinput\", read, true);\n if (!found)\n return null;\n let anchorNode = found.startContainer, anchorOffset = found.startOffset;\n let focusNode = found.endContainer, focusOffset = found.endOffset;\n let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor);\n // Since such a range doesn't distinguish between anchor and head,\n // use a heuristic that flips it around if its end matches the\n // current anchor.\n if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset))\n [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];\n return { anchorNode, anchorOffset, focusNode, focusOffset };\n}\n\n// The editor's update state machine looks something like this:\n//\n// Idle → Updating ⇆ Idle (unchecked) → Measuring → Idle\n// ↑ ↓\n// Updating (measure)\n//\n// The difference between 'Idle' and 'Idle (unchecked)' lies in\n// whether a layout check has been scheduled. A regular update through\n// the `update` method updates the DOM in a write-only fashion, and\n// relies on a check (scheduled with `requestAnimationFrame`) to make\n// sure everything is where it should be and the viewport covers the\n// visible code. That check continues to measure and then optionally\n// update until it reaches a coherent state.\n/**\nAn editor view represents the editor's user interface. It holds\nthe editable DOM surface, and possibly other elements such as the\nline number gutter. It handles events and dispatches state\ntransactions for editing actions.\n*/\nclass EditorView {\n /**\n The current editor state.\n */\n get state() { return this.viewState.state; }\n /**\n To be able to display large documents without consuming too much\n memory or overloading the browser, CodeMirror only draws the\n code that is visible (plus a margin around it) to the DOM. This\n property tells you the extent of the current drawn viewport, in\n document positions.\n */\n get viewport() { return this.viewState.viewport; }\n /**\n When there are, for example, large collapsed ranges in the\n viewport, its size can be a lot bigger than the actual visible\n content. Thus, if you are doing something like styling the\n content in the viewport, it is preferable to only do so for\n these ranges, which are the subset of the viewport that is\n actually drawn.\n */\n get visibleRanges() { return this.viewState.visibleRanges; }\n /**\n Returns false when the editor is entirely scrolled out of view\n or otherwise hidden.\n */\n get inView() { return this.viewState.inView; }\n /**\n Indicates whether the user is currently composing text via\n [IME](https://en.wikipedia.org/wiki/Input_method), and at least\n one change has been made in the current composition.\n */\n get composing() { return this.inputState.composing > 0; }\n /**\n Indicates whether the user is currently in composing state. Note\n that on some platforms, like Android, this will be the case a\n lot, since just putting the cursor on a word starts a\n composition there.\n */\n get compositionStarted() { return this.inputState.composing >= 0; }\n /**\n The document or shadow root that the view lives in.\n */\n get root() { return this._root; }\n /**\n @internal\n */\n get win() { return this.dom.ownerDocument.defaultView || window; }\n /**\n Construct a new view. You'll want to either provide a `parent`\n option, or put `view.dom` into your document after creating a\n view, so that the user can see the editor.\n */\n constructor(config = {}) {\n this.plugins = [];\n this.pluginMap = new Map;\n this.editorAttrs = {};\n this.contentAttrs = {};\n this.bidiCache = [];\n this.destroyed = false;\n /**\n @internal\n */\n this.updateState = 2 /* UpdateState.Updating */;\n /**\n @internal\n */\n this.measureScheduled = -1;\n /**\n @internal\n */\n this.measureRequests = [];\n this.contentDOM = document.createElement(\"div\");\n this.scrollDOM = document.createElement(\"div\");\n this.scrollDOM.tabIndex = -1;\n this.scrollDOM.className = \"cm-scroller\";\n this.scrollDOM.appendChild(this.contentDOM);\n this.announceDOM = document.createElement(\"div\");\n this.announceDOM.style.cssText = \"position: fixed; top: -10000px\";\n this.announceDOM.setAttribute(\"aria-live\", \"polite\");\n this.dom = document.createElement(\"div\");\n this.dom.appendChild(this.announceDOM);\n this.dom.appendChild(this.scrollDOM);\n let { dispatch } = config;\n this.dispatchTransactions = config.dispatchTransactions ||\n (dispatch && ((trs) => trs.forEach(tr => dispatch(tr, this)))) ||\n ((trs) => this.update(trs));\n this.dispatch = this.dispatch.bind(this);\n this._root = (config.root || getRoot(config.parent) || document);\n this.viewState = new ViewState(config.state || EditorState.create(config));\n if (config.scrollTo && config.scrollTo.is(scrollIntoView))\n this.viewState.scrollTarget = config.scrollTo.value.clip(this.viewState.state);\n this.plugins = this.state.facet(viewPlugin).map(spec => new PluginInstance(spec));\n for (let plugin of this.plugins)\n plugin.update(this);\n this.observer = new DOMObserver(this);\n this.inputState = new InputState(this);\n this.inputState.ensureHandlers(this.plugins);\n this.docView = new DocView(this);\n this.mountStyles();\n this.updateAttrs();\n this.updateState = 0 /* UpdateState.Idle */;\n this.requestMeasure();\n if (config.parent)\n config.parent.appendChild(this.dom);\n }\n dispatch(...input) {\n let trs = input.length == 1 && input[0] instanceof Transaction ? input\n : input.length == 1 && Array.isArray(input[0]) ? input[0]\n : [this.state.update(...input)];\n this.dispatchTransactions(trs, this);\n }\n /**\n Update the view for the given array of transactions. This will\n update the visible document and selection to match the state\n produced by the transactions, and notify view plugins of the\n change. You should usually call\n [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this\n as a primitive.\n */\n update(transactions) {\n if (this.updateState != 0 /* UpdateState.Idle */)\n throw new Error(\"Calls to EditorView.update are not allowed while an update is in progress\");\n let redrawn = false, attrsChanged = false, update;\n let state = this.state;\n for (let tr of transactions) {\n if (tr.startState != state)\n throw new RangeError(\"Trying to update state with a transaction that doesn't start from the previous state.\");\n state = tr.state;\n }\n if (this.destroyed) {\n this.viewState.state = state;\n return;\n }\n let focus = this.hasFocus, focusFlag = 0, dispatchFocus = null;\n if (transactions.some(tr => tr.annotation(isFocusChange))) {\n this.inputState.notifiedFocused = focus;\n // If a focus-change transaction is being dispatched, set this update flag.\n focusFlag = 1 /* UpdateFlag.Focus */;\n }\n else if (focus != this.inputState.notifiedFocused) {\n this.inputState.notifiedFocused = focus;\n // Schedule a separate focus transaction if necessary, otherwise\n // add a flag to this update\n dispatchFocus = focusChangeTransaction(state, focus);\n if (!dispatchFocus)\n focusFlag = 1 /* UpdateFlag.Focus */;\n }\n // If there was a pending DOM change, eagerly read it and try to\n // apply it after the given transactions.\n let pendingKey = this.observer.delayedAndroidKey, domChange = null;\n if (pendingKey) {\n this.observer.clearDelayedAndroidKey();\n domChange = this.observer.readChange();\n // Only try to apply DOM changes if the transactions didn't\n // change the doc or selection.\n if (domChange && !this.state.doc.eq(state.doc) || !this.state.selection.eq(state.selection))\n domChange = null;\n }\n else {\n this.observer.clear();\n }\n // When the phrases change, redraw the editor\n if (state.facet(EditorState.phrases) != this.state.facet(EditorState.phrases))\n return this.setState(state);\n update = ViewUpdate.create(this, state, transactions);\n update.flags |= focusFlag;\n let scrollTarget = this.viewState.scrollTarget;\n try {\n this.updateState = 2 /* UpdateState.Updating */;\n for (let tr of transactions) {\n if (scrollTarget)\n scrollTarget = scrollTarget.map(tr.changes);\n if (tr.scrollIntoView) {\n let { main } = tr.state.selection;\n scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1));\n }\n for (let e of tr.effects)\n if (e.is(scrollIntoView))\n scrollTarget = e.value.clip(this.state);\n }\n this.viewState.update(update, scrollTarget);\n this.bidiCache = CachedOrder.update(this.bidiCache, update.changes);\n if (!update.empty) {\n this.updatePlugins(update);\n this.inputState.update(update);\n }\n redrawn = this.docView.update(update);\n if (this.state.facet(styleModule) != this.styleModules)\n this.mountStyles();\n attrsChanged = this.updateAttrs();\n this.showAnnouncements(transactions);\n this.docView.updateSelection(redrawn, transactions.some(tr => tr.isUserEvent(\"select.pointer\")));\n }\n finally {\n this.updateState = 0 /* UpdateState.Idle */;\n }\n if (update.startState.facet(theme) != update.state.facet(theme))\n this.viewState.mustMeasureContent = true;\n if (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent)\n this.requestMeasure();\n if (!update.empty)\n for (let listener of this.state.facet(updateListener)) {\n try {\n listener(update);\n }\n catch (e) {\n logException(this.state, e, \"update listener\");\n }\n }\n if (dispatchFocus || domChange)\n Promise.resolve().then(() => {\n if (dispatchFocus && this.state == dispatchFocus.startState)\n this.dispatch(dispatchFocus);\n if (domChange) {\n if (!applyDOMChange(this, domChange) && pendingKey.force)\n dispatchKey(this.contentDOM, pendingKey.key, pendingKey.keyCode);\n }\n });\n }\n /**\n Reset the view to the given state. (This will cause the entire\n document to be redrawn and all view plugins to be reinitialized,\n so you should probably only use it when the new state isn't\n derived from the old state. Otherwise, use\n [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead.)\n */\n setState(newState) {\n if (this.updateState != 0 /* UpdateState.Idle */)\n throw new Error(\"Calls to EditorView.setState are not allowed while an update is in progress\");\n if (this.destroyed) {\n this.viewState.state = newState;\n return;\n }\n this.updateState = 2 /* UpdateState.Updating */;\n let hadFocus = this.hasFocus;\n try {\n for (let plugin of this.plugins)\n plugin.destroy(this);\n this.viewState = new ViewState(newState);\n this.plugins = newState.facet(viewPlugin).map(spec => new PluginInstance(spec));\n this.pluginMap.clear();\n for (let plugin of this.plugins)\n plugin.update(this);\n this.docView = new DocView(this);\n this.inputState.ensureHandlers(this.plugins);\n this.mountStyles();\n this.updateAttrs();\n this.bidiCache = [];\n }\n finally {\n this.updateState = 0 /* UpdateState.Idle */;\n }\n if (hadFocus)\n this.focus();\n this.requestMeasure();\n }\n updatePlugins(update) {\n let prevSpecs = update.startState.facet(viewPlugin), specs = update.state.facet(viewPlugin);\n if (prevSpecs != specs) {\n let newPlugins = [];\n for (let spec of specs) {\n let found = prevSpecs.indexOf(spec);\n if (found < 0) {\n newPlugins.push(new PluginInstance(spec));\n }\n else {\n let plugin = this.plugins[found];\n plugin.mustUpdate = update;\n newPlugins.push(plugin);\n }\n }\n for (let plugin of this.plugins)\n if (plugin.mustUpdate != update)\n plugin.destroy(this);\n this.plugins = newPlugins;\n this.pluginMap.clear();\n }\n else {\n for (let p of this.plugins)\n p.mustUpdate = update;\n }\n for (let i = 0; i < this.plugins.length; i++)\n this.plugins[i].update(this);\n if (prevSpecs != specs)\n this.inputState.ensureHandlers(this.plugins);\n }\n /**\n @internal\n */\n measure(flush = true) {\n if (this.destroyed)\n return;\n if (this.measureScheduled > -1)\n this.win.cancelAnimationFrame(this.measureScheduled);\n if (this.observer.delayedAndroidKey) {\n this.measureScheduled = -1;\n this.requestMeasure();\n return;\n }\n this.measureScheduled = 0; // Prevent requestMeasure calls from scheduling another animation frame\n if (flush)\n this.observer.forceFlush();\n let updated = null;\n let sDOM = this.scrollDOM, scrollTop = sDOM.scrollTop * this.scaleY;\n let { scrollAnchorPos, scrollAnchorHeight } = this.viewState;\n if (Math.abs(scrollTop - this.viewState.scrollTop) > 1)\n scrollAnchorHeight = -1;\n this.viewState.scrollAnchorHeight = -1;\n try {\n for (let i = 0;; i++) {\n if (scrollAnchorHeight < 0) {\n if (isScrolledToBottom(sDOM)) {\n scrollAnchorPos = -1;\n scrollAnchorHeight = this.viewState.heightMap.height;\n }\n else {\n let block = this.viewState.scrollAnchorAt(scrollTop);\n scrollAnchorPos = block.from;\n scrollAnchorHeight = block.top;\n }\n }\n this.updateState = 1 /* UpdateState.Measuring */;\n let changed = this.viewState.measure(this);\n if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null)\n break;\n if (i > 5) {\n console.warn(this.measureRequests.length\n ? \"Measure loop restarted more than 5 times\"\n : \"Viewport failed to stabilize\");\n break;\n }\n let measuring = [];\n // Only run measure requests in this cycle when the viewport didn't change\n if (!(changed & 4 /* UpdateFlag.Viewport */))\n [this.measureRequests, measuring] = [measuring, this.measureRequests];\n let measured = measuring.map(m => {\n try {\n return m.read(this);\n }\n catch (e) {\n logException(this.state, e);\n return BadMeasure;\n }\n });\n let update = ViewUpdate.create(this, this.state, []), redrawn = false;\n update.flags |= changed;\n if (!updated)\n updated = update;\n else\n updated.flags |= changed;\n this.updateState = 2 /* UpdateState.Updating */;\n if (!update.empty) {\n this.updatePlugins(update);\n this.inputState.update(update);\n this.updateAttrs();\n redrawn = this.docView.update(update);\n }\n for (let i = 0; i < measuring.length; i++)\n if (measured[i] != BadMeasure) {\n try {\n let m = measuring[i];\n if (m.write)\n m.write(measured[i], this);\n }\n catch (e) {\n logException(this.state, e);\n }\n }\n if (redrawn)\n this.docView.updateSelection(true);\n if (!update.viewportChanged && this.measureRequests.length == 0) {\n if (this.viewState.editorHeight) {\n if (this.viewState.scrollTarget) {\n this.docView.scrollIntoView(this.viewState.scrollTarget);\n this.viewState.scrollTarget = null;\n continue;\n }\n else {\n let newAnchorHeight = scrollAnchorPos < 0 ? this.viewState.heightMap.height :\n this.viewState.lineBlockAt(scrollAnchorPos).top;\n let diff = newAnchorHeight - scrollAnchorHeight;\n if (diff > 1 || diff < -1) {\n scrollTop = scrollTop + diff;\n sDOM.scrollTop = scrollTop / this.scaleY;\n scrollAnchorHeight = -1;\n continue;\n }\n }\n }\n break;\n }\n }\n }\n finally {\n this.updateState = 0 /* UpdateState.Idle */;\n this.measureScheduled = -1;\n }\n if (updated && !updated.empty)\n for (let listener of this.state.facet(updateListener))\n listener(updated);\n }\n /**\n Get the CSS classes for the currently active editor themes.\n */\n get themeClasses() {\n return baseThemeID + \" \" +\n (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + \" \" +\n this.state.facet(theme);\n }\n updateAttrs() {\n let editorAttrs = attrsFromFacet(this, editorAttributes, {\n class: \"cm-editor\" + (this.hasFocus ? \" cm-focused \" : \" \") + this.themeClasses\n });\n let contentAttrs = {\n spellcheck: \"false\",\n autocorrect: \"off\",\n autocapitalize: \"off\",\n translate: \"no\",\n contenteditable: !this.state.facet(editable) ? \"false\" : \"true\",\n class: \"cm-content\",\n style: `${browser.tabSize}: ${this.state.tabSize}`,\n role: \"textbox\",\n \"aria-multiline\": \"true\"\n };\n if (this.state.readOnly)\n contentAttrs[\"aria-readonly\"] = \"true\";\n attrsFromFacet(this, contentAttributes, contentAttrs);\n let changed = this.observer.ignore(() => {\n let changedContent = updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs);\n let changedEditor = updateAttrs(this.dom, this.editorAttrs, editorAttrs);\n return changedContent || changedEditor;\n });\n this.editorAttrs = editorAttrs;\n this.contentAttrs = contentAttrs;\n return changed;\n }\n showAnnouncements(trs) {\n let first = true;\n for (let tr of trs)\n for (let effect of tr.effects)\n if (effect.is(EditorView.announce)) {\n if (first)\n this.announceDOM.textContent = \"\";\n first = false;\n let div = this.announceDOM.appendChild(document.createElement(\"div\"));\n div.textContent = effect.value;\n }\n }\n mountStyles() {\n this.styleModules = this.state.facet(styleModule);\n let nonce = this.state.facet(EditorView.cspNonce);\n StyleModule.mount(this.root, this.styleModules.concat(baseTheme$1).reverse(), nonce ? { nonce } : undefined);\n }\n readMeasured() {\n if (this.updateState == 2 /* UpdateState.Updating */)\n throw new Error(\"Reading the editor layout isn't allowed during an update\");\n if (this.updateState == 0 /* UpdateState.Idle */ && this.measureScheduled > -1)\n this.measure(false);\n }\n /**\n Schedule a layout measurement, optionally providing callbacks to\n do custom DOM measuring followed by a DOM write phase. Using\n this is preferable reading DOM layout directly from, for\n example, an event handler, because it'll make sure measuring and\n drawing done by other components is synchronized, avoiding\n unnecessary DOM layout computations.\n */\n requestMeasure(request) {\n if (this.measureScheduled < 0)\n this.measureScheduled = this.win.requestAnimationFrame(() => this.measure());\n if (request) {\n if (this.measureRequests.indexOf(request) > -1)\n return;\n if (request.key != null)\n for (let i = 0; i < this.measureRequests.length; i++) {\n if (this.measureRequests[i].key === request.key) {\n this.measureRequests[i] = request;\n return;\n }\n }\n this.measureRequests.push(request);\n }\n }\n /**\n Get the value of a specific plugin, if present. Note that\n plugins that crash can be dropped from a view, so even when you\n know you registered a given plugin, it is recommended to check\n the return value of this method.\n */\n plugin(plugin) {\n let known = this.pluginMap.get(plugin);\n if (known === undefined || known && known.spec != plugin)\n this.pluginMap.set(plugin, known = this.plugins.find(p => p.spec == plugin) || null);\n return known && known.update(this).value;\n }\n /**\n The top position of the document, in screen coordinates. This\n may be negative when the editor is scrolled down. Points\n directly to the top of the first line, not above the padding.\n */\n get documentTop() {\n return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop;\n }\n /**\n Reports the padding above and below the document.\n */\n get documentPadding() {\n return { top: this.viewState.paddingTop, bottom: this.viewState.paddingBottom };\n }\n /**\n If the editor is transformed with CSS, this provides the scale\n along the X axis. Otherwise, it will just be 1. Note that\n transforms other than translation and scaling are not supported.\n */\n get scaleX() { return this.viewState.scaleX; }\n /**\n Provide the CSS transformed scale along the Y axis.\n */\n get scaleY() { return this.viewState.scaleY; }\n /**\n Find the text line or block widget at the given vertical\n position (which is interpreted as relative to the [top of the\n document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop)).\n */\n elementAtHeight(height) {\n this.readMeasured();\n return this.viewState.elementAtHeight(height);\n }\n /**\n Find the line block (see\n [`lineBlockAt`](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) at the given\n height, again interpreted relative to the [top of the\n document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop).\n */\n lineBlockAtHeight(height) {\n this.readMeasured();\n return this.viewState.lineBlockAtHeight(height);\n }\n /**\n Get the extent and vertical position of all [line\n blocks](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) in the viewport. Positions\n are relative to the [top of the\n document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop);\n */\n get viewportLineBlocks() {\n return this.viewState.viewportLines;\n }\n /**\n Find the line block around the given document position. A line\n block is a range delimited on both sides by either a\n non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^replace) line breaks, or the\n start/end of the document. It will usually just hold a line of\n text, but may be broken into multiple textblocks by block\n widgets.\n */\n lineBlockAt(pos) {\n return this.viewState.lineBlockAt(pos);\n }\n /**\n The editor's total content height.\n */\n get contentHeight() {\n return this.viewState.contentHeight;\n }\n /**\n Move a cursor position by [grapheme\n cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak). `forward` determines whether\n the motion is away from the line start, or towards it. In\n bidirectional text, the line is traversed in visual order, using\n the editor's [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).\n When the start position was the last one on the line, the\n returned position will be across the line break. If there is no\n further line, the original position is returned.\n \n By default, this method moves over a single cluster. The\n optional `by` argument can be used to move across more. It will\n be called with the first cluster as argument, and should return\n a predicate that determines, for each subsequent cluster,\n whether it should also be moved over.\n */\n moveByChar(start, forward, by) {\n return skipAtoms(this, start, moveByChar(this, start, forward, by));\n }\n /**\n Move a cursor position across the next group of either\n [letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter\n non-whitespace characters.\n */\n moveByGroup(start, forward) {\n return skipAtoms(this, start, moveByChar(this, start, forward, initial => byGroup(this, start.head, initial)));\n }\n /**\n Move to the next line boundary in the given direction. If\n `includeWrap` is true, line wrapping is on, and there is a\n further wrap point on the current line, the wrap point will be\n returned. Otherwise this function will return the start or end\n of the line.\n */\n moveToLineBoundary(start, forward, includeWrap = true) {\n return moveToLineBoundary(this, start, forward, includeWrap);\n }\n /**\n Move a cursor position vertically. When `distance` isn't given,\n it defaults to moving to the next line (including wrapped\n lines). Otherwise, `distance` should provide a positive distance\n in pixels.\n \n When `start` has a\n [`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical\n motion will use that as a target horizontal position. Otherwise,\n the cursor's own horizontal position is used. The returned\n cursor will have its goal column set to whichever column was\n used.\n */\n moveVertically(start, forward, distance) {\n return skipAtoms(this, start, moveVertically(this, start, forward, distance));\n }\n /**\n Find the DOM parent node and offset (child offset if `node` is\n an element, character offset when it is a text node) at the\n given document position.\n \n Note that for positions that aren't currently in\n `visibleRanges`, the resulting DOM position isn't necessarily\n meaningful (it may just point before or after a placeholder\n element).\n */\n domAtPos(pos) {\n return this.docView.domAtPos(pos);\n }\n /**\n Find the document position at the given DOM node. Can be useful\n for associating positions with DOM events. Will raise an error\n when `node` isn't part of the editor content.\n */\n posAtDOM(node, offset = 0) {\n return this.docView.posFromDOM(node, offset);\n }\n posAtCoords(coords, precise = true) {\n this.readMeasured();\n return posAtCoords(this, coords, precise);\n }\n /**\n Get the screen coordinates at the given document position.\n `side` determines whether the coordinates are based on the\n element before (-1) or after (1) the position (if no element is\n available on the given side, the method will transparently use\n another strategy to get reasonable coordinates).\n */\n coordsAtPos(pos, side = 1) {\n this.readMeasured();\n let rect = this.docView.coordsAt(pos, side);\n if (!rect || rect.left == rect.right)\n return rect;\n let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line);\n let span = order[BidiSpan.find(order, pos - line.from, -1, side)];\n return flattenRect(rect, (span.dir == Direction.LTR) == (side > 0));\n }\n /**\n Return the rectangle around a given character. If `pos` does not\n point in front of a character that is in the viewport and\n rendered (i.e. not replaced, not a line break), this will return\n null. For space characters that are a line wrap point, this will\n return the position before the line break.\n */\n coordsForChar(pos) {\n this.readMeasured();\n return this.docView.coordsForChar(pos);\n }\n /**\n The default width of a character in the editor. May not\n accurately reflect the width of all characters (given variable\n width fonts or styling of invididual ranges).\n */\n get defaultCharacterWidth() { return this.viewState.heightOracle.charWidth; }\n /**\n The default height of a line in the editor. May not be accurate\n for all lines.\n */\n get defaultLineHeight() { return this.viewState.heightOracle.lineHeight; }\n /**\n The text direction\n ([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction)\n CSS property) of the editor's content element.\n */\n get textDirection() { return this.viewState.defaultTextDirection; }\n /**\n Find the text direction of the block at the given position, as\n assigned by CSS. If\n [`perLineTextDirection`](https://codemirror.net/6/docs/ref/#view.EditorView^perLineTextDirection)\n isn't enabled, or the given position is outside of the viewport,\n this will always return the same as\n [`textDirection`](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). Note that\n this may trigger a DOM layout.\n */\n textDirectionAt(pos) {\n let perLine = this.state.facet(perLineTextDirection);\n if (!perLine || pos < this.viewport.from || pos > this.viewport.to)\n return this.textDirection;\n this.readMeasured();\n return this.docView.textDirectionAt(pos);\n }\n /**\n Whether this editor [wraps lines](https://codemirror.net/6/docs/ref/#view.EditorView.lineWrapping)\n (as determined by the\n [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space)\n CSS property of its content element).\n */\n get lineWrapping() { return this.viewState.heightOracle.lineWrapping; }\n /**\n Returns the bidirectional text structure of the given line\n (which should be in the current document) as an array of span\n objects. The order of these spans matches the [text\n direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection)—if that is\n left-to-right, the leftmost spans come first, otherwise the\n rightmost spans come first.\n */\n bidiSpans(line) {\n if (line.length > MaxBidiLine)\n return trivialOrder(line.length);\n let dir = this.textDirectionAt(line.from), isolates;\n for (let entry of this.bidiCache) {\n if (entry.from == line.from && entry.dir == dir &&\n (entry.fresh || isolatesEq(entry.isolates, isolates = getIsolatedRanges(this, line.from, line.to))))\n return entry.order;\n }\n if (!isolates)\n isolates = getIsolatedRanges(this, line.from, line.to);\n let order = computeOrder(line.text, dir, isolates);\n this.bidiCache.push(new CachedOrder(line.from, line.to, dir, isolates, true, order));\n return order;\n }\n /**\n Check whether the editor has focus.\n */\n get hasFocus() {\n var _a;\n // Safari return false for hasFocus when the context menu is open\n // or closing, which leads us to ignore selection changes from the\n // context menu because it looks like the editor isn't focused.\n // This kludges around that.\n return (this.dom.ownerDocument.hasFocus() || browser.safari && ((_a = this.inputState) === null || _a === void 0 ? void 0 : _a.lastContextMenu) > Date.now() - 3e4) &&\n this.root.activeElement == this.contentDOM;\n }\n /**\n Put focus on the editor.\n */\n focus() {\n this.observer.ignore(() => {\n focusPreventScroll(this.contentDOM);\n this.docView.updateSelection();\n });\n }\n /**\n Update the [root](https://codemirror.net/6/docs/ref/##view.EditorViewConfig.root) in which the editor lives. This is only\n necessary when moving the editor's existing DOM to a new window or shadow root.\n */\n setRoot(root) {\n if (this._root != root) {\n this._root = root;\n this.observer.setWindow((root.nodeType == 9 ? root : root.ownerDocument).defaultView || window);\n this.mountStyles();\n }\n }\n /**\n Clean up this editor view, removing its element from the\n document, unregistering event handlers, and notifying\n plugins. The view instance can no longer be used after\n calling this.\n */\n destroy() {\n for (let plugin of this.plugins)\n plugin.destroy(this);\n this.plugins = [];\n this.inputState.destroy();\n this.dom.remove();\n this.observer.destroy();\n if (this.measureScheduled > -1)\n this.win.cancelAnimationFrame(this.measureScheduled);\n this.destroyed = true;\n }\n /**\n Returns an effect that can be\n [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to\n cause it to scroll the given position or range into view.\n */\n static scrollIntoView(pos, options = {}) {\n return scrollIntoView.of(new ScrollTarget(typeof pos == \"number\" ? EditorSelection.cursor(pos) : pos, options.y, options.x, options.yMargin, options.xMargin));\n }\n /**\n Return an effect that resets the editor to its current (at the\n time this method was called) scroll position. Note that this\n only affects the editor's own scrollable element, not parents.\n See also\n [`EditorViewConfig.scrollTo`](https://codemirror.net/6/docs/ref/#view.EditorViewConfig.scrollTo).\n \n The effect should be used with a document identical to the one\n it was created for. Failing to do so is not an error, but may\n not scroll to the expected position. You can\n [map](https://codemirror.net/6/docs/ref/#state.StateEffect.map) the effect to account for changes.\n */\n scrollSnapshot() {\n let { scrollTop, scrollLeft } = this.scrollDOM;\n let ref = this.viewState.scrollAnchorAt(scrollTop);\n return scrollIntoView.of(new ScrollTarget(EditorSelection.cursor(ref.from), \"start\", \"start\", ref.top - scrollTop, scrollLeft, true));\n }\n /**\n Returns an extension that can be used to add DOM event handlers.\n The value should be an object mapping event names to handler\n functions. For any given event, such functions are ordered by\n extension precedence, and the first handler to return true will\n be assumed to have handled that event, and no other handlers or\n built-in behavior will be activated for it. These are registered\n on the [content element](https://codemirror.net/6/docs/ref/#view.EditorView.contentDOM), except\n for `scroll` handlers, which will be called any time the\n editor's [scroll element](https://codemirror.net/6/docs/ref/#view.EditorView.scrollDOM) or one of\n its parent nodes is scrolled.\n */\n static domEventHandlers(handlers) {\n return ViewPlugin.define(() => ({}), { eventHandlers: handlers });\n }\n /**\n Create an extension that registers DOM event observers. Contrary\n to event [handlers](https://codemirror.net/6/docs/ref/#view.EditorView^domEventHandlers),\n observers can't be prevented from running by a higher-precedence\n handler returning true. They also don't prevent other handlers\n and observers from running when they return true, and should not\n call `preventDefault`.\n */\n static domEventObservers(observers) {\n return ViewPlugin.define(() => ({}), { eventObservers: observers });\n }\n /**\n Create a theme extension. The first argument can be a\n [`style-mod`](https://github.com/marijnh/style-mod#documentation)\n style spec providing the styles for the theme. These will be\n prefixed with a generated class for the style.\n \n Because the selectors will be prefixed with a scope class, rule\n that directly match the editor's [wrapper\n element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be\n added—need to be explicitly differentiated by adding an `&` to\n the selector for that element—for example\n `&.cm-focused`.\n \n When `dark` is set to true, the theme will be marked as dark,\n which will cause the `&dark` rules from [base\n themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to\n `&light` when a light theme is active).\n */\n static theme(spec, options) {\n let prefix = StyleModule.newName();\n let result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))];\n if (options && options.dark)\n result.push(darkTheme.of(true));\n return result;\n }\n /**\n Create an extension that adds styles to the base theme. Like\n with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the\n place of the editor wrapper element when directly targeting\n that. You can also use `&dark` or `&light` instead to only\n target editors with a dark or light theme.\n */\n static baseTheme(spec) {\n return Prec.lowest(styleModule.of(buildTheme(\".\" + baseThemeID, spec, lightDarkIDs)));\n }\n /**\n Retrieve an editor view instance from the view's DOM\n representation.\n */\n static findFromDOM(dom) {\n var _a;\n let content = dom.querySelector(\".cm-content\");\n let cView = content && ContentView.get(content) || ContentView.get(dom);\n return ((_a = cView === null || cView === void 0 ? void 0 : cView.rootView) === null || _a === void 0 ? void 0 : _a.view) || null;\n }\n}\n/**\nFacet to add a [style\nmodule](https://github.com/marijnh/style-mod#documentation) to\nan editor view. The view will ensure that the module is\nmounted in its [document\nroot](https://codemirror.net/6/docs/ref/#view.EditorView.constructor^config.root).\n*/\nEditorView.styleModule = styleModule;\n/**\nAn input handler can override the way changes to the editable\nDOM content are handled. Handlers are passed the document\npositions between which the change was found, and the new\ncontent. When one returns true, no further input handlers are\ncalled and the default behavior is prevented.\n\nThe `insert` argument can be used to get the default transaction\nthat would be applied for this input. This can be useful when\ndispatching the custom behavior as a separate transaction.\n*/\nEditorView.inputHandler = inputHandler;\n/**\nThis facet can be used to provide functions that create effects\nto be dispatched when the editor's focus state changes.\n*/\nEditorView.focusChangeEffect = focusChangeEffect;\n/**\nBy default, the editor assumes all its content has the same\n[text direction](https://codemirror.net/6/docs/ref/#view.Direction). Configure this with a `true`\nvalue to make it read the text direction of every (rendered)\nline separately.\n*/\nEditorView.perLineTextDirection = perLineTextDirection;\n/**\nAllows you to provide a function that should be called when the\nlibrary catches an exception from an extension (mostly from view\nplugins, but may be used by other extensions to route exceptions\nfrom user-code-provided callbacks). This is mostly useful for\ndebugging and logging. See [`logException`](https://codemirror.net/6/docs/ref/#view.logException).\n*/\nEditorView.exceptionSink = exceptionSink;\n/**\nA facet that can be used to register a function to be called\nevery time the view updates.\n*/\nEditorView.updateListener = updateListener;\n/**\nFacet that controls whether the editor content DOM is editable.\nWhen its highest-precedence value is `false`, the element will\nnot have its `contenteditable` attribute set. (Note that this\ndoesn't affect API calls that change the editor content, even\nwhen those are bound to keys or buttons. See the\n[`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) facet for that.)\n*/\nEditorView.editable = editable;\n/**\nAllows you to influence the way mouse selection happens. The\nfunctions in this facet will be called for a `mousedown` event\non the editor, and can return an object that overrides the way a\nselection is computed from that mouse click or drag.\n*/\nEditorView.mouseSelectionStyle = mouseSelectionStyle;\n/**\nFacet used to configure whether a given selection drag event\nshould move or copy the selection. The given predicate will be\ncalled with the `mousedown` event, and can return `true` when\nthe drag should move the content.\n*/\nEditorView.dragMovesSelection = dragMovesSelection$1;\n/**\nFacet used to configure whether a given selecting click adds a\nnew range to the existing selection or replaces it entirely. The\ndefault behavior is to check `event.metaKey` on macOS, and\n`event.ctrlKey` elsewhere.\n*/\nEditorView.clickAddsSelectionRange = clickAddsSelectionRange;\n/**\nA facet that determines which [decorations](https://codemirror.net/6/docs/ref/#view.Decoration)\nare shown in the view. Decorations can be provided in two\nways—directly, or via a function that takes an editor view.\n\nOnly decoration sets provided directly are allowed to influence\nthe editor's vertical layout structure. The ones provided as\nfunctions are called _after_ the new viewport has been computed,\nand thus **must not** introduce block widgets or replacing\ndecorations that cover line breaks.\n\nIf you want decorated ranges to behave like atomic units for\ncursor motion and deletion purposes, also provide the range set\ncontaining the decorations to\n[`EditorView.atomicRanges`](https://codemirror.net/6/docs/ref/#view.EditorView^atomicRanges).\n*/\nEditorView.decorations = decorations;\n/**\nUsed to provide ranges that should be treated as atoms as far as\ncursor motion is concerned. This causes methods like\n[`moveByChar`](https://codemirror.net/6/docs/ref/#view.EditorView.moveByChar) and\n[`moveVertically`](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) (and the\ncommands built on top of them) to skip across such regions when\na selection endpoint would enter them. This does _not_ prevent\ndirect programmatic [selection\nupdates](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) from moving into such\nregions.\n*/\nEditorView.atomicRanges = atomicRanges;\n/**\nWhen range decorations add a `unicode-bidi: isolate` style, they\nshould also include a\n[`bidiIsolate`](https://codemirror.net/6/docs/ref/#view.MarkDecorationSpec.bidiIsolate) property\nin their decoration spec, and be exposed through this facet, so\nthat the editor can compute the proper text order. (Other values\nfor `unicode-bidi`, except of course `normal`, are not\nsupported.)\n*/\nEditorView.bidiIsolatedRanges = bidiIsolatedRanges;\n/**\nFacet that allows extensions to provide additional scroll\nmargins (space around the sides of the scrolling element that\nshould be considered invisible). This can be useful when the\nplugin introduces elements that cover part of that element (for\nexample a horizontally fixed gutter).\n*/\nEditorView.scrollMargins = scrollMargins;\n/**\nThis facet records whether a dark theme is active. The extension\nreturned by [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme) automatically\nincludes an instance of this when the `dark` option is set to\ntrue.\n*/\nEditorView.darkTheme = darkTheme;\n/**\nProvides a Content Security Policy nonce to use when creating\nthe style sheets for the editor. Holds the empty string when no\nnonce has been provided.\n*/\nEditorView.cspNonce = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : \"\" });\n/**\nFacet that provides additional DOM attributes for the editor's\neditable DOM element.\n*/\nEditorView.contentAttributes = contentAttributes;\n/**\nFacet that provides DOM attributes for the editor's outer\nelement.\n*/\nEditorView.editorAttributes = editorAttributes;\n/**\nAn extension that enables line wrapping in the editor (by\nsetting CSS `white-space` to `pre-wrap` in the content).\n*/\nEditorView.lineWrapping = /*@__PURE__*/EditorView.contentAttributes.of({ \"class\": \"cm-lineWrapping\" });\n/**\nState effect used to include screen reader announcements in a\ntransaction. These will be added to the DOM in a visually hidden\nelement with `aria-live=\"polite\"` set, and should be used to\ndescribe effects that are visually obvious but may not be\nnoticed by screen reader users (such as moving to the next\nsearch match).\n*/\nEditorView.announce = /*@__PURE__*/StateEffect.define();\n// Maximum line length for which we compute accurate bidi info\nconst MaxBidiLine = 4096;\nconst BadMeasure = {};\nclass CachedOrder {\n constructor(from, to, dir, isolates, fresh, order) {\n this.from = from;\n this.to = to;\n this.dir = dir;\n this.isolates = isolates;\n this.fresh = fresh;\n this.order = order;\n }\n static update(cache, changes) {\n if (changes.empty && !cache.some(c => c.fresh))\n return cache;\n let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : Direction.LTR;\n for (let i = Math.max(0, cache.length - 10); i < cache.length; i++) {\n let entry = cache[i];\n if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to))\n result.push(new CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.isolates, false, entry.order));\n }\n return result;\n }\n}\nfunction attrsFromFacet(view, facet, base) {\n for (let sources = view.state.facet(facet), i = sources.length - 1; i >= 0; i--) {\n let source = sources[i], value = typeof source == \"function\" ? source(view) : source;\n if (value)\n combineAttrs(value, base);\n }\n return base;\n}\n\nconst currentPlatform = browser.mac ? \"mac\" : browser.windows ? \"win\" : browser.linux ? \"linux\" : \"key\";\nfunction normalizeKeyName(name, platform) {\n const parts = name.split(/-(?!$)/);\n let result = parts[parts.length - 1];\n if (result == \"Space\")\n result = \" \";\n let alt, ctrl, shift, meta;\n for (let i = 0; i < parts.length - 1; ++i) {\n const mod = parts[i];\n if (/^(cmd|meta|m)$/i.test(mod))\n meta = true;\n else if (/^a(lt)?$/i.test(mod))\n alt = true;\n else if (/^(c|ctrl|control)$/i.test(mod))\n ctrl = true;\n else if (/^s(hift)?$/i.test(mod))\n shift = true;\n else if (/^mod$/i.test(mod)) {\n if (platform == \"mac\")\n meta = true;\n else\n ctrl = true;\n }\n else\n throw new Error(\"Unrecognized modifier name: \" + mod);\n }\n if (alt)\n result = \"Alt-\" + result;\n if (ctrl)\n result = \"Ctrl-\" + result;\n if (meta)\n result = \"Meta-\" + result;\n if (shift)\n result = \"Shift-\" + result;\n return result;\n}\nfunction modifiers(name, event, shift) {\n if (event.altKey)\n name = \"Alt-\" + name;\n if (event.ctrlKey)\n name = \"Ctrl-\" + name;\n if (event.metaKey)\n name = \"Meta-\" + name;\n if (shift !== false && event.shiftKey)\n name = \"Shift-\" + name;\n return name;\n}\nconst handleKeyEvents = /*@__PURE__*/Prec.default(/*@__PURE__*/EditorView.domEventHandlers({\n keydown(event, view) {\n return runHandlers(getKeymap(view.state), event, view, \"editor\");\n }\n}));\n/**\nFacet used for registering keymaps.\n\nYou can add multiple keymaps to an editor. Their priorities\ndetermine their precedence (the ones specified early or with high\npriority get checked first). When a handler has returned `true`\nfor a given key, no further handlers are called.\n*/\nconst keymap = /*@__PURE__*/Facet.define({ enables: handleKeyEvents });\nconst Keymaps = /*@__PURE__*/new WeakMap();\n// This is hidden behind an indirection, rather than directly computed\n// by the facet, to keep internal types out of the facet's type.\nfunction getKeymap(state) {\n let bindings = state.facet(keymap);\n let map = Keymaps.get(bindings);\n if (!map)\n Keymaps.set(bindings, map = buildKeymap(bindings.reduce((a, b) => a.concat(b), [])));\n return map;\n}\n/**\nRun the key handlers registered for a given scope. The event\nobject should be a `\"keydown\"` event. Returns true if any of the\nhandlers handled it.\n*/\nfunction runScopeHandlers(view, event, scope) {\n return runHandlers(getKeymap(view.state), event, view, scope);\n}\nlet storedPrefix = null;\nconst PrefixTimeout = 4000;\nfunction buildKeymap(bindings, platform = currentPlatform) {\n let bound = Object.create(null);\n let isPrefix = Object.create(null);\n let checkPrefix = (name, is) => {\n let current = isPrefix[name];\n if (current == null)\n isPrefix[name] = is;\n else if (current != is)\n throw new Error(\"Key binding \" + name + \" is used both as a regular binding and as a multi-stroke prefix\");\n };\n let add = (scope, key, command, preventDefault, stopPropagation) => {\n var _a, _b;\n let scopeObj = bound[scope] || (bound[scope] = Object.create(null));\n let parts = key.split(/ (?!$)/).map(k => normalizeKeyName(k, platform));\n for (let i = 1; i < parts.length; i++) {\n let prefix = parts.slice(0, i).join(\" \");\n checkPrefix(prefix, true);\n if (!scopeObj[prefix])\n scopeObj[prefix] = {\n preventDefault: true,\n stopPropagation: false,\n run: [(view) => {\n let ourObj = storedPrefix = { view, prefix, scope };\n setTimeout(() => { if (storedPrefix == ourObj)\n storedPrefix = null; }, PrefixTimeout);\n return true;\n }]\n };\n }\n let full = parts.join(\" \");\n checkPrefix(full, false);\n let binding = scopeObj[full] || (scopeObj[full] = {\n preventDefault: false,\n stopPropagation: false,\n run: ((_b = (_a = scopeObj._any) === null || _a === void 0 ? void 0 : _a.run) === null || _b === void 0 ? void 0 : _b.slice()) || []\n });\n if (command)\n binding.run.push(command);\n if (preventDefault)\n binding.preventDefault = true;\n if (stopPropagation)\n binding.stopPropagation = true;\n };\n for (let b of bindings) {\n let scopes = b.scope ? b.scope.split(\" \") : [\"editor\"];\n if (b.any)\n for (let scope of scopes) {\n let scopeObj = bound[scope] || (bound[scope] = Object.create(null));\n if (!scopeObj._any)\n scopeObj._any = { preventDefault: false, stopPropagation: false, run: [] };\n for (let key in scopeObj)\n scopeObj[key].run.push(b.any);\n }\n let name = b[platform] || b.key;\n if (!name)\n continue;\n for (let scope of scopes) {\n add(scope, name, b.run, b.preventDefault, b.stopPropagation);\n if (b.shift)\n add(scope, \"Shift-\" + name, b.shift, b.preventDefault, b.stopPropagation);\n }\n }\n return bound;\n}\nfunction runHandlers(map, event, view, scope) {\n let name = keyName(event);\n let charCode = codePointAt(name, 0), isChar = codePointSize(charCode) == name.length && name != \" \";\n let prefix = \"\", handled = false, prevented = false, stopPropagation = false;\n if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) {\n prefix = storedPrefix.prefix + \" \";\n if (modifierCodes.indexOf(event.keyCode) < 0) {\n prevented = true;\n storedPrefix = null;\n }\n }\n let ran = new Set;\n let runFor = (binding) => {\n if (binding) {\n for (let cmd of binding.run)\n if (!ran.has(cmd)) {\n ran.add(cmd);\n if (cmd(view, event)) {\n if (binding.stopPropagation)\n stopPropagation = true;\n return true;\n }\n }\n if (binding.preventDefault) {\n if (binding.stopPropagation)\n stopPropagation = true;\n prevented = true;\n }\n }\n return false;\n };\n let scopeObj = map[scope], baseName, shiftName;\n if (scopeObj) {\n if (runFor(scopeObj[prefix + modifiers(name, event, !isChar)])) {\n handled = true;\n }\n else if (isChar && (event.altKey || event.metaKey || event.ctrlKey) &&\n // Ctrl-Alt may be used for AltGr on Windows\n !(browser.windows && event.ctrlKey && event.altKey) &&\n (baseName = base[event.keyCode]) && baseName != name) {\n if (runFor(scopeObj[prefix + modifiers(baseName, event, true)])) {\n handled = true;\n }\n else if (event.shiftKey && (shiftName = shift[event.keyCode]) != name && shiftName != baseName &&\n runFor(scopeObj[prefix + modifiers(shiftName, event, false)])) {\n handled = true;\n }\n }\n else if (isChar && event.shiftKey &&\n runFor(scopeObj[prefix + modifiers(name, event, true)])) {\n handled = true;\n }\n if (!handled && runFor(scopeObj._any))\n handled = true;\n }\n if (prevented)\n handled = true;\n if (handled && stopPropagation)\n event.stopPropagation();\n return handled;\n}\n\n/**\nImplementation of [`LayerMarker`](https://codemirror.net/6/docs/ref/#view.LayerMarker) that creates\na rectangle at a given set of coordinates.\n*/\nclass RectangleMarker {\n /**\n Create a marker with the given class and dimensions. If `width`\n is null, the DOM element will get no width style.\n */\n constructor(className, \n /**\n The left position of the marker (in pixels, document-relative).\n */\n left, \n /**\n The top position of the marker.\n */\n top, \n /**\n The width of the marker, or null if it shouldn't get a width assigned.\n */\n width, \n /**\n The height of the marker.\n */\n height) {\n this.className = className;\n this.left = left;\n this.top = top;\n this.width = width;\n this.height = height;\n }\n draw() {\n let elt = document.createElement(\"div\");\n elt.className = this.className;\n this.adjust(elt);\n return elt;\n }\n update(elt, prev) {\n if (prev.className != this.className)\n return false;\n this.adjust(elt);\n return true;\n }\n adjust(elt) {\n elt.style.left = this.left + \"px\";\n elt.style.top = this.top + \"px\";\n if (this.width != null)\n elt.style.width = this.width + \"px\";\n elt.style.height = this.height + \"px\";\n }\n eq(p) {\n return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height &&\n this.className == p.className;\n }\n /**\n Create a set of rectangles for the given selection range,\n assigning them theclass`className`. Will create a single\n rectangle for empty ranges, and a set of selection-style\n rectangles covering the range's content (in a bidi-aware\n way) for non-empty ones.\n */\n static forRange(view, className, range) {\n if (range.empty) {\n let pos = view.coordsAtPos(range.head, range.assoc || 1);\n if (!pos)\n return [];\n let base = getBase(view);\n return [new RectangleMarker(className, pos.left - base.left, pos.top - base.top, null, pos.bottom - pos.top)];\n }\n else {\n return rectanglesForRange(view, className, range);\n }\n }\n}\nfunction getBase(view) {\n let rect = view.scrollDOM.getBoundingClientRect();\n let left = view.textDirection == Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth * view.scaleX;\n return { left: left - view.scrollDOM.scrollLeft * view.scaleX, top: rect.top - view.scrollDOM.scrollTop * view.scaleY };\n}\nfunction wrappedLine(view, pos, inside) {\n let range = EditorSelection.cursor(pos);\n return { from: Math.max(inside.from, view.moveToLineBoundary(range, false, true).from),\n to: Math.min(inside.to, view.moveToLineBoundary(range, true, true).from),\n type: BlockType.Text };\n}\nfunction rectanglesForRange(view, className, range) {\n if (range.to <= view.viewport.from || range.from >= view.viewport.to)\n return [];\n let from = Math.max(range.from, view.viewport.from), to = Math.min(range.to, view.viewport.to);\n let ltr = view.textDirection == Direction.LTR;\n let content = view.contentDOM, contentRect = content.getBoundingClientRect(), base = getBase(view);\n let lineElt = content.querySelector(\".cm-line\"), lineStyle = lineElt && window.getComputedStyle(lineElt);\n let leftSide = contentRect.left +\n (lineStyle ? parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)) : 0);\n let rightSide = contentRect.right - (lineStyle ? parseInt(lineStyle.paddingRight) : 0);\n let startBlock = blockAt(view, from), endBlock = blockAt(view, to);\n let visualStart = startBlock.type == BlockType.Text ? startBlock : null;\n let visualEnd = endBlock.type == BlockType.Text ? endBlock : null;\n if (visualStart && (view.lineWrapping || startBlock.widgetLineBreaks))\n visualStart = wrappedLine(view, from, visualStart);\n if (visualEnd && (view.lineWrapping || endBlock.widgetLineBreaks))\n visualEnd = wrappedLine(view, to, visualEnd);\n if (visualStart && visualEnd && visualStart.from == visualEnd.from) {\n return pieces(drawForLine(range.from, range.to, visualStart));\n }\n else {\n let top = visualStart ? drawForLine(range.from, null, visualStart) : drawForWidget(startBlock, false);\n let bottom = visualEnd ? drawForLine(null, range.to, visualEnd) : drawForWidget(endBlock, true);\n let between = [];\n if ((visualStart || startBlock).to < (visualEnd || endBlock).from - (visualStart && visualEnd ? 1 : 0) ||\n startBlock.widgetLineBreaks > 1 && top.bottom + view.defaultLineHeight / 2 < bottom.top)\n between.push(piece(leftSide, top.bottom, rightSide, bottom.top));\n else if (top.bottom < bottom.top && view.elementAtHeight((top.bottom + bottom.top) / 2).type == BlockType.Text)\n top.bottom = bottom.top = (top.bottom + bottom.top) / 2;\n return pieces(top).concat(between).concat(pieces(bottom));\n }\n function piece(left, top, right, bottom) {\n return new RectangleMarker(className, left - base.left, top - base.top - 0.01 /* C.Epsilon */, right - left, bottom - top + 0.01 /* C.Epsilon */);\n }\n function pieces({ top, bottom, horizontal }) {\n let pieces = [];\n for (let i = 0; i < horizontal.length; i += 2)\n pieces.push(piece(horizontal[i], top, horizontal[i + 1], bottom));\n return pieces;\n }\n // Gets passed from/to in line-local positions\n function drawForLine(from, to, line) {\n let top = 1e9, bottom = -1e9, horizontal = [];\n function addSpan(from, fromOpen, to, toOpen, dir) {\n // Passing 2/-2 is a kludge to force the view to return\n // coordinates on the proper side of block widgets, since\n // normalizing the side there, though appropriate for most\n // coordsAtPos queries, would break selection drawing.\n let fromCoords = view.coordsAtPos(from, (from == line.to ? -2 : 2));\n let toCoords = view.coordsAtPos(to, (to == line.from ? 2 : -2));\n if (!fromCoords || !toCoords)\n return;\n top = Math.min(fromCoords.top, toCoords.top, top);\n bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom);\n if (dir == Direction.LTR)\n horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right);\n else\n horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right);\n }\n let start = from !== null && from !== void 0 ? from : line.from, end = to !== null && to !== void 0 ? to : line.to;\n // Split the range by visible range and document line\n for (let r of view.visibleRanges)\n if (r.to > start && r.from < end) {\n for (let pos = Math.max(r.from, start), endPos = Math.min(r.to, end);;) {\n let docLine = view.state.doc.lineAt(pos);\n for (let span of view.bidiSpans(docLine)) {\n let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from;\n if (spanFrom >= endPos)\n break;\n if (spanTo > pos)\n addSpan(Math.max(spanFrom, pos), from == null && spanFrom <= start, Math.min(spanTo, endPos), to == null && spanTo >= end, span.dir);\n }\n pos = docLine.to + 1;\n if (pos >= endPos)\n break;\n }\n }\n if (horizontal.length == 0)\n addSpan(start, from == null, end, to == null, view.textDirection);\n return { top, bottom, horizontal };\n }\n function drawForWidget(block, top) {\n let y = contentRect.top + (top ? block.top : block.bottom);\n return { top: y, bottom: y, horizontal: [] };\n }\n}\nfunction sameMarker(a, b) {\n return a.constructor == b.constructor && a.eq(b);\n}\nclass LayerView {\n constructor(view, layer) {\n this.view = view;\n this.layer = layer;\n this.drawn = [];\n this.scaleX = 1;\n this.scaleY = 1;\n this.measureReq = { read: this.measure.bind(this), write: this.draw.bind(this) };\n this.dom = view.scrollDOM.appendChild(document.createElement(\"div\"));\n this.dom.classList.add(\"cm-layer\");\n if (layer.above)\n this.dom.classList.add(\"cm-layer-above\");\n if (layer.class)\n this.dom.classList.add(layer.class);\n this.scale();\n this.dom.setAttribute(\"aria-hidden\", \"true\");\n this.setOrder(view.state);\n view.requestMeasure(this.measureReq);\n if (layer.mount)\n layer.mount(this.dom, view);\n }\n update(update) {\n if (update.startState.facet(layerOrder) != update.state.facet(layerOrder))\n this.setOrder(update.state);\n if (this.layer.update(update, this.dom) || update.geometryChanged) {\n this.scale();\n update.view.requestMeasure(this.measureReq);\n }\n }\n setOrder(state) {\n let pos = 0, order = state.facet(layerOrder);\n while (pos < order.length && order[pos] != this.layer)\n pos++;\n this.dom.style.zIndex = String((this.layer.above ? 150 : -1) - pos);\n }\n measure() {\n return this.layer.markers(this.view);\n }\n scale() {\n let { scaleX, scaleY } = this.view;\n if (scaleX != this.scaleX || scaleY != this.scaleY) {\n this.scaleX = scaleX;\n this.scaleY = scaleY;\n this.dom.style.transform = `scale(${1 / scaleX}, ${1 / scaleY})`;\n }\n }\n draw(markers) {\n if (markers.length != this.drawn.length || markers.some((p, i) => !sameMarker(p, this.drawn[i]))) {\n let old = this.dom.firstChild, oldI = 0;\n for (let marker of markers) {\n if (marker.update && old && marker.constructor && this.drawn[oldI].constructor &&\n marker.update(old, this.drawn[oldI])) {\n old = old.nextSibling;\n oldI++;\n }\n else {\n this.dom.insertBefore(marker.draw(), old);\n }\n }\n while (old) {\n let next = old.nextSibling;\n old.remove();\n old = next;\n }\n this.drawn = markers;\n }\n }\n destroy() {\n if (this.layer.destroy)\n this.layer.destroy(this.dom, this.view);\n this.dom.remove();\n }\n}\nconst layerOrder = /*@__PURE__*/Facet.define();\n/**\nDefine a layer.\n*/\nfunction layer(config) {\n return [\n ViewPlugin.define(v => new LayerView(v, config)),\n layerOrder.of(config)\n ];\n}\n\nconst CanHidePrimary = !browser.ios; // FIXME test IE\nconst selectionConfig = /*@__PURE__*/Facet.define({\n combine(configs) {\n return combineConfig(configs, {\n cursorBlinkRate: 1200,\n drawRangeCursor: true\n }, {\n cursorBlinkRate: (a, b) => Math.min(a, b),\n drawRangeCursor: (a, b) => a || b\n });\n }\n});\n/**\nReturns an extension that hides the browser's native selection and\ncursor, replacing the selection with a background behind the text\n(with the `cm-selectionBackground` class), and the\ncursors with elements overlaid over the code (using\n`cm-cursor-primary` and `cm-cursor-secondary`).\n\nThis allows the editor to display secondary selection ranges, and\ntends to produce a type of selection more in line with that users\nexpect in a text editor (the native selection styling will often\nleave gaps between lines and won't fill the horizontal space after\na line when the selection continues past it).\n\nIt does have a performance cost, in that it requires an extra DOM\nlayout cycle for many updates (the selection is drawn based on DOM\nlayout information that's only available after laying out the\ncontent).\n*/\nfunction drawSelection(config = {}) {\n return [\n selectionConfig.of(config),\n cursorLayer,\n selectionLayer,\n hideNativeSelection,\n nativeSelectionHidden.of(true)\n ];\n}\n/**\nRetrieve the [`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) configuration\nfor this state. (Note that this will return a set of defaults even\nif `drawSelection` isn't enabled.)\n*/\nfunction getDrawSelectionConfig(state) {\n return state.facet(selectionConfig);\n}\nfunction configChanged(update) {\n return update.startState.facet(selectionConfig) != update.state.facet(selectionConfig);\n}\nconst cursorLayer = /*@__PURE__*/layer({\n above: true,\n markers(view) {\n let { state } = view, conf = state.facet(selectionConfig);\n let cursors = [];\n for (let r of state.selection.ranges) {\n let prim = r == state.selection.main;\n if (r.empty ? !prim || CanHidePrimary : conf.drawRangeCursor) {\n let className = prim ? \"cm-cursor cm-cursor-primary\" : \"cm-cursor cm-cursor-secondary\";\n let cursor = r.empty ? r : EditorSelection.cursor(r.head, r.head > r.anchor ? -1 : 1);\n for (let piece of RectangleMarker.forRange(view, className, cursor))\n cursors.push(piece);\n }\n }\n return cursors;\n },\n update(update, dom) {\n if (update.transactions.some(tr => tr.selection))\n dom.style.animationName = dom.style.animationName == \"cm-blink\" ? \"cm-blink2\" : \"cm-blink\";\n let confChange = configChanged(update);\n if (confChange)\n setBlinkRate(update.state, dom);\n return update.docChanged || update.selectionSet || confChange;\n },\n mount(dom, view) {\n setBlinkRate(view.state, dom);\n },\n class: \"cm-cursorLayer\"\n});\nfunction setBlinkRate(state, dom) {\n dom.style.animationDuration = state.facet(selectionConfig).cursorBlinkRate + \"ms\";\n}\nconst selectionLayer = /*@__PURE__*/layer({\n above: false,\n markers(view) {\n return view.state.selection.ranges.map(r => r.empty ? [] : RectangleMarker.forRange(view, \"cm-selectionBackground\", r))\n .reduce((a, b) => a.concat(b));\n },\n update(update, dom) {\n return update.docChanged || update.selectionSet || update.viewportChanged || configChanged(update);\n },\n class: \"cm-selectionLayer\"\n});\nconst themeSpec = {\n \".cm-line\": {\n \"& ::selection\": { backgroundColor: \"transparent !important\" },\n \"&::selection\": { backgroundColor: \"transparent !important\" }\n }\n};\nif (CanHidePrimary)\n themeSpec[\".cm-line\"].caretColor = \"transparent !important\";\nconst hideNativeSelection = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.theme(themeSpec));\n\nconst setDropCursorPos = /*@__PURE__*/StateEffect.define({\n map(pos, mapping) { return pos == null ? null : mapping.mapPos(pos); }\n});\nconst dropCursorPos = /*@__PURE__*/StateField.define({\n create() { return null; },\n update(pos, tr) {\n if (pos != null)\n pos = tr.changes.mapPos(pos);\n return tr.effects.reduce((pos, e) => e.is(setDropCursorPos) ? e.value : pos, pos);\n }\n});\nconst drawDropCursor = /*@__PURE__*/ViewPlugin.fromClass(class {\n constructor(view) {\n this.view = view;\n this.cursor = null;\n this.measureReq = { read: this.readPos.bind(this), write: this.drawCursor.bind(this) };\n }\n update(update) {\n var _a;\n let cursorPos = update.state.field(dropCursorPos);\n if (cursorPos == null) {\n if (this.cursor != null) {\n (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.remove();\n this.cursor = null;\n }\n }\n else {\n if (!this.cursor) {\n this.cursor = this.view.scrollDOM.appendChild(document.createElement(\"div\"));\n this.cursor.className = \"cm-dropCursor\";\n }\n if (update.startState.field(dropCursorPos) != cursorPos || update.docChanged || update.geometryChanged)\n this.view.requestMeasure(this.measureReq);\n }\n }\n readPos() {\n let { view } = this;\n let pos = view.state.field(dropCursorPos);\n let rect = pos != null && view.coordsAtPos(pos);\n if (!rect)\n return null;\n let outer = view.scrollDOM.getBoundingClientRect();\n return {\n left: rect.left - outer.left + view.scrollDOM.scrollLeft * view.scaleX,\n top: rect.top - outer.top + view.scrollDOM.scrollTop * view.scaleY,\n height: rect.bottom - rect.top\n };\n }\n drawCursor(pos) {\n if (this.cursor) {\n let { scaleX, scaleY } = this.view;\n if (pos) {\n this.cursor.style.left = pos.left / scaleX + \"px\";\n this.cursor.style.top = pos.top / scaleY + \"px\";\n this.cursor.style.height = pos.height / scaleY + \"px\";\n }\n else {\n this.cursor.style.left = \"-100000px\";\n }\n }\n }\n destroy() {\n if (this.cursor)\n this.cursor.remove();\n }\n setDropPos(pos) {\n if (this.view.state.field(dropCursorPos) != pos)\n this.view.dispatch({ effects: setDropCursorPos.of(pos) });\n }\n}, {\n eventObservers: {\n dragover(event) {\n this.setDropPos(this.view.posAtCoords({ x: event.clientX, y: event.clientY }));\n },\n dragleave(event) {\n if (event.target == this.view.contentDOM || !this.view.contentDOM.contains(event.relatedTarget))\n this.setDropPos(null);\n },\n dragend() {\n this.setDropPos(null);\n },\n drop() {\n this.setDropPos(null);\n }\n }\n});\n/**\nDraws a cursor at the current drop position when something is\ndragged over the editor.\n*/\nfunction dropCursor() {\n return [dropCursorPos, drawDropCursor];\n}\n\nfunction iterMatches(doc, re, from, to, f) {\n re.lastIndex = 0;\n for (let cursor = doc.iterRange(from, to), pos = from, m; !cursor.next().done; pos += cursor.value.length) {\n if (!cursor.lineBreak)\n while (m = re.exec(cursor.value))\n f(pos + m.index, m);\n }\n}\nfunction matchRanges(view, maxLength) {\n let visible = view.visibleRanges;\n if (visible.length == 1 && visible[0].from == view.viewport.from &&\n visible[0].to == view.viewport.to)\n return visible;\n let result = [];\n for (let { from, to } of visible) {\n from = Math.max(view.state.doc.lineAt(from).from, from - maxLength);\n to = Math.min(view.state.doc.lineAt(to).to, to + maxLength);\n if (result.length && result[result.length - 1].to >= from)\n result[result.length - 1].to = to;\n else\n result.push({ from, to });\n }\n return result;\n}\n/**\nHelper class used to make it easier to maintain decorations on\nvisible code that matches a given regular expression. To be used\nin a [view plugin](https://codemirror.net/6/docs/ref/#view.ViewPlugin). Instances of this object\nrepresent a matching configuration.\n*/\nclass MatchDecorator {\n /**\n Create a decorator.\n */\n constructor(config) {\n const { regexp, decoration, decorate, boundary, maxLength = 1000 } = config;\n if (!regexp.global)\n throw new RangeError(\"The regular expression given to MatchDecorator should have its 'g' flag set\");\n this.regexp = regexp;\n if (decorate) {\n this.addMatch = (match, view, from, add) => decorate(add, from, from + match[0].length, match, view);\n }\n else if (typeof decoration == \"function\") {\n this.addMatch = (match, view, from, add) => {\n let deco = decoration(match, view, from);\n if (deco)\n add(from, from + match[0].length, deco);\n };\n }\n else if (decoration) {\n this.addMatch = (match, _view, from, add) => add(from, from + match[0].length, decoration);\n }\n else {\n throw new RangeError(\"Either 'decorate' or 'decoration' should be provided to MatchDecorator\");\n }\n this.boundary = boundary;\n this.maxLength = maxLength;\n }\n /**\n Compute the full set of decorations for matches in the given\n view's viewport. You'll want to call this when initializing your\n plugin.\n */\n createDeco(view) {\n let build = new RangeSetBuilder(), add = build.add.bind(build);\n for (let { from, to } of matchRanges(view, this.maxLength))\n iterMatches(view.state.doc, this.regexp, from, to, (from, m) => this.addMatch(m, view, from, add));\n return build.finish();\n }\n /**\n Update a set of decorations for a view update. `deco` _must_ be\n the set of decorations produced by _this_ `MatchDecorator` for\n the view state before the update.\n */\n updateDeco(update, deco) {\n let changeFrom = 1e9, changeTo = -1;\n if (update.docChanged)\n update.changes.iterChanges((_f, _t, from, to) => {\n if (to > update.view.viewport.from && from < update.view.viewport.to) {\n changeFrom = Math.min(from, changeFrom);\n changeTo = Math.max(to, changeTo);\n }\n });\n if (update.viewportChanged || changeTo - changeFrom > 1000)\n return this.createDeco(update.view);\n if (changeTo > -1)\n return this.updateRange(update.view, deco.map(update.changes), changeFrom, changeTo);\n return deco;\n }\n updateRange(view, deco, updateFrom, updateTo) {\n for (let r of view.visibleRanges) {\n let from = Math.max(r.from, updateFrom), to = Math.min(r.to, updateTo);\n if (to > from) {\n let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine;\n let start = Math.max(r.from, fromLine.from), end = Math.min(r.to, toLine.to);\n if (this.boundary) {\n for (; from > fromLine.from; from--)\n if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) {\n start = from;\n break;\n }\n for (; to < toLine.to; to++)\n if (this.boundary.test(toLine.text[to - toLine.from])) {\n end = to;\n break;\n }\n }\n let ranges = [], m;\n let add = (from, to, deco) => ranges.push(deco.range(from, to));\n if (fromLine == toLine) {\n this.regexp.lastIndex = start - fromLine.from;\n while ((m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from)\n this.addMatch(m, view, m.index + fromLine.from, add);\n }\n else {\n iterMatches(view.state.doc, this.regexp, start, end, (from, m) => this.addMatch(m, view, from, add));\n }\n deco = deco.update({ filterFrom: start, filterTo: end, filter: (from, to) => from < start || to > end, add: ranges });\n }\n }\n return deco;\n }\n}\n\nconst UnicodeRegexpSupport = /x/.unicode != null ? \"gu\" : \"g\";\nconst Specials = /*@__PURE__*/new RegExp(\"[\\u0000-\\u0008\\u000a-\\u001f\\u007f-\\u009f\\u00ad\\u061c\\u200b\\u200e\\u200f\\u2028\\u2029\\u202d\\u202e\\u2066\\u2067\\u2069\\ufeff\\ufff9-\\ufffc]\", UnicodeRegexpSupport);\nconst Names = {\n 0: \"null\",\n 7: \"bell\",\n 8: \"backspace\",\n 10: \"newline\",\n 11: \"vertical tab\",\n 13: \"carriage return\",\n 27: \"escape\",\n 8203: \"zero width space\",\n 8204: \"zero width non-joiner\",\n 8205: \"zero width joiner\",\n 8206: \"left-to-right mark\",\n 8207: \"right-to-left mark\",\n 8232: \"line separator\",\n 8237: \"left-to-right override\",\n 8238: \"right-to-left override\",\n 8294: \"left-to-right isolate\",\n 8295: \"right-to-left isolate\",\n 8297: \"pop directional isolate\",\n 8233: \"paragraph separator\",\n 65279: \"zero width no-break space\",\n 65532: \"object replacement\"\n};\nlet _supportsTabSize = null;\nfunction supportsTabSize() {\n var _a;\n if (_supportsTabSize == null && typeof document != \"undefined\" && document.body) {\n let styles = document.body.style;\n _supportsTabSize = ((_a = styles.tabSize) !== null && _a !== void 0 ? _a : styles.MozTabSize) != null;\n }\n return _supportsTabSize || false;\n}\nconst specialCharConfig = /*@__PURE__*/Facet.define({\n combine(configs) {\n let config = combineConfig(configs, {\n render: null,\n specialChars: Specials,\n addSpecialChars: null\n });\n if (config.replaceTabs = !supportsTabSize())\n config.specialChars = new RegExp(\"\\t|\" + config.specialChars.source, UnicodeRegexpSupport);\n if (config.addSpecialChars)\n config.specialChars = new RegExp(config.specialChars.source + \"|\" + config.addSpecialChars.source, UnicodeRegexpSupport);\n return config;\n }\n});\n/**\nReturns an extension that installs highlighting of special\ncharacters.\n*/\nfunction highlightSpecialChars(\n/**\nConfiguration options.\n*/\nconfig = {}) {\n return [specialCharConfig.of(config), specialCharPlugin()];\n}\nlet _plugin = null;\nfunction specialCharPlugin() {\n return _plugin || (_plugin = ViewPlugin.fromClass(class {\n constructor(view) {\n this.view = view;\n this.decorations = Decoration.none;\n this.decorationCache = Object.create(null);\n this.decorator = this.makeDecorator(view.state.facet(specialCharConfig));\n this.decorations = this.decorator.createDeco(view);\n }\n makeDecorator(conf) {\n return new MatchDecorator({\n regexp: conf.specialChars,\n decoration: (m, view, pos) => {\n let { doc } = view.state;\n let code = codePointAt(m[0], 0);\n if (code == 9) {\n let line = doc.lineAt(pos);\n let size = view.state.tabSize, col = countColumn(line.text, size, pos - line.from);\n return Decoration.replace({\n widget: new TabWidget((size - (col % size)) * this.view.defaultCharacterWidth / this.view.scaleX)\n });\n }\n return this.decorationCache[code] ||\n (this.decorationCache[code] = Decoration.replace({ widget: new SpecialCharWidget(conf, code) }));\n },\n boundary: conf.replaceTabs ? undefined : /[^]/\n });\n }\n update(update) {\n let conf = update.state.facet(specialCharConfig);\n if (update.startState.facet(specialCharConfig) != conf) {\n this.decorator = this.makeDecorator(conf);\n this.decorations = this.decorator.createDeco(update.view);\n }\n else {\n this.decorations = this.decorator.updateDeco(update, this.decorations);\n }\n }\n }, {\n decorations: v => v.decorations\n }));\n}\nconst DefaultPlaceholder = \"\\u2022\";\n// Assigns placeholder characters from the Control Pictures block to\n// ASCII control characters\nfunction placeholder$1(code) {\n if (code >= 32)\n return DefaultPlaceholder;\n if (code == 10)\n return \"\\u2424\";\n return String.fromCharCode(9216 + code);\n}\nclass SpecialCharWidget extends WidgetType {\n constructor(options, code) {\n super();\n this.options = options;\n this.code = code;\n }\n eq(other) { return other.code == this.code; }\n toDOM(view) {\n let ph = placeholder$1(this.code);\n let desc = view.state.phrase(\"Control character\") + \" \" + (Names[this.code] || \"0x\" + this.code.toString(16));\n let custom = this.options.render && this.options.render(this.code, desc, ph);\n if (custom)\n return custom;\n let span = document.createElement(\"span\");\n span.textContent = ph;\n span.title = desc;\n span.setAttribute(\"aria-label\", desc);\n span.className = \"cm-specialChar\";\n return span;\n }\n ignoreEvent() { return false; }\n}\nclass TabWidget extends WidgetType {\n constructor(width) {\n super();\n this.width = width;\n }\n eq(other) { return other.width == this.width; }\n toDOM() {\n let span = document.createElement(\"span\");\n span.textContent = \"\\t\";\n span.className = \"cm-tab\";\n span.style.width = this.width + \"px\";\n return span;\n }\n ignoreEvent() { return false; }\n}\n\nconst plugin = /*@__PURE__*/ViewPlugin.fromClass(class {\n constructor() {\n this.height = 1000;\n this.attrs = { style: \"padding-bottom: 1000px\" };\n }\n update(update) {\n let { view } = update;\n let height = view.viewState.editorHeight * view.scaleY -\n view.defaultLineHeight - view.documentPadding.top - 0.5;\n if (height >= 0 && height != this.height) {\n this.height = height;\n this.attrs = { style: `padding-bottom: ${height}px` };\n }\n }\n});\n/**\nReturns an extension that makes sure the content has a bottom\nmargin equivalent to the height of the editor, minus one line\nheight, so that every line in the document can be scrolled to the\ntop of the editor.\n\nThis is only meaningful when the editor is scrollable, and should\nnot be enabled in editors that take the size of their content.\n*/\nfunction scrollPastEnd() {\n return [plugin, contentAttributes.of(view => { var _a; return ((_a = view.plugin(plugin)) === null || _a === void 0 ? void 0 : _a.attrs) || null; })];\n}\n\n/**\nMark lines that have a cursor on them with the `\"cm-activeLine\"`\nDOM class.\n*/\nfunction highlightActiveLine() {\n return activeLineHighlighter;\n}\nconst lineDeco = /*@__PURE__*/Decoration.line({ class: \"cm-activeLine\" });\nconst activeLineHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class {\n constructor(view) {\n this.decorations = this.getDeco(view);\n }\n update(update) {\n if (update.docChanged || update.selectionSet)\n this.decorations = this.getDeco(update.view);\n }\n getDeco(view) {\n let lastLineStart = -1, deco = [];\n for (let r of view.state.selection.ranges) {\n let line = view.lineBlockAt(r.head);\n if (line.from > lastLineStart) {\n deco.push(lineDeco.range(line.from));\n lastLineStart = line.from;\n }\n }\n return Decoration.set(deco);\n }\n}, {\n decorations: v => v.decorations\n});\n\nclass Placeholder extends WidgetType {\n constructor(content) {\n super();\n this.content = content;\n }\n toDOM() {\n let wrap = document.createElement(\"span\");\n wrap.className = \"cm-placeholder\";\n wrap.style.pointerEvents = \"none\";\n wrap.appendChild(typeof this.content == \"string\" ? document.createTextNode(this.content) : this.content);\n if (typeof this.content == \"string\")\n wrap.setAttribute(\"aria-label\", \"placeholder \" + this.content);\n else\n wrap.setAttribute(\"aria-hidden\", \"true\");\n return wrap;\n }\n coordsAt(dom) {\n let rects = dom.firstChild ? clientRectsFor(dom.firstChild) : [];\n if (!rects.length)\n return null;\n let style = window.getComputedStyle(dom.parentNode);\n let rect = flattenRect(rects[0], style.direction != \"rtl\");\n let lineHeight = parseInt(style.lineHeight);\n if (rect.bottom - rect.top > lineHeight * 1.5)\n return { left: rect.left, right: rect.right, top: rect.top, bottom: rect.top + lineHeight };\n return rect;\n }\n ignoreEvent() { return false; }\n}\n/**\nExtension that enables a placeholder—a piece of example content\nto show when the editor is empty.\n*/\nfunction placeholder(content) {\n return ViewPlugin.fromClass(class {\n constructor(view) {\n this.view = view;\n this.placeholder = content\n ? Decoration.set([Decoration.widget({ widget: new Placeholder(content), side: 1 }).range(0)])\n : Decoration.none;\n }\n get decorations() { return this.view.state.doc.length ? Decoration.none : this.placeholder; }\n }, { decorations: v => v.decorations });\n}\n\n// Don't compute precise column positions for line offsets above this\n// (since it could get expensive). Assume offset==column for them.\nconst MaxOff = 2000;\nfunction rectangleFor(state, a, b) {\n let startLine = Math.min(a.line, b.line), endLine = Math.max(a.line, b.line);\n let ranges = [];\n if (a.off > MaxOff || b.off > MaxOff || a.col < 0 || b.col < 0) {\n let startOff = Math.min(a.off, b.off), endOff = Math.max(a.off, b.off);\n for (let i = startLine; i <= endLine; i++) {\n let line = state.doc.line(i);\n if (line.length <= endOff)\n ranges.push(EditorSelection.range(line.from + startOff, line.to + endOff));\n }\n }\n else {\n let startCol = Math.min(a.col, b.col), endCol = Math.max(a.col, b.col);\n for (let i = startLine; i <= endLine; i++) {\n let line = state.doc.line(i);\n let start = findColumn(line.text, startCol, state.tabSize, true);\n if (start < 0) {\n ranges.push(EditorSelection.cursor(line.to));\n }\n else {\n let end = findColumn(line.text, endCol, state.tabSize);\n ranges.push(EditorSelection.range(line.from + start, line.from + end));\n }\n }\n }\n return ranges;\n}\nfunction absoluteColumn(view, x) {\n let ref = view.coordsAtPos(view.viewport.from);\n return ref ? Math.round(Math.abs((ref.left - x) / view.defaultCharacterWidth)) : -1;\n}\nfunction getPos(view, event) {\n let offset = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);\n let line = view.state.doc.lineAt(offset), off = offset - line.from;\n let col = off > MaxOff ? -1\n : off == line.length ? absoluteColumn(view, event.clientX)\n : countColumn(line.text, view.state.tabSize, offset - line.from);\n return { line: line.number, col, off };\n}\nfunction rectangleSelectionStyle(view, event) {\n let start = getPos(view, event), startSel = view.state.selection;\n if (!start)\n return null;\n return {\n update(update) {\n if (update.docChanged) {\n let newStart = update.changes.mapPos(update.startState.doc.line(start.line).from);\n let newLine = update.state.doc.lineAt(newStart);\n start = { line: newLine.number, col: start.col, off: Math.min(start.off, newLine.length) };\n startSel = startSel.map(update.changes);\n }\n },\n get(event, _extend, multiple) {\n let cur = getPos(view, event);\n if (!cur)\n return startSel;\n let ranges = rectangleFor(view.state, start, cur);\n if (!ranges.length)\n return startSel;\n if (multiple)\n return EditorSelection.create(ranges.concat(startSel.ranges));\n else\n return EditorSelection.create(ranges);\n }\n };\n}\n/**\nCreate an extension that enables rectangular selections. By\ndefault, it will react to left mouse drag with the Alt key held\ndown. When such a selection occurs, the text within the rectangle\nthat was dragged over will be selected, as one selection\n[range](https://codemirror.net/6/docs/ref/#state.SelectionRange) per line.\n*/\nfunction rectangularSelection(options) {\n let filter = (options === null || options === void 0 ? void 0 : options.eventFilter) || (e => e.altKey && e.button == 0);\n return EditorView.mouseSelectionStyle.of((view, event) => filter(event) ? rectangleSelectionStyle(view, event) : null);\n}\nconst keys = {\n Alt: [18, e => !!e.altKey],\n Control: [17, e => !!e.ctrlKey],\n Shift: [16, e => !!e.shiftKey],\n Meta: [91, e => !!e.metaKey]\n};\nconst showCrosshair = { style: \"cursor: crosshair\" };\n/**\nReturns an extension that turns the pointer cursor into a\ncrosshair when a given modifier key, defaulting to Alt, is held\ndown. Can serve as a visual hint that rectangular selection is\ngoing to happen when paired with\n[`rectangularSelection`](https://codemirror.net/6/docs/ref/#view.rectangularSelection).\n*/\nfunction crosshairCursor(options = {}) {\n let [code, getter] = keys[options.key || \"Alt\"];\n let plugin = ViewPlugin.fromClass(class {\n constructor(view) {\n this.view = view;\n this.isDown = false;\n }\n set(isDown) {\n if (this.isDown != isDown) {\n this.isDown = isDown;\n this.view.update([]);\n }\n }\n }, {\n eventObservers: {\n keydown(e) {\n this.set(e.keyCode == code || getter(e));\n },\n keyup(e) {\n if (e.keyCode == code || !getter(e))\n this.set(false);\n },\n mousemove(e) {\n this.set(getter(e));\n }\n }\n });\n return [\n plugin,\n EditorView.contentAttributes.of(view => { var _a; return ((_a = view.plugin(plugin)) === null || _a === void 0 ? void 0 : _a.isDown) ? showCrosshair : null; })\n ];\n}\n\nconst Outside = \"-10000px\";\nclass TooltipViewManager {\n constructor(view, facet, createTooltipView) {\n this.facet = facet;\n this.createTooltipView = createTooltipView;\n this.input = view.state.facet(facet);\n this.tooltips = this.input.filter(t => t);\n this.tooltipViews = this.tooltips.map(createTooltipView);\n }\n update(update, above) {\n var _a;\n let input = update.state.facet(this.facet);\n let tooltips = input.filter(x => x);\n if (input === this.input) {\n for (let t of this.tooltipViews)\n if (t.update)\n t.update(update);\n return false;\n }\n let tooltipViews = [], newAbove = above ? [] : null;\n for (let i = 0; i < tooltips.length; i++) {\n let tip = tooltips[i], known = -1;\n if (!tip)\n continue;\n for (let i = 0; i < this.tooltips.length; i++) {\n let other = this.tooltips[i];\n if (other && other.create == tip.create)\n known = i;\n }\n if (known < 0) {\n tooltipViews[i] = this.createTooltipView(tip);\n if (newAbove)\n newAbove[i] = !!tip.above;\n }\n else {\n let tooltipView = tooltipViews[i] = this.tooltipViews[known];\n if (newAbove)\n newAbove[i] = above[known];\n if (tooltipView.update)\n tooltipView.update(update);\n }\n }\n for (let t of this.tooltipViews)\n if (tooltipViews.indexOf(t) < 0) {\n t.dom.remove();\n (_a = t.destroy) === null || _a === void 0 ? void 0 : _a.call(t);\n }\n if (above) {\n newAbove.forEach((val, i) => above[i] = val);\n above.length = newAbove.length;\n }\n this.input = input;\n this.tooltips = tooltips;\n this.tooltipViews = tooltipViews;\n return true;\n }\n}\n/**\nCreates an extension that configures tooltip behavior.\n*/\nfunction tooltips(config = {}) {\n return tooltipConfig.of(config);\n}\nfunction windowSpace(view) {\n let { win } = view;\n return { top: 0, left: 0, bottom: win.innerHeight, right: win.innerWidth };\n}\nconst tooltipConfig = /*@__PURE__*/Facet.define({\n combine: values => {\n var _a, _b, _c;\n return ({\n position: browser.ios ? \"absolute\" : ((_a = values.find(conf => conf.position)) === null || _a === void 0 ? void 0 : _a.position) || \"fixed\",\n parent: ((_b = values.find(conf => conf.parent)) === null || _b === void 0 ? void 0 : _b.parent) || null,\n tooltipSpace: ((_c = values.find(conf => conf.tooltipSpace)) === null || _c === void 0 ? void 0 : _c.tooltipSpace) || windowSpace,\n });\n }\n});\nconst knownHeight = /*@__PURE__*/new WeakMap();\nconst tooltipPlugin = /*@__PURE__*/ViewPlugin.fromClass(class {\n constructor(view) {\n this.view = view;\n this.above = [];\n this.inView = true;\n this.madeAbsolute = false;\n this.lastTransaction = 0;\n this.measureTimeout = -1;\n let config = view.state.facet(tooltipConfig);\n this.position = config.position;\n this.parent = config.parent;\n this.classes = view.themeClasses;\n this.createContainer();\n this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this };\n this.manager = new TooltipViewManager(view, showTooltip, t => this.createTooltip(t));\n this.intersectionObserver = typeof IntersectionObserver == \"function\" ? new IntersectionObserver(entries => {\n if (Date.now() > this.lastTransaction - 50 &&\n entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1)\n this.measureSoon();\n }, { threshold: [1] }) : null;\n this.observeIntersection();\n view.win.addEventListener(\"resize\", this.measureSoon = this.measureSoon.bind(this));\n this.maybeMeasure();\n }\n createContainer() {\n if (this.parent) {\n this.container = document.createElement(\"div\");\n this.container.style.position = \"relative\";\n this.container.className = this.view.themeClasses;\n this.parent.appendChild(this.container);\n }\n else {\n this.container = this.view.dom;\n }\n }\n observeIntersection() {\n if (this.intersectionObserver) {\n this.intersectionObserver.disconnect();\n for (let tooltip of this.manager.tooltipViews)\n this.intersectionObserver.observe(tooltip.dom);\n }\n }\n measureSoon() {\n if (this.measureTimeout < 0)\n this.measureTimeout = setTimeout(() => {\n this.measureTimeout = -1;\n this.maybeMeasure();\n }, 50);\n }\n update(update) {\n if (update.transactions.length)\n this.lastTransaction = Date.now();\n let updated = this.manager.update(update, this.above);\n if (updated)\n this.observeIntersection();\n let shouldMeasure = updated || update.geometryChanged;\n let newConfig = update.state.facet(tooltipConfig);\n if (newConfig.position != this.position && !this.madeAbsolute) {\n this.position = newConfig.position;\n for (let t of this.manager.tooltipViews)\n t.dom.style.position = this.position;\n shouldMeasure = true;\n }\n if (newConfig.parent != this.parent) {\n if (this.parent)\n this.container.remove();\n this.parent = newConfig.parent;\n this.createContainer();\n for (let t of this.manager.tooltipViews)\n this.container.appendChild(t.dom);\n shouldMeasure = true;\n }\n else if (this.parent && this.view.themeClasses != this.classes) {\n this.classes = this.container.className = this.view.themeClasses;\n }\n if (shouldMeasure)\n this.maybeMeasure();\n }\n createTooltip(tooltip) {\n let tooltipView = tooltip.create(this.view);\n tooltipView.dom.classList.add(\"cm-tooltip\");\n if (tooltip.arrow && !tooltipView.dom.querySelector(\".cm-tooltip > .cm-tooltip-arrow\")) {\n let arrow = document.createElement(\"div\");\n arrow.className = \"cm-tooltip-arrow\";\n tooltipView.dom.appendChild(arrow);\n }\n tooltipView.dom.style.position = this.position;\n tooltipView.dom.style.top = Outside;\n tooltipView.dom.style.left = \"0px\";\n this.container.appendChild(tooltipView.dom);\n if (tooltipView.mount)\n tooltipView.mount(this.view);\n return tooltipView;\n }\n destroy() {\n var _a, _b;\n this.view.win.removeEventListener(\"resize\", this.measureSoon);\n for (let tooltipView of this.manager.tooltipViews) {\n tooltipView.dom.remove();\n (_a = tooltipView.destroy) === null || _a === void 0 ? void 0 : _a.call(tooltipView);\n }\n if (this.parent)\n this.container.remove();\n (_b = this.intersectionObserver) === null || _b === void 0 ? void 0 : _b.disconnect();\n clearTimeout(this.measureTimeout);\n }\n readMeasure() {\n let editor = this.view.dom.getBoundingClientRect();\n let scaleX = 1, scaleY = 1, makeAbsolute = false;\n if (this.position == \"fixed\" && this.manager.tooltipViews.length) {\n let { dom } = this.manager.tooltipViews[0];\n if (browser.gecko) {\n // Firefox sets the element's `offsetParent` to the\n // transformed element when a transform interferes with fixed\n // positioning.\n makeAbsolute = dom.offsetParent != this.container.ownerDocument.body;\n }\n else {\n // On other browsers, we have to awkwardly try and use other\n // information to detect a transform.\n if (this.view.scaleX != 1 || this.view.scaleY != 1) {\n makeAbsolute = true;\n }\n else if (dom.style.top == Outside && dom.style.left == \"0px\") {\n let rect = dom.getBoundingClientRect();\n makeAbsolute = Math.abs(rect.top + 10000) > 1 || Math.abs(rect.left) > 1;\n }\n }\n }\n if (makeAbsolute || this.position == \"absolute\") {\n if (this.parent) {\n let rect = this.parent.getBoundingClientRect();\n if (rect.width && rect.height) {\n scaleX = rect.width / this.parent.offsetWidth;\n scaleY = rect.height / this.parent.offsetHeight;\n }\n }\n else {\n ({ scaleX, scaleY } = this.view.viewState);\n }\n }\n return {\n editor,\n parent: this.parent ? this.container.getBoundingClientRect() : editor,\n pos: this.manager.tooltips.map((t, i) => {\n let tv = this.manager.tooltipViews[i];\n return tv.getCoords ? tv.getCoords(t.pos) : this.view.coordsAtPos(t.pos);\n }),\n size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()),\n space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view),\n scaleX, scaleY, makeAbsolute\n };\n }\n writeMeasure(measured) {\n var _a;\n if (measured.makeAbsolute) {\n this.madeAbsolute = true;\n this.position = \"absolute\";\n for (let t of this.manager.tooltipViews)\n t.dom.style.position = \"absolute\";\n }\n let { editor, space, scaleX, scaleY } = measured;\n let others = [];\n for (let i = 0; i < this.manager.tooltips.length; i++) {\n let tooltip = this.manager.tooltips[i], tView = this.manager.tooltipViews[i], { dom } = tView;\n let pos = measured.pos[i], size = measured.size[i];\n // Hide tooltips that are outside of the editor.\n if (!pos || pos.bottom <= Math.max(editor.top, space.top) ||\n pos.top >= Math.min(editor.bottom, space.bottom) ||\n pos.right < Math.max(editor.left, space.left) - .1 ||\n pos.left > Math.min(editor.right, space.right) + .1) {\n dom.style.top = Outside;\n continue;\n }\n let arrow = tooltip.arrow ? tView.dom.querySelector(\".cm-tooltip-arrow\") : null;\n let arrowHeight = arrow ? 7 /* Arrow.Size */ : 0;\n let width = size.right - size.left, height = (_a = knownHeight.get(tView)) !== null && _a !== void 0 ? _a : size.bottom - size.top;\n let offset = tView.offset || noOffset, ltr = this.view.textDirection == Direction.LTR;\n let left = size.width > space.right - space.left ? (ltr ? space.left : space.right - size.width)\n : ltr ? Math.min(pos.left - (arrow ? 14 /* Arrow.Offset */ : 0) + offset.x, space.right - width)\n : Math.max(space.left, pos.left - width + (arrow ? 14 /* Arrow.Offset */ : 0) - offset.x);\n let above = this.above[i];\n if (!tooltip.strictSide && (above\n ? pos.top - (size.bottom - size.top) - offset.y < space.top\n : pos.bottom + (size.bottom - size.top) + offset.y > space.bottom) &&\n above == (space.bottom - pos.bottom > pos.top - space.top))\n above = this.above[i] = !above;\n let spaceVert = (above ? pos.top - space.top : space.bottom - pos.bottom) - arrowHeight;\n if (spaceVert < height && tView.resize !== false) {\n if (spaceVert < this.view.defaultLineHeight) {\n dom.style.top = Outside;\n continue;\n }\n knownHeight.set(tView, height);\n dom.style.height = (height = spaceVert) / scaleY + \"px\";\n }\n else if (dom.style.height) {\n dom.style.height = \"\";\n }\n let top = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y;\n let right = left + width;\n if (tView.overlap !== true)\n for (let r of others)\n if (r.left < right && r.right > left && r.top < top + height && r.bottom > top)\n top = above ? r.top - height - 2 - arrowHeight : r.bottom + arrowHeight + 2;\n if (this.position == \"absolute\") {\n dom.style.top = (top - measured.parent.top) / scaleY + \"px\";\n dom.style.left = (left - measured.parent.left) / scaleX + \"px\";\n }\n else {\n dom.style.top = top / scaleY + \"px\";\n dom.style.left = left / scaleX + \"px\";\n }\n if (arrow) {\n let arrowLeft = pos.left + (ltr ? offset.x : -offset.x) - (left + 14 /* Arrow.Offset */ - 7 /* Arrow.Size */);\n arrow.style.left = arrowLeft / scaleX + \"px\";\n }\n if (tView.overlap !== true)\n others.push({ left, top, right, bottom: top + height });\n dom.classList.toggle(\"cm-tooltip-above\", above);\n dom.classList.toggle(\"cm-tooltip-below\", !above);\n if (tView.positioned)\n tView.positioned(measured.space);\n }\n }\n maybeMeasure() {\n if (this.manager.tooltips.length) {\n if (this.view.inView)\n this.view.requestMeasure(this.measureReq);\n if (this.inView != this.view.inView) {\n this.inView = this.view.inView;\n if (!this.inView)\n for (let tv of this.manager.tooltipViews)\n tv.dom.style.top = Outside;\n }\n }\n }\n}, {\n eventObservers: {\n scroll() { this.maybeMeasure(); }\n }\n});\nconst baseTheme = /*@__PURE__*/EditorView.baseTheme({\n \".cm-tooltip\": {\n zIndex: 100,\n boxSizing: \"border-box\"\n },\n \"&light .cm-tooltip\": {\n border: \"1px solid #bbb\",\n backgroundColor: \"#f5f5f5\"\n },\n \"&light .cm-tooltip-section:not(:first-child)\": {\n borderTop: \"1px solid #bbb\",\n },\n \"&dark .cm-tooltip\": {\n backgroundColor: \"#333338\",\n color: \"white\"\n },\n \".cm-tooltip-arrow\": {\n height: `${7 /* Arrow.Size */}px`,\n width: `${7 /* Arrow.Size */ * 2}px`,\n position: \"absolute\",\n zIndex: -1,\n overflow: \"hidden\",\n \"&:before, &:after\": {\n content: \"''\",\n position: \"absolute\",\n width: 0,\n height: 0,\n borderLeft: `${7 /* Arrow.Size */}px solid transparent`,\n borderRight: `${7 /* Arrow.Size */}px solid transparent`,\n },\n \".cm-tooltip-above &\": {\n bottom: `-${7 /* Arrow.Size */}px`,\n \"&:before\": {\n borderTop: `${7 /* Arrow.Size */}px solid #bbb`,\n },\n \"&:after\": {\n borderTop: `${7 /* Arrow.Size */}px solid #f5f5f5`,\n bottom: \"1px\"\n }\n },\n \".cm-tooltip-below &\": {\n top: `-${7 /* Arrow.Size */}px`,\n \"&:before\": {\n borderBottom: `${7 /* Arrow.Size */}px solid #bbb`,\n },\n \"&:after\": {\n borderBottom: `${7 /* Arrow.Size */}px solid #f5f5f5`,\n top: \"1px\"\n }\n },\n },\n \"&dark .cm-tooltip .cm-tooltip-arrow\": {\n \"&:before\": {\n borderTopColor: \"#333338\",\n borderBottomColor: \"#333338\"\n },\n \"&:after\": {\n borderTopColor: \"transparent\",\n borderBottomColor: \"transparent\"\n }\n }\n});\nconst noOffset = { x: 0, y: 0 };\n/**\nFacet to which an extension can add a value to show a tooltip.\n*/\nconst showTooltip = /*@__PURE__*/Facet.define({\n enables: [tooltipPlugin, baseTheme]\n});\nconst showHoverTooltip = /*@__PURE__*/Facet.define();\nclass HoverTooltipHost {\n // Needs to be static so that host tooltip instances always match\n static create(view) {\n return new HoverTooltipHost(view);\n }\n constructor(view) {\n this.view = view;\n this.mounted = false;\n this.dom = document.createElement(\"div\");\n this.dom.classList.add(\"cm-tooltip-hover\");\n this.manager = new TooltipViewManager(view, showHoverTooltip, t => this.createHostedView(t));\n }\n createHostedView(tooltip) {\n let hostedView = tooltip.create(this.view);\n hostedView.dom.classList.add(\"cm-tooltip-section\");\n this.dom.appendChild(hostedView.dom);\n if (this.mounted && hostedView.mount)\n hostedView.mount(this.view);\n return hostedView;\n }\n mount(view) {\n for (let hostedView of this.manager.tooltipViews) {\n if (hostedView.mount)\n hostedView.mount(view);\n }\n this.mounted = true;\n }\n positioned(space) {\n for (let hostedView of this.manager.tooltipViews) {\n if (hostedView.positioned)\n hostedView.positioned(space);\n }\n }\n update(update) {\n this.manager.update(update);\n }\n destroy() {\n var _a;\n for (let t of this.manager.tooltipViews)\n (_a = t.destroy) === null || _a === void 0 ? void 0 : _a.call(t);\n }\n passProp(name) {\n let value = undefined;\n for (let view of this.manager.tooltipViews) {\n let given = view[name];\n if (given !== undefined) {\n if (value === undefined)\n value = given;\n else if (value !== given)\n return undefined;\n }\n }\n return value;\n }\n get offset() { return this.passProp(\"offset\"); }\n get getCoords() { return this.passProp(\"getCoords\"); }\n get overlap() { return this.passProp(\"overlap\"); }\n get resize() { return this.passProp(\"resize\"); }\n}\nconst showHoverTooltipHost = /*@__PURE__*/showTooltip.compute([showHoverTooltip], state => {\n let tooltips = state.facet(showHoverTooltip).filter(t => t);\n if (tooltips.length === 0)\n return null;\n return {\n pos: Math.min(...tooltips.map(t => t.pos)),\n end: Math.max(...tooltips.filter(t => t.end != null).map(t => t.end)),\n create: HoverTooltipHost.create,\n above: tooltips[0].above,\n arrow: tooltips.some(t => t.arrow),\n };\n});\nclass HoverPlugin {\n constructor(view, source, field, setHover, hoverTime) {\n this.view = view;\n this.source = source;\n this.field = field;\n this.setHover = setHover;\n this.hoverTime = hoverTime;\n this.hoverTimeout = -1;\n this.restartTimeout = -1;\n this.pending = null;\n this.lastMove = { x: 0, y: 0, target: view.dom, time: 0 };\n this.checkHover = this.checkHover.bind(this);\n view.dom.addEventListener(\"mouseleave\", this.mouseleave = this.mouseleave.bind(this));\n view.dom.addEventListener(\"mousemove\", this.mousemove = this.mousemove.bind(this));\n }\n update() {\n if (this.pending) {\n this.pending = null;\n clearTimeout(this.restartTimeout);\n this.restartTimeout = setTimeout(() => this.startHover(), 20);\n }\n }\n get active() {\n return this.view.state.field(this.field);\n }\n checkHover() {\n this.hoverTimeout = -1;\n if (this.active)\n return;\n let hovered = Date.now() - this.lastMove.time;\n if (hovered < this.hoverTime)\n this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered);\n else\n this.startHover();\n }\n startHover() {\n clearTimeout(this.restartTimeout);\n let { view, lastMove } = this;\n let desc = view.docView.nearest(lastMove.target);\n if (!desc)\n return;\n let pos, side = 1;\n if (desc instanceof WidgetView) {\n pos = desc.posAtStart;\n }\n else {\n pos = view.posAtCoords(lastMove);\n if (pos == null)\n return;\n let posCoords = view.coordsAtPos(pos);\n if (!posCoords ||\n lastMove.y < posCoords.top || lastMove.y > posCoords.bottom ||\n lastMove.x < posCoords.left - view.defaultCharacterWidth ||\n lastMove.x > posCoords.right + view.defaultCharacterWidth)\n return;\n let bidi = view.bidiSpans(view.state.doc.lineAt(pos)).find(s => s.from <= pos && s.to >= pos);\n let rtl = bidi && bidi.dir == Direction.RTL ? -1 : 1;\n side = (lastMove.x < posCoords.left ? -rtl : rtl);\n }\n let open = this.source(view, pos, side);\n if (open === null || open === void 0 ? void 0 : open.then) {\n let pending = this.pending = { pos };\n open.then(result => {\n if (this.pending == pending) {\n this.pending = null;\n if (result)\n view.dispatch({ effects: this.setHover.of(result) });\n }\n }, e => logException(view.state, e, \"hover tooltip\"));\n }\n else if (open) {\n view.dispatch({ effects: this.setHover.of(open) });\n }\n }\n mousemove(event) {\n var _a;\n this.lastMove = { x: event.clientX, y: event.clientY, target: event.target, time: Date.now() };\n if (this.hoverTimeout < 0)\n this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime);\n let tooltip = this.active;\n if (tooltip && !isInTooltip(this.lastMove.target) || this.pending) {\n let { pos } = tooltip || this.pending, end = (_a = tooltip === null || tooltip === void 0 ? void 0 : tooltip.end) !== null && _a !== void 0 ? _a : pos;\n if ((pos == end ? this.view.posAtCoords(this.lastMove) != pos\n : !isOverRange(this.view, pos, end, event.clientX, event.clientY))) {\n this.view.dispatch({ effects: this.setHover.of(null) });\n this.pending = null;\n }\n }\n }\n mouseleave(e) {\n clearTimeout(this.hoverTimeout);\n this.hoverTimeout = -1;\n if (this.active && !isInTooltip(e.relatedTarget))\n this.view.dispatch({ effects: this.setHover.of(null) });\n }\n destroy() {\n clearTimeout(this.hoverTimeout);\n this.view.dom.removeEventListener(\"mouseleave\", this.mouseleave);\n this.view.dom.removeEventListener(\"mousemove\", this.mousemove);\n }\n}\nfunction isInTooltip(elt) {\n for (let cur = elt; cur; cur = cur.parentNode)\n if (cur.nodeType == 1 && cur.classList.contains(\"cm-tooltip\"))\n return true;\n return false;\n}\nfunction isOverRange(view, from, to, x, y, margin) {\n let rect = view.scrollDOM.getBoundingClientRect();\n let docBottom = view.documentTop + view.documentPadding.top + view.contentHeight;\n if (rect.left > x || rect.right < x || rect.top > y || Math.min(rect.bottom, docBottom) < y)\n return false;\n let pos = view.posAtCoords({ x, y }, false);\n return pos >= from && pos <= to;\n}\n/**\nSet up a hover tooltip, which shows up when the pointer hovers\nover ranges of text. The callback is called when the mouse hovers\nover the document text. It should, if there is a tooltip\nassociated with position `pos`, return the tooltip description\n(either directly or in a promise). The `side` argument indicates\non which side of the position the pointer is—it will be -1 if the\npointer is before the position, 1 if after the position.\n\nNote that all hover tooltips are hosted within a single tooltip\ncontainer element. This allows multiple tooltips over the same\nrange to be \"merged\" together without overlapping.\n*/\nfunction hoverTooltip(source, options = {}) {\n let setHover = StateEffect.define();\n let hoverState = StateField.define({\n create() { return null; },\n update(value, tr) {\n if (value && (options.hideOnChange && (tr.docChanged || tr.selection) ||\n options.hideOn && options.hideOn(tr, value)))\n return null;\n if (value && tr.docChanged) {\n let newPos = tr.changes.mapPos(value.pos, -1, MapMode.TrackDel);\n if (newPos == null)\n return null;\n let copy = Object.assign(Object.create(null), value);\n copy.pos = newPos;\n if (value.end != null)\n copy.end = tr.changes.mapPos(value.end);\n value = copy;\n }\n for (let effect of tr.effects) {\n if (effect.is(setHover))\n value = effect.value;\n if (effect.is(closeHoverTooltipEffect))\n value = null;\n }\n return value;\n },\n provide: f => showHoverTooltip.from(f)\n });\n return [\n hoverState,\n ViewPlugin.define(view => new HoverPlugin(view, source, hoverState, setHover, options.hoverTime || 300 /* Hover.Time */)),\n showHoverTooltipHost\n ];\n}\n/**\nGet the active tooltip view for a given tooltip, if available.\n*/\nfunction getTooltip(view, tooltip) {\n let plugin = view.plugin(tooltipPlugin);\n if (!plugin)\n return null;\n let found = plugin.manager.tooltips.indexOf(tooltip);\n return found < 0 ? null : plugin.manager.tooltipViews[found];\n}\n/**\nReturns true if any hover tooltips are currently active.\n*/\nfunction hasHoverTooltips(state) {\n return state.facet(showHoverTooltip).some(x => x);\n}\nconst closeHoverTooltipEffect = /*@__PURE__*/StateEffect.define();\n/**\nTransaction effect that closes all hover tooltips.\n*/\nconst closeHoverTooltips = /*@__PURE__*/closeHoverTooltipEffect.of(null);\n/**\nTell the tooltip extension to recompute the position of the active\ntooltips. This can be useful when something happens (such as a\nre-positioning or CSS change affecting the editor) that could\ninvalidate the existing tooltip positions.\n*/\nfunction repositionTooltips(view) {\n let plugin = view.plugin(tooltipPlugin);\n if (plugin)\n plugin.maybeMeasure();\n}\n\nconst panelConfig = /*@__PURE__*/Facet.define({\n combine(configs) {\n let topContainer, bottomContainer;\n for (let c of configs) {\n topContainer = topContainer || c.topContainer;\n bottomContainer = bottomContainer || c.bottomContainer;\n }\n return { topContainer, bottomContainer };\n }\n});\n/**\nConfigures the panel-managing extension.\n*/\nfunction panels(config) {\n return config ? [panelConfig.of(config)] : [];\n}\n/**\nGet the active panel created by the given constructor, if any.\nThis can be useful when you need access to your panels' DOM\nstructure.\n*/\nfunction getPanel(view, panel) {\n let plugin = view.plugin(panelPlugin);\n let index = plugin ? plugin.specs.indexOf(panel) : -1;\n return index > -1 ? plugin.panels[index] : null;\n}\nconst panelPlugin = /*@__PURE__*/ViewPlugin.fromClass(class {\n constructor(view) {\n this.input = view.state.facet(showPanel);\n this.specs = this.input.filter(s => s);\n this.panels = this.specs.map(spec => spec(view));\n let conf = view.state.facet(panelConfig);\n this.top = new PanelGroup(view, true, conf.topContainer);\n this.bottom = new PanelGroup(view, false, conf.bottomContainer);\n this.top.sync(this.panels.filter(p => p.top));\n this.bottom.sync(this.panels.filter(p => !p.top));\n for (let p of this.panels) {\n p.dom.classList.add(\"cm-panel\");\n if (p.mount)\n p.mount();\n }\n }\n update(update) {\n let conf = update.state.facet(panelConfig);\n if (this.top.container != conf.topContainer) {\n this.top.sync([]);\n this.top = new PanelGroup(update.view, true, conf.topContainer);\n }\n if (this.bottom.container != conf.bottomContainer) {\n this.bottom.sync([]);\n this.bottom = new PanelGroup(update.view, false, conf.bottomContainer);\n }\n this.top.syncClasses();\n this.bottom.syncClasses();\n let input = update.state.facet(showPanel);\n if (input != this.input) {\n let specs = input.filter(x => x);\n let panels = [], top = [], bottom = [], mount = [];\n for (let spec of specs) {\n let known = this.specs.indexOf(spec), panel;\n if (known < 0) {\n panel = spec(update.view);\n mount.push(panel);\n }\n else {\n panel = this.panels[known];\n if (panel.update)\n panel.update(update);\n }\n panels.push(panel);\n (panel.top ? top : bottom).push(panel);\n }\n this.specs = specs;\n this.panels = panels;\n this.top.sync(top);\n this.bottom.sync(bottom);\n for (let p of mount) {\n p.dom.classList.add(\"cm-panel\");\n if (p.mount)\n p.mount();\n }\n }\n else {\n for (let p of this.panels)\n if (p.update)\n p.update(update);\n }\n }\n destroy() {\n this.top.sync([]);\n this.bottom.sync([]);\n }\n}, {\n provide: plugin => EditorView.scrollMargins.of(view => {\n let value = view.plugin(plugin);\n return value && { top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() };\n })\n});\nclass PanelGroup {\n constructor(view, top, container) {\n this.view = view;\n this.top = top;\n this.container = container;\n this.dom = undefined;\n this.classes = \"\";\n this.panels = [];\n this.syncClasses();\n }\n sync(panels) {\n for (let p of this.panels)\n if (p.destroy && panels.indexOf(p) < 0)\n p.destroy();\n this.panels = panels;\n this.syncDOM();\n }\n syncDOM() {\n if (this.panels.length == 0) {\n if (this.dom) {\n this.dom.remove();\n this.dom = undefined;\n }\n return;\n }\n if (!this.dom) {\n this.dom = document.createElement(\"div\");\n this.dom.className = this.top ? \"cm-panels cm-panels-top\" : \"cm-panels cm-panels-bottom\";\n this.dom.style[this.top ? \"top\" : \"bottom\"] = \"0\";\n let parent = this.container || this.view.dom;\n parent.insertBefore(this.dom, this.top ? parent.firstChild : null);\n }\n let curDOM = this.dom.firstChild;\n for (let panel of this.panels) {\n if (panel.dom.parentNode == this.dom) {\n while (curDOM != panel.dom)\n curDOM = rm(curDOM);\n curDOM = curDOM.nextSibling;\n }\n else {\n this.dom.insertBefore(panel.dom, curDOM);\n }\n }\n while (curDOM)\n curDOM = rm(curDOM);\n }\n scrollMargin() {\n return !this.dom || this.container ? 0\n : Math.max(0, this.top ?\n this.dom.getBoundingClientRect().bottom - Math.max(0, this.view.scrollDOM.getBoundingClientRect().top) :\n Math.min(innerHeight, this.view.scrollDOM.getBoundingClientRect().bottom) - this.dom.getBoundingClientRect().top);\n }\n syncClasses() {\n if (!this.container || this.classes == this.view.themeClasses)\n return;\n for (let cls of this.classes.split(\" \"))\n if (cls)\n this.container.classList.remove(cls);\n for (let cls of (this.classes = this.view.themeClasses).split(\" \"))\n if (cls)\n this.container.classList.add(cls);\n }\n}\nfunction rm(node) {\n let next = node.nextSibling;\n node.remove();\n return next;\n}\n/**\nOpening a panel is done by providing a constructor function for\nthe panel through this facet. (The panel is closed again when its\nconstructor is no longer provided.) Values of `null` are ignored.\n*/\nconst showPanel = /*@__PURE__*/Facet.define({\n enables: panelPlugin\n});\n\n/**\nA gutter marker represents a bit of information attached to a line\nin a specific gutter. Your own custom markers have to extend this\nclass.\n*/\nclass GutterMarker extends RangeValue {\n /**\n @internal\n */\n compare(other) {\n return this == other || this.constructor == other.constructor && this.eq(other);\n }\n /**\n Compare this marker to another marker of the same type.\n */\n eq(other) { return false; }\n /**\n Called if the marker has a `toDOM` method and its representation\n was removed from a gutter.\n */\n destroy(dom) { }\n}\nGutterMarker.prototype.elementClass = \"\";\nGutterMarker.prototype.toDOM = undefined;\nGutterMarker.prototype.mapMode = MapMode.TrackBefore;\nGutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1;\nGutterMarker.prototype.point = true;\n/**\nFacet used to add a class to all gutter elements for a given line.\nMarkers given to this facet should _only_ define an\n[`elementclass`](https://codemirror.net/6/docs/ref/#view.GutterMarker.elementClass), not a\n[`toDOM`](https://codemirror.net/6/docs/ref/#view.GutterMarker.toDOM) (or the marker will appear\nin all gutters for the line).\n*/\nconst gutterLineClass = /*@__PURE__*/Facet.define();\nconst defaults = {\n class: \"\",\n renderEmptyElements: false,\n elementStyle: \"\",\n markers: () => RangeSet.empty,\n lineMarker: () => null,\n widgetMarker: () => null,\n lineMarkerChange: null,\n initialSpacer: null,\n updateSpacer: null,\n domEventHandlers: {}\n};\nconst activeGutters = /*@__PURE__*/Facet.define();\n/**\nDefine an editor gutter. The order in which the gutters appear is\ndetermined by their extension priority.\n*/\nfunction gutter(config) {\n return [gutters(), activeGutters.of(Object.assign(Object.assign({}, defaults), config))];\n}\nconst unfixGutters = /*@__PURE__*/Facet.define({\n combine: values => values.some(x => x)\n});\n/**\nThe gutter-drawing plugin is automatically enabled when you add a\ngutter, but you can use this function to explicitly configure it.\n\nUnless `fixed` is explicitly set to `false`, the gutters are\nfixed, meaning they don't scroll along with the content\nhorizontally (except on Internet Explorer, which doesn't support\nCSS [`position:\nsticky`](https://developer.mozilla.org/en-US/docs/Web/CSS/position#sticky)).\n*/\nfunction gutters(config) {\n let result = [\n gutterView,\n ];\n if (config && config.fixed === false)\n result.push(unfixGutters.of(true));\n return result;\n}\nconst gutterView = /*@__PURE__*/ViewPlugin.fromClass(class {\n constructor(view) {\n this.view = view;\n this.prevViewport = view.viewport;\n this.dom = document.createElement(\"div\");\n this.dom.className = \"cm-gutters\";\n this.dom.setAttribute(\"aria-hidden\", \"true\");\n this.dom.style.minHeight = (this.view.contentHeight / this.view.scaleY) + \"px\";\n this.gutters = view.state.facet(activeGutters).map(conf => new SingleGutterView(view, conf));\n for (let gutter of this.gutters)\n this.dom.appendChild(gutter.dom);\n this.fixed = !view.state.facet(unfixGutters);\n if (this.fixed) {\n // FIXME IE11 fallback, which doesn't support position: sticky,\n // by using position: relative + event handlers that realign the\n // gutter (or just force fixed=false on IE11?)\n this.dom.style.position = \"sticky\";\n }\n this.syncGutters(false);\n view.scrollDOM.insertBefore(this.dom, view.contentDOM);\n }\n update(update) {\n if (this.updateGutters(update)) {\n // Detach during sync when the viewport changed significantly\n // (such as during scrolling), since for large updates that is\n // faster.\n let vpA = this.prevViewport, vpB = update.view.viewport;\n let vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from);\n this.syncGutters(vpOverlap < (vpB.to - vpB.from) * 0.8);\n }\n if (update.geometryChanged)\n this.dom.style.minHeight = this.view.contentHeight + \"px\";\n if (this.view.state.facet(unfixGutters) != !this.fixed) {\n this.fixed = !this.fixed;\n this.dom.style.position = this.fixed ? \"sticky\" : \"\";\n }\n this.prevViewport = update.view.viewport;\n }\n syncGutters(detach) {\n let after = this.dom.nextSibling;\n if (detach)\n this.dom.remove();\n let lineClasses = RangeSet.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from);\n let classSet = [];\n let contexts = this.gutters.map(gutter => new UpdateContext(gutter, this.view.viewport, -this.view.documentPadding.top));\n for (let line of this.view.viewportLineBlocks) {\n if (classSet.length)\n classSet = [];\n if (Array.isArray(line.type)) {\n let first = true;\n for (let b of line.type) {\n if (b.type == BlockType.Text && first) {\n advanceCursor(lineClasses, classSet, b.from);\n for (let cx of contexts)\n cx.line(this.view, b, classSet);\n first = false;\n }\n else if (b.widget) {\n for (let cx of contexts)\n cx.widget(this.view, b);\n }\n }\n }\n else if (line.type == BlockType.Text) {\n advanceCursor(lineClasses, classSet, line.from);\n for (let cx of contexts)\n cx.line(this.view, line, classSet);\n }\n else if (line.widget) {\n for (let cx of contexts)\n cx.widget(this.view, line);\n }\n }\n for (let cx of contexts)\n cx.finish();\n if (detach)\n this.view.scrollDOM.insertBefore(this.dom, after);\n }\n updateGutters(update) {\n let prev = update.startState.facet(activeGutters), cur = update.state.facet(activeGutters);\n let change = update.docChanged || update.heightChanged || update.viewportChanged ||\n !RangeSet.eq(update.startState.facet(gutterLineClass), update.state.facet(gutterLineClass), update.view.viewport.from, update.view.viewport.to);\n if (prev == cur) {\n for (let gutter of this.gutters)\n if (gutter.update(update))\n change = true;\n }\n else {\n change = true;\n let gutters = [];\n for (let conf of cur) {\n let known = prev.indexOf(conf);\n if (known < 0) {\n gutters.push(new SingleGutterView(this.view, conf));\n }\n else {\n this.gutters[known].update(update);\n gutters.push(this.gutters[known]);\n }\n }\n for (let g of this.gutters) {\n g.dom.remove();\n if (gutters.indexOf(g) < 0)\n g.destroy();\n }\n for (let g of gutters)\n this.dom.appendChild(g.dom);\n this.gutters = gutters;\n }\n return change;\n }\n destroy() {\n for (let view of this.gutters)\n view.destroy();\n this.dom.remove();\n }\n}, {\n provide: plugin => EditorView.scrollMargins.of(view => {\n let value = view.plugin(plugin);\n if (!value || value.gutters.length == 0 || !value.fixed)\n return null;\n return view.textDirection == Direction.LTR\n ? { left: value.dom.offsetWidth * view.scaleX }\n : { right: value.dom.offsetWidth * view.scaleX };\n })\n});\nfunction asArray(val) { return (Array.isArray(val) ? val : [val]); }\nfunction advanceCursor(cursor, collect, pos) {\n while (cursor.value && cursor.from <= pos) {\n if (cursor.from == pos)\n collect.push(cursor.value);\n cursor.next();\n }\n}\nclass UpdateContext {\n constructor(gutter, viewport, height) {\n this.gutter = gutter;\n this.height = height;\n this.i = 0;\n this.cursor = RangeSet.iter(gutter.markers, viewport.from);\n }\n addElement(view, block, markers) {\n let { gutter } = this, above = (block.top - this.height) / view.scaleY, height = block.height / view.scaleY;\n if (this.i == gutter.elements.length) {\n let newElt = new GutterElement(view, height, above, markers);\n gutter.elements.push(newElt);\n gutter.dom.appendChild(newElt.dom);\n }\n else {\n gutter.elements[this.i].update(view, height, above, markers);\n }\n this.height = block.bottom;\n this.i++;\n }\n line(view, line, extraMarkers) {\n let localMarkers = [];\n advanceCursor(this.cursor, localMarkers, line.from);\n if (extraMarkers.length)\n localMarkers = localMarkers.concat(extraMarkers);\n let forLine = this.gutter.config.lineMarker(view, line, localMarkers);\n if (forLine)\n localMarkers.unshift(forLine);\n let gutter = this.gutter;\n if (localMarkers.length == 0 && !gutter.config.renderEmptyElements)\n return;\n this.addElement(view, line, localMarkers);\n }\n widget(view, block) {\n let marker = this.gutter.config.widgetMarker(view, block.widget, block);\n if (marker)\n this.addElement(view, block, [marker]);\n }\n finish() {\n let gutter = this.gutter;\n while (gutter.elements.length > this.i) {\n let last = gutter.elements.pop();\n gutter.dom.removeChild(last.dom);\n last.destroy();\n }\n }\n}\nclass SingleGutterView {\n constructor(view, config) {\n this.view = view;\n this.config = config;\n this.elements = [];\n this.spacer = null;\n this.dom = document.createElement(\"div\");\n this.dom.className = \"cm-gutter\" + (this.config.class ? \" \" + this.config.class : \"\");\n for (let prop in config.domEventHandlers) {\n this.dom.addEventListener(prop, (event) => {\n let target = event.target, y;\n if (target != this.dom && this.dom.contains(target)) {\n while (target.parentNode != this.dom)\n target = target.parentNode;\n let rect = target.getBoundingClientRect();\n y = (rect.top + rect.bottom) / 2;\n }\n else {\n y = event.clientY;\n }\n let line = view.lineBlockAtHeight(y - view.documentTop);\n if (config.domEventHandlers[prop](view, line, event))\n event.preventDefault();\n });\n }\n this.markers = asArray(config.markers(view));\n if (config.initialSpacer) {\n this.spacer = new GutterElement(view, 0, 0, [config.initialSpacer(view)]);\n this.dom.appendChild(this.spacer.dom);\n this.spacer.dom.style.cssText += \"visibility: hidden; pointer-events: none\";\n }\n }\n update(update) {\n let prevMarkers = this.markers;\n this.markers = asArray(this.config.markers(update.view));\n if (this.spacer && this.config.updateSpacer) {\n let updated = this.config.updateSpacer(this.spacer.markers[0], update);\n if (updated != this.spacer.markers[0])\n this.spacer.update(update.view, 0, 0, [updated]);\n }\n let vp = update.view.viewport;\n return !RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) ||\n (this.config.lineMarkerChange ? this.config.lineMarkerChange(update) : false);\n }\n destroy() {\n for (let elt of this.elements)\n elt.destroy();\n }\n}\nclass GutterElement {\n constructor(view, height, above, markers) {\n this.height = -1;\n this.above = 0;\n this.markers = [];\n this.dom = document.createElement(\"div\");\n this.dom.className = \"cm-gutterElement\";\n this.update(view, height, above, markers);\n }\n update(view, height, above, markers) {\n if (this.height != height) {\n this.height = height;\n this.dom.style.height = height + \"px\";\n }\n if (this.above != above)\n this.dom.style.marginTop = (this.above = above) ? above + \"px\" : \"\";\n if (!sameMarkers(this.markers, markers))\n this.setMarkers(view, markers);\n }\n setMarkers(view, markers) {\n let cls = \"cm-gutterElement\", domPos = this.dom.firstChild;\n for (let iNew = 0, iOld = 0;;) {\n let skipTo = iOld, marker = iNew < markers.length ? markers[iNew++] : null, matched = false;\n if (marker) {\n let c = marker.elementClass;\n if (c)\n cls += \" \" + c;\n for (let i = iOld; i < this.markers.length; i++)\n if (this.markers[i].compare(marker)) {\n skipTo = i;\n matched = true;\n break;\n }\n }\n else {\n skipTo = this.markers.length;\n }\n while (iOld < skipTo) {\n let next = this.markers[iOld++];\n if (next.toDOM) {\n next.destroy(domPos);\n let after = domPos.nextSibling;\n domPos.remove();\n domPos = after;\n }\n }\n if (!marker)\n break;\n if (marker.toDOM) {\n if (matched)\n domPos = domPos.nextSibling;\n else\n this.dom.insertBefore(marker.toDOM(view), domPos);\n }\n if (matched)\n iOld++;\n }\n this.dom.className = cls;\n this.markers = markers;\n }\n destroy() {\n this.setMarkers(null, []); // First argument not used unless creating markers\n }\n}\nfunction sameMarkers(a, b) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!a[i].compare(b[i]))\n return false;\n return true;\n}\n/**\nFacet used to provide markers to the line number gutter.\n*/\nconst lineNumberMarkers = /*@__PURE__*/Facet.define();\nconst lineNumberConfig = /*@__PURE__*/Facet.define({\n combine(values) {\n return combineConfig(values, { formatNumber: String, domEventHandlers: {} }, {\n domEventHandlers(a, b) {\n let result = Object.assign({}, a);\n for (let event in b) {\n let exists = result[event], add = b[event];\n result[event] = exists ? (view, line, event) => exists(view, line, event) || add(view, line, event) : add;\n }\n return result;\n }\n });\n }\n});\nclass NumberMarker extends GutterMarker {\n constructor(number) {\n super();\n this.number = number;\n }\n eq(other) { return this.number == other.number; }\n toDOM() { return document.createTextNode(this.number); }\n}\nfunction formatNumber(view, number) {\n return view.state.facet(lineNumberConfig).formatNumber(number, view.state);\n}\nconst lineNumberGutter = /*@__PURE__*/activeGutters.compute([lineNumberConfig], state => ({\n class: \"cm-lineNumbers\",\n renderEmptyElements: false,\n markers(view) { return view.state.facet(lineNumberMarkers); },\n lineMarker(view, line, others) {\n if (others.some(m => m.toDOM))\n return null;\n return new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number));\n },\n widgetMarker: () => null,\n lineMarkerChange: update => update.startState.facet(lineNumberConfig) != update.state.facet(lineNumberConfig),\n initialSpacer(view) {\n return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines)));\n },\n updateSpacer(spacer, update) {\n let max = formatNumber(update.view, maxLineNumber(update.view.state.doc.lines));\n return max == spacer.number ? spacer : new NumberMarker(max);\n },\n domEventHandlers: state.facet(lineNumberConfig).domEventHandlers\n}));\n/**\nCreate a line number gutter extension.\n*/\nfunction lineNumbers(config = {}) {\n return [\n lineNumberConfig.of(config),\n gutters(),\n lineNumberGutter\n ];\n}\nfunction maxLineNumber(lines) {\n let last = 9;\n while (last < lines)\n last = last * 10 + 9;\n return last;\n}\nconst activeLineGutterMarker = /*@__PURE__*/new class extends GutterMarker {\n constructor() {\n super(...arguments);\n this.elementClass = \"cm-activeLineGutter\";\n }\n};\nconst activeLineGutterHighlighter = /*@__PURE__*/gutterLineClass.compute([\"selection\"], state => {\n let marks = [], last = -1;\n for (let range of state.selection.ranges) {\n let linePos = state.doc.lineAt(range.head).from;\n if (linePos > last) {\n last = linePos;\n marks.push(activeLineGutterMarker.range(linePos));\n }\n }\n return RangeSet.of(marks);\n});\n/**\nReturns an extension that adds a `cm-activeLineGutter` class to\nall gutter elements on the [active\nline](https://codemirror.net/6/docs/ref/#view.highlightActiveLine).\n*/\nfunction highlightActiveLineGutter() {\n return activeLineGutterHighlighter;\n}\n\nconst WhitespaceDeco = /*@__PURE__*/new Map();\nfunction getWhitespaceDeco(space) {\n let deco = WhitespaceDeco.get(space);\n if (!deco)\n WhitespaceDeco.set(space, deco = Decoration.mark({\n attributes: space === \"\\t\" ? {\n class: \"cm-highlightTab\",\n } : {\n class: \"cm-highlightSpace\",\n \"data-display\": space.replace(/ /g, \"·\")\n }\n }));\n return deco;\n}\nfunction matcher(decorator) {\n return ViewPlugin.define(view => ({\n decorations: decorator.createDeco(view),\n update(u) {\n this.decorations = decorator.updateDeco(u, this.decorations);\n },\n }), {\n decorations: v => v.decorations\n });\n}\nconst whitespaceHighlighter = /*@__PURE__*/matcher(/*@__PURE__*/new MatchDecorator({\n regexp: /\\t| +/g,\n decoration: match => getWhitespaceDeco(match[0]),\n boundary: /\\S/,\n}));\n/**\nReturns an extension that highlights whitespace, adding a\n`cm-highlightSpace` class to stretches of spaces, and a\n`cm-highlightTab` class to individual tab characters. By default,\nthe former are shown as faint dots, and the latter as arrows.\n*/\nfunction highlightWhitespace() {\n return whitespaceHighlighter;\n}\nconst trailingHighlighter = /*@__PURE__*/matcher(/*@__PURE__*/new MatchDecorator({\n regexp: /\\s+$/g,\n decoration: /*@__PURE__*/Decoration.mark({ class: \"cm-trailingSpace\" }),\n boundary: /\\S/,\n}));\n/**\nReturns an extension that adds a `cm-trailingSpace` class to all\ntrailing whitespace.\n*/\nfunction highlightTrailingWhitespace() {\n return trailingHighlighter;\n}\n\n/**\n@internal\n*/\nconst __test = { HeightMap, HeightOracle, MeasuredHeights, QueryType, ChangedRange, computeOrder, moveVisually };\n\nexport { BidiSpan, BlockInfo, BlockType, Decoration, Direction, EditorView, GutterMarker, MatchDecorator, RectangleMarker, ViewPlugin, ViewUpdate, WidgetType, __test, closeHoverTooltips, crosshairCursor, drawSelection, dropCursor, getDrawSelectionConfig, getPanel, getTooltip, gutter, gutterLineClass, gutters, hasHoverTooltips, highlightActiveLine, highlightActiveLineGutter, highlightSpecialChars, highlightTrailingWhitespace, highlightWhitespace, hoverTooltip, keymap, layer, lineNumberMarkers, lineNumbers, logException, panels, placeholder, rectangularSelection, repositionTooltips, runScopeHandlers, scrollPastEnd, showPanel, showTooltip, tooltips };\n","/**\nThe default maximum length of a `TreeBuffer` node.\n*/\nconst DefaultBufferLength = 1024;\nlet nextPropID = 0;\nclass Range {\n constructor(from, to) {\n this.from = from;\n this.to = to;\n }\n}\n/**\nEach [node type](#common.NodeType) or [individual tree](#common.Tree)\ncan have metadata associated with it in props. Instances of this\nclass represent prop names.\n*/\nclass NodeProp {\n /**\n Create a new node prop type.\n */\n constructor(config = {}) {\n this.id = nextPropID++;\n this.perNode = !!config.perNode;\n this.deserialize = config.deserialize || (() => {\n throw new Error(\"This node type doesn't define a deserialize function\");\n });\n }\n /**\n This is meant to be used with\n [`NodeSet.extend`](#common.NodeSet.extend) or\n [`LRParser.configure`](#lr.ParserConfig.props) to compute\n prop values for each node type in the set. Takes a [match\n object](#common.NodeType^match) or function that returns undefined\n if the node type doesn't get this prop, and the prop's value if\n it does.\n */\n add(match) {\n if (this.perNode)\n throw new RangeError(\"Can't add per-node props to node types\");\n if (typeof match != \"function\")\n match = NodeType.match(match);\n return (type) => {\n let result = match(type);\n return result === undefined ? null : [this, result];\n };\n }\n}\n/**\nProp that is used to describe matching delimiters. For opening\ndelimiters, this holds an array of node names (written as a\nspace-separated string when declaring this prop in a grammar)\nfor the node types of closing delimiters that match it.\n*/\nNodeProp.closedBy = new NodeProp({ deserialize: str => str.split(\" \") });\n/**\nThe inverse of [`closedBy`](#common.NodeProp^closedBy). This is\nattached to closing delimiters, holding an array of node names\nof types of matching opening delimiters.\n*/\nNodeProp.openedBy = new NodeProp({ deserialize: str => str.split(\" \") });\n/**\nUsed to assign node types to groups (for example, all node\ntypes that represent an expression could be tagged with an\n`\"Expression\"` group).\n*/\nNodeProp.group = new NodeProp({ deserialize: str => str.split(\" \") });\n/**\nThe hash of the [context](#lr.ContextTracker.constructor)\nthat the node was parsed in, if any. Used to limit reuse of\ncontextual nodes.\n*/\nNodeProp.contextHash = new NodeProp({ perNode: true });\n/**\nThe distance beyond the end of the node that the tokenizer\nlooked ahead for any of the tokens inside the node. (The LR\nparser only stores this when it is larger than 25, for\nefficiency reasons.)\n*/\nNodeProp.lookAhead = new NodeProp({ perNode: true });\n/**\nThis per-node prop is used to replace a given node, or part of a\nnode, with another tree. This is useful to include trees from\ndifferent languages in mixed-language parsers.\n*/\nNodeProp.mounted = new NodeProp({ perNode: true });\n/**\nA mounted tree, which can be [stored](#common.NodeProp^mounted) on\na tree node to indicate that parts of its content are\nrepresented by another tree.\n*/\nclass MountedTree {\n constructor(\n /**\n The inner tree.\n */\n tree, \n /**\n If this is null, this tree replaces the entire node (it will\n be included in the regular iteration instead of its host\n node). If not, only the given ranges are considered to be\n covered by this tree. This is used for trees that are mixed in\n a way that isn't strictly hierarchical. Such mounted trees are\n only entered by [`resolveInner`](#common.Tree.resolveInner)\n and [`enter`](#common.SyntaxNode.enter).\n */\n overlay, \n /**\n The parser used to create this subtree.\n */\n parser) {\n this.tree = tree;\n this.overlay = overlay;\n this.parser = parser;\n }\n /**\n @internal\n */\n static get(tree) {\n return tree && tree.props && tree.props[NodeProp.mounted.id];\n }\n}\nconst noProps = Object.create(null);\n/**\nEach node in a syntax tree has a node type associated with it.\n*/\nclass NodeType {\n /**\n @internal\n */\n constructor(\n /**\n The name of the node type. Not necessarily unique, but if the\n grammar was written properly, different node types with the\n same name within a node set should play the same semantic\n role.\n */\n name, \n /**\n @internal\n */\n props, \n /**\n The id of this node in its set. Corresponds to the term ids\n used in the parser.\n */\n id, \n /**\n @internal\n */\n flags = 0) {\n this.name = name;\n this.props = props;\n this.id = id;\n this.flags = flags;\n }\n /**\n Define a node type.\n */\n static define(spec) {\n let props = spec.props && spec.props.length ? Object.create(null) : noProps;\n let flags = (spec.top ? 1 /* NodeFlag.Top */ : 0) | (spec.skipped ? 2 /* NodeFlag.Skipped */ : 0) |\n (spec.error ? 4 /* NodeFlag.Error */ : 0) | (spec.name == null ? 8 /* NodeFlag.Anonymous */ : 0);\n let type = new NodeType(spec.name || \"\", props, spec.id, flags);\n if (spec.props)\n for (let src of spec.props) {\n if (!Array.isArray(src))\n src = src(type);\n if (src) {\n if (src[0].perNode)\n throw new RangeError(\"Can't store a per-node prop on a node type\");\n props[src[0].id] = src[1];\n }\n }\n return type;\n }\n /**\n Retrieves a node prop for this type. Will return `undefined` if\n the prop isn't present on this node.\n */\n prop(prop) { return this.props[prop.id]; }\n /**\n True when this is the top node of a grammar.\n */\n get isTop() { return (this.flags & 1 /* NodeFlag.Top */) > 0; }\n /**\n True when this node is produced by a skip rule.\n */\n get isSkipped() { return (this.flags & 2 /* NodeFlag.Skipped */) > 0; }\n /**\n Indicates whether this is an error node.\n */\n get isError() { return (this.flags & 4 /* NodeFlag.Error */) > 0; }\n /**\n When true, this node type doesn't correspond to a user-declared\n named node, for example because it is used to cache repetition.\n */\n get isAnonymous() { return (this.flags & 8 /* NodeFlag.Anonymous */) > 0; }\n /**\n Returns true when this node's name or one of its\n [groups](#common.NodeProp^group) matches the given string.\n */\n is(name) {\n if (typeof name == 'string') {\n if (this.name == name)\n return true;\n let group = this.prop(NodeProp.group);\n return group ? group.indexOf(name) > -1 : false;\n }\n return this.id == name;\n }\n /**\n Create a function from node types to arbitrary values by\n specifying an object whose property names are node or\n [group](#common.NodeProp^group) names. Often useful with\n [`NodeProp.add`](#common.NodeProp.add). You can put multiple\n names, separated by spaces, in a single property name to map\n multiple node names to a single value.\n */\n static match(map) {\n let direct = Object.create(null);\n for (let prop in map)\n for (let name of prop.split(\" \"))\n direct[name] = map[prop];\n return (node) => {\n for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {\n let found = direct[i < 0 ? node.name : groups[i]];\n if (found)\n return found;\n }\n };\n }\n}\n/**\nAn empty dummy node type to use when no actual type is available.\n*/\nNodeType.none = new NodeType(\"\", Object.create(null), 0, 8 /* NodeFlag.Anonymous */);\n/**\nA node set holds a collection of node types. It is used to\ncompactly represent trees by storing their type ids, rather than a\nfull pointer to the type object, in a numeric array. Each parser\n[has](#lr.LRParser.nodeSet) a node set, and [tree\nbuffers](#common.TreeBuffer) can only store collections of nodes\nfrom the same set. A set can have a maximum of 2**16 (65536) node\ntypes in it, so that the ids fit into 16-bit typed array slots.\n*/\nclass NodeSet {\n /**\n Create a set with the given types. The `id` property of each\n type should correspond to its position within the array.\n */\n constructor(\n /**\n The node types in this set, by id.\n */\n types) {\n this.types = types;\n for (let i = 0; i < types.length; i++)\n if (types[i].id != i)\n throw new RangeError(\"Node type ids should correspond to array positions when creating a node set\");\n }\n /**\n Create a copy of this set with some node properties added. The\n arguments to this method can be created with\n [`NodeProp.add`](#common.NodeProp.add).\n */\n extend(...props) {\n let newTypes = [];\n for (let type of this.types) {\n let newProps = null;\n for (let source of props) {\n let add = source(type);\n if (add) {\n if (!newProps)\n newProps = Object.assign({}, type.props);\n newProps[add[0].id] = add[1];\n }\n }\n newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);\n }\n return new NodeSet(newTypes);\n }\n}\nconst CachedNode = new WeakMap(), CachedInnerNode = new WeakMap();\n/**\nOptions that control iteration. Can be combined with the `|`\noperator to enable multiple ones.\n*/\nvar IterMode;\n(function (IterMode) {\n /**\n When enabled, iteration will only visit [`Tree`](#common.Tree)\n objects, not nodes packed into\n [`TreeBuffer`](#common.TreeBuffer)s.\n */\n IterMode[IterMode[\"ExcludeBuffers\"] = 1] = \"ExcludeBuffers\";\n /**\n Enable this to make iteration include anonymous nodes (such as\n the nodes that wrap repeated grammar constructs into a balanced\n tree).\n */\n IterMode[IterMode[\"IncludeAnonymous\"] = 2] = \"IncludeAnonymous\";\n /**\n By default, regular [mounted](#common.NodeProp^mounted) nodes\n replace their base node in iteration. Enable this to ignore them\n instead.\n */\n IterMode[IterMode[\"IgnoreMounts\"] = 4] = \"IgnoreMounts\";\n /**\n This option only applies in\n [`enter`](#common.SyntaxNode.enter)-style methods. It tells the\n library to not enter mounted overlays if one covers the given\n position.\n */\n IterMode[IterMode[\"IgnoreOverlays\"] = 8] = \"IgnoreOverlays\";\n})(IterMode || (IterMode = {}));\n/**\nA piece of syntax tree. There are two ways to approach these\ntrees: the way they are actually stored in memory, and the\nconvenient way.\n\nSyntax trees are stored as a tree of `Tree` and `TreeBuffer`\nobjects. By packing detail information into `TreeBuffer` leaf\nnodes, the representation is made a lot more memory-efficient.\n\nHowever, when you want to actually work with tree nodes, this\nrepresentation is very awkward, so most client code will want to\nuse the [`TreeCursor`](#common.TreeCursor) or\n[`SyntaxNode`](#common.SyntaxNode) interface instead, which provides\na view on some part of this data structure, and can be used to\nmove around to adjacent nodes.\n*/\nclass Tree {\n /**\n Construct a new tree. See also [`Tree.build`](#common.Tree^build).\n */\n constructor(\n /**\n The type of the top node.\n */\n type, \n /**\n This node's child nodes.\n */\n children, \n /**\n The positions (offsets relative to the start of this tree) of\n the children.\n */\n positions, \n /**\n The total length of this tree\n */\n length, \n /**\n Per-node [node props](#common.NodeProp) to associate with this node.\n */\n props) {\n this.type = type;\n this.children = children;\n this.positions = positions;\n this.length = length;\n /**\n @internal\n */\n this.props = null;\n if (props && props.length) {\n this.props = Object.create(null);\n for (let [prop, value] of props)\n this.props[typeof prop == \"number\" ? prop : prop.id] = value;\n }\n }\n /**\n @internal\n */\n toString() {\n let mounted = MountedTree.get(this);\n if (mounted && !mounted.overlay)\n return mounted.tree.toString();\n let children = \"\";\n for (let ch of this.children) {\n let str = ch.toString();\n if (str) {\n if (children)\n children += \",\";\n children += str;\n }\n }\n return !this.type.name ? children :\n (/\\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) +\n (children.length ? \"(\" + children + \")\" : \"\");\n }\n /**\n Get a [tree cursor](#common.TreeCursor) positioned at the top of\n the tree. Mode can be used to [control](#common.IterMode) which\n nodes the cursor visits.\n */\n cursor(mode = 0) {\n return new TreeCursor(this.topNode, mode);\n }\n /**\n Get a [tree cursor](#common.TreeCursor) pointing into this tree\n at the given position and side (see\n [`moveTo`](#common.TreeCursor.moveTo).\n */\n cursorAt(pos, side = 0, mode = 0) {\n let scope = CachedNode.get(this) || this.topNode;\n let cursor = new TreeCursor(scope);\n cursor.moveTo(pos, side);\n CachedNode.set(this, cursor._tree);\n return cursor;\n }\n /**\n Get a [syntax node](#common.SyntaxNode) object for the top of the\n tree.\n */\n get topNode() {\n return new TreeNode(this, 0, 0, null);\n }\n /**\n Get the [syntax node](#common.SyntaxNode) at the given position.\n If `side` is -1, this will move into nodes that end at the\n position. If 1, it'll move into nodes that start at the\n position. With 0, it'll only enter nodes that cover the position\n from both sides.\n \n Note that this will not enter\n [overlays](#common.MountedTree.overlay), and you often want\n [`resolveInner`](#common.Tree.resolveInner) instead.\n */\n resolve(pos, side = 0) {\n let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);\n CachedNode.set(this, node);\n return node;\n }\n /**\n Like [`resolve`](#common.Tree.resolve), but will enter\n [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node\n pointing into the innermost overlaid tree at the given position\n (with parent links going through all parent structure, including\n the host trees).\n */\n resolveInner(pos, side = 0) {\n let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);\n CachedInnerNode.set(this, node);\n return node;\n }\n /**\n In some situations, it can be useful to iterate through all\n nodes around a position, including those in overlays that don't\n directly cover the position. This method gives you an iterator\n that will produce all nodes, from small to big, around the given\n position.\n */\n resolveStack(pos, side = 0) {\n return stackIterator(this, pos, side);\n }\n /**\n Iterate over the tree and its children, calling `enter` for any\n node that touches the `from`/`to` region (if given) before\n running over such a node's children, and `leave` (if given) when\n leaving the node. When `enter` returns `false`, that node will\n not have its children iterated over (or `leave` called).\n */\n iterate(spec) {\n let { enter, leave, from = 0, to = this.length } = spec;\n let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;\n for (let c = this.cursor(mode | IterMode.IncludeAnonymous);;) {\n let entered = false;\n if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {\n if (c.firstChild())\n continue;\n entered = true;\n }\n for (;;) {\n if (entered && leave && (anon || !c.type.isAnonymous))\n leave(c);\n if (c.nextSibling())\n break;\n if (!c.parent())\n return;\n entered = true;\n }\n }\n }\n /**\n Get the value of the given [node prop](#common.NodeProp) for this\n node. Works with both per-node and per-type props.\n */\n prop(prop) {\n return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined;\n }\n /**\n Returns the node's [per-node props](#common.NodeProp.perNode) in a\n format that can be passed to the [`Tree`](#common.Tree)\n constructor.\n */\n get propValues() {\n let result = [];\n if (this.props)\n for (let id in this.props)\n result.push([+id, this.props[id]]);\n return result;\n }\n /**\n Balance the direct children of this tree, producing a copy of\n which may have children grouped into subtrees with type\n [`NodeType.none`](#common.NodeType^none).\n */\n balance(config = {}) {\n return this.children.length <= 8 /* Balance.BranchFactor */ ? this :\n balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length)));\n }\n /**\n Build a tree from a postfix-ordered buffer of node information,\n or a cursor over such a buffer.\n */\n static build(data) { return buildTree(data); }\n}\n/**\nThe empty tree\n*/\nTree.empty = new Tree(NodeType.none, [], [], 0);\nclass FlatBufferCursor {\n constructor(buffer, index) {\n this.buffer = buffer;\n this.index = index;\n }\n get id() { return this.buffer[this.index - 4]; }\n get start() { return this.buffer[this.index - 3]; }\n get end() { return this.buffer[this.index - 2]; }\n get size() { return this.buffer[this.index - 1]; }\n get pos() { return this.index; }\n next() { this.index -= 4; }\n fork() { return new FlatBufferCursor(this.buffer, this.index); }\n}\n/**\nTree buffers contain (type, start, end, endIndex) quads for each\nnode. In such a buffer, nodes are stored in prefix order (parents\nbefore children, with the endIndex of the parent indicating which\nchildren belong to it).\n*/\nclass TreeBuffer {\n /**\n Create a tree buffer.\n */\n constructor(\n /**\n The buffer's content.\n */\n buffer, \n /**\n The total length of the group of nodes in the buffer.\n */\n length, \n /**\n The node set used in this buffer.\n */\n set) {\n this.buffer = buffer;\n this.length = length;\n this.set = set;\n }\n /**\n @internal\n */\n get type() { return NodeType.none; }\n /**\n @internal\n */\n toString() {\n let result = [];\n for (let index = 0; index < this.buffer.length;) {\n result.push(this.childString(index));\n index = this.buffer[index + 3];\n }\n return result.join(\",\");\n }\n /**\n @internal\n */\n childString(index) {\n let id = this.buffer[index], endIndex = this.buffer[index + 3];\n let type = this.set.types[id], result = type.name;\n if (/\\W/.test(result) && !type.isError)\n result = JSON.stringify(result);\n index += 4;\n if (endIndex == index)\n return result;\n let children = [];\n while (index < endIndex) {\n children.push(this.childString(index));\n index = this.buffer[index + 3];\n }\n return result + \"(\" + children.join(\",\") + \")\";\n }\n /**\n @internal\n */\n findChild(startIndex, endIndex, dir, pos, side) {\n let { buffer } = this, pick = -1;\n for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {\n if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {\n pick = i;\n if (dir > 0)\n break;\n }\n }\n return pick;\n }\n /**\n @internal\n */\n slice(startI, endI, from) {\n let b = this.buffer;\n let copy = new Uint16Array(endI - startI), len = 0;\n for (let i = startI, j = 0; i < endI;) {\n copy[j++] = b[i++];\n copy[j++] = b[i++] - from;\n let to = copy[j++] = b[i++] - from;\n copy[j++] = b[i++] - startI;\n len = Math.max(len, to);\n }\n return new TreeBuffer(copy, len, this.set);\n }\n}\nfunction checkSide(side, pos, from, to) {\n switch (side) {\n case -2 /* Side.Before */: return from < pos;\n case -1 /* Side.AtOrBefore */: return to >= pos && from < pos;\n case 0 /* Side.Around */: return from < pos && to > pos;\n case 1 /* Side.AtOrAfter */: return from <= pos && to > pos;\n case 2 /* Side.After */: return to > pos;\n case 4 /* Side.DontCare */: return true;\n }\n}\nfunction resolveNode(node, pos, side, overlays) {\n var _a;\n // Move up to a node that actually holds the position, if possible\n while (node.from == node.to ||\n (side < 1 ? node.from >= pos : node.from > pos) ||\n (side > -1 ? node.to <= pos : node.to < pos)) {\n let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;\n if (!parent)\n return node;\n node = parent;\n }\n let mode = overlays ? 0 : IterMode.IgnoreOverlays;\n // Must go up out of overlays when those do not overlap with pos\n if (overlays)\n for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {\n if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from)\n node = parent;\n }\n for (;;) {\n let inner = node.enter(pos, side, mode);\n if (!inner)\n return node;\n node = inner;\n }\n}\nclass BaseNode {\n cursor(mode = 0) { return new TreeCursor(this, mode); }\n getChild(type, before = null, after = null) {\n let r = getChildren(this, type, before, after);\n return r.length ? r[0] : null;\n }\n getChildren(type, before = null, after = null) {\n return getChildren(this, type, before, after);\n }\n resolve(pos, side = 0) {\n return resolveNode(this, pos, side, false);\n }\n resolveInner(pos, side = 0) {\n return resolveNode(this, pos, side, true);\n }\n matchContext(context) {\n return matchNodeContext(this, context);\n }\n enterUnfinishedNodesBefore(pos) {\n let scan = this.childBefore(pos), node = this;\n while (scan) {\n let last = scan.lastChild;\n if (!last || last.to != scan.to)\n break;\n if (last.type.isError && last.from == last.to) {\n node = scan;\n scan = last.prevSibling;\n }\n else {\n scan = last;\n }\n }\n return node;\n }\n get node() { return this; }\n get next() { return this.parent; }\n}\nclass TreeNode extends BaseNode {\n constructor(_tree, from, \n // Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay)\n index, _parent) {\n super();\n this._tree = _tree;\n this.from = from;\n this.index = index;\n this._parent = _parent;\n }\n get type() { return this._tree.type; }\n get name() { return this._tree.type.name; }\n get to() { return this.from + this._tree.length; }\n nextChild(i, dir, pos, side, mode = 0) {\n for (let parent = this;;) {\n for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) {\n let next = children[i], start = positions[i] + parent.from;\n if (!checkSide(side, pos, start, start + next.length))\n continue;\n if (next instanceof TreeBuffer) {\n if (mode & IterMode.ExcludeBuffers)\n continue;\n let index = next.findChild(0, next.buffer.length, dir, pos - start, side);\n if (index > -1)\n return new BufferNode(new BufferContext(parent, next, i, start), null, index);\n }\n else if ((mode & IterMode.IncludeAnonymous) || (!next.type.isAnonymous || hasChild(next))) {\n let mounted;\n if (!(mode & IterMode.IgnoreMounts) && (mounted = MountedTree.get(next)) && !mounted.overlay)\n return new TreeNode(mounted.tree, start, i, parent);\n let inner = new TreeNode(next, start, i, parent);\n return (mode & IterMode.IncludeAnonymous) || !inner.type.isAnonymous ? inner\n : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side);\n }\n }\n if ((mode & IterMode.IncludeAnonymous) || !parent.type.isAnonymous)\n return null;\n if (parent.index >= 0)\n i = parent.index + dir;\n else\n i = dir < 0 ? -1 : parent._parent._tree.children.length;\n parent = parent._parent;\n if (!parent)\n return null;\n }\n }\n get firstChild() { return this.nextChild(0, 1, 0, 4 /* Side.DontCare */); }\n get lastChild() { return this.nextChild(this._tree.children.length - 1, -1, 0, 4 /* Side.DontCare */); }\n childAfter(pos) { return this.nextChild(0, 1, pos, 2 /* Side.After */); }\n childBefore(pos) { return this.nextChild(this._tree.children.length - 1, -1, pos, -2 /* Side.Before */); }\n enter(pos, side, mode = 0) {\n let mounted;\n if (!(mode & IterMode.IgnoreOverlays) && (mounted = MountedTree.get(this._tree)) && mounted.overlay) {\n let rPos = pos - this.from;\n for (let { from, to } of mounted.overlay) {\n if ((side > 0 ? from <= rPos : from < rPos) &&\n (side < 0 ? to >= rPos : to > rPos))\n return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);\n }\n }\n return this.nextChild(0, 1, pos, side, mode);\n }\n nextSignificantParent() {\n let val = this;\n while (val.type.isAnonymous && val._parent)\n val = val._parent;\n return val;\n }\n get parent() {\n return this._parent ? this._parent.nextSignificantParent() : null;\n }\n get nextSibling() {\n return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4 /* Side.DontCare */) : null;\n }\n get prevSibling() {\n return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4 /* Side.DontCare */) : null;\n }\n get tree() { return this._tree; }\n toTree() { return this._tree; }\n /**\n @internal\n */\n toString() { return this._tree.toString(); }\n}\nfunction getChildren(node, type, before, after) {\n let cur = node.cursor(), result = [];\n if (!cur.firstChild())\n return result;\n if (before != null)\n while (!cur.type.is(before))\n if (!cur.nextSibling())\n return result;\n for (;;) {\n if (after != null && cur.type.is(after))\n return result;\n if (cur.type.is(type))\n result.push(cur.node);\n if (!cur.nextSibling())\n return after == null ? result : [];\n }\n}\nfunction matchNodeContext(node, context, i = context.length - 1) {\n for (let p = node.parent; i >= 0; p = p.parent) {\n if (!p)\n return false;\n if (!p.type.isAnonymous) {\n if (context[i] && context[i] != p.name)\n return false;\n i--;\n }\n }\n return true;\n}\nclass BufferContext {\n constructor(parent, buffer, index, start) {\n this.parent = parent;\n this.buffer = buffer;\n this.index = index;\n this.start = start;\n }\n}\nclass BufferNode extends BaseNode {\n get name() { return this.type.name; }\n get from() { return this.context.start + this.context.buffer.buffer[this.index + 1]; }\n get to() { return this.context.start + this.context.buffer.buffer[this.index + 2]; }\n constructor(context, _parent, index) {\n super();\n this.context = context;\n this._parent = _parent;\n this.index = index;\n this.type = context.buffer.set.types[context.buffer.buffer[index]];\n }\n child(dir, pos, side) {\n let { buffer } = this.context;\n let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);\n return index < 0 ? null : new BufferNode(this.context, this, index);\n }\n get firstChild() { return this.child(1, 0, 4 /* Side.DontCare */); }\n get lastChild() { return this.child(-1, 0, 4 /* Side.DontCare */); }\n childAfter(pos) { return this.child(1, pos, 2 /* Side.After */); }\n childBefore(pos) { return this.child(-1, pos, -2 /* Side.Before */); }\n enter(pos, side, mode = 0) {\n if (mode & IterMode.ExcludeBuffers)\n return null;\n let { buffer } = this.context;\n let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);\n return index < 0 ? null : new BufferNode(this.context, this, index);\n }\n get parent() {\n return this._parent || this.context.parent.nextSignificantParent();\n }\n externalSibling(dir) {\n return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4 /* Side.DontCare */);\n }\n get nextSibling() {\n let { buffer } = this.context;\n let after = buffer.buffer[this.index + 3];\n if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))\n return new BufferNode(this.context, this._parent, after);\n return this.externalSibling(1);\n }\n get prevSibling() {\n let { buffer } = this.context;\n let parentStart = this._parent ? this._parent.index + 4 : 0;\n if (this.index == parentStart)\n return this.externalSibling(-1);\n return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4 /* Side.DontCare */));\n }\n get tree() { return null; }\n toTree() {\n let children = [], positions = [];\n let { buffer } = this.context;\n let startI = this.index + 4, endI = buffer.buffer[this.index + 3];\n if (endI > startI) {\n let from = buffer.buffer[this.index + 1];\n children.push(buffer.slice(startI, endI, from));\n positions.push(0);\n }\n return new Tree(this.type, children, positions, this.to - this.from);\n }\n /**\n @internal\n */\n toString() { return this.context.buffer.childString(this.index); }\n}\nfunction iterStack(heads) {\n if (!heads.length)\n return null;\n let pick = 0, picked = heads[0];\n for (let i = 1; i < heads.length; i++) {\n let node = heads[i];\n if (node.from > picked.from || node.to < picked.to) {\n picked = node;\n pick = i;\n }\n }\n let next = picked instanceof TreeNode && picked.index < 0 ? null : picked.parent;\n let newHeads = heads.slice();\n if (next)\n newHeads[pick] = next;\n else\n newHeads.splice(pick, 1);\n return new StackIterator(newHeads, picked);\n}\nclass StackIterator {\n constructor(heads, node) {\n this.heads = heads;\n this.node = node;\n }\n get next() { return iterStack(this.heads); }\n}\nfunction stackIterator(tree, pos, side) {\n let inner = tree.resolveInner(pos, side), layers = null;\n for (let scan = inner instanceof TreeNode ? inner : inner.context.parent; scan; scan = scan.parent) {\n if (scan.index < 0) { // This is an overlay root\n let parent = scan.parent;\n (layers || (layers = [inner])).push(parent.resolve(pos, side));\n scan = parent;\n }\n else {\n let mount = MountedTree.get(scan.tree);\n // Relevant overlay branching off\n if (mount && mount.overlay && mount.overlay[0].from <= pos && mount.overlay[mount.overlay.length - 1].to >= pos) {\n let root = new TreeNode(mount.tree, mount.overlay[0].from + scan.from, -1, scan);\n (layers || (layers = [inner])).push(resolveNode(root, pos, side, false));\n }\n }\n }\n return layers ? iterStack(layers) : inner;\n}\n/**\nA tree cursor object focuses on a given node in a syntax tree, and\nallows you to move to adjacent nodes.\n*/\nclass TreeCursor {\n /**\n Shorthand for `.type.name`.\n */\n get name() { return this.type.name; }\n /**\n @internal\n */\n constructor(node, \n /**\n @internal\n */\n mode = 0) {\n this.mode = mode;\n /**\n @internal\n */\n this.buffer = null;\n this.stack = [];\n /**\n @internal\n */\n this.index = 0;\n this.bufferNode = null;\n if (node instanceof TreeNode) {\n this.yieldNode(node);\n }\n else {\n this._tree = node.context.parent;\n this.buffer = node.context;\n for (let n = node._parent; n; n = n._parent)\n this.stack.unshift(n.index);\n this.bufferNode = node;\n this.yieldBuf(node.index);\n }\n }\n yieldNode(node) {\n if (!node)\n return false;\n this._tree = node;\n this.type = node.type;\n this.from = node.from;\n this.to = node.to;\n return true;\n }\n yieldBuf(index, type) {\n this.index = index;\n let { start, buffer } = this.buffer;\n this.type = type || buffer.set.types[buffer.buffer[index]];\n this.from = start + buffer.buffer[index + 1];\n this.to = start + buffer.buffer[index + 2];\n return true;\n }\n /**\n @internal\n */\n yield(node) {\n if (!node)\n return false;\n if (node instanceof TreeNode) {\n this.buffer = null;\n return this.yieldNode(node);\n }\n this.buffer = node.context;\n return this.yieldBuf(node.index, node.type);\n }\n /**\n @internal\n */\n toString() {\n return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();\n }\n /**\n @internal\n */\n enterChild(dir, pos, side) {\n if (!this.buffer)\n return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));\n let { buffer } = this.buffer;\n let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);\n if (index < 0)\n return false;\n this.stack.push(this.index);\n return this.yieldBuf(index);\n }\n /**\n Move the cursor to this node's first child. When this returns\n false, the node has no child, and the cursor has not been moved.\n */\n firstChild() { return this.enterChild(1, 0, 4 /* Side.DontCare */); }\n /**\n Move the cursor to this node's last child.\n */\n lastChild() { return this.enterChild(-1, 0, 4 /* Side.DontCare */); }\n /**\n Move the cursor to the first child that ends after `pos`.\n */\n childAfter(pos) { return this.enterChild(1, pos, 2 /* Side.After */); }\n /**\n Move to the last child that starts before `pos`.\n */\n childBefore(pos) { return this.enterChild(-1, pos, -2 /* Side.Before */); }\n /**\n Move the cursor to the child around `pos`. If side is -1 the\n child may end at that position, when 1 it may start there. This\n will also enter [overlaid](#common.MountedTree.overlay)\n [mounted](#common.NodeProp^mounted) trees unless `overlays` is\n set to false.\n */\n enter(pos, side, mode = this.mode) {\n if (!this.buffer)\n return this.yield(this._tree.enter(pos, side, mode));\n return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);\n }\n /**\n Move to the node's parent node, if this isn't the top node.\n */\n parent() {\n if (!this.buffer)\n return this.yieldNode((this.mode & IterMode.IncludeAnonymous) ? this._tree._parent : this._tree.parent);\n if (this.stack.length)\n return this.yieldBuf(this.stack.pop());\n let parent = (this.mode & IterMode.IncludeAnonymous) ? this.buffer.parent : this.buffer.parent.nextSignificantParent();\n this.buffer = null;\n return this.yieldNode(parent);\n }\n /**\n @internal\n */\n sibling(dir) {\n if (!this.buffer)\n return !this._tree._parent ? false\n : this.yield(this._tree.index < 0 ? null\n : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4 /* Side.DontCare */, this.mode));\n let { buffer } = this.buffer, d = this.stack.length - 1;\n if (dir < 0) {\n let parentStart = d < 0 ? 0 : this.stack[d] + 4;\n if (this.index != parentStart)\n return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4 /* Side.DontCare */));\n }\n else {\n let after = buffer.buffer[this.index + 3];\n if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))\n return this.yieldBuf(after);\n }\n return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4 /* Side.DontCare */, this.mode)) : false;\n }\n /**\n Move to this node's next sibling, if any.\n */\n nextSibling() { return this.sibling(1); }\n /**\n Move to this node's previous sibling, if any.\n */\n prevSibling() { return this.sibling(-1); }\n atLastNode(dir) {\n let index, parent, { buffer } = this;\n if (buffer) {\n if (dir > 0) {\n if (this.index < buffer.buffer.buffer.length)\n return false;\n }\n else {\n for (let i = 0; i < this.index; i++)\n if (buffer.buffer.buffer[i + 3] < this.index)\n return false;\n }\n ({ index, parent } = buffer);\n }\n else {\n ({ index, _parent: parent } = this._tree);\n }\n for (; parent; { index, _parent: parent } = parent) {\n if (index > -1)\n for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) {\n let child = parent._tree.children[i];\n if ((this.mode & IterMode.IncludeAnonymous) ||\n child instanceof TreeBuffer ||\n !child.type.isAnonymous ||\n hasChild(child))\n return false;\n }\n }\n return true;\n }\n move(dir, enter) {\n if (enter && this.enterChild(dir, 0, 4 /* Side.DontCare */))\n return true;\n for (;;) {\n if (this.sibling(dir))\n return true;\n if (this.atLastNode(dir) || !this.parent())\n return false;\n }\n }\n /**\n Move to the next node in a\n [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)\n traversal, going from a node to its first child or, if the\n current node is empty or `enter` is false, its next sibling or\n the next sibling of the first parent node that has one.\n */\n next(enter = true) { return this.move(1, enter); }\n /**\n Move to the next node in a last-to-first pre-order traveral. A\n node is followed by its last child or, if it has none, its\n previous sibling or the previous sibling of the first parent\n node that has one.\n */\n prev(enter = true) { return this.move(-1, enter); }\n /**\n Move the cursor to the innermost node that covers `pos`. If\n `side` is -1, it will enter nodes that end at `pos`. If it is 1,\n it will enter nodes that start at `pos`.\n */\n moveTo(pos, side = 0) {\n // Move up to a node that actually holds the position, if possible\n while (this.from == this.to ||\n (side < 1 ? this.from >= pos : this.from > pos) ||\n (side > -1 ? this.to <= pos : this.to < pos))\n if (!this.parent())\n break;\n // Then scan down into child nodes as far as possible\n while (this.enterChild(1, pos, side)) { }\n return this;\n }\n /**\n Get a [syntax node](#common.SyntaxNode) at the cursor's current\n position.\n */\n get node() {\n if (!this.buffer)\n return this._tree;\n let cache = this.bufferNode, result = null, depth = 0;\n if (cache && cache.context == this.buffer) {\n scan: for (let index = this.index, d = this.stack.length; d >= 0;) {\n for (let c = cache; c; c = c._parent)\n if (c.index == index) {\n if (index == this.index)\n return c;\n result = c;\n depth = d + 1;\n break scan;\n }\n index = this.stack[--d];\n }\n }\n for (let i = depth; i < this.stack.length; i++)\n result = new BufferNode(this.buffer, result, this.stack[i]);\n return this.bufferNode = new BufferNode(this.buffer, result, this.index);\n }\n /**\n Get the [tree](#common.Tree) that represents the current node, if\n any. Will return null when the node is in a [tree\n buffer](#common.TreeBuffer).\n */\n get tree() {\n return this.buffer ? null : this._tree._tree;\n }\n /**\n Iterate over the current node and all its descendants, calling\n `enter` when entering a node and `leave`, if given, when leaving\n one. When `enter` returns `false`, any children of that node are\n skipped, and `leave` isn't called for it.\n */\n iterate(enter, leave) {\n for (let depth = 0;;) {\n let mustLeave = false;\n if (this.type.isAnonymous || enter(this) !== false) {\n if (this.firstChild()) {\n depth++;\n continue;\n }\n if (!this.type.isAnonymous)\n mustLeave = true;\n }\n for (;;) {\n if (mustLeave && leave)\n leave(this);\n mustLeave = this.type.isAnonymous;\n if (this.nextSibling())\n break;\n if (!depth)\n return;\n this.parent();\n depth--;\n mustLeave = true;\n }\n }\n }\n /**\n Test whether the current node matches a given context—a sequence\n of direct parent node names. Empty strings in the context array\n are treated as wildcards.\n */\n matchContext(context) {\n if (!this.buffer)\n return matchNodeContext(this.node, context);\n let { buffer } = this.buffer, { types } = buffer.set;\n for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {\n if (d < 0)\n return matchNodeContext(this.node, context, i);\n let type = types[buffer.buffer[this.stack[d]]];\n if (!type.isAnonymous) {\n if (context[i] && context[i] != type.name)\n return false;\n i--;\n }\n }\n return true;\n }\n}\nfunction hasChild(tree) {\n return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));\n}\nfunction buildTree(data) {\n var _a;\n let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;\n let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;\n let types = nodeSet.types;\n let contextHash = 0, lookAhead = 0;\n function takeNode(parentStart, minPos, children, positions, inRepeat, depth) {\n let { id, start, end, size } = cursor;\n let lookAheadAtStart = lookAhead;\n while (size < 0) {\n cursor.next();\n if (size == -1 /* SpecialRecord.Reuse */) {\n let node = reused[id];\n children.push(node);\n positions.push(start - parentStart);\n return;\n }\n else if (size == -3 /* SpecialRecord.ContextChange */) { // Context change\n contextHash = id;\n return;\n }\n else if (size == -4 /* SpecialRecord.LookAhead */) {\n lookAhead = id;\n return;\n }\n else {\n throw new RangeError(`Unrecognized record size: ${size}`);\n }\n }\n let type = types[id], node, buffer;\n let startPos = start - parentStart;\n if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) {\n // Small enough for a buffer, and no reused nodes inside\n let data = new Uint16Array(buffer.size - buffer.skip);\n let endPos = cursor.pos - buffer.size, index = data.length;\n while (cursor.pos > endPos)\n index = copyToBuffer(buffer.start, data, index);\n node = new TreeBuffer(data, end - buffer.start, nodeSet);\n startPos = buffer.start - parentStart;\n }\n else { // Make it a node\n let endPos = cursor.pos - size;\n cursor.next();\n let localChildren = [], localPositions = [];\n let localInRepeat = id >= minRepeatType ? id : -1;\n let lastGroup = 0, lastEnd = end;\n while (cursor.pos > endPos) {\n if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {\n if (cursor.end <= lastEnd - maxBufferLength) {\n makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart);\n lastGroup = localChildren.length;\n lastEnd = cursor.end;\n }\n cursor.next();\n }\n else if (depth > 2500 /* CutOff.Depth */) {\n takeFlatNode(start, endPos, localChildren, localPositions);\n }\n else {\n takeNode(start, endPos, localChildren, localPositions, localInRepeat, depth + 1);\n }\n }\n if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)\n makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart);\n localChildren.reverse();\n localPositions.reverse();\n if (localInRepeat > -1 && lastGroup > 0) {\n let make = makeBalanced(type);\n node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);\n }\n else {\n node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end);\n }\n }\n children.push(node);\n positions.push(startPos);\n }\n function takeFlatNode(parentStart, minPos, children, positions) {\n let nodes = []; // Temporary, inverted array of leaf nodes found, with absolute positions\n let nodeCount = 0, stopAt = -1;\n while (cursor.pos > minPos) {\n let { id, start, end, size } = cursor;\n if (size > 4) { // Not a leaf\n cursor.next();\n }\n else if (stopAt > -1 && start < stopAt) {\n break;\n }\n else {\n if (stopAt < 0)\n stopAt = end - maxBufferLength;\n nodes.push(id, start, end);\n nodeCount++;\n cursor.next();\n }\n }\n if (nodeCount) {\n let buffer = new Uint16Array(nodeCount * 4);\n let start = nodes[nodes.length - 2];\n for (let i = nodes.length - 3, j = 0; i >= 0; i -= 3) {\n buffer[j++] = nodes[i];\n buffer[j++] = nodes[i + 1] - start;\n buffer[j++] = nodes[i + 2] - start;\n buffer[j++] = j;\n }\n children.push(new TreeBuffer(buffer, nodes[2] - start, nodeSet));\n positions.push(start - parentStart);\n }\n }\n function makeBalanced(type) {\n return (children, positions, length) => {\n let lookAhead = 0, lastI = children.length - 1, last, lookAheadProp;\n if (lastI >= 0 && (last = children[lastI]) instanceof Tree) {\n if (!lastI && last.type == type && last.length == length)\n return last;\n if (lookAheadProp = last.prop(NodeProp.lookAhead))\n lookAhead = positions[lastI] + last.length + lookAheadProp;\n }\n return makeTree(type, children, positions, length, lookAhead);\n };\n }\n function makeRepeatLeaf(children, positions, base, i, from, to, type, lookAhead) {\n let localChildren = [], localPositions = [];\n while (children.length > i) {\n localChildren.push(children.pop());\n localPositions.push(positions.pop() + base - from);\n }\n children.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead - to));\n positions.push(from - base);\n }\n function makeTree(type, children, positions, length, lookAhead = 0, props) {\n if (contextHash) {\n let pair = [NodeProp.contextHash, contextHash];\n props = props ? [pair].concat(props) : [pair];\n }\n if (lookAhead > 25) {\n let pair = [NodeProp.lookAhead, lookAhead];\n props = props ? [pair].concat(props) : [pair];\n }\n return new Tree(type, children, positions, length, props);\n }\n function findBufferSize(maxSize, inRepeat) {\n // Scan through the buffer to find previous siblings that fit\n // together in a TreeBuffer, and don't contain any reused nodes\n // (which can't be stored in a buffer).\n // If `inRepeat` is > -1, ignore node boundaries of that type for\n // nesting, but make sure the end falls either at the start\n // (`maxSize`) or before such a node.\n let fork = cursor.fork();\n let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;\n let result = { size: 0, start: 0, skip: 0 };\n scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) {\n let nodeSize = fork.size;\n // Pretend nested repeat nodes of the same type don't exist\n if (fork.id == inRepeat && nodeSize >= 0) {\n // Except that we store the current state as a valid return\n // value.\n result.size = size;\n result.start = start;\n result.skip = skip;\n skip += 4;\n size += 4;\n fork.next();\n continue;\n }\n let startPos = fork.pos - nodeSize;\n if (nodeSize < 0 || startPos < minPos || fork.start < minStart)\n break;\n let localSkipped = fork.id >= minRepeatType ? 4 : 0;\n let nodeStart = fork.start;\n fork.next();\n while (fork.pos > startPos) {\n if (fork.size < 0) {\n if (fork.size == -3 /* SpecialRecord.ContextChange */)\n localSkipped += 4;\n else\n break scan;\n }\n else if (fork.id >= minRepeatType) {\n localSkipped += 4;\n }\n fork.next();\n }\n start = nodeStart;\n size += nodeSize;\n skip += localSkipped;\n }\n if (inRepeat < 0 || size == maxSize) {\n result.size = size;\n result.start = start;\n result.skip = skip;\n }\n return result.size > 4 ? result : undefined;\n }\n function copyToBuffer(bufferStart, buffer, index) {\n let { id, start, end, size } = cursor;\n cursor.next();\n if (size >= 0 && id < minRepeatType) {\n let startIndex = index;\n if (size > 4) {\n let endPos = cursor.pos - (size - 4);\n while (cursor.pos > endPos)\n index = copyToBuffer(bufferStart, buffer, index);\n }\n buffer[--index] = startIndex;\n buffer[--index] = end - bufferStart;\n buffer[--index] = start - bufferStart;\n buffer[--index] = id;\n }\n else if (size == -3 /* SpecialRecord.ContextChange */) {\n contextHash = id;\n }\n else if (size == -4 /* SpecialRecord.LookAhead */) {\n lookAhead = id;\n }\n return index;\n }\n let children = [], positions = [];\n while (cursor.pos > 0)\n takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1, 0);\n let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0);\n return new Tree(types[data.topID], children.reverse(), positions.reverse(), length);\n}\nconst nodeSizeCache = new WeakMap;\nfunction nodeSize(balanceType, node) {\n if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)\n return 1;\n let size = nodeSizeCache.get(node);\n if (size == null) {\n size = 1;\n for (let child of node.children) {\n if (child.type != balanceType || !(child instanceof Tree)) {\n size = 1;\n break;\n }\n size += nodeSize(balanceType, child);\n }\n nodeSizeCache.set(node, size);\n }\n return size;\n}\nfunction balanceRange(\n// The type the balanced tree's inner nodes.\nbalanceType, \n// The direct children and their positions\nchildren, positions, \n// The index range in children/positions to use\nfrom, to, \n// The start position of the nodes, relative to their parent.\nstart, \n// Length of the outer node\nlength, \n// Function to build the top node of the balanced tree\nmkTop, \n// Function to build internal nodes for the balanced tree\nmkTree) {\n let total = 0;\n for (let i = from; i < to; i++)\n total += nodeSize(balanceType, children[i]);\n let maxChild = Math.ceil((total * 1.5) / 8 /* Balance.BranchFactor */);\n let localChildren = [], localPositions = [];\n function divide(children, positions, from, to, offset) {\n for (let i = from; i < to;) {\n let groupFrom = i, groupStart = positions[i], groupSize = nodeSize(balanceType, children[i]);\n i++;\n for (; i < to; i++) {\n let nextSize = nodeSize(balanceType, children[i]);\n if (groupSize + nextSize >= maxChild)\n break;\n groupSize += nextSize;\n }\n if (i == groupFrom + 1) {\n if (groupSize > maxChild) {\n let only = children[groupFrom]; // Only trees can have a size > 1\n divide(only.children, only.positions, 0, only.children.length, positions[groupFrom] + offset);\n continue;\n }\n localChildren.push(children[groupFrom]);\n }\n else {\n let length = positions[i - 1] + children[i - 1].length - groupStart;\n localChildren.push(balanceRange(balanceType, children, positions, groupFrom, i, groupStart, length, null, mkTree));\n }\n localPositions.push(groupStart + offset - start);\n }\n }\n divide(children, positions, from, to, 0);\n return (mkTop || mkTree)(localChildren, localPositions, length);\n}\n/**\nProvides a way to associate values with pieces of trees. As long\nas that part of the tree is reused, the associated values can be\nretrieved from an updated tree.\n*/\nclass NodeWeakMap {\n constructor() {\n this.map = new WeakMap();\n }\n setBuffer(buffer, index, value) {\n let inner = this.map.get(buffer);\n if (!inner)\n this.map.set(buffer, inner = new Map);\n inner.set(index, value);\n }\n getBuffer(buffer, index) {\n let inner = this.map.get(buffer);\n return inner && inner.get(index);\n }\n /**\n Set the value for this syntax node.\n */\n set(node, value) {\n if (node instanceof BufferNode)\n this.setBuffer(node.context.buffer, node.index, value);\n else if (node instanceof TreeNode)\n this.map.set(node.tree, value);\n }\n /**\n Retrieve value for this syntax node, if it exists in the map.\n */\n get(node) {\n return node instanceof BufferNode ? this.getBuffer(node.context.buffer, node.index)\n : node instanceof TreeNode ? this.map.get(node.tree) : undefined;\n }\n /**\n Set the value for the node that a cursor currently points to.\n */\n cursorSet(cursor, value) {\n if (cursor.buffer)\n this.setBuffer(cursor.buffer.buffer, cursor.index, value);\n else\n this.map.set(cursor.tree, value);\n }\n /**\n Retrieve the value for the node that a cursor currently points\n to.\n */\n cursorGet(cursor) {\n return cursor.buffer ? this.getBuffer(cursor.buffer.buffer, cursor.index) : this.map.get(cursor.tree);\n }\n}\n\n/**\nTree fragments are used during [incremental\nparsing](#common.Parser.startParse) to track parts of old trees\nthat can be reused in a new parse. An array of fragments is used\nto track regions of an old tree whose nodes might be reused in new\nparses. Use the static\n[`applyChanges`](#common.TreeFragment^applyChanges) method to\nupdate fragments for document changes.\n*/\nclass TreeFragment {\n /**\n Construct a tree fragment. You'll usually want to use\n [`addTree`](#common.TreeFragment^addTree) and\n [`applyChanges`](#common.TreeFragment^applyChanges) instead of\n calling this directly.\n */\n constructor(\n /**\n The start of the unchanged range pointed to by this fragment.\n This refers to an offset in the _updated_ document (as opposed\n to the original tree).\n */\n from, \n /**\n The end of the unchanged range.\n */\n to, \n /**\n The tree that this fragment is based on.\n */\n tree, \n /**\n The offset between the fragment's tree and the document that\n this fragment can be used against. Add this when going from\n document to tree positions, subtract it to go from tree to\n document positions.\n */\n offset, openStart = false, openEnd = false) {\n this.from = from;\n this.to = to;\n this.tree = tree;\n this.offset = offset;\n this.open = (openStart ? 1 /* Open.Start */ : 0) | (openEnd ? 2 /* Open.End */ : 0);\n }\n /**\n Whether the start of the fragment represents the start of a\n parse, or the end of a change. (In the second case, it may not\n be safe to reuse some nodes at the start, depending on the\n parsing algorithm.)\n */\n get openStart() { return (this.open & 1 /* Open.Start */) > 0; }\n /**\n Whether the end of the fragment represents the end of a\n full-document parse, or the start of a change.\n */\n get openEnd() { return (this.open & 2 /* Open.End */) > 0; }\n /**\n Create a set of fragments from a freshly parsed tree, or update\n an existing set of fragments by replacing the ones that overlap\n with a tree with content from the new tree. When `partial` is\n true, the parse is treated as incomplete, and the resulting\n fragment has [`openEnd`](#common.TreeFragment.openEnd) set to\n true.\n */\n static addTree(tree, fragments = [], partial = false) {\n let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)];\n for (let f of fragments)\n if (f.to > tree.length)\n result.push(f);\n return result;\n }\n /**\n Apply a set of edits to an array of fragments, removing or\n splitting fragments as necessary to remove edited ranges, and\n adjusting offsets for fragments that moved.\n */\n static applyChanges(fragments, changes, minGap = 128) {\n if (!changes.length)\n return fragments;\n let result = [];\n let fI = 1, nextF = fragments.length ? fragments[0] : null;\n for (let cI = 0, pos = 0, off = 0;; cI++) {\n let nextC = cI < changes.length ? changes[cI] : null;\n let nextPos = nextC ? nextC.fromA : 1e9;\n if (nextPos - pos >= minGap)\n while (nextF && nextF.from < nextPos) {\n let cut = nextF;\n if (pos >= cut.from || nextPos <= cut.to || off) {\n let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off;\n cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC);\n }\n if (cut)\n result.push(cut);\n if (nextF.to > nextPos)\n break;\n nextF = fI < fragments.length ? fragments[fI++] : null;\n }\n if (!nextC)\n break;\n pos = nextC.toA;\n off = nextC.toA - nextC.toB;\n }\n return result;\n }\n}\n/**\nA superclass that parsers should extend.\n*/\nclass Parser {\n /**\n Start a parse, returning a [partial parse](#common.PartialParse)\n object. [`fragments`](#common.TreeFragment) can be passed in to\n make the parse incremental.\n \n By default, the entire input is parsed. You can pass `ranges`,\n which should be a sorted array of non-empty, non-overlapping\n ranges, to parse only those ranges. The tree returned in that\n case will start at `ranges[0].from`.\n */\n startParse(input, fragments, ranges) {\n if (typeof input == \"string\")\n input = new StringInput(input);\n ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map(r => new Range(r.from, r.to)) : [new Range(0, 0)];\n return this.createParse(input, fragments || [], ranges);\n }\n /**\n Run a full parse, returning the resulting tree.\n */\n parse(input, fragments, ranges) {\n let parse = this.startParse(input, fragments, ranges);\n for (;;) {\n let done = parse.advance();\n if (done)\n return done;\n }\n }\n}\nclass StringInput {\n constructor(string) {\n this.string = string;\n }\n get length() { return this.string.length; }\n chunk(from) { return this.string.slice(from); }\n get lineChunks() { return false; }\n read(from, to) { return this.string.slice(from, to); }\n}\n\n/**\nCreate a parse wrapper that, after the inner parse completes,\nscans its tree for mixed language regions with the `nest`\nfunction, runs the resulting [inner parses](#common.NestedParse),\nand then [mounts](#common.NodeProp^mounted) their results onto the\ntree.\n*/\nfunction parseMixed(nest) {\n return (parse, input, fragments, ranges) => new MixedParse(parse, nest, input, fragments, ranges);\n}\nclass InnerParse {\n constructor(parser, parse, overlay, target, from) {\n this.parser = parser;\n this.parse = parse;\n this.overlay = overlay;\n this.target = target;\n this.from = from;\n }\n}\nfunction checkRanges(ranges) {\n if (!ranges.length || ranges.some(r => r.from >= r.to))\n throw new RangeError(\"Invalid inner parse ranges given: \" + JSON.stringify(ranges));\n}\nclass ActiveOverlay {\n constructor(parser, predicate, mounts, index, start, target, prev) {\n this.parser = parser;\n this.predicate = predicate;\n this.mounts = mounts;\n this.index = index;\n this.start = start;\n this.target = target;\n this.prev = prev;\n this.depth = 0;\n this.ranges = [];\n }\n}\nconst stoppedInner = new NodeProp({ perNode: true });\nclass MixedParse {\n constructor(base, nest, input, fragments, ranges) {\n this.nest = nest;\n this.input = input;\n this.fragments = fragments;\n this.ranges = ranges;\n this.inner = [];\n this.innerDone = 0;\n this.baseTree = null;\n this.stoppedAt = null;\n this.baseParse = base;\n }\n advance() {\n if (this.baseParse) {\n let done = this.baseParse.advance();\n if (!done)\n return null;\n this.baseParse = null;\n this.baseTree = done;\n this.startInner();\n if (this.stoppedAt != null)\n for (let inner of this.inner)\n inner.parse.stopAt(this.stoppedAt);\n }\n if (this.innerDone == this.inner.length) {\n let result = this.baseTree;\n if (this.stoppedAt != null)\n result = new Tree(result.type, result.children, result.positions, result.length, result.propValues.concat([[stoppedInner, this.stoppedAt]]));\n return result;\n }\n let inner = this.inner[this.innerDone], done = inner.parse.advance();\n if (done) {\n this.innerDone++;\n // This is a somewhat dodgy but super helpful hack where we\n // patch up nodes created by the inner parse (and thus\n // presumably not aliased anywhere else) to hold the information\n // about the inner parse.\n let props = Object.assign(Object.create(null), inner.target.props);\n props[NodeProp.mounted.id] = new MountedTree(done, inner.overlay, inner.parser);\n inner.target.props = props;\n }\n return null;\n }\n get parsedPos() {\n if (this.baseParse)\n return 0;\n let pos = this.input.length;\n for (let i = this.innerDone; i < this.inner.length; i++) {\n if (this.inner[i].from < pos)\n pos = Math.min(pos, this.inner[i].parse.parsedPos);\n }\n return pos;\n }\n stopAt(pos) {\n this.stoppedAt = pos;\n if (this.baseParse)\n this.baseParse.stopAt(pos);\n else\n for (let i = this.innerDone; i < this.inner.length; i++)\n this.inner[i].parse.stopAt(pos);\n }\n startInner() {\n let fragmentCursor = new FragmentCursor(this.fragments);\n let overlay = null;\n let covered = null;\n let cursor = new TreeCursor(new TreeNode(this.baseTree, this.ranges[0].from, 0, null), IterMode.IncludeAnonymous | IterMode.IgnoreMounts);\n scan: for (let nest, isCovered;;) {\n let enter = true, range;\n if (this.stoppedAt != null && cursor.from >= this.stoppedAt) {\n enter = false;\n }\n else if (fragmentCursor.hasNode(cursor)) {\n if (overlay) {\n let match = overlay.mounts.find(m => m.frag.from <= cursor.from && m.frag.to >= cursor.to && m.mount.overlay);\n if (match)\n for (let r of match.mount.overlay) {\n let from = r.from + match.pos, to = r.to + match.pos;\n if (from >= cursor.from && to <= cursor.to && !overlay.ranges.some(r => r.from < to && r.to > from))\n overlay.ranges.push({ from, to });\n }\n }\n enter = false;\n }\n else if (covered && (isCovered = checkCover(covered.ranges, cursor.from, cursor.to))) {\n enter = isCovered != 2 /* Cover.Full */;\n }\n else if (!cursor.type.isAnonymous && (nest = this.nest(cursor, this.input)) &&\n (cursor.from < cursor.to || !nest.overlay)) {\n if (!cursor.tree)\n materialize(cursor);\n let oldMounts = fragmentCursor.findMounts(cursor.from, nest.parser);\n if (typeof nest.overlay == \"function\") {\n overlay = new ActiveOverlay(nest.parser, nest.overlay, oldMounts, this.inner.length, cursor.from, cursor.tree, overlay);\n }\n else {\n let ranges = punchRanges(this.ranges, nest.overlay ||\n (cursor.from < cursor.to ? [new Range(cursor.from, cursor.to)] : []));\n if (ranges.length)\n checkRanges(ranges);\n if (ranges.length || !nest.overlay)\n this.inner.push(new InnerParse(nest.parser, ranges.length ? nest.parser.startParse(this.input, enterFragments(oldMounts, ranges), ranges)\n : nest.parser.startParse(\"\"), nest.overlay ? nest.overlay.map(r => new Range(r.from - cursor.from, r.to - cursor.from)) : null, cursor.tree, ranges.length ? ranges[0].from : cursor.from));\n if (!nest.overlay)\n enter = false;\n else if (ranges.length)\n covered = { ranges, depth: 0, prev: covered };\n }\n }\n else if (overlay && (range = overlay.predicate(cursor))) {\n if (range === true)\n range = new Range(cursor.from, cursor.to);\n if (range.from < range.to)\n overlay.ranges.push(range);\n }\n if (enter && cursor.firstChild()) {\n if (overlay)\n overlay.depth++;\n if (covered)\n covered.depth++;\n }\n else {\n for (;;) {\n if (cursor.nextSibling())\n break;\n if (!cursor.parent())\n break scan;\n if (overlay && !--overlay.depth) {\n let ranges = punchRanges(this.ranges, overlay.ranges);\n if (ranges.length) {\n checkRanges(ranges);\n this.inner.splice(overlay.index, 0, new InnerParse(overlay.parser, overlay.parser.startParse(this.input, enterFragments(overlay.mounts, ranges), ranges), overlay.ranges.map(r => new Range(r.from - overlay.start, r.to - overlay.start)), overlay.target, ranges[0].from));\n }\n overlay = overlay.prev;\n }\n if (covered && !--covered.depth)\n covered = covered.prev;\n }\n }\n }\n }\n}\nfunction checkCover(covered, from, to) {\n for (let range of covered) {\n if (range.from >= to)\n break;\n if (range.to > from)\n return range.from <= from && range.to >= to ? 2 /* Cover.Full */ : 1 /* Cover.Partial */;\n }\n return 0 /* Cover.None */;\n}\n// Take a piece of buffer and convert it into a stand-alone\n// TreeBuffer.\nfunction sliceBuf(buf, startI, endI, nodes, positions, off) {\n if (startI < endI) {\n let from = buf.buffer[startI + 1];\n nodes.push(buf.slice(startI, endI, from));\n positions.push(from - off);\n }\n}\n// This function takes a node that's in a buffer, and converts it, and\n// its parent buffer nodes, into a Tree. This is again acting on the\n// assumption that the trees and buffers have been constructed by the\n// parse that was ran via the mix parser, and thus aren't shared with\n// any other code, making violations of the immutability safe.\nfunction materialize(cursor) {\n let { node } = cursor, stack = [];\n // Scan up to the nearest tree\n do {\n stack.push(cursor.index);\n cursor.parent();\n } while (!cursor.tree);\n // Find the index of the buffer in that tree\n let i = 0, base = cursor.tree, off = 0;\n for (;; i++) {\n off = base.positions[i] + cursor.from;\n if (off <= node.from && off + base.children[i].length >= node.to)\n break;\n }\n let buf = base.children[i], b = buf.buffer, newStack = [i];\n // Split a level in the buffer, putting the nodes before and after\n // the child that contains `node` into new buffers.\n function split(startI, endI, type, innerOffset, length, stackPos) {\n let targetI = stack[stackPos];\n let children = [], positions = [];\n sliceBuf(buf, startI, targetI, children, positions, innerOffset);\n let from = b[targetI + 1], to = b[targetI + 2];\n newStack.push(children.length);\n let child = stackPos\n ? split(targetI + 4, b[targetI + 3], buf.set.types[b[targetI]], from, to - from, stackPos - 1)\n : node.toTree();\n children.push(child);\n positions.push(from - innerOffset);\n sliceBuf(buf, b[targetI + 3], endI, children, positions, innerOffset);\n return new Tree(type, children, positions, length);\n }\n base.children[i] = split(0, b.length, NodeType.none, 0, buf.length, stack.length - 1);\n // Move the cursor back to the target node\n for (let index of newStack) {\n let tree = cursor.tree.children[index], pos = cursor.tree.positions[index];\n cursor.yield(new TreeNode(tree, pos + cursor.from, index, cursor._tree));\n }\n}\nclass StructureCursor {\n constructor(root, offset) {\n this.offset = offset;\n this.done = false;\n this.cursor = root.cursor(IterMode.IncludeAnonymous | IterMode.IgnoreMounts);\n }\n // Move to the first node (in pre-order) that starts at or after `pos`.\n moveTo(pos) {\n let { cursor } = this, p = pos - this.offset;\n while (!this.done && cursor.from < p) {\n if (cursor.to >= pos && cursor.enter(p, 1, IterMode.IgnoreOverlays | IterMode.ExcludeBuffers)) ;\n else if (!cursor.next(false))\n this.done = true;\n }\n }\n hasNode(cursor) {\n this.moveTo(cursor.from);\n if (!this.done && this.cursor.from + this.offset == cursor.from && this.cursor.tree) {\n for (let tree = this.cursor.tree;;) {\n if (tree == cursor.tree)\n return true;\n if (tree.children.length && tree.positions[0] == 0 && tree.children[0] instanceof Tree)\n tree = tree.children[0];\n else\n break;\n }\n }\n return false;\n }\n}\nclass FragmentCursor {\n constructor(fragments) {\n var _a;\n this.fragments = fragments;\n this.curTo = 0;\n this.fragI = 0;\n if (fragments.length) {\n let first = this.curFrag = fragments[0];\n this.curTo = (_a = first.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : first.to;\n this.inner = new StructureCursor(first.tree, -first.offset);\n }\n else {\n this.curFrag = this.inner = null;\n }\n }\n hasNode(node) {\n while (this.curFrag && node.from >= this.curTo)\n this.nextFrag();\n return this.curFrag && this.curFrag.from <= node.from && this.curTo >= node.to && this.inner.hasNode(node);\n }\n nextFrag() {\n var _a;\n this.fragI++;\n if (this.fragI == this.fragments.length) {\n this.curFrag = this.inner = null;\n }\n else {\n let frag = this.curFrag = this.fragments[this.fragI];\n this.curTo = (_a = frag.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : frag.to;\n this.inner = new StructureCursor(frag.tree, -frag.offset);\n }\n }\n findMounts(pos, parser) {\n var _a;\n let result = [];\n if (this.inner) {\n this.inner.cursor.moveTo(pos, 1);\n for (let pos = this.inner.cursor.node; pos; pos = pos.parent) {\n let mount = (_a = pos.tree) === null || _a === void 0 ? void 0 : _a.prop(NodeProp.mounted);\n if (mount && mount.parser == parser) {\n for (let i = this.fragI; i < this.fragments.length; i++) {\n let frag = this.fragments[i];\n if (frag.from >= pos.to)\n break;\n if (frag.tree == this.curFrag.tree)\n result.push({\n frag,\n pos: pos.from - frag.offset,\n mount\n });\n }\n }\n }\n }\n return result;\n }\n}\nfunction punchRanges(outer, ranges) {\n let copy = null, current = ranges;\n for (let i = 1, j = 0; i < outer.length; i++) {\n let gapFrom = outer[i - 1].to, gapTo = outer[i].from;\n for (; j < current.length; j++) {\n let r = current[j];\n if (r.from >= gapTo)\n break;\n if (r.to <= gapFrom)\n continue;\n if (!copy)\n current = copy = ranges.slice();\n if (r.from < gapFrom) {\n copy[j] = new Range(r.from, gapFrom);\n if (r.to > gapTo)\n copy.splice(j + 1, 0, new Range(gapTo, r.to));\n }\n else if (r.to > gapTo) {\n copy[j--] = new Range(gapTo, r.to);\n }\n else {\n copy.splice(j--, 1);\n }\n }\n }\n return current;\n}\nfunction findCoverChanges(a, b, from, to) {\n let iA = 0, iB = 0, inA = false, inB = false, pos = -1e9;\n let result = [];\n for (;;) {\n let nextA = iA == a.length ? 1e9 : inA ? a[iA].to : a[iA].from;\n let nextB = iB == b.length ? 1e9 : inB ? b[iB].to : b[iB].from;\n if (inA != inB) {\n let start = Math.max(pos, from), end = Math.min(nextA, nextB, to);\n if (start < end)\n result.push(new Range(start, end));\n }\n pos = Math.min(nextA, nextB);\n if (pos == 1e9)\n break;\n if (nextA == pos) {\n if (!inA)\n inA = true;\n else {\n inA = false;\n iA++;\n }\n }\n if (nextB == pos) {\n if (!inB)\n inB = true;\n else {\n inB = false;\n iB++;\n }\n }\n }\n return result;\n}\n// Given a number of fragments for the outer tree, and a set of ranges\n// to parse, find fragments for inner trees mounted around those\n// ranges, if any.\nfunction enterFragments(mounts, ranges) {\n let result = [];\n for (let { pos, mount, frag } of mounts) {\n let startPos = pos + (mount.overlay ? mount.overlay[0].from : 0), endPos = startPos + mount.tree.length;\n let from = Math.max(frag.from, startPos), to = Math.min(frag.to, endPos);\n if (mount.overlay) {\n let overlay = mount.overlay.map(r => new Range(r.from + pos, r.to + pos));\n let changes = findCoverChanges(ranges, overlay, from, to);\n for (let i = 0, pos = from;; i++) {\n let last = i == changes.length, end = last ? to : changes[i].from;\n if (end > pos)\n result.push(new TreeFragment(pos, end, mount.tree, -startPos, frag.from >= pos || frag.openStart, frag.to <= end || frag.openEnd));\n if (last)\n break;\n pos = changes[i].to;\n }\n }\n else {\n result.push(new TreeFragment(from, to, mount.tree, -startPos, frag.from >= startPos || frag.openStart, frag.to <= endPos || frag.openEnd));\n }\n }\n return result;\n}\n\nexport { DefaultBufferLength, IterMode, MountedTree, NodeProp, NodeSet, NodeType, NodeWeakMap, Parser, Tree, TreeBuffer, TreeCursor, TreeFragment, parseMixed };\n","import { NodeProp } from '@lezer/common';\n\nlet nextTagID = 0;\n/**\nHighlighting tags are markers that denote a highlighting category.\nThey are [associated](#highlight.styleTags) with parts of a syntax\ntree by a language mode, and then mapped to an actual CSS style by\na [highlighter](#highlight.Highlighter).\n\nBecause syntax tree node types and highlight styles have to be\nable to talk the same language, CodeMirror uses a mostly _closed_\n[vocabulary](#highlight.tags) of syntax tags (as opposed to\ntraditional open string-based systems, which make it hard for\nhighlighting themes to cover all the tokens produced by the\nvarious languages).\n\nIt _is_ possible to [define](#highlight.Tag^define) your own\nhighlighting tags for system-internal use (where you control both\nthe language package and the highlighter), but such tags will not\nbe picked up by regular highlighters (though you can derive them\nfrom standard tags to allow highlighters to fall back to those).\n*/\nclass Tag {\n /**\n @internal\n */\n constructor(\n /**\n The set of this tag and all its parent tags, starting with\n this one itself and sorted in order of decreasing specificity.\n */\n set, \n /**\n The base unmodified tag that this one is based on, if it's\n modified @internal\n */\n base, \n /**\n The modifiers applied to this.base @internal\n */\n modified) {\n this.set = set;\n this.base = base;\n this.modified = modified;\n /**\n @internal\n */\n this.id = nextTagID++;\n }\n /**\n Define a new tag. If `parent` is given, the tag is treated as a\n sub-tag of that parent, and\n [highlighters](#highlight.tagHighlighter) that don't mention\n this tag will try to fall back to the parent tag (or grandparent\n tag, etc).\n */\n static define(parent) {\n if (parent === null || parent === void 0 ? void 0 : parent.base)\n throw new Error(\"Can not derive from a modified tag\");\n let tag = new Tag([], null, []);\n tag.set.push(tag);\n if (parent)\n for (let t of parent.set)\n tag.set.push(t);\n return tag;\n }\n /**\n Define a tag _modifier_, which is a function that, given a tag,\n will return a tag that is a subtag of the original. Applying the\n same modifier to a twice tag will return the same value (`m1(t1)\n == m1(t1)`) and applying multiple modifiers will, regardless or\n order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`).\n \n When multiple modifiers are applied to a given base tag, each\n smaller set of modifiers is registered as a parent, so that for\n example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`,\n `m1(m3(t1)`, and so on.\n */\n static defineModifier() {\n let mod = new Modifier;\n return (tag) => {\n if (tag.modified.indexOf(mod) > -1)\n return tag;\n return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id));\n };\n }\n}\nlet nextModifierID = 0;\nclass Modifier {\n constructor() {\n this.instances = [];\n this.id = nextModifierID++;\n }\n static get(base, mods) {\n if (!mods.length)\n return base;\n let exists = mods[0].instances.find(t => t.base == base && sameArray(mods, t.modified));\n if (exists)\n return exists;\n let set = [], tag = new Tag(set, base, mods);\n for (let m of mods)\n m.instances.push(tag);\n let configs = powerSet(mods);\n for (let parent of base.set)\n if (!parent.modified.length)\n for (let config of configs)\n set.push(Modifier.get(parent, config));\n return tag;\n }\n}\nfunction sameArray(a, b) {\n return a.length == b.length && a.every((x, i) => x == b[i]);\n}\nfunction powerSet(array) {\n let sets = [[]];\n for (let i = 0; i < array.length; i++) {\n for (let j = 0, e = sets.length; j < e; j++) {\n sets.push(sets[j].concat(array[i]));\n }\n }\n return sets.sort((a, b) => b.length - a.length);\n}\n/**\nThis function is used to add a set of tags to a language syntax\nvia [`NodeSet.extend`](#common.NodeSet.extend) or\n[`LRParser.configure`](#lr.LRParser.configure).\n\nThe argument object maps node selectors to [highlighting\ntags](#highlight.Tag) or arrays of tags.\n\nNode selectors may hold one or more (space-separated) node paths.\nSuch a path can be a [node name](#common.NodeType.name), or\nmultiple node names (or `*` wildcards) separated by slash\ncharacters, as in `\"Block/Declaration/VariableName\"`. Such a path\nmatches the final node but only if its direct parent nodes are the\nother nodes mentioned. A `*` in such a path matches any parent,\nbut only a single level—wildcards that match multiple parents\naren't supported, both for efficiency reasons and because Lezer\ntrees make it rather hard to reason about what they would match.)\n\nA path can be ended with `/...` to indicate that the tag assigned\nto the node should also apply to all child nodes, even if they\nmatch their own style (by default, only the innermost style is\nused).\n\nWhen a path ends in `!`, as in `Attribute!`, no further matching\nhappens for the node's child nodes, and the entire node gets the\ngiven style.\n\nIn this notation, node names that contain `/`, `!`, `*`, or `...`\nmust be quoted as JSON strings.\n\nFor example:\n\n```javascript\nparser.withProps(\n styleTags({\n // Style Number and BigNumber nodes\n \"Number BigNumber\": tags.number,\n // Style Escape nodes whose parent is String\n \"String/Escape\": tags.escape,\n // Style anything inside Attributes nodes\n \"Attributes!\": tags.meta,\n // Add a style to all content inside Italic nodes\n \"Italic/...\": tags.emphasis,\n // Style InvalidString nodes as both `string` and `invalid`\n \"InvalidString\": [tags.string, tags.invalid],\n // Style the node named \"/\" as punctuation\n '\"/\"': tags.punctuation\n })\n)\n```\n*/\nfunction styleTags(spec) {\n let byName = Object.create(null);\n for (let prop in spec) {\n let tags = spec[prop];\n if (!Array.isArray(tags))\n tags = [tags];\n for (let part of prop.split(\" \"))\n if (part) {\n let pieces = [], mode = 2 /* Mode.Normal */, rest = part;\n for (let pos = 0;;) {\n if (rest == \"...\" && pos > 0 && pos + 3 == part.length) {\n mode = 1 /* Mode.Inherit */;\n break;\n }\n let m = /^\"(?:[^\"\\\\]|\\\\.)*?\"|[^\\/!]+/.exec(rest);\n if (!m)\n throw new RangeError(\"Invalid path: \" + part);\n pieces.push(m[0] == \"*\" ? \"\" : m[0][0] == '\"' ? JSON.parse(m[0]) : m[0]);\n pos += m[0].length;\n if (pos == part.length)\n break;\n let next = part[pos++];\n if (pos == part.length && next == \"!\") {\n mode = 0 /* Mode.Opaque */;\n break;\n }\n if (next != \"/\")\n throw new RangeError(\"Invalid path: \" + part);\n rest = part.slice(pos);\n }\n let last = pieces.length - 1, inner = pieces[last];\n if (!inner)\n throw new RangeError(\"Invalid path: \" + part);\n let rule = new Rule(tags, mode, last > 0 ? pieces.slice(0, last) : null);\n byName[inner] = rule.sort(byName[inner]);\n }\n }\n return ruleNodeProp.add(byName);\n}\nconst ruleNodeProp = new NodeProp();\nclass Rule {\n constructor(tags, mode, context, next) {\n this.tags = tags;\n this.mode = mode;\n this.context = context;\n this.next = next;\n }\n get opaque() { return this.mode == 0 /* Mode.Opaque */; }\n get inherit() { return this.mode == 1 /* Mode.Inherit */; }\n sort(other) {\n if (!other || other.depth < this.depth) {\n this.next = other;\n return this;\n }\n other.next = this.sort(other.next);\n return other;\n }\n get depth() { return this.context ? this.context.length : 0; }\n}\nRule.empty = new Rule([], 2 /* Mode.Normal */, null);\n/**\nDefine a [highlighter](#highlight.Highlighter) from an array of\ntag/class pairs. Classes associated with more specific tags will\ntake precedence.\n*/\nfunction tagHighlighter(tags, options) {\n let map = Object.create(null);\n for (let style of tags) {\n if (!Array.isArray(style.tag))\n map[style.tag.id] = style.class;\n else\n for (let tag of style.tag)\n map[tag.id] = style.class;\n }\n let { scope, all = null } = options || {};\n return {\n style: (tags) => {\n let cls = all;\n for (let tag of tags) {\n for (let sub of tag.set) {\n let tagClass = map[sub.id];\n if (tagClass) {\n cls = cls ? cls + \" \" + tagClass : tagClass;\n break;\n }\n }\n }\n return cls;\n },\n scope\n };\n}\nfunction highlightTags(highlighters, tags) {\n let result = null;\n for (let highlighter of highlighters) {\n let value = highlighter.style(tags);\n if (value)\n result = result ? result + \" \" + value : value;\n }\n return result;\n}\n/**\nHighlight the given [tree](#common.Tree) with the given\n[highlighter](#highlight.Highlighter). Often, the higher-level\n[`highlightCode`](#highlight.highlightCode) function is easier to\nuse.\n*/\nfunction highlightTree(tree, highlighter, \n/**\nAssign styling to a region of the text. Will be called, in order\nof position, for any ranges where more than zero classes apply.\n`classes` is a space separated string of CSS classes.\n*/\nputStyle, \n/**\nThe start of the range to highlight.\n*/\nfrom = 0, \n/**\nThe end of the range.\n*/\nto = tree.length) {\n let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle);\n builder.highlightRange(tree.cursor(), from, to, \"\", builder.highlighters);\n builder.flush(to);\n}\n/**\nHighlight the given tree with the given highlighter, calling\n`putText` for every piece of text, either with a set of classes or\nwith the empty string when unstyled, and `putBreak` for every line\nbreak.\n*/\nfunction highlightCode(code, tree, highlighter, putText, putBreak, from = 0, to = code.length) {\n let pos = from;\n function writeTo(p, classes) {\n if (p <= pos)\n return;\n for (let text = code.slice(pos, p), i = 0;;) {\n let nextBreak = text.indexOf(\"\\n\", i);\n let upto = nextBreak < 0 ? text.length : nextBreak;\n if (upto > i)\n putText(text.slice(i, upto), classes);\n if (nextBreak < 0)\n break;\n putBreak();\n i = nextBreak + 1;\n }\n pos = p;\n }\n highlightTree(tree, highlighter, (from, to, classes) => {\n writeTo(from, \"\");\n writeTo(to, classes);\n }, from, to);\n writeTo(to, \"\");\n}\nclass HighlightBuilder {\n constructor(at, highlighters, span) {\n this.at = at;\n this.highlighters = highlighters;\n this.span = span;\n this.class = \"\";\n }\n startSpan(at, cls) {\n if (cls != this.class) {\n this.flush(at);\n if (at > this.at)\n this.at = at;\n this.class = cls;\n }\n }\n flush(to) {\n if (to > this.at && this.class)\n this.span(this.at, to, this.class);\n }\n highlightRange(cursor, from, to, inheritedClass, highlighters) {\n let { type, from: start, to: end } = cursor;\n if (start >= to || end <= from)\n return;\n if (type.isTop)\n highlighters = this.highlighters.filter(h => !h.scope || h.scope(type));\n let cls = inheritedClass;\n let rule = getStyleTags(cursor) || Rule.empty;\n let tagCls = highlightTags(highlighters, rule.tags);\n if (tagCls) {\n if (cls)\n cls += \" \";\n cls += tagCls;\n if (rule.mode == 1 /* Mode.Inherit */)\n inheritedClass += (inheritedClass ? \" \" : \"\") + tagCls;\n }\n this.startSpan(Math.max(from, start), cls);\n if (rule.opaque)\n return;\n let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted);\n if (mounted && mounted.overlay) {\n let inner = cursor.node.enter(mounted.overlay[0].from + start, 1);\n let innerHighlighters = this.highlighters.filter(h => !h.scope || h.scope(mounted.tree.type));\n let hasChild = cursor.firstChild();\n for (let i = 0, pos = start;; i++) {\n let next = i < mounted.overlay.length ? mounted.overlay[i] : null;\n let nextPos = next ? next.from + start : end;\n let rangeFrom = Math.max(from, pos), rangeTo = Math.min(to, nextPos);\n if (rangeFrom < rangeTo && hasChild) {\n while (cursor.from < rangeTo) {\n this.highlightRange(cursor, rangeFrom, rangeTo, inheritedClass, highlighters);\n this.startSpan(Math.min(rangeTo, cursor.to), cls);\n if (cursor.to >= nextPos || !cursor.nextSibling())\n break;\n }\n }\n if (!next || nextPos > to)\n break;\n pos = next.to + start;\n if (pos > from) {\n this.highlightRange(inner.cursor(), Math.max(from, next.from + start), Math.min(to, pos), \"\", innerHighlighters);\n this.startSpan(Math.min(to, pos), cls);\n }\n }\n if (hasChild)\n cursor.parent();\n }\n else if (cursor.firstChild()) {\n if (mounted)\n inheritedClass = \"\";\n do {\n if (cursor.to <= from)\n continue;\n if (cursor.from >= to)\n break;\n this.highlightRange(cursor, from, to, inheritedClass, highlighters);\n this.startSpan(Math.min(to, cursor.to), cls);\n } while (cursor.nextSibling());\n cursor.parent();\n }\n }\n}\n/**\nMatch a syntax node's [highlight rules](#highlight.styleTags). If\nthere's a match, return its set of tags, and whether it is\nopaque (uses a `!`) or applies to all child nodes (`/...`).\n*/\nfunction getStyleTags(node) {\n let rule = node.type.prop(ruleNodeProp);\n while (rule && rule.context && !node.matchContext(rule.context))\n rule = rule.next;\n return rule || null;\n}\nconst t = Tag.define;\nconst comment = t(), name = t(), typeName = t(name), propertyName = t(name), literal = t(), string = t(literal), number = t(literal), content = t(), heading = t(content), keyword = t(), operator = t(), punctuation = t(), bracket = t(punctuation), meta = t();\n/**\nThe default set of highlighting [tags](#highlight.Tag).\n\nThis collection is heavily biased towards programming languages,\nand necessarily incomplete. A full ontology of syntactic\nconstructs would fill a stack of books, and be impractical to\nwrite themes for. So try to make do with this set. If all else\nfails, [open an\nissue](https://github.com/codemirror/codemirror.next) to propose a\nnew tag, or [define](#highlight.Tag^define) a local custom tag for\nyour use case.\n\nNote that it is not obligatory to always attach the most specific\ntag possible to an element—if your grammar can't easily\ndistinguish a certain type of element (such as a local variable),\nit is okay to style it as its more general variant (a variable).\n\nFor tags that extend some parent tag, the documentation links to\nthe parent.\n*/\nconst tags = {\n /**\n A comment.\n */\n comment,\n /**\n A line [comment](#highlight.tags.comment).\n */\n lineComment: t(comment),\n /**\n A block [comment](#highlight.tags.comment).\n */\n blockComment: t(comment),\n /**\n A documentation [comment](#highlight.tags.comment).\n */\n docComment: t(comment),\n /**\n Any kind of identifier.\n */\n name,\n /**\n The [name](#highlight.tags.name) of a variable.\n */\n variableName: t(name),\n /**\n A type [name](#highlight.tags.name).\n */\n typeName: typeName,\n /**\n A tag name (subtag of [`typeName`](#highlight.tags.typeName)).\n */\n tagName: t(typeName),\n /**\n A property or field [name](#highlight.tags.name).\n */\n propertyName: propertyName,\n /**\n An attribute name (subtag of [`propertyName`](#highlight.tags.propertyName)).\n */\n attributeName: t(propertyName),\n /**\n The [name](#highlight.tags.name) of a class.\n */\n className: t(name),\n /**\n A label [name](#highlight.tags.name).\n */\n labelName: t(name),\n /**\n A namespace [name](#highlight.tags.name).\n */\n namespace: t(name),\n /**\n The [name](#highlight.tags.name) of a macro.\n */\n macroName: t(name),\n /**\n A literal value.\n */\n literal,\n /**\n A string [literal](#highlight.tags.literal).\n */\n string,\n /**\n A documentation [string](#highlight.tags.string).\n */\n docString: t(string),\n /**\n A character literal (subtag of [string](#highlight.tags.string)).\n */\n character: t(string),\n /**\n An attribute value (subtag of [string](#highlight.tags.string)).\n */\n attributeValue: t(string),\n /**\n A number [literal](#highlight.tags.literal).\n */\n number,\n /**\n An integer [number](#highlight.tags.number) literal.\n */\n integer: t(number),\n /**\n A floating-point [number](#highlight.tags.number) literal.\n */\n float: t(number),\n /**\n A boolean [literal](#highlight.tags.literal).\n */\n bool: t(literal),\n /**\n Regular expression [literal](#highlight.tags.literal).\n */\n regexp: t(literal),\n /**\n An escape [literal](#highlight.tags.literal), for example a\n backslash escape in a string.\n */\n escape: t(literal),\n /**\n A color [literal](#highlight.tags.literal).\n */\n color: t(literal),\n /**\n A URL [literal](#highlight.tags.literal).\n */\n url: t(literal),\n /**\n A language keyword.\n */\n keyword,\n /**\n The [keyword](#highlight.tags.keyword) for the self or this\n object.\n */\n self: t(keyword),\n /**\n The [keyword](#highlight.tags.keyword) for null.\n */\n null: t(keyword),\n /**\n A [keyword](#highlight.tags.keyword) denoting some atomic value.\n */\n atom: t(keyword),\n /**\n A [keyword](#highlight.tags.keyword) that represents a unit.\n */\n unit: t(keyword),\n /**\n A modifier [keyword](#highlight.tags.keyword).\n */\n modifier: t(keyword),\n /**\n A [keyword](#highlight.tags.keyword) that acts as an operator.\n */\n operatorKeyword: t(keyword),\n /**\n A control-flow related [keyword](#highlight.tags.keyword).\n */\n controlKeyword: t(keyword),\n /**\n A [keyword](#highlight.tags.keyword) that defines something.\n */\n definitionKeyword: t(keyword),\n /**\n A [keyword](#highlight.tags.keyword) related to defining or\n interfacing with modules.\n */\n moduleKeyword: t(keyword),\n /**\n An operator.\n */\n operator,\n /**\n An [operator](#highlight.tags.operator) that dereferences something.\n */\n derefOperator: t(operator),\n /**\n Arithmetic-related [operator](#highlight.tags.operator).\n */\n arithmeticOperator: t(operator),\n /**\n Logical [operator](#highlight.tags.operator).\n */\n logicOperator: t(operator),\n /**\n Bit [operator](#highlight.tags.operator).\n */\n bitwiseOperator: t(operator),\n /**\n Comparison [operator](#highlight.tags.operator).\n */\n compareOperator: t(operator),\n /**\n [Operator](#highlight.tags.operator) that updates its operand.\n */\n updateOperator: t(operator),\n /**\n [Operator](#highlight.tags.operator) that defines something.\n */\n definitionOperator: t(operator),\n /**\n Type-related [operator](#highlight.tags.operator).\n */\n typeOperator: t(operator),\n /**\n Control-flow [operator](#highlight.tags.operator).\n */\n controlOperator: t(operator),\n /**\n Program or markup punctuation.\n */\n punctuation,\n /**\n [Punctuation](#highlight.tags.punctuation) that separates\n things.\n */\n separator: t(punctuation),\n /**\n Bracket-style [punctuation](#highlight.tags.punctuation).\n */\n bracket,\n /**\n Angle [brackets](#highlight.tags.bracket) (usually `<` and `>`\n tokens).\n */\n angleBracket: t(bracket),\n /**\n Square [brackets](#highlight.tags.bracket) (usually `[` and `]`\n tokens).\n */\n squareBracket: t(bracket),\n /**\n Parentheses (usually `(` and `)` tokens). Subtag of\n [bracket](#highlight.tags.bracket).\n */\n paren: t(bracket),\n /**\n Braces (usually `{` and `}` tokens). Subtag of\n [bracket](#highlight.tags.bracket).\n */\n brace: t(bracket),\n /**\n Content, for example plain text in XML or markup documents.\n */\n content,\n /**\n [Content](#highlight.tags.content) that represents a heading.\n */\n heading,\n /**\n A level 1 [heading](#highlight.tags.heading).\n */\n heading1: t(heading),\n /**\n A level 2 [heading](#highlight.tags.heading).\n */\n heading2: t(heading),\n /**\n A level 3 [heading](#highlight.tags.heading).\n */\n heading3: t(heading),\n /**\n A level 4 [heading](#highlight.tags.heading).\n */\n heading4: t(heading),\n /**\n A level 5 [heading](#highlight.tags.heading).\n */\n heading5: t(heading),\n /**\n A level 6 [heading](#highlight.tags.heading).\n */\n heading6: t(heading),\n /**\n A prose separator (such as a horizontal rule).\n */\n contentSeparator: t(content),\n /**\n [Content](#highlight.tags.content) that represents a list.\n */\n list: t(content),\n /**\n [Content](#highlight.tags.content) that represents a quote.\n */\n quote: t(content),\n /**\n [Content](#highlight.tags.content) that is emphasized.\n */\n emphasis: t(content),\n /**\n [Content](#highlight.tags.content) that is styled strong.\n */\n strong: t(content),\n /**\n [Content](#highlight.tags.content) that is part of a link.\n */\n link: t(content),\n /**\n [Content](#highlight.tags.content) that is styled as code or\n monospace.\n */\n monospace: t(content),\n /**\n [Content](#highlight.tags.content) that has a strike-through\n style.\n */\n strikethrough: t(content),\n /**\n Inserted text in a change-tracking format.\n */\n inserted: t(),\n /**\n Deleted text.\n */\n deleted: t(),\n /**\n Changed text.\n */\n changed: t(),\n /**\n An invalid or unsyntactic element.\n */\n invalid: t(),\n /**\n Metadata or meta-instruction.\n */\n meta,\n /**\n [Metadata](#highlight.tags.meta) that applies to the entire\n document.\n */\n documentMeta: t(meta),\n /**\n [Metadata](#highlight.tags.meta) that annotates or adds\n attributes to a given syntactic element.\n */\n annotation: t(meta),\n /**\n Processing instruction or preprocessor directive. Subtag of\n [meta](#highlight.tags.meta).\n */\n processingInstruction: t(meta),\n /**\n [Modifier](#highlight.Tag^defineModifier) that indicates that a\n given element is being defined. Expected to be used with the\n various [name](#highlight.tags.name) tags.\n */\n definition: Tag.defineModifier(),\n /**\n [Modifier](#highlight.Tag^defineModifier) that indicates that\n something is constant. Mostly expected to be used with\n [variable names](#highlight.tags.variableName).\n */\n constant: Tag.defineModifier(),\n /**\n [Modifier](#highlight.Tag^defineModifier) used to indicate that\n a [variable](#highlight.tags.variableName) or [property\n name](#highlight.tags.propertyName) is being called or defined\n as a function.\n */\n function: Tag.defineModifier(),\n /**\n [Modifier](#highlight.Tag^defineModifier) that can be applied to\n [names](#highlight.tags.name) to indicate that they belong to\n the language's standard environment.\n */\n standard: Tag.defineModifier(),\n /**\n [Modifier](#highlight.Tag^defineModifier) that indicates a given\n [names](#highlight.tags.name) is local to some scope.\n */\n local: Tag.defineModifier(),\n /**\n A generic variant [modifier](#highlight.Tag^defineModifier) that\n can be used to tag language-specific alternative variants of\n some common tag. It is recommended for themes to define special\n forms of at least the [string](#highlight.tags.string) and\n [variable name](#highlight.tags.variableName) tags, since those\n come up a lot.\n */\n special: Tag.defineModifier()\n};\n/**\nThis is a highlighter that adds stable, predictable classes to\ntokens, for styling with external CSS.\n\nThe following tags are mapped to their name prefixed with `\"tok-\"`\n(for example `\"tok-comment\"`):\n\n* [`link`](#highlight.tags.link)\n* [`heading`](#highlight.tags.heading)\n* [`emphasis`](#highlight.tags.emphasis)\n* [`strong`](#highlight.tags.strong)\n* [`keyword`](#highlight.tags.keyword)\n* [`atom`](#highlight.tags.atom)\n* [`bool`](#highlight.tags.bool)\n* [`url`](#highlight.tags.url)\n* [`labelName`](#highlight.tags.labelName)\n* [`inserted`](#highlight.tags.inserted)\n* [`deleted`](#highlight.tags.deleted)\n* [`literal`](#highlight.tags.literal)\n* [`string`](#highlight.tags.string)\n* [`number`](#highlight.tags.number)\n* [`variableName`](#highlight.tags.variableName)\n* [`typeName`](#highlight.tags.typeName)\n* [`namespace`](#highlight.tags.namespace)\n* [`className`](#highlight.tags.className)\n* [`macroName`](#highlight.tags.macroName)\n* [`propertyName`](#highlight.tags.propertyName)\n* [`operator`](#highlight.tags.operator)\n* [`comment`](#highlight.tags.comment)\n* [`meta`](#highlight.tags.meta)\n* [`punctuation`](#highlight.tags.punctuation)\n* [`invalid`](#highlight.tags.invalid)\n\nIn addition, these mappings are provided:\n\n* [`regexp`](#highlight.tags.regexp),\n [`escape`](#highlight.tags.escape), and\n [`special`](#highlight.tags.special)[`(string)`](#highlight.tags.string)\n are mapped to `\"tok-string2\"`\n* [`special`](#highlight.tags.special)[`(variableName)`](#highlight.tags.variableName)\n to `\"tok-variableName2\"`\n* [`local`](#highlight.tags.local)[`(variableName)`](#highlight.tags.variableName)\n to `\"tok-variableName tok-local\"`\n* [`definition`](#highlight.tags.definition)[`(variableName)`](#highlight.tags.variableName)\n to `\"tok-variableName tok-definition\"`\n* [`definition`](#highlight.tags.definition)[`(propertyName)`](#highlight.tags.propertyName)\n to `\"tok-propertyName tok-definition\"`\n*/\nconst classHighlighter = tagHighlighter([\n { tag: tags.link, class: \"tok-link\" },\n { tag: tags.heading, class: \"tok-heading\" },\n { tag: tags.emphasis, class: \"tok-emphasis\" },\n { tag: tags.strong, class: \"tok-strong\" },\n { tag: tags.keyword, class: \"tok-keyword\" },\n { tag: tags.atom, class: \"tok-atom\" },\n { tag: tags.bool, class: \"tok-bool\" },\n { tag: tags.url, class: \"tok-url\" },\n { tag: tags.labelName, class: \"tok-labelName\" },\n { tag: tags.inserted, class: \"tok-inserted\" },\n { tag: tags.deleted, class: \"tok-deleted\" },\n { tag: tags.literal, class: \"tok-literal\" },\n { tag: tags.string, class: \"tok-string\" },\n { tag: tags.number, class: \"tok-number\" },\n { tag: [tags.regexp, tags.escape, tags.special(tags.string)], class: \"tok-string2\" },\n { tag: tags.variableName, class: \"tok-variableName\" },\n { tag: tags.local(tags.variableName), class: \"tok-variableName tok-local\" },\n { tag: tags.definition(tags.variableName), class: \"tok-variableName tok-definition\" },\n { tag: tags.special(tags.variableName), class: \"tok-variableName2\" },\n { tag: tags.definition(tags.propertyName), class: \"tok-propertyName tok-definition\" },\n { tag: tags.typeName, class: \"tok-typeName\" },\n { tag: tags.namespace, class: \"tok-namespace\" },\n { tag: tags.className, class: \"tok-className\" },\n { tag: tags.macroName, class: \"tok-macroName\" },\n { tag: tags.propertyName, class: \"tok-propertyName\" },\n { tag: tags.operator, class: \"tok-operator\" },\n { tag: tags.comment, class: \"tok-comment\" },\n { tag: tags.meta, class: \"tok-meta\" },\n { tag: tags.invalid, class: \"tok-invalid\" },\n { tag: tags.punctuation, class: \"tok-punctuation\" }\n]);\n\nexport { Tag, classHighlighter, getStyleTags, highlightCode, highlightTree, styleTags, tagHighlighter, tags };\n","import { Parser, NodeProp, NodeSet, NodeType, DefaultBufferLength, Tree, IterMode } from '@lezer/common';\n\n/**\nA parse stack. These are used internally by the parser to track\nparsing progress. They also provide some properties and methods\nthat external code such as a tokenizer can use to get information\nabout the parse state.\n*/\nclass Stack {\n /**\n @internal\n */\n constructor(\n /**\n The parse that this stack is part of @internal\n */\n p, \n /**\n Holds state, input pos, buffer index triplets for all but the\n top state @internal\n */\n stack, \n /**\n The current parse state @internal\n */\n state, \n // The position at which the next reduce should take place. This\n // can be less than `this.pos` when skipped expressions have been\n // added to the stack (which should be moved outside of the next\n // reduction)\n /**\n @internal\n */\n reducePos, \n /**\n The input position up to which this stack has parsed.\n */\n pos, \n /**\n The dynamic score of the stack, including dynamic precedence\n and error-recovery penalties\n @internal\n */\n score, \n // The output buffer. Holds (type, start, end, size) quads\n // representing nodes created by the parser, where `size` is\n // amount of buffer array entries covered by this node.\n /**\n @internal\n */\n buffer, \n // The base offset of the buffer. When stacks are split, the split\n // instance shared the buffer history with its parent up to\n // `bufferBase`, which is the absolute offset (including the\n // offset of previous splits) into the buffer at which this stack\n // starts writing.\n /**\n @internal\n */\n bufferBase, \n /**\n @internal\n */\n curContext, \n /**\n @internal\n */\n lookAhead = 0, \n // A parent stack from which this was split off, if any. This is\n // set up so that it always points to a stack that has some\n // additional buffer content, never to a stack with an equal\n // `bufferBase`.\n /**\n @internal\n */\n parent) {\n this.p = p;\n this.stack = stack;\n this.state = state;\n this.reducePos = reducePos;\n this.pos = pos;\n this.score = score;\n this.buffer = buffer;\n this.bufferBase = bufferBase;\n this.curContext = curContext;\n this.lookAhead = lookAhead;\n this.parent = parent;\n }\n /**\n @internal\n */\n toString() {\n return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? \"!\" + this.score : \"\"}`;\n }\n // Start an empty stack\n /**\n @internal\n */\n static start(p, state, pos = 0) {\n let cx = p.parser.context;\n return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null);\n }\n /**\n The stack's current [context](#lr.ContextTracker) value, if\n any. Its type will depend on the context tracker's type\n parameter, or it will be `null` if there is no context\n tracker.\n */\n get context() { return this.curContext ? this.curContext.context : null; }\n // Push a state onto the stack, tracking its start position as well\n // as the buffer base at that point.\n /**\n @internal\n */\n pushState(state, start) {\n this.stack.push(this.state, start, this.bufferBase + this.buffer.length);\n this.state = state;\n }\n // Apply a reduce action\n /**\n @internal\n */\n reduce(action) {\n var _a;\n let depth = action >> 19 /* Action.ReduceDepthShift */, type = action & 65535 /* Action.ValueMask */;\n let { parser } = this.p;\n let dPrec = parser.dynamicPrecedence(type);\n if (dPrec)\n this.score += dPrec;\n if (depth == 0) {\n this.pushState(parser.getGoto(this.state, type, true), this.reducePos);\n // Zero-depth reductions are a special case—they add stuff to\n // the stack without popping anything off.\n if (type < parser.minRepeatTerm)\n this.storeNode(type, this.reducePos, this.reducePos, 4, true);\n this.reduceContext(type, this.reducePos);\n return;\n }\n // Find the base index into `this.stack`, content after which will\n // be dropped. Note that with `StayFlag` reductions we need to\n // consume two extra frames (the dummy parent node for the skipped\n // expression and the state that we'll be staying in, which should\n // be moved to `this.state`).\n let base = this.stack.length - ((depth - 1) * 3) - (action & 262144 /* Action.StayFlag */ ? 6 : 0);\n let start = base ? this.stack[base - 2] : this.p.ranges[0].from, size = this.reducePos - start;\n // This is a kludge to try and detect overly deep left-associative\n // trees, which will not increase the parse stack depth and thus\n // won't be caught by the regular stack-depth limit check.\n if (size >= 2000 /* Recover.MinBigReduction */ && !((_a = this.p.parser.nodeSet.types[type]) === null || _a === void 0 ? void 0 : _a.isAnonymous)) {\n if (start == this.p.lastBigReductionStart) {\n this.p.bigReductionCount++;\n this.p.lastBigReductionSize = size;\n }\n else if (this.p.lastBigReductionSize < size) {\n this.p.bigReductionCount = 1;\n this.p.lastBigReductionStart = start;\n this.p.lastBigReductionSize = size;\n }\n }\n let bufferBase = base ? this.stack[base - 1] : 0, count = this.bufferBase + this.buffer.length - bufferBase;\n // Store normal terms or `R -> R R` repeat reductions\n if (type < parser.minRepeatTerm || (action & 131072 /* Action.RepeatFlag */)) {\n let pos = parser.stateFlag(this.state, 1 /* StateFlag.Skipped */) ? this.pos : this.reducePos;\n this.storeNode(type, start, pos, count + 4, true);\n }\n if (action & 262144 /* Action.StayFlag */) {\n this.state = this.stack[base];\n }\n else {\n let baseStateID = this.stack[base - 3];\n this.state = parser.getGoto(baseStateID, type, true);\n }\n while (this.stack.length > base)\n this.stack.pop();\n this.reduceContext(type, start);\n }\n // Shift a value into the buffer\n /**\n @internal\n */\n storeNode(term, start, end, size = 4, isReduce = false) {\n if (term == 0 /* Term.Err */ &&\n (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) {\n // Try to omit/merge adjacent error nodes\n let cur = this, top = this.buffer.length;\n if (top == 0 && cur.parent) {\n top = cur.bufferBase - cur.parent.bufferBase;\n cur = cur.parent;\n }\n if (top > 0 && cur.buffer[top - 4] == 0 /* Term.Err */ && cur.buffer[top - 1] > -1) {\n if (start == end)\n return;\n if (cur.buffer[top - 2] >= start) {\n cur.buffer[top - 2] = end;\n return;\n }\n }\n }\n if (!isReduce || this.pos == end) { // Simple case, just append\n this.buffer.push(term, start, end, size);\n }\n else { // There may be skipped nodes that have to be moved forward\n let index = this.buffer.length;\n if (index > 0 && this.buffer[index - 4] != 0 /* Term.Err */)\n while (index > 0 && this.buffer[index - 2] > end) {\n // Move this record forward\n this.buffer[index] = this.buffer[index - 4];\n this.buffer[index + 1] = this.buffer[index - 3];\n this.buffer[index + 2] = this.buffer[index - 2];\n this.buffer[index + 3] = this.buffer[index - 1];\n index -= 4;\n if (size > 4)\n size -= 4;\n }\n this.buffer[index] = term;\n this.buffer[index + 1] = start;\n this.buffer[index + 2] = end;\n this.buffer[index + 3] = size;\n }\n }\n // Apply a shift action\n /**\n @internal\n */\n shift(action, type, start, end) {\n if (action & 131072 /* Action.GotoFlag */) {\n this.pushState(action & 65535 /* Action.ValueMask */, this.pos);\n }\n else if ((action & 262144 /* Action.StayFlag */) == 0) { // Regular shift\n let nextState = action, { parser } = this.p;\n if (end > this.pos || type <= parser.maxNode) {\n this.pos = end;\n if (!parser.stateFlag(nextState, 1 /* StateFlag.Skipped */))\n this.reducePos = end;\n }\n this.pushState(nextState, start);\n this.shiftContext(type, start);\n if (type <= parser.maxNode)\n this.buffer.push(type, start, end, 4);\n }\n else { // Shift-and-stay, which means this is a skipped token\n this.pos = end;\n this.shiftContext(type, start);\n if (type <= this.p.parser.maxNode)\n this.buffer.push(type, start, end, 4);\n }\n }\n // Apply an action\n /**\n @internal\n */\n apply(action, next, nextStart, nextEnd) {\n if (action & 65536 /* Action.ReduceFlag */)\n this.reduce(action);\n else\n this.shift(action, next, nextStart, nextEnd);\n }\n // Add a prebuilt (reused) node into the buffer.\n /**\n @internal\n */\n useNode(value, next) {\n let index = this.p.reused.length - 1;\n if (index < 0 || this.p.reused[index] != value) {\n this.p.reused.push(value);\n index++;\n }\n let start = this.pos;\n this.reducePos = this.pos = start + value.length;\n this.pushState(next, start);\n this.buffer.push(index, start, this.reducePos, -1 /* size == -1 means this is a reused value */);\n if (this.curContext)\n this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length)));\n }\n // Split the stack. Due to the buffer sharing and the fact\n // that `this.stack` tends to stay quite shallow, this isn't very\n // expensive.\n /**\n @internal\n */\n split() {\n let parent = this;\n let off = parent.buffer.length;\n // Because the top of the buffer (after this.pos) may be mutated\n // to reorder reductions and skipped tokens, and shared buffers\n // should be immutable, this copies any outstanding skipped tokens\n // to the new buffer, and puts the base pointer before them.\n while (off > 0 && parent.buffer[off - 2] > parent.reducePos)\n off -= 4;\n let buffer = parent.buffer.slice(off), base = parent.bufferBase + off;\n // Make sure parent points to an actual parent with content, if there is such a parent.\n while (parent && base == parent.bufferBase)\n parent = parent.parent;\n return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent);\n }\n // Try to recover from an error by 'deleting' (ignoring) one token.\n /**\n @internal\n */\n recoverByDelete(next, nextEnd) {\n let isNode = next <= this.p.parser.maxNode;\n if (isNode)\n this.storeNode(next, this.pos, nextEnd, 4);\n this.storeNode(0 /* Term.Err */, this.pos, nextEnd, isNode ? 8 : 4);\n this.pos = this.reducePos = nextEnd;\n this.score -= 190 /* Recover.Delete */;\n }\n /**\n Check if the given term would be able to be shifted (optionally\n after some reductions) on this stack. This can be useful for\n external tokenizers that want to make sure they only provide a\n given token when it applies.\n */\n canShift(term) {\n for (let sim = new SimulatedStack(this);;) {\n let action = this.p.parser.stateSlot(sim.state, 4 /* ParseState.DefaultReduce */) || this.p.parser.hasAction(sim.state, term);\n if (action == 0)\n return false;\n if ((action & 65536 /* Action.ReduceFlag */) == 0)\n return true;\n sim.reduce(action);\n }\n }\n // Apply up to Recover.MaxNext recovery actions that conceptually\n // inserts some missing token or rule.\n /**\n @internal\n */\n recoverByInsert(next) {\n if (this.stack.length >= 300 /* Recover.MaxInsertStackDepth */)\n return [];\n let nextStates = this.p.parser.nextStates(this.state);\n if (nextStates.length > 4 /* Recover.MaxNext */ << 1 || this.stack.length >= 120 /* Recover.DampenInsertStackDepth */) {\n let best = [];\n for (let i = 0, s; i < nextStates.length; i += 2) {\n if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next))\n best.push(nextStates[i], s);\n }\n if (this.stack.length < 120 /* Recover.DampenInsertStackDepth */)\n for (let i = 0; best.length < 4 /* Recover.MaxNext */ << 1 && i < nextStates.length; i += 2) {\n let s = nextStates[i + 1];\n if (!best.some((v, i) => (i & 1) && v == s))\n best.push(nextStates[i], s);\n }\n nextStates = best;\n }\n let result = [];\n for (let i = 0; i < nextStates.length && result.length < 4 /* Recover.MaxNext */; i += 2) {\n let s = nextStates[i + 1];\n if (s == this.state)\n continue;\n let stack = this.split();\n stack.pushState(s, this.pos);\n stack.storeNode(0 /* Term.Err */, stack.pos, stack.pos, 4, true);\n stack.shiftContext(nextStates[i], this.pos);\n stack.reducePos = this.pos;\n stack.score -= 200 /* Recover.Insert */;\n result.push(stack);\n }\n return result;\n }\n // Force a reduce, if possible. Return false if that can't\n // be done.\n /**\n @internal\n */\n forceReduce() {\n let { parser } = this.p;\n let reduce = parser.stateSlot(this.state, 5 /* ParseState.ForcedReduce */);\n if ((reduce & 65536 /* Action.ReduceFlag */) == 0)\n return false;\n if (!parser.validAction(this.state, reduce)) {\n let depth = reduce >> 19 /* Action.ReduceDepthShift */, term = reduce & 65535 /* Action.ValueMask */;\n let target = this.stack.length - depth * 3;\n if (target < 0 || parser.getGoto(this.stack[target], term, false) < 0) {\n let backup = this.findForcedReduction();\n if (backup == null)\n return false;\n reduce = backup;\n }\n this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);\n this.score -= 100 /* Recover.Reduce */;\n }\n this.reducePos = this.pos;\n this.reduce(reduce);\n return true;\n }\n /**\n Try to scan through the automaton to find some kind of reduction\n that can be applied. Used when the regular ForcedReduce field\n isn't a valid action. @internal\n */\n findForcedReduction() {\n let { parser } = this.p, seen = [];\n let explore = (state, depth) => {\n if (seen.includes(state))\n return;\n seen.push(state);\n return parser.allActions(state, (action) => {\n if (action & (262144 /* Action.StayFlag */ | 131072 /* Action.GotoFlag */)) ;\n else if (action & 65536 /* Action.ReduceFlag */) {\n let rDepth = (action >> 19 /* Action.ReduceDepthShift */) - depth;\n if (rDepth > 1) {\n let term = action & 65535 /* Action.ValueMask */, target = this.stack.length - rDepth * 3;\n if (target >= 0 && parser.getGoto(this.stack[target], term, false) >= 0)\n return (rDepth << 19 /* Action.ReduceDepthShift */) | 65536 /* Action.ReduceFlag */ | term;\n }\n }\n else {\n let found = explore(action, depth + 1);\n if (found != null)\n return found;\n }\n });\n };\n return explore(this.state, 0);\n }\n /**\n @internal\n */\n forceAll() {\n while (!this.p.parser.stateFlag(this.state, 2 /* StateFlag.Accepting */)) {\n if (!this.forceReduce()) {\n this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);\n break;\n }\n }\n return this;\n }\n /**\n Check whether this state has no further actions (assumed to be a direct descendant of the\n top state, since any other states must be able to continue\n somehow). @internal\n */\n get deadEnd() {\n if (this.stack.length != 3)\n return false;\n let { parser } = this.p;\n return parser.data[parser.stateSlot(this.state, 1 /* ParseState.Actions */)] == 65535 /* Seq.End */ &&\n !parser.stateSlot(this.state, 4 /* ParseState.DefaultReduce */);\n }\n /**\n Restart the stack (put it back in its start state). Only safe\n when this.stack.length == 3 (state is directly below the top\n state). @internal\n */\n restart() {\n this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);\n this.state = this.stack[0];\n this.stack.length = 0;\n }\n /**\n @internal\n */\n sameState(other) {\n if (this.state != other.state || this.stack.length != other.stack.length)\n return false;\n for (let i = 0; i < this.stack.length; i += 3)\n if (this.stack[i] != other.stack[i])\n return false;\n return true;\n }\n /**\n Get the parser used by this stack.\n */\n get parser() { return this.p.parser; }\n /**\n Test whether a given dialect (by numeric ID, as exported from\n the terms file) is enabled.\n */\n dialectEnabled(dialectID) { return this.p.parser.dialect.flags[dialectID]; }\n shiftContext(term, start) {\n if (this.curContext)\n this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start)));\n }\n reduceContext(term, start) {\n if (this.curContext)\n this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start)));\n }\n /**\n @internal\n */\n emitContext() {\n let last = this.buffer.length - 1;\n if (last < 0 || this.buffer[last] != -3)\n this.buffer.push(this.curContext.hash, this.pos, this.pos, -3);\n }\n /**\n @internal\n */\n emitLookAhead() {\n let last = this.buffer.length - 1;\n if (last < 0 || this.buffer[last] != -4)\n this.buffer.push(this.lookAhead, this.pos, this.pos, -4);\n }\n updateContext(context) {\n if (context != this.curContext.context) {\n let newCx = new StackContext(this.curContext.tracker, context);\n if (newCx.hash != this.curContext.hash)\n this.emitContext();\n this.curContext = newCx;\n }\n }\n /**\n @internal\n */\n setLookAhead(lookAhead) {\n if (lookAhead > this.lookAhead) {\n this.emitLookAhead();\n this.lookAhead = lookAhead;\n }\n }\n /**\n @internal\n */\n close() {\n if (this.curContext && this.curContext.tracker.strict)\n this.emitContext();\n if (this.lookAhead > 0)\n this.emitLookAhead();\n }\n}\nclass StackContext {\n constructor(tracker, context) {\n this.tracker = tracker;\n this.context = context;\n this.hash = tracker.strict ? tracker.hash(context) : 0;\n }\n}\n// Used to cheaply run some reductions to scan ahead without mutating\n// an entire stack\nclass SimulatedStack {\n constructor(start) {\n this.start = start;\n this.state = start.state;\n this.stack = start.stack;\n this.base = this.stack.length;\n }\n reduce(action) {\n let term = action & 65535 /* Action.ValueMask */, depth = action >> 19 /* Action.ReduceDepthShift */;\n if (depth == 0) {\n if (this.stack == this.start.stack)\n this.stack = this.stack.slice();\n this.stack.push(this.state, 0, 0);\n this.base += 3;\n }\n else {\n this.base -= (depth - 1) * 3;\n }\n let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true);\n this.state = goto;\n }\n}\n// This is given to `Tree.build` to build a buffer, and encapsulates\n// the parent-stack-walking necessary to read the nodes.\nclass StackBufferCursor {\n constructor(stack, pos, index) {\n this.stack = stack;\n this.pos = pos;\n this.index = index;\n this.buffer = stack.buffer;\n if (this.index == 0)\n this.maybeNext();\n }\n static create(stack, pos = stack.bufferBase + stack.buffer.length) {\n return new StackBufferCursor(stack, pos, pos - stack.bufferBase);\n }\n maybeNext() {\n let next = this.stack.parent;\n if (next != null) {\n this.index = this.stack.bufferBase - next.bufferBase;\n this.stack = next;\n this.buffer = next.buffer;\n }\n }\n get id() { return this.buffer[this.index - 4]; }\n get start() { return this.buffer[this.index - 3]; }\n get end() { return this.buffer[this.index - 2]; }\n get size() { return this.buffer[this.index - 1]; }\n next() {\n this.index -= 4;\n this.pos -= 4;\n if (this.index == 0)\n this.maybeNext();\n }\n fork() {\n return new StackBufferCursor(this.stack, this.pos, this.index);\n }\n}\n\n// See lezer-generator/src/encode.ts for comments about the encoding\n// used here\nfunction decodeArray(input, Type = Uint16Array) {\n if (typeof input != \"string\")\n return input;\n let array = null;\n for (let pos = 0, out = 0; pos < input.length;) {\n let value = 0;\n for (;;) {\n let next = input.charCodeAt(pos++), stop = false;\n if (next == 126 /* Encode.BigValCode */) {\n value = 65535 /* Encode.BigVal */;\n break;\n }\n if (next >= 92 /* Encode.Gap2 */)\n next--;\n if (next >= 34 /* Encode.Gap1 */)\n next--;\n let digit = next - 32 /* Encode.Start */;\n if (digit >= 46 /* Encode.Base */) {\n digit -= 46 /* Encode.Base */;\n stop = true;\n }\n value += digit;\n if (stop)\n break;\n value *= 46 /* Encode.Base */;\n }\n if (array)\n array[out++] = value;\n else\n array = new Type(value);\n }\n return array;\n}\n\nclass CachedToken {\n constructor() {\n this.start = -1;\n this.value = -1;\n this.end = -1;\n this.extended = -1;\n this.lookAhead = 0;\n this.mask = 0;\n this.context = 0;\n }\n}\nconst nullToken = new CachedToken;\n/**\n[Tokenizers](#lr.ExternalTokenizer) interact with the input\nthrough this interface. It presents the input as a stream of\ncharacters, tracking lookahead and hiding the complexity of\n[ranges](#common.Parser.parse^ranges) from tokenizer code.\n*/\nclass InputStream {\n /**\n @internal\n */\n constructor(\n /**\n @internal\n */\n input, \n /**\n @internal\n */\n ranges) {\n this.input = input;\n this.ranges = ranges;\n /**\n @internal\n */\n this.chunk = \"\";\n /**\n @internal\n */\n this.chunkOff = 0;\n /**\n Backup chunk\n */\n this.chunk2 = \"\";\n this.chunk2Pos = 0;\n /**\n The character code of the next code unit in the input, or -1\n when the stream is at the end of the input.\n */\n this.next = -1;\n /**\n @internal\n */\n this.token = nullToken;\n this.rangeIndex = 0;\n this.pos = this.chunkPos = ranges[0].from;\n this.range = ranges[0];\n this.end = ranges[ranges.length - 1].to;\n this.readNext();\n }\n /**\n @internal\n */\n resolveOffset(offset, assoc) {\n let range = this.range, index = this.rangeIndex;\n let pos = this.pos + offset;\n while (pos < range.from) {\n if (!index)\n return null;\n let next = this.ranges[--index];\n pos -= range.from - next.to;\n range = next;\n }\n while (assoc < 0 ? pos > range.to : pos >= range.to) {\n if (index == this.ranges.length - 1)\n return null;\n let next = this.ranges[++index];\n pos += next.from - range.to;\n range = next;\n }\n return pos;\n }\n /**\n @internal\n */\n clipPos(pos) {\n if (pos >= this.range.from && pos < this.range.to)\n return pos;\n for (let range of this.ranges)\n if (range.to > pos)\n return Math.max(pos, range.from);\n return this.end;\n }\n /**\n Look at a code unit near the stream position. `.peek(0)` equals\n `.next`, `.peek(-1)` gives you the previous character, and so\n on.\n \n Note that looking around during tokenizing creates dependencies\n on potentially far-away content, which may reduce the\n effectiveness incremental parsing—when looking forward—or even\n cause invalid reparses when looking backward more than 25 code\n units, since the library does not track lookbehind.\n */\n peek(offset) {\n let idx = this.chunkOff + offset, pos, result;\n if (idx >= 0 && idx < this.chunk.length) {\n pos = this.pos + offset;\n result = this.chunk.charCodeAt(idx);\n }\n else {\n let resolved = this.resolveOffset(offset, 1);\n if (resolved == null)\n return -1;\n pos = resolved;\n if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) {\n result = this.chunk2.charCodeAt(pos - this.chunk2Pos);\n }\n else {\n let i = this.rangeIndex, range = this.range;\n while (range.to <= pos)\n range = this.ranges[++i];\n this.chunk2 = this.input.chunk(this.chunk2Pos = pos);\n if (pos + this.chunk2.length > range.to)\n this.chunk2 = this.chunk2.slice(0, range.to - pos);\n result = this.chunk2.charCodeAt(0);\n }\n }\n if (pos >= this.token.lookAhead)\n this.token.lookAhead = pos + 1;\n return result;\n }\n /**\n Accept a token. By default, the end of the token is set to the\n current stream position, but you can pass an offset (relative to\n the stream position) to change that.\n */\n acceptToken(token, endOffset = 0) {\n let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos;\n if (end == null || end < this.token.start)\n throw new RangeError(\"Token end out of bounds\");\n this.token.value = token;\n this.token.end = end;\n }\n getChunk() {\n if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) {\n let { chunk, chunkPos } = this;\n this.chunk = this.chunk2;\n this.chunkPos = this.chunk2Pos;\n this.chunk2 = chunk;\n this.chunk2Pos = chunkPos;\n this.chunkOff = this.pos - this.chunkPos;\n }\n else {\n this.chunk2 = this.chunk;\n this.chunk2Pos = this.chunkPos;\n let nextChunk = this.input.chunk(this.pos);\n let end = this.pos + nextChunk.length;\n this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk;\n this.chunkPos = this.pos;\n this.chunkOff = 0;\n }\n }\n readNext() {\n if (this.chunkOff >= this.chunk.length) {\n this.getChunk();\n if (this.chunkOff == this.chunk.length)\n return this.next = -1;\n }\n return this.next = this.chunk.charCodeAt(this.chunkOff);\n }\n /**\n Move the stream forward N (defaults to 1) code units. Returns\n the new value of [`next`](#lr.InputStream.next).\n */\n advance(n = 1) {\n this.chunkOff += n;\n while (this.pos + n >= this.range.to) {\n if (this.rangeIndex == this.ranges.length - 1)\n return this.setDone();\n n -= this.range.to - this.pos;\n this.range = this.ranges[++this.rangeIndex];\n this.pos = this.range.from;\n }\n this.pos += n;\n if (this.pos >= this.token.lookAhead)\n this.token.lookAhead = this.pos + 1;\n return this.readNext();\n }\n setDone() {\n this.pos = this.chunkPos = this.end;\n this.range = this.ranges[this.rangeIndex = this.ranges.length - 1];\n this.chunk = \"\";\n return this.next = -1;\n }\n /**\n @internal\n */\n reset(pos, token) {\n if (token) {\n this.token = token;\n token.start = pos;\n token.lookAhead = pos + 1;\n token.value = token.extended = -1;\n }\n else {\n this.token = nullToken;\n }\n if (this.pos != pos) {\n this.pos = pos;\n if (pos == this.end) {\n this.setDone();\n return this;\n }\n while (pos < this.range.from)\n this.range = this.ranges[--this.rangeIndex];\n while (pos >= this.range.to)\n this.range = this.ranges[++this.rangeIndex];\n if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) {\n this.chunkOff = pos - this.chunkPos;\n }\n else {\n this.chunk = \"\";\n this.chunkOff = 0;\n }\n this.readNext();\n }\n return this;\n }\n /**\n @internal\n */\n read(from, to) {\n if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length)\n return this.chunk.slice(from - this.chunkPos, to - this.chunkPos);\n if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length)\n return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos);\n if (from >= this.range.from && to <= this.range.to)\n return this.input.read(from, to);\n let result = \"\";\n for (let r of this.ranges) {\n if (r.from >= to)\n break;\n if (r.to > from)\n result += this.input.read(Math.max(r.from, from), Math.min(r.to, to));\n }\n return result;\n }\n}\n/**\n@internal\n*/\nclass TokenGroup {\n constructor(data, id) {\n this.data = data;\n this.id = id;\n }\n token(input, stack) {\n let { parser } = stack.p;\n readToken(this.data, input, stack, this.id, parser.data, parser.tokenPrecTable);\n }\n}\nTokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;\n/**\n@hide\n*/\nclass LocalTokenGroup {\n constructor(data, precTable, elseToken) {\n this.precTable = precTable;\n this.elseToken = elseToken;\n this.data = typeof data == \"string\" ? decodeArray(data) : data;\n }\n token(input, stack) {\n let start = input.pos, skipped = 0;\n for (;;) {\n let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);\n readToken(this.data, input, stack, 0, this.data, this.precTable);\n if (input.token.value > -1)\n break;\n if (this.elseToken == null)\n return;\n if (!atEof)\n skipped++;\n if (nextPos == null)\n break;\n input.reset(nextPos, input.token);\n }\n if (skipped) {\n input.reset(start, input.token);\n input.acceptToken(this.elseToken, skipped);\n }\n }\n}\nLocalTokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;\n/**\n`@external tokens` declarations in the grammar should resolve to\nan instance of this class.\n*/\nclass ExternalTokenizer {\n /**\n Create a tokenizer. The first argument is the function that,\n given an input stream, scans for the types of tokens it\n recognizes at the stream's position, and calls\n [`acceptToken`](#lr.InputStream.acceptToken) when it finds\n one.\n */\n constructor(\n /**\n @internal\n */\n token, options = {}) {\n this.token = token;\n this.contextual = !!options.contextual;\n this.fallback = !!options.fallback;\n this.extend = !!options.extend;\n }\n}\n// Tokenizer data is stored a big uint16 array containing, for each\n// state:\n//\n// - A group bitmask, indicating what token groups are reachable from\n// this state, so that paths that can only lead to tokens not in\n// any of the current groups can be cut off early.\n//\n// - The position of the end of the state's sequence of accepting\n// tokens\n//\n// - The number of outgoing edges for the state\n//\n// - The accepting tokens, as (token id, group mask) pairs\n//\n// - The outgoing edges, as (start character, end character, state\n// index) triples, with end character being exclusive\n//\n// This function interprets that data, running through a stream as\n// long as new states with the a matching group mask can be reached,\n// and updating `input.token` when it matches a token.\nfunction readToken(data, input, stack, group, precTable, precOffset) {\n let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;\n scan: for (;;) {\n if ((groupMask & data[state]) == 0)\n break;\n let accEnd = data[state + 1];\n // Check whether this state can lead to a token in the current group\n // Accept tokens in this state, possibly overwriting\n // lower-precedence / shorter tokens\n for (let i = state + 3; i < accEnd; i += 2)\n if ((data[i + 1] & groupMask) > 0) {\n let term = data[i];\n if (dialect.allows(term) &&\n (input.token.value == -1 || input.token.value == term ||\n overrides(term, input.token.value, precTable, precOffset))) {\n input.acceptToken(term);\n break;\n }\n }\n let next = input.next, low = 0, high = data[state + 2];\n // Special case for EOF\n if (input.next < 0 && high > low && data[accEnd + high * 3 - 3] == 65535 /* Seq.End */) {\n state = data[accEnd + high * 3 - 1];\n continue scan;\n }\n // Do a binary search on the state's edges\n for (; low < high;) {\n let mid = (low + high) >> 1;\n let index = accEnd + mid + (mid << 1);\n let from = data[index], to = data[index + 1] || 0x10000;\n if (next < from)\n high = mid;\n else if (next >= to)\n low = mid + 1;\n else {\n state = data[index + 2];\n input.advance();\n continue scan;\n }\n }\n break;\n }\n}\nfunction findOffset(data, start, term) {\n for (let i = start, next; (next = data[i]) != 65535 /* Seq.End */; i++)\n if (next == term)\n return i - start;\n return -1;\n}\nfunction overrides(token, prev, tableData, tableOffset) {\n let iPrev = findOffset(tableData, tableOffset, prev);\n return iPrev < 0 || findOffset(tableData, tableOffset, token) < iPrev;\n}\n\n// Environment variable used to control console output\nconst verbose = typeof process != \"undefined\" && process.env && /\\bparse\\b/.test(process.env.LOG);\nlet stackIDs = null;\nfunction cutAt(tree, pos, side) {\n let cursor = tree.cursor(IterMode.IncludeAnonymous);\n cursor.moveTo(pos);\n for (;;) {\n if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos)))\n for (;;) {\n if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError)\n return side < 0 ? Math.max(0, Math.min(cursor.to - 1, pos - 25 /* Safety.Margin */))\n : Math.min(tree.length, Math.max(cursor.from + 1, pos + 25 /* Safety.Margin */));\n if (side < 0 ? cursor.prevSibling() : cursor.nextSibling())\n break;\n if (!cursor.parent())\n return side < 0 ? 0 : tree.length;\n }\n }\n}\nclass FragmentCursor {\n constructor(fragments, nodeSet) {\n this.fragments = fragments;\n this.nodeSet = nodeSet;\n this.i = 0;\n this.fragment = null;\n this.safeFrom = -1;\n this.safeTo = -1;\n this.trees = [];\n this.start = [];\n this.index = [];\n this.nextFragment();\n }\n nextFragment() {\n let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++];\n if (fr) {\n this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from;\n this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to;\n while (this.trees.length) {\n this.trees.pop();\n this.start.pop();\n this.index.pop();\n }\n this.trees.push(fr.tree);\n this.start.push(-fr.offset);\n this.index.push(0);\n this.nextStart = this.safeFrom;\n }\n else {\n this.nextStart = 1e9;\n }\n }\n // `pos` must be >= any previously given `pos` for this cursor\n nodeAt(pos) {\n if (pos < this.nextStart)\n return null;\n while (this.fragment && this.safeTo <= pos)\n this.nextFragment();\n if (!this.fragment)\n return null;\n for (;;) {\n let last = this.trees.length - 1;\n if (last < 0) { // End of tree\n this.nextFragment();\n return null;\n }\n let top = this.trees[last], index = this.index[last];\n if (index == top.children.length) {\n this.trees.pop();\n this.start.pop();\n this.index.pop();\n continue;\n }\n let next = top.children[index];\n let start = this.start[last] + top.positions[index];\n if (start > pos) {\n this.nextStart = start;\n return null;\n }\n if (next instanceof Tree) {\n if (start == pos) {\n if (start < this.safeFrom)\n return null;\n let end = start + next.length;\n if (end <= this.safeTo) {\n let lookAhead = next.prop(NodeProp.lookAhead);\n if (!lookAhead || end + lookAhead < this.fragment.to)\n return next;\n }\n }\n this.index[last]++;\n if (start + next.length >= Math.max(this.safeFrom, pos)) { // Enter this node\n this.trees.push(next);\n this.start.push(start);\n this.index.push(0);\n }\n }\n else {\n this.index[last]++;\n this.nextStart = start + next.length;\n }\n }\n }\n}\nclass TokenCache {\n constructor(parser, stream) {\n this.stream = stream;\n this.tokens = [];\n this.mainToken = null;\n this.actions = [];\n this.tokens = parser.tokenizers.map(_ => new CachedToken);\n }\n getActions(stack) {\n let actionIndex = 0;\n let main = null;\n let { parser } = stack.p, { tokenizers } = parser;\n let mask = parser.stateSlot(stack.state, 3 /* ParseState.TokenizerMask */);\n let context = stack.curContext ? stack.curContext.hash : 0;\n let lookAhead = 0;\n for (let i = 0; i < tokenizers.length; i++) {\n if (((1 << i) & mask) == 0)\n continue;\n let tokenizer = tokenizers[i], token = this.tokens[i];\n if (main && !tokenizer.fallback)\n continue;\n if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) {\n this.updateCachedToken(token, tokenizer, stack);\n token.mask = mask;\n token.context = context;\n }\n if (token.lookAhead > token.end + 25 /* Safety.Margin */)\n lookAhead = Math.max(token.lookAhead, lookAhead);\n if (token.value != 0 /* Term.Err */) {\n let startIndex = actionIndex;\n if (token.extended > -1)\n actionIndex = this.addActions(stack, token.extended, token.end, actionIndex);\n actionIndex = this.addActions(stack, token.value, token.end, actionIndex);\n if (!tokenizer.extend) {\n main = token;\n if (actionIndex > startIndex)\n break;\n }\n }\n }\n while (this.actions.length > actionIndex)\n this.actions.pop();\n if (lookAhead)\n stack.setLookAhead(lookAhead);\n if (!main && stack.pos == this.stream.end) {\n main = new CachedToken;\n main.value = stack.p.parser.eofTerm;\n main.start = main.end = stack.pos;\n actionIndex = this.addActions(stack, main.value, main.end, actionIndex);\n }\n this.mainToken = main;\n return this.actions;\n }\n getMainToken(stack) {\n if (this.mainToken)\n return this.mainToken;\n let main = new CachedToken, { pos, p } = stack;\n main.start = pos;\n main.end = Math.min(pos + 1, p.stream.end);\n main.value = pos == p.stream.end ? p.parser.eofTerm : 0 /* Term.Err */;\n return main;\n }\n updateCachedToken(token, tokenizer, stack) {\n let start = this.stream.clipPos(stack.pos);\n tokenizer.token(this.stream.reset(start, token), stack);\n if (token.value > -1) {\n let { parser } = stack.p;\n for (let i = 0; i < parser.specialized.length; i++)\n if (parser.specialized[i] == token.value) {\n let result = parser.specializers[i](this.stream.read(token.start, token.end), stack);\n if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) {\n if ((result & 1) == 0 /* Specialize.Specialize */)\n token.value = result >> 1;\n else\n token.extended = result >> 1;\n break;\n }\n }\n }\n else {\n token.value = 0 /* Term.Err */;\n token.end = this.stream.clipPos(start + 1);\n }\n }\n putAction(action, token, end, index) {\n // Don't add duplicate actions\n for (let i = 0; i < index; i += 3)\n if (this.actions[i] == action)\n return index;\n this.actions[index++] = action;\n this.actions[index++] = token;\n this.actions[index++] = end;\n return index;\n }\n addActions(stack, token, end, index) {\n let { state } = stack, { parser } = stack.p, { data } = parser;\n for (let set = 0; set < 2; set++) {\n for (let i = parser.stateSlot(state, set ? 2 /* ParseState.Skip */ : 1 /* ParseState.Actions */);; i += 3) {\n if (data[i] == 65535 /* Seq.End */) {\n if (data[i + 1] == 1 /* Seq.Next */) {\n i = pair(data, i + 2);\n }\n else {\n if (index == 0 && data[i + 1] == 2 /* Seq.Other */)\n index = this.putAction(pair(data, i + 2), token, end, index);\n break;\n }\n }\n if (data[i] == token)\n index = this.putAction(pair(data, i + 1), token, end, index);\n }\n }\n return index;\n }\n}\nclass Parse {\n constructor(parser, input, fragments, ranges) {\n this.parser = parser;\n this.input = input;\n this.ranges = ranges;\n this.recovering = 0;\n this.nextStackID = 0x2654; // ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧\n this.minStackPos = 0;\n this.reused = [];\n this.stoppedAt = null;\n this.lastBigReductionStart = -1;\n this.lastBigReductionSize = 0;\n this.bigReductionCount = 0;\n this.stream = new InputStream(input, ranges);\n this.tokens = new TokenCache(parser, this.stream);\n this.topTerm = parser.top[1];\n let { from } = ranges[0];\n this.stacks = [Stack.start(this, parser.top[0], from)];\n this.fragments = fragments.length && this.stream.end - from > parser.bufferLength * 4\n ? new FragmentCursor(fragments, parser.nodeSet) : null;\n }\n get parsedPos() {\n return this.minStackPos;\n }\n // Move the parser forward. This will process all parse stacks at\n // `this.pos` and try to advance them to a further position. If no\n // stack for such a position is found, it'll start error-recovery.\n //\n // When the parse is finished, this will return a syntax tree. When\n // not, it returns `null`.\n advance() {\n let stacks = this.stacks, pos = this.minStackPos;\n // This will hold stacks beyond `pos`.\n let newStacks = this.stacks = [];\n let stopped, stoppedTokens;\n // If a large amount of reductions happened with the same start\n // position, force the stack out of that production in order to\n // avoid creating a tree too deep to recurse through.\n // (This is an ugly kludge, because unfortunately there is no\n // straightforward, cheap way to check for this happening, due to\n // the history of reductions only being available in an\n // expensive-to-access format in the stack buffers.)\n if (this.bigReductionCount > 300 /* Rec.MaxLeftAssociativeReductionCount */ && stacks.length == 1) {\n let [s] = stacks;\n while (s.forceReduce() && s.stack.length && s.stack[s.stack.length - 2] >= this.lastBigReductionStart) { }\n this.bigReductionCount = this.lastBigReductionSize = 0;\n }\n // Keep advancing any stacks at `pos` until they either move\n // forward or can't be advanced. Gather stacks that can't be\n // advanced further in `stopped`.\n for (let i = 0; i < stacks.length; i++) {\n let stack = stacks[i];\n for (;;) {\n this.tokens.mainToken = null;\n if (stack.pos > pos) {\n newStacks.push(stack);\n }\n else if (this.advanceStack(stack, newStacks, stacks)) {\n continue;\n }\n else {\n if (!stopped) {\n stopped = [];\n stoppedTokens = [];\n }\n stopped.push(stack);\n let tok = this.tokens.getMainToken(stack);\n stoppedTokens.push(tok.value, tok.end);\n }\n break;\n }\n }\n if (!newStacks.length) {\n let finished = stopped && findFinished(stopped);\n if (finished) {\n if (verbose)\n console.log(\"Finish with \" + this.stackID(finished));\n return this.stackToTree(finished);\n }\n if (this.parser.strict) {\n if (verbose && stopped)\n console.log(\"Stuck with token \" + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : \"none\"));\n throw new SyntaxError(\"No parse at \" + pos);\n }\n if (!this.recovering)\n this.recovering = 5 /* Rec.Distance */;\n }\n if (this.recovering && stopped) {\n let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0]\n : this.runRecovery(stopped, stoppedTokens, newStacks);\n if (finished) {\n if (verbose)\n console.log(\"Force-finish \" + this.stackID(finished));\n return this.stackToTree(finished.forceAll());\n }\n }\n if (this.recovering) {\n let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3 /* Rec.MaxRemainingPerStep */;\n if (newStacks.length > maxRemaining) {\n newStacks.sort((a, b) => b.score - a.score);\n while (newStacks.length > maxRemaining)\n newStacks.pop();\n }\n if (newStacks.some(s => s.reducePos > pos))\n this.recovering--;\n }\n else if (newStacks.length > 1) {\n // Prune stacks that are in the same state, or that have been\n // running without splitting for a while, to avoid getting stuck\n // with multiple successful stacks running endlessly on.\n outer: for (let i = 0; i < newStacks.length - 1; i++) {\n let stack = newStacks[i];\n for (let j = i + 1; j < newStacks.length; j++) {\n let other = newStacks[j];\n if (stack.sameState(other) ||\n stack.buffer.length > 500 /* Rec.MinBufferLengthPrune */ && other.buffer.length > 500 /* Rec.MinBufferLengthPrune */) {\n if (((stack.score - other.score) || (stack.buffer.length - other.buffer.length)) > 0) {\n newStacks.splice(j--, 1);\n }\n else {\n newStacks.splice(i--, 1);\n continue outer;\n }\n }\n }\n }\n if (newStacks.length > 12 /* Rec.MaxStackCount */)\n newStacks.splice(12 /* Rec.MaxStackCount */, newStacks.length - 12 /* Rec.MaxStackCount */);\n }\n this.minStackPos = newStacks[0].pos;\n for (let i = 1; i < newStacks.length; i++)\n if (newStacks[i].pos < this.minStackPos)\n this.minStackPos = newStacks[i].pos;\n return null;\n }\n stopAt(pos) {\n if (this.stoppedAt != null && this.stoppedAt < pos)\n throw new RangeError(\"Can't move stoppedAt forward\");\n this.stoppedAt = pos;\n }\n // Returns an updated version of the given stack, or null if the\n // stack can't advance normally. When `split` and `stacks` are\n // given, stacks split off by ambiguous operations will be pushed to\n // `split`, or added to `stacks` if they move `pos` forward.\n advanceStack(stack, stacks, split) {\n let start = stack.pos, { parser } = this;\n let base = verbose ? this.stackID(stack) + \" -> \" : \"\";\n if (this.stoppedAt != null && start > this.stoppedAt)\n return stack.forceReduce() ? stack : null;\n if (this.fragments) {\n let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0;\n for (let cached = this.fragments.nodeAt(start); cached;) {\n let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser.getGoto(stack.state, cached.type.id) : -1;\n if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) {\n stack.useNode(cached, match);\n if (verbose)\n console.log(base + this.stackID(stack) + ` (via reuse of ${parser.getName(cached.type.id)})`);\n return true;\n }\n if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0)\n break;\n let inner = cached.children[0];\n if (inner instanceof Tree && cached.positions[0] == 0)\n cached = inner;\n else\n break;\n }\n }\n let defaultReduce = parser.stateSlot(stack.state, 4 /* ParseState.DefaultReduce */);\n if (defaultReduce > 0) {\n stack.reduce(defaultReduce);\n if (verbose)\n console.log(base + this.stackID(stack) + ` (via always-reduce ${parser.getName(defaultReduce & 65535 /* Action.ValueMask */)})`);\n return true;\n }\n if (stack.stack.length >= 8400 /* Rec.CutDepth */) {\n while (stack.stack.length > 6000 /* Rec.CutTo */ && stack.forceReduce()) { }\n }\n let actions = this.tokens.getActions(stack);\n for (let i = 0; i < actions.length;) {\n let action = actions[i++], term = actions[i++], end = actions[i++];\n let last = i == actions.length || !split;\n let localStack = last ? stack : stack.split();\n let main = this.tokens.mainToken;\n localStack.apply(action, term, main ? main.start : localStack.pos, end);\n if (verbose)\n console.log(base + this.stackID(localStack) + ` (via ${(action & 65536 /* Action.ReduceFlag */) == 0 ? \"shift\"\n : `reduce of ${parser.getName(action & 65535 /* Action.ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack == stack ? \"\" : \", split\"})`);\n if (last)\n return true;\n else if (localStack.pos > start)\n stacks.push(localStack);\n else\n split.push(localStack);\n }\n return false;\n }\n // Advance a given stack forward as far as it will go. Returns the\n // (possibly updated) stack if it got stuck, or null if it moved\n // forward and was given to `pushStackDedup`.\n advanceFully(stack, newStacks) {\n let pos = stack.pos;\n for (;;) {\n if (!this.advanceStack(stack, null, null))\n return false;\n if (stack.pos > pos) {\n pushStackDedup(stack, newStacks);\n return true;\n }\n }\n }\n runRecovery(stacks, tokens, newStacks) {\n let finished = null, restarted = false;\n for (let i = 0; i < stacks.length; i++) {\n let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1];\n let base = verbose ? this.stackID(stack) + \" -> \" : \"\";\n if (stack.deadEnd) {\n if (restarted)\n continue;\n restarted = true;\n stack.restart();\n if (verbose)\n console.log(base + this.stackID(stack) + \" (restarted)\");\n let done = this.advanceFully(stack, newStacks);\n if (done)\n continue;\n }\n let force = stack.split(), forceBase = base;\n for (let j = 0; force.forceReduce() && j < 10 /* Rec.ForceReduceLimit */; j++) {\n if (verbose)\n console.log(forceBase + this.stackID(force) + \" (via force-reduce)\");\n let done = this.advanceFully(force, newStacks);\n if (done)\n break;\n if (verbose)\n forceBase = this.stackID(force) + \" -> \";\n }\n for (let insert of stack.recoverByInsert(token)) {\n if (verbose)\n console.log(base + this.stackID(insert) + \" (via recover-insert)\");\n this.advanceFully(insert, newStacks);\n }\n if (this.stream.end > stack.pos) {\n if (tokenEnd == stack.pos) {\n tokenEnd++;\n token = 0 /* Term.Err */;\n }\n stack.recoverByDelete(token, tokenEnd);\n if (verbose)\n console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`);\n pushStackDedup(stack, newStacks);\n }\n else if (!finished || finished.score < stack.score) {\n finished = stack;\n }\n }\n return finished;\n }\n // Convert the stack's buffer to a syntax tree.\n stackToTree(stack) {\n stack.close();\n return Tree.build({ buffer: StackBufferCursor.create(stack),\n nodeSet: this.parser.nodeSet,\n topID: this.topTerm,\n maxBufferLength: this.parser.bufferLength,\n reused: this.reused,\n start: this.ranges[0].from,\n length: stack.pos - this.ranges[0].from,\n minRepeatType: this.parser.minRepeatTerm });\n }\n stackID(stack) {\n let id = (stackIDs || (stackIDs = new WeakMap)).get(stack);\n if (!id)\n stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++));\n return id + stack;\n }\n}\nfunction pushStackDedup(stack, newStacks) {\n for (let i = 0; i < newStacks.length; i++) {\n let other = newStacks[i];\n if (other.pos == stack.pos && other.sameState(stack)) {\n if (newStacks[i].score < stack.score)\n newStacks[i] = stack;\n return;\n }\n }\n newStacks.push(stack);\n}\nclass Dialect {\n constructor(source, flags, disabled) {\n this.source = source;\n this.flags = flags;\n this.disabled = disabled;\n }\n allows(term) { return !this.disabled || this.disabled[term] == 0; }\n}\nconst id = x => x;\n/**\nContext trackers are used to track stateful context (such as\nindentation in the Python grammar, or parent elements in the XML\ngrammar) needed by external tokenizers. You declare them in a\ngrammar file as `@context exportName from \"module\"`.\n\nContext values should be immutable, and can be updated (replaced)\non shift or reduce actions.\n\nThe export used in a `@context` declaration should be of this\ntype.\n*/\nclass ContextTracker {\n /**\n Define a context tracker.\n */\n constructor(spec) {\n this.start = spec.start;\n this.shift = spec.shift || id;\n this.reduce = spec.reduce || id;\n this.reuse = spec.reuse || id;\n this.hash = spec.hash || (() => 0);\n this.strict = spec.strict !== false;\n }\n}\n/**\nHolds the parse tables for a given grammar, as generated by\n`lezer-generator`, and provides [methods](#common.Parser) to parse\ncontent with.\n*/\nclass LRParser extends Parser {\n /**\n @internal\n */\n constructor(spec) {\n super();\n /**\n @internal\n */\n this.wrappers = [];\n if (spec.version != 14 /* File.Version */)\n throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14 /* File.Version */})`);\n let nodeNames = spec.nodeNames.split(\" \");\n this.minRepeatTerm = nodeNames.length;\n for (let i = 0; i < spec.repeatNodeCount; i++)\n nodeNames.push(\"\");\n let topTerms = Object.keys(spec.topRules).map(r => spec.topRules[r][1]);\n let nodeProps = [];\n for (let i = 0; i < nodeNames.length; i++)\n nodeProps.push([]);\n function setProp(nodeID, prop, value) {\n nodeProps[nodeID].push([prop, prop.deserialize(String(value))]);\n }\n if (spec.nodeProps)\n for (let propSpec of spec.nodeProps) {\n let prop = propSpec[0];\n if (typeof prop == \"string\")\n prop = NodeProp[prop];\n for (let i = 1; i < propSpec.length;) {\n let next = propSpec[i++];\n if (next >= 0) {\n setProp(next, prop, propSpec[i++]);\n }\n else {\n let value = propSpec[i + -next];\n for (let j = -next; j > 0; j--)\n setProp(propSpec[i++], prop, value);\n i++;\n }\n }\n }\n this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({\n name: i >= this.minRepeatTerm ? undefined : name,\n id: i,\n props: nodeProps[i],\n top: topTerms.indexOf(i) > -1,\n error: i == 0,\n skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1\n })));\n if (spec.propSources)\n this.nodeSet = this.nodeSet.extend(...spec.propSources);\n this.strict = false;\n this.bufferLength = DefaultBufferLength;\n let tokenArray = decodeArray(spec.tokenData);\n this.context = spec.context;\n this.specializerSpecs = spec.specialized || [];\n this.specialized = new Uint16Array(this.specializerSpecs.length);\n for (let i = 0; i < this.specializerSpecs.length; i++)\n this.specialized[i] = this.specializerSpecs[i].term;\n this.specializers = this.specializerSpecs.map(getSpecializer);\n this.states = decodeArray(spec.states, Uint32Array);\n this.data = decodeArray(spec.stateData);\n this.goto = decodeArray(spec.goto);\n this.maxTerm = spec.maxTerm;\n this.tokenizers = spec.tokenizers.map(value => typeof value == \"number\" ? new TokenGroup(tokenArray, value) : value);\n this.topRules = spec.topRules;\n this.dialects = spec.dialects || {};\n this.dynamicPrecedences = spec.dynamicPrecedences || null;\n this.tokenPrecTable = spec.tokenPrec;\n this.termNames = spec.termNames || null;\n this.maxNode = this.nodeSet.types.length - 1;\n this.dialect = this.parseDialect();\n this.top = this.topRules[Object.keys(this.topRules)[0]];\n }\n createParse(input, fragments, ranges) {\n let parse = new Parse(this, input, fragments, ranges);\n for (let w of this.wrappers)\n parse = w(parse, input, fragments, ranges);\n return parse;\n }\n /**\n Get a goto table entry @internal\n */\n getGoto(state, term, loose = false) {\n let table = this.goto;\n if (term >= table[0])\n return -1;\n for (let pos = table[term + 1];;) {\n let groupTag = table[pos++], last = groupTag & 1;\n let target = table[pos++];\n if (last && loose)\n return target;\n for (let end = pos + (groupTag >> 1); pos < end; pos++)\n if (table[pos] == state)\n return target;\n if (last)\n return -1;\n }\n }\n /**\n Check if this state has an action for a given terminal @internal\n */\n hasAction(state, terminal) {\n let data = this.data;\n for (let set = 0; set < 2; set++) {\n for (let i = this.stateSlot(state, set ? 2 /* ParseState.Skip */ : 1 /* ParseState.Actions */), next;; i += 3) {\n if ((next = data[i]) == 65535 /* Seq.End */) {\n if (data[i + 1] == 1 /* Seq.Next */)\n next = data[i = pair(data, i + 2)];\n else if (data[i + 1] == 2 /* Seq.Other */)\n return pair(data, i + 2);\n else\n break;\n }\n if (next == terminal || next == 0 /* Term.Err */)\n return pair(data, i + 1);\n }\n }\n return 0;\n }\n /**\n @internal\n */\n stateSlot(state, slot) {\n return this.states[(state * 6 /* ParseState.Size */) + slot];\n }\n /**\n @internal\n */\n stateFlag(state, flag) {\n return (this.stateSlot(state, 0 /* ParseState.Flags */) & flag) > 0;\n }\n /**\n @internal\n */\n validAction(state, action) {\n return !!this.allActions(state, a => a == action ? true : null);\n }\n /**\n @internal\n */\n allActions(state, action) {\n let deflt = this.stateSlot(state, 4 /* ParseState.DefaultReduce */);\n let result = deflt ? action(deflt) : undefined;\n for (let i = this.stateSlot(state, 1 /* ParseState.Actions */); result == null; i += 3) {\n if (this.data[i] == 65535 /* Seq.End */) {\n if (this.data[i + 1] == 1 /* Seq.Next */)\n i = pair(this.data, i + 2);\n else\n break;\n }\n result = action(pair(this.data, i + 1));\n }\n return result;\n }\n /**\n Get the states that can follow this one through shift actions or\n goto jumps. @internal\n */\n nextStates(state) {\n let result = [];\n for (let i = this.stateSlot(state, 1 /* ParseState.Actions */);; i += 3) {\n if (this.data[i] == 65535 /* Seq.End */) {\n if (this.data[i + 1] == 1 /* Seq.Next */)\n i = pair(this.data, i + 2);\n else\n break;\n }\n if ((this.data[i + 2] & (65536 /* Action.ReduceFlag */ >> 16)) == 0) {\n let value = this.data[i + 1];\n if (!result.some((v, i) => (i & 1) && v == value))\n result.push(this.data[i], value);\n }\n }\n return result;\n }\n /**\n Configure the parser. Returns a new parser instance that has the\n given settings modified. Settings not provided in `config` are\n kept from the original parser.\n */\n configure(config) {\n // Hideous reflection-based kludge to make it easy to create a\n // slightly modified copy of a parser.\n let copy = Object.assign(Object.create(LRParser.prototype), this);\n if (config.props)\n copy.nodeSet = this.nodeSet.extend(...config.props);\n if (config.top) {\n let info = this.topRules[config.top];\n if (!info)\n throw new RangeError(`Invalid top rule name ${config.top}`);\n copy.top = info;\n }\n if (config.tokenizers)\n copy.tokenizers = this.tokenizers.map(t => {\n let found = config.tokenizers.find(r => r.from == t);\n return found ? found.to : t;\n });\n if (config.specializers) {\n copy.specializers = this.specializers.slice();\n copy.specializerSpecs = this.specializerSpecs.map((s, i) => {\n let found = config.specializers.find(r => r.from == s.external);\n if (!found)\n return s;\n let spec = Object.assign(Object.assign({}, s), { external: found.to });\n copy.specializers[i] = getSpecializer(spec);\n return spec;\n });\n }\n if (config.contextTracker)\n copy.context = config.contextTracker;\n if (config.dialect)\n copy.dialect = this.parseDialect(config.dialect);\n if (config.strict != null)\n copy.strict = config.strict;\n if (config.wrap)\n copy.wrappers = copy.wrappers.concat(config.wrap);\n if (config.bufferLength != null)\n copy.bufferLength = config.bufferLength;\n return copy;\n }\n /**\n Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)\n are registered for this parser.\n */\n hasWrappers() {\n return this.wrappers.length > 0;\n }\n /**\n Returns the name associated with a given term. This will only\n work for all terms when the parser was generated with the\n `--names` option. By default, only the names of tagged terms are\n stored.\n */\n getName(term) {\n return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term);\n }\n /**\n The eof term id is always allocated directly after the node\n types. @internal\n */\n get eofTerm() { return this.maxNode + 1; }\n /**\n The type of top node produced by the parser.\n */\n get topNode() { return this.nodeSet.types[this.top[1]]; }\n /**\n @internal\n */\n dynamicPrecedence(term) {\n let prec = this.dynamicPrecedences;\n return prec == null ? 0 : prec[term] || 0;\n }\n /**\n @internal\n */\n parseDialect(dialect) {\n let values = Object.keys(this.dialects), flags = values.map(() => false);\n if (dialect)\n for (let part of dialect.split(\" \")) {\n let id = values.indexOf(part);\n if (id >= 0)\n flags[id] = true;\n }\n let disabled = null;\n for (let i = 0; i < values.length; i++)\n if (!flags[i]) {\n for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535 /* Seq.End */;)\n (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1;\n }\n return new Dialect(dialect, flags, disabled);\n }\n /**\n Used by the output of the parser generator. Not available to\n user code. @hide\n */\n static deserialize(spec) {\n return new LRParser(spec);\n }\n}\nfunction pair(data, off) { return data[off] | (data[off + 1] << 16); }\nfunction findFinished(stacks) {\n let best = null;\n for (let stack of stacks) {\n let stopped = stack.p.stoppedAt;\n if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) &&\n stack.p.parser.stateFlag(stack.state, 2 /* StateFlag.Accepting */) &&\n (!best || best.score < stack.score))\n best = stack;\n }\n return best;\n}\nfunction getSpecializer(spec) {\n if (spec.external) {\n let mask = spec.extend ? 1 /* Specialize.Extend */ : 0 /* Specialize.Specialize */;\n return (value, stack) => (spec.external(value, stack) << 1) | mask;\n }\n return spec.get;\n}\n\nexport { ContextTracker, ExternalTokenizer, InputStream, LRParser, LocalTokenGroup, Stack };\n","const C = \"\\u037c\"\nconst COUNT = typeof Symbol == \"undefined\" ? \"__\" + C : Symbol.for(C)\nconst SET = typeof Symbol == \"undefined\" ? \"__styleSet\" + Math.floor(Math.random() * 1e8) : Symbol(\"styleSet\")\nconst top = typeof globalThis != \"undefined\" ? globalThis : typeof window != \"undefined\" ? window : {}\n\n// :: - Style modules encapsulate a set of CSS rules defined from\n// JavaScript. Their definitions are only available in a given DOM\n// root after it has been _mounted_ there with `StyleModule.mount`.\n//\n// Style modules should be created once and stored somewhere, as\n// opposed to re-creating them every time you need them. The amount of\n// CSS rules generated for a given DOM root is bounded by the amount\n// of style modules that were used. So to avoid leaking rules, don't\n// create these dynamically, but treat them as one-time allocations.\nexport class StyleModule {\n // :: (Object +logo + + + + + + + + diff --git a/book/_build/html/_static/images/logo_colab.png b/book/_build/html/_static/images/logo_colab.png new file mode 100644 index 0000000..b7560ec Binary files /dev/null and b/book/_build/html/_static/images/logo_colab.png differ diff --git a/book/_build/html/_static/images/logo_deepnote.svg b/book/_build/html/_static/images/logo_deepnote.svg new file mode 100644 index 0000000..fa77ebf --- /dev/null +++ b/book/_build/html/_static/images/logo_deepnote.svg @@ -0,0 +1 @@ + diff --git a/book/_build/html/_static/images/logo_jupyterhub.svg b/book/_build/html/_static/images/logo_jupyterhub.svg new file mode 100644 index 0000000..60cfe9f --- /dev/null +++ b/book/_build/html/_static/images/logo_jupyterhub.svg @@ -0,0 +1 @@ +logo_jupyterhubHub diff --git a/book/_build/html/_static/index.js b/book/_build/html/_static/index.js new file mode 100644 index 0000000..64a55c2 --- /dev/null +++ b/book/_build/html/_static/index.js @@ -0,0 +1,3 @@ +/*! For license information please see index.js.LICENSE.txt */ +(()=>{var __webpack_modules__={92918:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BaseManager=void 0;const i=n(60544),r=n(22700);t.BaseManager=class{constructor(e){var t;this._isDisposed=!1,this._disposed=new i.Signal(this),this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:r.ServerConnection.makeSettings()}get disposed(){return this._disposed}get isDisposed(){return this._isDisposed}get isActive(){return!0}dispose(){this.isDisposed||(this._disposed.emit(void 0),i.Signal.clearData(this))}}},81611:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BuildManager=void 0;const i=n(18920),r=n(22700);t.BuildManager=class{constructor(e={}){var t;this._url="",this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:r.ServerConnection.makeSettings();const{baseUrl:n,appUrl:s}=this.serverSettings;this._url=i.URLExt.join(n,s,"api/build")}get isAvailable(){return"true"===i.PageConfig.getOption("buildAvailable").toLowerCase()}get shouldCheck(){return"true"===i.PageConfig.getOption("buildCheck").toLowerCase()}getStatus(){const{_url:e,serverSettings:t}=this;return r.ServerConnection.makeRequest(e,{},t).then((e=>{if(200!==e.status)throw new r.ServerConnection.ResponseError(e);return e.json()})).then((e=>{if("string"!=typeof e.status)throw new Error("Invalid data");if("string"!=typeof e.message)throw new Error("Invalid data");return e}))}build(){const{_url:e,serverSettings:t}=this;return r.ServerConnection.makeRequest(e,{method:"POST"},t).then((e=>{if(400===e.status)throw new r.ServerConnection.ResponseError(e,"Build aborted");if(200!==e.status){const t=`Build failed with ${e.status}.\n\n If you are experiencing the build failure after installing an extension (or trying to include previously installed extension after updating JupyterLab) please check the extension repository for new installation instructions as many extensions migrated to the prebuilt extensions system which no longer requires rebuilding JupyterLab (but uses a different installation procedure, typically involving a package manager such as 'pip' or 'conda').\n\n If you specifically intended to install a source extension, please run 'jupyter lab build' on the server for full output.`;throw new r.ServerConnection.ResponseError(e,t)}}))}cancel(){const{_url:e,serverSettings:t}=this;return r.ServerConnection.makeRequest(e,{method:"DELETE"},t).then((e=>{if(204!==e.status)throw new r.ServerConnection.ResponseError(e)}))}}},42677:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConfigWithDefaults=t.ConfigSection=void 0;const i=n(18920),r=n(16914);(t.ConfigSection||(t.ConfigSection={})).create=function(e){const t=new s(e);return t.load().then((()=>t))};class s{constructor(e){var t;this._url="unknown";const n=this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:r.ServerConnection.makeSettings();this._url=i.URLExt.join(n.baseUrl,"api/config",encodeURIComponent(e.name))}get data(){return this._data}async load(){const e=await r.ServerConnection.makeRequest(this._url,{},this.serverSettings);if(200!==e.status)throw await r.ServerConnection.ResponseError.create(e);this._data=await e.json()}async update(e){this._data={...this._data,...e};const t={method:"PATCH",body:JSON.stringify(e)},n=await r.ServerConnection.makeRequest(this._url,t,this.serverSettings);if(200!==n.status)throw await r.ServerConnection.ResponseError.create(n);return this._data=await n.json(),this._data}}t.ConfigWithDefaults=class{constructor(e){var t,n;this._className="",this._section=e.section,this._defaults=null!==(t=e.defaults)&&void 0!==t?t:{},this._className=null!==(n=e.className)&&void 0!==n?n:""}get(e){const t=this._classData();return e in t?t[e]:this._defaults[e]}set(e,t){const n={};if(n[e]=t,this._className){const e={};return e[this._className]=n,this._section.update(e)}return this._section.update(n)}_classData(){const e=this._section.data;return this._className&&this._className in e?e[this._className]:e}}},57593:(e,t)=>{},93354:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EventManager=void 0;const i=n(18920),r=n(59033),s=n(60544),o=n(22700),a="api/events";t.EventManager=class{constructor(e={}){var t;this._socket=null,this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:o.ServerConnection.makeSettings(),this._poll=new r.Poll({factory:()=>this._subscribe()}),this._stream=new s.Stream(this),this._poll.start()}get isDisposed(){return this._poll.isDisposed}get stream(){return this._stream}dispose(){if(this.isDisposed)return;this._poll.dispose();const e=this._socket;e&&(this._socket=null,e.onopen=()=>{},e.onerror=()=>{},e.onmessage=()=>{},e.onclose=()=>{},e.close()),s.Signal.clearData(this),this._stream.stop()}async emit(e){const{serverSettings:t}=this,{baseUrl:n,token:r}=t,{makeRequest:s,ResponseError:l}=o.ServerConnection,u=i.URLExt.join(n,a)+(r?`?token=${r}`:""),d={body:JSON.stringify(e),method:"POST"},c=await s(u,d,t);if(204!==c.status)throw new l(c)}_subscribe(){return new Promise(((e,t)=>{if(this.isDisposed)return;const{token:n,WebSocket:r,wsUrl:s}=this.serverSettings,o=i.URLExt.join(s,a,"subscribe")+(n?`?token=${encodeURIComponent(n)}`:""),l=this._socket=new r(o),u=this._stream;l.onclose=()=>t(new Error("EventManager socket closed")),l.onmessage=e=>e.data&&u.emit(JSON.parse(e.data))}))}}},16914:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),r(n(92918),t),r(n(42677),t),r(n(57593),t),r(n(93354),t),r(n(10582),t),r(n(55312),t),r(n(88463),t),r(n(22700),t),r(n(67054),t),r(n(6052),t),r(n(98235),t),r(n(67523),t),r(n(10087),t),r(n(54933),t)},25045:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CommHandler=void 0;const o=n(34643),a=s(n(41632));class l extends o.DisposableDelegate{constructor(e,t,n,i){super(i),this._target="",this._id="",this._id=t,this._target=e,this._kernel=n}get commId(){return this._id}get targetName(){return this._target}get onClose(){return this._onClose}set onClose(e){this._onClose=e}get onMsg(){return this._onMsg}set onMsg(e){this._onMsg=e}open(e,t,n=[]){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot open");const i=a.createMessage({msgType:"comm_open",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,content:{comm_id:this._id,target_name:this._target,data:null!=e?e:{}},metadata:t,buffers:n});return this._kernel.sendShellMessage(i,!1,!0)}send(e,t,n=[],i=!0){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot send");const r=a.createMessage({msgType:"comm_msg",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,content:{comm_id:this._id,data:e},metadata:t,buffers:n});return this._kernel.sendShellMessage(r,!1,i)}close(e,t,n=[]){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot close");const i=a.createMessage({msgType:"comm_close",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,content:{comm_id:this._id,data:null!=e?e:{}},metadata:t,buffers:n}),r=this._kernel.sendShellMessage(i,!1,!0),s=this._onClose;return s&&s(a.createMessage({msgType:"comm_close",channel:"iopub",username:this._kernel.username,session:this._kernel.clientId,content:{comm_id:this._id,data:null!=e?e:{}},metadata:t,buffers:n})),this.dispose(),r}}t.CommHandler=l},82094:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelConnection=void 0;const o=n(18920),a=n(65168),l=n(60544),u=n(16914),d=n(25045),c=s(n(41632)),h=n(79178),p=n(67411),g=s(n(95537)),f=n(55312),m=s(n(60925)),v="_RESTARTING_";class b{constructor(e){var t,n,i,r;this._createSocket=(e=!0)=>{this._errorIfDisposed(),this._clearSocket(),this._updateConnectionStatus("connecting");const t=this.serverSettings,n=o.URLExt.join(t.wsUrl,m.KERNEL_SERVICE_URL,encodeURIComponent(this._id)),i=n.replace(/^((?:\w+:)?\/\/)(?:[^@\/]+@)/,"$1");console.debug(`Starting WebSocket: ${i}`);let r=o.URLExt.join(n,"channels?session_id="+encodeURIComponent(this._clientId));const s=t.token;t.appendToken&&""!==s&&(r+=`&token=${encodeURIComponent(s)}`);const a=e?this._supportedProtocols:[];this._ws=new t.WebSocket(r,a),this._ws.binaryType="arraybuffer";let l=!1;const d=async e=>{var n,i;if(!this._isDisposed){this._reason="",this._model=void 0;try{const n=await m.getKernelModel(this._id,t);this._model=n,"dead"===(null==n?void 0:n.execution_state)?this._updateStatus("dead"):this._onWSClose(e)}catch(t){if(t instanceof u.ServerConnection.NetworkError||503===(null===(n=t.response)||void 0===n?void 0:n.status)||424===(null===(i=t.response)||void 0===i?void 0:i.status)){const t=1e3*_.getRandomIntInclusive(10,30);setTimeout(d,t,e)}else this._reason="Kernel died unexpectedly",this._updateStatus("dead")}}},c=async e=>{l||(l=!0,await d(e))};this._ws.onmessage=this._onWSMessage,this._ws.onopen=this._onWSOpen,this._ws.onclose=c,this._ws.onerror=c},this._onWSOpen=e=>{if(""!==this._ws.protocol&&!this._supportedProtocols.includes(this._ws.protocol))throw console.log("Server selected unknown kernel wire protocol:",this._ws.protocol),this._updateStatus("dead"),new Error(`Unknown kernel wire protocol: ${this._ws.protocol}`);this._selectedProtocol=this._ws.protocol,this._ws.onclose=this._onWSClose,this._ws.onerror=this._onWSClose,this._updateConnectionStatus("connected")},this._onWSMessage=e=>{let t;try{t=(0,p.deserialize)(e.data,this._ws.protocol),g.validateMessage(t)}catch(e){throw e.message=`Kernel message validation error: ${e.message}`,e}this._kernelSession=t.header.session,this._msgChain=this._msgChain.then((()=>this._handleMessage(t))).catch((e=>{e.message.startsWith("Canceled future for ")&&console.error(e)})),this._anyMessage.emit({msg:t,direction:"recv"})},this._onWSClose=e=>{this.isDisposed||this._reconnect()},this._id="",this._name="",this._status="unknown",this._connectionStatus="connecting",this._kernelSession="",this._isDisposed=!1,this._ws=null,this._username="",this._reconnectLimit=7,this._reconnectAttempt=0,this._reconnectTimeout=null,this._supportedProtocols=Object.values(c.supportedKernelWebSocketProtocols),this._selectedProtocol="",this._futures=new Map,this._comms=new Map,this._targetRegistry=Object.create(null),this._info=new a.PromiseDelegate,this._pendingMessages=[],this._statusChanged=new l.Signal(this),this._connectionStatusChanged=new l.Signal(this),this._disposed=new l.Signal(this),this._iopubMessage=new l.Signal(this),this._anyMessage=new l.Signal(this),this._pendingInput=new l.Signal(this),this._unhandledMessage=new l.Signal(this),this._displayIdToParentIds=new Map,this._msgIdToDisplayIds=new Map,this._msgChain=Promise.resolve(),this._hasPendingInput=!1,this._reason="",this._noOp=()=>{},this._name=e.model.name,this._id=e.model.id,this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:u.ServerConnection.makeSettings(),this._clientId=null!==(n=e.clientId)&&void 0!==n?n:a.UUID.uuid4(),this._username=null!==(i=e.username)&&void 0!==i?i:"",this.handleComms=null===(r=e.handleComms)||void 0===r||r,this._createSocket()}get disposed(){return this._disposed}get statusChanged(){return this._statusChanged}get connectionStatusChanged(){return this._connectionStatusChanged}get iopubMessage(){return this._iopubMessage}get unhandledMessage(){return this._unhandledMessage}get model(){return this._model||{id:this.id,name:this.name,reason:this._reason}}get anyMessage(){return this._anyMessage}get pendingInput(){return this._pendingInput}get id(){return this._id}get name(){return this._name}get username(){return this._username}get clientId(){return this._clientId}get status(){return this._status}get connectionStatus(){return this._connectionStatus}get isDisposed(){return this._isDisposed}get info(){return this._info.promise}get spec(){return this._specPromise||(this._specPromise=f.KernelSpecAPI.getSpecs(this.serverSettings).then((e=>e.kernelspecs[this._name]))),this._specPromise}clone(e={}){return new b({model:this.model,username:this.username,serverSettings:this.serverSettings,handleComms:!1,...e})}dispose(){this.isDisposed||(this._isDisposed=!0,this._disposed.emit(),this._updateConnectionStatus("disconnected"),this._clearKernelState(),this._pendingMessages=[],this._clearSocket(),l.Signal.clearData(this))}sendShellMessage(e,t=!1,n=!0){return this._sendKernelShellControl(h.KernelShellFutureHandler,e,t,n)}sendControlMessage(e,t=!1,n=!0){return this._sendKernelShellControl(h.KernelControlFutureHandler,e,t,n)}_sendKernelShellControl(e,t,n=!1,i=!0){this._sendMessage(t),this._anyMessage.emit({msg:t,direction:"send"});const r=new e((()=>{const e=t.header.msg_id;this._futures.delete(e);const n=this._msgIdToDisplayIds.get(e);n&&(n.forEach((t=>{const n=this._displayIdToParentIds.get(t);if(n){const i=n.indexOf(e);if(-1===i)return;1===n.length?this._displayIdToParentIds.delete(t):(n.splice(i,1),this._displayIdToParentIds.set(t,n))}})),this._msgIdToDisplayIds.delete(e))}),t,n,i,this);return this._futures.set(t.header.msg_id,r),r}_sendMessage(e,t=!0){if("dead"===this.status)throw new Error("Kernel is dead");if((""===this._kernelSession||this._kernelSession===v)&&c.isInfoRequestMsg(e)){if("connected"===this.connectionStatus)return void this._ws.send((0,p.serialize)(e,this._ws.protocol));throw new Error("Could not send message: status is not connected")}if(t&&this._pendingMessages.length>0)this._pendingMessages.push(e);else if("connected"===this.connectionStatus&&this._kernelSession!==v)this._ws.send((0,p.serialize)(e,this._ws.protocol));else{if(!t)throw new Error("Could not send message");this._pendingMessages.push(e)}}async interrupt(){if(this.hasPendingInput=!1,"dead"===this.status)throw new Error("Kernel is dead");return m.interruptKernel(this.id,this.serverSettings)}async restart(){if("dead"===this.status)throw new Error("Kernel is dead");this._updateStatus("restarting"),this._clearKernelState(),this._kernelSession=v,await m.restartKernel(this.id,this.serverSettings),await this.reconnect(),this.hasPendingInput=!1}reconnect(){this._errorIfDisposed();const e=new a.PromiseDelegate,t=(n,i)=>{"connected"===i?(e.resolve(),this.connectionStatusChanged.disconnect(t,this)):"disconnected"===i&&(e.reject(new Error("Kernel connection disconnected")),this.connectionStatusChanged.disconnect(t,this))};return this.connectionStatusChanged.connect(t,this),this._reconnectAttempt=0,this._reconnect(),e.promise}async shutdown(){"dead"!==this.status&&await m.shutdownKernel(this.id,this.serverSettings),this.handleShutdown()}handleShutdown(){this._updateStatus("dead"),this.dispose()}async requestKernelInfo(){const e=c.createMessage({msgType:"kernel_info_request",channel:"shell",username:this._username,session:this._clientId,content:{}});let t;try{t=await _.handleShellMessage(this,e)}catch(e){if(this.isDisposed)return;throw e}if(this._errorIfDisposed(),t)return void 0===t.content.status&&(t.content.status="ok"),"ok"!==t.content.status?(this._info.reject("Kernel info reply errored"),t):(this._info.resolve(t.content),this._kernelSession=t.header.session,t)}requestComplete(e){const t=c.createMessage({msgType:"complete_request",channel:"shell",username:this._username,session:this._clientId,content:e});return _.handleShellMessage(this,t)}requestInspect(e){const t=c.createMessage({msgType:"inspect_request",channel:"shell",username:this._username,session:this._clientId,content:e});return _.handleShellMessage(this,t)}requestHistory(e){const t=c.createMessage({msgType:"history_request",channel:"shell",username:this._username,session:this._clientId,content:e});return _.handleShellMessage(this,t)}requestExecute(e,t=!0,n){const i=c.createMessage({msgType:"execute_request",channel:"shell",username:this._username,session:this._clientId,content:{silent:!1,store_history:!0,user_expressions:{},allow_stdin:!0,stop_on_error:!1,...e},metadata:n});return this.sendShellMessage(i,!0,t)}requestDebug(e,t=!0){const n=c.createMessage({msgType:"debug_request",channel:"control",username:this._username,session:this._clientId,content:e});return this.sendControlMessage(n,!0,t)}requestIsComplete(e){const t=c.createMessage({msgType:"is_complete_request",channel:"shell",username:this._username,session:this._clientId,content:e});return _.handleShellMessage(this,t)}requestCommInfo(e){const t=c.createMessage({msgType:"comm_info_request",channel:"shell",username:this._username,session:this._clientId,content:e});return _.handleShellMessage(this,t)}sendInputReply(e,t){const n=c.createMessage({msgType:"input_reply",channel:"stdin",username:this._username,session:this._clientId,content:e});n.parent_header=t,this._sendMessage(n),this._anyMessage.emit({msg:n,direction:"send"}),this.hasPendingInput=!1}createComm(e,t=a.UUID.uuid4()){if(!this.handleComms)throw new Error("Comms are disabled on this kernel connection");if(this._comms.has(t))throw new Error("Comm is already created");const n=new d.CommHandler(e,t,this,(()=>{this._unregisterComm(t)}));return this._comms.set(t,n),n}hasComm(e){return this._comms.has(e)}registerCommTarget(e,t){this.handleComms&&(this._targetRegistry[e]=t)}removeCommTarget(e,t){this.handleComms&&(this.isDisposed||this._targetRegistry[e]!==t||delete this._targetRegistry[e])}registerMessageHook(e,t){var n;const i=null===(n=this._futures)||void 0===n?void 0:n.get(e);i&&i.registerMessageHook(t)}removeMessageHook(e,t){var n;const i=null===(n=this._futures)||void 0===n?void 0:n.get(e);i&&i.removeMessageHook(t)}removeInputGuard(){this.hasPendingInput=!1}async _handleDisplayId(e,t){var n,i;const r=t.parent_header.msg_id;let s=this._displayIdToParentIds.get(e);if(s){const e={header:a.JSONExt.deepCopy(t.header),parent_header:a.JSONExt.deepCopy(t.parent_header),metadata:a.JSONExt.deepCopy(t.metadata),content:a.JSONExt.deepCopy(t.content),channel:t.channel,buffers:t.buffers?t.buffers.slice():[]};e.header.msg_type="update_display_data",await Promise.all(s.map((async t=>{const n=this._futures&&this._futures.get(t);n&&await n.handleMsg(e)})))}if("update_display_data"===t.header.msg_type)return!0;s=null!==(n=this._displayIdToParentIds.get(e))&&void 0!==n?n:[],-1===s.indexOf(r)&&s.push(r),this._displayIdToParentIds.set(e,s);const o=null!==(i=this._msgIdToDisplayIds.get(r))&&void 0!==i?i:[];return-1===o.indexOf(r)&&o.push(r),this._msgIdToDisplayIds.set(r,o),!1}_clearSocket(){null!==this._ws&&(this._ws.onopen=this._noOp,this._ws.onclose=this._noOp,this._ws.onerror=this._noOp,this._ws.onmessage=this._noOp,this._ws.close(),this._ws=null)}_updateStatus(e){this._status!==e&&"dead"!==this._status&&(this._status=e,_.logKernelStatus(this),this._statusChanged.emit(e),"dead"===e&&this.dispose())}_sendPending(){for(;"connected"===this.connectionStatus&&this._kernelSession!==v&&this._pendingMessages.length>0;)this._sendMessage(this._pendingMessages[0],!1),this._pendingMessages.shift()}_clearKernelState(){this._kernelSession="",this._pendingMessages=[],this._futures.forEach((e=>{e.dispose()})),this._comms.forEach((e=>{e.dispose()})),this._msgChain=Promise.resolve(),this._futures=new Map,this._comms=new Map,this._displayIdToParentIds.clear(),this._msgIdToDisplayIds.clear()}_assertCurrentMessage(e){if(this._errorIfDisposed(),e.header.session!==this._kernelSession)throw new Error(`Canceling handling of old message: ${e.header.msg_type}`)}async _handleCommOpen(e){this._assertCurrentMessage(e);const t=e.content,n=new d.CommHandler(t.target_name,t.comm_id,this,(()=>{this._unregisterComm(t.comm_id)}));this._comms.set(t.comm_id,n);try{const i=await _.loadObject(t.target_name,t.target_module,this._targetRegistry);await i(n,e)}catch(e){throw n.close(),console.error("Exception opening new comm"),e}}async _handleCommClose(e){this._assertCurrentMessage(e);const t=e.content,n=this._comms.get(t.comm_id);if(!n)return void console.error("Comm not found for comm id "+t.comm_id);this._unregisterComm(n.commId);const i=n.onClose;i&&await i(e),n.dispose()}async _handleCommMsg(e){this._assertCurrentMessage(e);const t=e.content,n=this._comms.get(t.comm_id);if(!n)return;const i=n.onMsg;i&&await i(e)}_unregisterComm(e){this._comms.delete(e)}_updateConnectionStatus(e){if(this._connectionStatus!==e){if(this._connectionStatus=e,"connecting"!==e&&(this._reconnectAttempt=0,clearTimeout(this._reconnectTimeout)),"dead"!==this.status)if("connected"===e){let e=this._kernelSession===v,t=this.requestKernelInfo(),n=!1,i=()=>{n||(n=!0,e&&this._kernelSession===v&&(this._kernelSession=""),clearTimeout(r),this._pendingMessages.length>0&&this._sendPending())};t.then(i);let r=setTimeout(i,3e3)}else this._updateStatus("unknown");this._connectionStatusChanged.emit(e)}}async _handleMessage(e){var t,n;let i=!1;if(e.parent_header&&"iopub"===e.channel&&(c.isDisplayDataMsg(e)||c.isUpdateDisplayDataMsg(e)||c.isExecuteResultMsg(e))){const n=(null!==(t=e.content.transient)&&void 0!==t?t:{}).display_id;n&&(i=await this._handleDisplayId(n,e),this._assertCurrentMessage(e))}if(!i&&e.parent_header){const t=e.parent_header,i=null===(n=this._futures)||void 0===n?void 0:n.get(t.msg_id);if(i)await i.handleMsg(e),this._assertCurrentMessage(e);else{const n=t.session===this.clientId;"iopub"!==e.channel&&n&&this._unhandledMessage.emit(e)}}if("iopub"===e.channel){switch(e.header.msg_type){case"status":{const t=e.content.execution_state;"restarting"===t&&Promise.resolve().then((async()=>{this._updateStatus("autorestarting"),this._clearKernelState(),await this.reconnect()})),this._updateStatus(t);break}case"comm_open":this.handleComms&&await this._handleCommOpen(e);break;case"comm_msg":this.handleComms&&await this._handleCommMsg(e);break;case"comm_close":this.handleComms&&await this._handleCommClose(e)}this.isDisposed||(this._assertCurrentMessage(e),this._iopubMessage.emit(e))}}_reconnect(){if(this._errorIfDisposed(),clearTimeout(this._reconnectTimeout),this._reconnectAttempt{if(t){if("undefined"==typeof requirejs)throw new Error("requirejs not found");requirejs([t],(n=>{void 0===n[e]?r(new Error(`Object '${e}' not found in module '${t}'`)):i(n[e])}),r)}else(null==n?void 0:n[e])?i(n[e]):r(new Error(`Object '${e}' not found in registry`))}))},e.getRandomIntInclusive=function(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e}}(_||(_={}))},79178:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelShellFutureHandler=t.KernelControlFutureHandler=t.KernelFutureHandler=void 0;const o=n(65168),a=n(34643),l=s(n(41632));class u extends a.DisposableDelegate{constructor(e,t,n,i,r){super(e),this._status=0,this._stdin=d.noOp,this._iopub=d.noOp,this._reply=d.noOp,this._done=new o.PromiseDelegate,this._hooks=new d.HookList,this._disposeOnDone=!0,this._msg=t,n||this._setFlag(d.KernelFutureFlag.GotReply),this._disposeOnDone=i,this._kernel=r}get msg(){return this._msg}get done(){return this._done.promise}get onReply(){return this._reply}set onReply(e){this._reply=e}get onIOPub(){return this._iopub}set onIOPub(e){this._iopub=e}get onStdin(){return this._stdin}set onStdin(e){this._stdin=e}registerMessageHook(e){if(this.isDisposed)throw new Error("Kernel future is disposed");this._hooks.add(e)}removeMessageHook(e){this.isDisposed||this._hooks.remove(e)}sendInputReply(e,t){this._kernel.sendInputReply(e,t)}dispose(){this._stdin=d.noOp,this._iopub=d.noOp,this._reply=d.noOp,this._hooks=null,this._testFlag(d.KernelFutureFlag.IsDone)||(this._done.promise.catch((()=>{})),this._done.reject(new Error(`Canceled future for ${this.msg.header.msg_type} message before replies were done`))),super.dispose()}async handleMsg(e){switch(e.channel){case"control":case"shell":e.channel===this.msg.channel&&e.parent_header.msg_id===this.msg.header.msg_id&&await this._handleReply(e);break;case"stdin":await this._handleStdin(e);break;case"iopub":await this._handleIOPub(e)}}async _handleReply(e){const t=this._reply;t&&await t(e),this._replyMsg=e,this._setFlag(d.KernelFutureFlag.GotReply),this._testFlag(d.KernelFutureFlag.GotIdle)&&this._handleDone()}async _handleStdin(e){this._kernel.hasPendingInput=!0;const t=this._stdin;t&&await t(e)}async _handleIOPub(e){const t=await this._hooks.process(e),n=this._iopub;t&&n&&await n(e),l.isStatusMsg(e)&&"idle"===e.content.execution_state&&(this._setFlag(d.KernelFutureFlag.GotIdle),this._testFlag(d.KernelFutureFlag.GotReply)&&this._handleDone())}_handleDone(){this._testFlag(d.KernelFutureFlag.IsDone)||(this._setFlag(d.KernelFutureFlag.IsDone),this._done.resolve(this._replyMsg),this._disposeOnDone&&this.dispose())}_testFlag(e){return 0!=(this._status&e)}_setFlag(e){this._status|=e}}var d;t.KernelFutureHandler=u,t.KernelControlFutureHandler=class extends u{},t.KernelShellFutureHandler=class extends u{},function(e){e.noOp=()=>{};const t="function"==typeof requestAnimationFrame?requestAnimationFrame:setImmediate;let n;e.HookList=class{constructor(){this._hooks=[]}add(e){this.remove(e),this._hooks.push(e)}remove(e){const t=this._hooks.indexOf(e);t>=0&&(this._hooks[t]=null,this._scheduleCompact())}async process(e){await this._processing;const t=new o.PromiseDelegate;let n;this._processing=t.promise;for(let i=this._hooks.length-1;i>=0;i--){const r=this._hooks[i];if(null!==r){try{n=await r(e)}catch(e){n=!0,console.error(e)}if(!1===n)return t.resolve(void 0),!1}}return t.resolve(void 0),!0}_scheduleCompact(){this._compactScheduled||(this._compactScheduled=!0,t((()=>{this._processing=this._processing.then((()=>{this._compactScheduled=!1,this._compact()}))})))}_compact(){let e=0;for(let t=0,n=this._hooks.length;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},72810:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KernelManager=void 0;const i=n(59033),r=n(60544),s=n(16914),o=n(92918),a=n(60925),l=n(82094);class u extends o.BaseManager{constructor(e={}){var t;super(e),this._isReady=!1,this._kernelConnections=new Set,this._models=new Map,this._runningChanged=new r.Signal(this),this._connectionFailure=new r.Signal(this),this._pollModels=new i.Poll({auto:!1,factory:()=>this.requestRunning(),frequency:{interval:1e4,backoff:!0,max:3e5},name:"@jupyterlab/services:KernelManager#models",standby:null!==(t=e.standby)&&void 0!==t?t:"when-hidden"}),this._ready=(async()=>{await this._pollModels.start(),await this._pollModels.tick,this._isReady=!0})()}get isReady(){return this._isReady}get ready(){return this._ready}get runningChanged(){return this._runningChanged}get connectionFailure(){return this._connectionFailure}dispose(){this.isDisposed||(this._models.clear(),this._kernelConnections.forEach((e=>e.dispose())),this._pollModels.dispose(),super.dispose())}connectTo(e){var t;const{id:n}=e.model;let i=null===(t=e.handleComms)||void 0===t||t;if(void 0===e.handleComms)for(const e of this._kernelConnections)if(e.id===n&&e.handleComms){i=!1;break}const r=new l.KernelConnection({handleComms:i,...e,serverSettings:this.serverSettings});return this._onStarted(r),this._models.has(n)||this.refreshRunning().catch((()=>{})),r}running(){return this._models.values()}async refreshRunning(){await this._pollModels.refresh(),await this._pollModels.tick}async startNew(e={},t={}){const n=await(0,a.startNew)(e,this.serverSettings);return this.connectTo({...t,model:n})}async shutdown(e){await(0,a.shutdownKernel)(e,this.serverSettings),await this.refreshRunning()}async shutdownAll(){await this.refreshRunning(),await Promise.all([...this._models.keys()].map((e=>(0,a.shutdownKernel)(e,this.serverSettings)))),await this.refreshRunning()}async findById(e){return this._models.has(e)||await this.refreshRunning(),this._models.get(e)}async requestRunning(){var e,t;let n;try{n=await(0,a.listRunning)(this.serverSettings)}catch(n){throw(n instanceof s.ServerConnection.NetworkError||503===(null===(e=n.response)||void 0===e?void 0:e.status)||424===(null===(t=n.response)||void 0===t?void 0:t.status))&&this._connectionFailure.emit(n),n}this.isDisposed||this._models.size===n.length&&n.every((e=>{const t=this._models.get(e.id);return!!t&&t.connections===e.connections&&t.execution_state===e.execution_state&&t.last_activity===e.last_activity&&t.name===e.name&&t.reason===e.reason&&t.traceback===e.traceback}))||(this._models=new Map(n.map((e=>[e.id,e]))),this._kernelConnections.forEach((e=>{this._models.has(e.id)||e.handleShutdown()})),this._runningChanged.emit(n))}_onStarted(e){this._kernelConnections.add(e),e.statusChanged.connect(this._onStatusChanged,this),e.disposed.connect(this._onDisposed,this)}_onDisposed(e){this._kernelConnections.delete(e),this.refreshRunning().catch((()=>{}))}_onStatusChanged(e,t){"dead"===t&&this.refreshRunning().catch((()=>{}))}}t.KernelManager=u,function(e){e.NoopManager=class extends e{constructor(){super(...arguments),this._readyPromise=new Promise((()=>{}))}get isActive(){return!1}get parentReady(){return super.ready}async startNew(e={},t={}){return Promise.reject(new Error("Not implemented in no-op Kernel Manager"))}connectTo(e){throw new Error("Not implemented in no-op Kernel Manager")}async shutdown(e){return Promise.reject(new Error("Not implemented in no-op Kernel Manager"))}get ready(){return this.parentReady.then((()=>this._readyPromise))}async requestRunning(){return Promise.resolve()}}}(u=t.KernelManager||(t.KernelManager={}))},41632:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.supportedKernelWebSocketProtocols=t.isInputReplyMsg=t.isInputRequestMsg=t.isDebugReplyMsg=t.isDebugRequestMsg=t.isExecuteReplyMsg=t.isInfoRequestMsg=t.isCommMsgMsg=t.isCommCloseMsg=t.isCommOpenMsg=t.isDebugEventMsg=t.isClearOutputMsg=t.isStatusMsg=t.isErrorMsg=t.isExecuteResultMsg=t.isExecuteInputMsg=t.isUpdateDisplayDataMsg=t.isDisplayDataMsg=t.isStreamMsg=t.createMessage=void 0;const i=n(65168);t.createMessage=function(e){var t,n,r,s,o;return{buffers:null!==(t=e.buffers)&&void 0!==t?t:[],channel:e.channel,content:e.content,header:{date:(new Date).toISOString(),msg_id:null!==(n=e.msgId)&&void 0!==n?n:i.UUID.uuid4(),msg_type:e.msgType,session:e.session,username:null!==(r=e.username)&&void 0!==r?r:"",version:"5.2"},metadata:null!==(s=e.metadata)&&void 0!==s?s:{},parent_header:null!==(o=e.parentHeader)&&void 0!==o?o:{}}},t.isStreamMsg=function(e){return"stream"===e.header.msg_type},t.isDisplayDataMsg=function(e){return"display_data"===e.header.msg_type},t.isUpdateDisplayDataMsg=function(e){return"update_display_data"===e.header.msg_type},t.isExecuteInputMsg=function(e){return"execute_input"===e.header.msg_type},t.isExecuteResultMsg=function(e){return"execute_result"===e.header.msg_type},t.isErrorMsg=function(e){return"error"===e.header.msg_type},t.isStatusMsg=function(e){return"status"===e.header.msg_type},t.isClearOutputMsg=function(e){return"clear_output"===e.header.msg_type},t.isDebugEventMsg=function(e){return"debug_event"===e.header.msg_type},t.isCommOpenMsg=function(e){return"comm_open"===e.header.msg_type},t.isCommCloseMsg=function(e){return"comm_close"===e.header.msg_type},t.isCommMsgMsg=function(e){return"comm_msg"===e.header.msg_type},t.isInfoRequestMsg=function(e){return"kernel_info_request"===e.header.msg_type},t.isExecuteReplyMsg=function(e){return"execute_reply"===e.header.msg_type},t.isDebugRequestMsg=function(e){return"debug_request"===e.header.msg_type},t.isDebugReplyMsg=function(e){return"debug_reply"===e.header.msg_type},t.isInputRequestMsg=function(e){return"input_request"===e.header.msg_type},t.isInputReplyMsg=function(e){return"input_reply"===e.header.msg_type},(t.supportedKernelWebSocketProtocols||(t.supportedKernelWebSocketProtocols={})).v1KernelWebsocketJupyterOrg="v1.kernel.websocket.jupyter.org"},60925:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getKernelModel=t.shutdownKernel=t.interruptKernel=t.restartKernel=t.startNew=t.listRunning=t.KERNEL_SERVICE_URL=void 0;const i=n(22700),r=n(18920),s=n(95537);t.KERNEL_SERVICE_URL="api/kernels",t.listRunning=async function(e=i.ServerConnection.makeSettings()){const n=r.URLExt.join(e.baseUrl,t.KERNEL_SERVICE_URL),o=await i.ServerConnection.makeRequest(n,{},e);if(200!==o.status)throw await i.ServerConnection.ResponseError.create(o);const a=await o.json();return(0,s.validateModels)(a),a},t.startNew=async function(e={},n=i.ServerConnection.makeSettings()){const o=r.URLExt.join(n.baseUrl,t.KERNEL_SERVICE_URL),a={method:"POST",body:JSON.stringify(e)},l=await i.ServerConnection.makeRequest(o,a,n);if(201!==l.status)throw await i.ServerConnection.ResponseError.create(l);const u=await l.json();return(0,s.validateModel)(u),u},t.restartKernel=async function(e,n=i.ServerConnection.makeSettings()){const o=r.URLExt.join(n.baseUrl,t.KERNEL_SERVICE_URL,encodeURIComponent(e),"restart"),a=await i.ServerConnection.makeRequest(o,{method:"POST"},n);if(200!==a.status)throw await i.ServerConnection.ResponseError.create(a);const l=await a.json();(0,s.validateModel)(l)},t.interruptKernel=async function(e,n=i.ServerConnection.makeSettings()){const s=r.URLExt.join(n.baseUrl,t.KERNEL_SERVICE_URL,encodeURIComponent(e),"interrupt"),o=await i.ServerConnection.makeRequest(s,{method:"POST"},n);if(204!==o.status)throw await i.ServerConnection.ResponseError.create(o)},t.shutdownKernel=async function(e,n=i.ServerConnection.makeSettings()){const s=r.URLExt.join(n.baseUrl,t.KERNEL_SERVICE_URL,encodeURIComponent(e)),o=await i.ServerConnection.makeRequest(s,{method:"DELETE"},n);if(404===o.status){const t=`The kernel "${e}" does not exist on the server`;console.warn(t)}else if(204!==o.status)throw await i.ServerConnection.ResponseError.create(o)},t.getKernelModel=async function(e,n=i.ServerConnection.makeSettings()){const o=r.URLExt.join(n.baseUrl,t.KERNEL_SERVICE_URL,encodeURIComponent(e)),a=await i.ServerConnection.makeRequest(o,{},n);if(404===a.status)return;if(200!==a.status)throw await i.ServerConnection.ResponseError.create(a);const l=await a.json();return(0,s.validateModel)(l),l}},67411:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.deserialize=t.serialize=void 0;const o=s(n(41632));var a;t.serialize=function(e,t=""){return t===o.supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg?a.serializeV1KernelWebsocketJupyterOrg(e):a.serializeDefault(e)},t.deserialize=function(e,t=""){return t===o.supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg?a.deserializeV1KernelWebsocketJupyterOrg(e):a.deserializeDefault(e)},function(e){e.deserializeV1KernelWebsocketJupyterOrg=function(e){let t;const n=new DataView(e),i=Number(n.getBigUint64(0,!0));let r=[];for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateModels=t.validateModel=t.validateMessage=void 0;const i=n(68193),r=["username","version","session","msg_id","msg_type"],s={stream:{name:"string",text:"string"},display_data:{data:"object",metadata:"object"},execute_input:{code:"string",execution_count:"number"},execute_result:{execution_count:"number",data:"object",metadata:"object"},error:{ename:"string",evalue:"string",traceback:"object"},status:{execution_state:["string",["starting","idle","busy","restarting","dead"]]},clear_output:{wait:"boolean"},comm_open:{comm_id:"string",target_name:"string",data:"object"},comm_msg:{comm_id:"string",data:"object"},comm_close:{comm_id:"string"},shutdown_reply:{restart:"boolean"}};function o(e){(0,i.validateProperty)(e,"name","string"),(0,i.validateProperty)(e,"id","string")}t.validateMessage=function(e){(0,i.validateProperty)(e,"metadata","object"),(0,i.validateProperty)(e,"content","object"),(0,i.validateProperty)(e,"channel","string"),function(e){for(let t=0;to(e)))}},55312:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelSpecAPI=t.KernelSpec=void 0;const a=s(n(20523));t.KernelSpec=a;const l=s(n(47352));t.KernelSpecAPI=l,o(n(73973),t)},20523:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},73973:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelSpecManager=void 0;const o=n(65168),a=n(59033),l=n(60544),u=s(n(47352)),d=n(92918);class c extends d.BaseManager{constructor(e={}){var t;super(e),this._isReady=!1,this._connectionFailure=new l.Signal(this),this._specs=null,this._specsChanged=new l.Signal(this),this._ready=Promise.all([this.requestSpecs()]).then((e=>{})).catch((e=>{})).then((()=>{this.isDisposed||(this._isReady=!0)})),this._pollSpecs=new a.Poll({auto:!1,factory:()=>this.requestSpecs(),frequency:{interval:61e3,backoff:!0,max:3e5},name:"@jupyterlab/services:KernelSpecManager#specs",standby:null!==(t=e.standby)&&void 0!==t?t:"when-hidden"}),this.ready.then((()=>{this._pollSpecs.start()}))}get isReady(){return this._isReady}get ready(){return this._ready}get specs(){return this._specs}get specsChanged(){return this._specsChanged}get connectionFailure(){return this._connectionFailure}dispose(){this._pollSpecs.dispose(),super.dispose()}async refreshSpecs(){await this._pollSpecs.refresh(),await this._pollSpecs.tick}async requestSpecs(){const e=await u.getSpecs(this.serverSettings);this.isDisposed||o.JSONExt.deepEqual(e,this._specs)||(this._specs=e,this._specsChanged.emit(e))}}t.KernelSpecManager=c},47352:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSpecs=void 0;const i=n(22700),r=n(80007),s=n(18920);t.getSpecs=async function(e=i.ServerConnection.makeSettings()){const t=s.URLExt.join(e.baseUrl,"api/kernelspecs"),n=await i.ServerConnection.makeRequest(t,{},e);if(200!==n.status)throw await i.ServerConnection.ResponseError.create(n);const o=await n.json();return(0,r.validateSpecModels)(o)}},80007:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateSpecModels=t.validateSpecModel=void 0;const i=n(68193);function r(e){const t=e.spec;if(!t)throw new Error("Invalid kernel spec");(0,i.validateProperty)(e,"name","string"),(0,i.validateProperty)(e,"resources","object"),(0,i.validateProperty)(t,"language","string"),(0,i.validateProperty)(t,"display_name","string"),(0,i.validateProperty)(t,"argv","array");let n=null;t.hasOwnProperty("metadata")&&((0,i.validateProperty)(t,"metadata","object"),n=t.metadata);let r=null;return t.hasOwnProperty("env")&&((0,i.validateProperty)(t,"env","object"),r=t.env),{name:e.name,resources:e.resources,language:t.language,display_name:t.display_name,argv:t.argv,metadata:n,env:r}}t.validateSpecModel=r,t.validateSpecModels=function(e){if(!e.hasOwnProperty("kernelspecs"))throw new Error("No kernelspecs found");let t=Object.keys(e.kernelspecs);const n=Object.create(null);let i=e.default;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceManager=void 0;const i=n(60544),r=n(81611),s=n(57593),o=n(93354),a=n(10582),l=n(55312),u=n(54933),d=n(22700),c=n(67054),h=n(6052),p=n(98235),g=n(67523),f=n(10087);t.ServiceManager=class{constructor(e={}){var t,n;this._isDisposed=!1,this._connectionFailure=new i.Signal(this),this._isReady=!1;const m=e.defaultDrive,v=null!==(t=e.serverSettings)&&void 0!==t?t:d.ServerConnection.makeSettings(),b={defaultDrive:m,serverSettings:v,standby:null!==(n=e.standby)&&void 0!==n?n:"when-hidden"};this.serverSettings=v,this.contents=e.contents||new s.ContentsManager(b),this.events=e.events||new o.EventManager(b),this.kernels=e.kernels||new a.KernelManager(b),this.sessions=e.sessions||new c.SessionManager({...b,kernelManager:this.kernels}),this.settings=e.settings||new h.SettingManager(b),this.terminals=e.terminals||new p.TerminalManager(b),this.builder=e.builder||new r.BuildManager(b),this.workspaces=e.workspaces||new f.WorkspaceManager(b),this.nbconvert=e.nbconvert||new u.NbConvertManager(b),this.kernelspecs=e.kernelspecs||new l.KernelSpecManager(b),this.user=e.user||new g.UserManager(b),this.kernelspecs.connectionFailure.connect(this._onConnectionFailure,this),this.sessions.connectionFailure.connect(this._onConnectionFailure,this),this.terminals.connectionFailure.connect(this._onConnectionFailure,this);const _=[this.sessions.ready,this.kernelspecs.ready];this.terminals.isAvailable()&&_.push(this.terminals.ready),this._readyPromise=Promise.all(_).then((()=>{this._isReady=!0}))}get connectionFailure(){return this._connectionFailure}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,i.Signal.clearData(this),this.contents.dispose(),this.events.dispose(),this.sessions.dispose(),this.terminals.dispose())}get isReady(){return this._isReady}get ready(){return this._readyPromise}_onConnectionFailure(e,t){this._connectionFailure.emit(t)}}},54933:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NbConvertManager=void 0;const i=n(18920),r=n(22700),s=n(65168);t.NbConvertManager=class{constructor(e={}){var t;this._exportFormats=null,this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:r.ServerConnection.makeSettings()}async fetchExportFormats(){this._requestingFormats=new s.PromiseDelegate,this._exportFormats=null;const e=this.serverSettings.baseUrl,t=i.URLExt.join(e,"api/nbconvert"),{serverSettings:n}=this,o=await r.ServerConnection.makeRequest(t,{},n);if(200!==o.status)throw await r.ServerConnection.ResponseError.create(o);const a=await o.json(),l={};return Object.keys(a).forEach((function(e){const t=a[e].output_mimetype;l[e]={output_mimetype:t}})),this._exportFormats=l,this._requestingFormats.resolve(l),l}async getExportFormats(e=!0){return this._requestingFormats?this._requestingFormats.promise:e||!this._exportFormats?await this.fetchExportFormats():this._exportFormats}}},22700:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServerConnection=void 0;const i=n(18920);let r;var s,o;r="undefined"==typeof window?n(32195):WebSocket,function(e){e.makeSettings=function(e){return o.makeSettings(e)},e.makeRequest=function(e,t,n){return o.handleRequest(e,t,n)};class t extends Error{static async create(e){try{const n=await e.json(),{message:i,traceback:r}=n;return r&&console.error(r),new t(e,null!=i?i:t._defaultMessage(e),null!=r?r:"")}catch(n){return console.debug(n),new t(e)}}constructor(e,n=t._defaultMessage(e),i=""){super(n),this.response=e,this.traceback=i}static _defaultMessage(e){return`Invalid response: ${e.status} ${e.statusText}`}}e.ResponseError=t;class n extends TypeError{constructor(e){super(e.message),this.stack=e.stack}}e.NetworkError=n}(s=t.ServerConnection||(t.ServerConnection={})),function(e){e.makeSettings=function(e={}){var t;const n=i.PageConfig.getBaseUrl(),s=i.PageConfig.getWsUrl(),o=i.URLExt.normalize(e.baseUrl)||n;let a=e.wsUrl;return a||o!==n||(a=s),a||0!==o.indexOf("http")||(a="ws"+o.slice(4)),a=null!=a?a:s,{init:{cache:"no-store",credentials:"same-origin"},fetch,Headers,Request,WebSocket:r,token:i.PageConfig.getToken(),appUrl:i.PageConfig.getOption("appUrl"),appendToken:"undefined"==typeof window||"undefined"!=typeof process&&void 0!==(null===(t=null===process||void 0===process?void 0:process.env)||void 0===t?void 0:t.JEST_WORKER_ID)||i.URLExt.getHostName(n)!==i.URLExt.getHostName(a),...e,baseUrl:o,wsUrl:a}},e.handleRequest=function(e,t,n){var i;if(0!==e.indexOf(n.baseUrl))throw new Error("Can only be used for notebook server requests");"no-store"===(null!==(i=t.cache)&&void 0!==i?i:n.init.cache)&&(e+=(/\?/.test(e)?"&":"?")+(new Date).getTime());const r=new n.Request(e,{...n.init,...t});let o=!1;if(n.token&&(o=!0,r.headers.append("Authorization",`token ${n.token}`)),"undefined"!=typeof document&&(null===document||void 0===document?void 0:document.cookie)){const e=function(e){const t=document.cookie.match("\\b_xsrf=([^;]*)\\b");return null==t?void 0:t[1]}();void 0!==e&&(o=!0,r.headers.append("X-XSRFToken",e))}return!r.headers.has("Content-Type")&&o&&r.headers.set("Content-Type","application/json"),n.fetch.call(null,r).catch((e=>{throw new s.NetworkError(e)}))}}(o||(o={}))},75575:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SessionConnection=void 0;const i=n(60544),r=n(16914),s=n(28351),o=n(65168);t.SessionConnection=class{constructor(e){var t,n,s,a;this._id="",this._path="",this._name="",this._type="",this._kernel=null,this._isDisposed=!1,this._disposed=new i.Signal(this),this._kernelChanged=new i.Signal(this),this._statusChanged=new i.Signal(this),this._connectionStatusChanged=new i.Signal(this),this._pendingInput=new i.Signal(this),this._iopubMessage=new i.Signal(this),this._unhandledMessage=new i.Signal(this),this._anyMessage=new i.Signal(this),this._propertyChanged=new i.Signal(this),this._id=e.model.id,this._name=e.model.name,this._path=e.model.path,this._type=e.model.type,this._username=null!==(t=e.username)&&void 0!==t?t:"",this._clientId=null!==(n=e.clientId)&&void 0!==n?n:o.UUID.uuid4(),this._connectToKernel=e.connectToKernel,this._kernelConnectionOptions=null!==(s=e.kernelConnectionOptions)&&void 0!==s?s:{},this.serverSettings=null!==(a=e.serverSettings)&&void 0!==a?a:r.ServerConnection.makeSettings(),this.setupKernel(e.model.kernel)}get disposed(){return this._disposed}get kernelChanged(){return this._kernelChanged}get statusChanged(){return this._statusChanged}get connectionStatusChanged(){return this._connectionStatusChanged}get pendingInput(){return this._pendingInput}get iopubMessage(){return this._iopubMessage}get unhandledMessage(){return this._unhandledMessage}get anyMessage(){return this._anyMessage}get propertyChanged(){return this._propertyChanged}get id(){return this._id}get kernel(){return this._kernel}get path(){return this._path}get type(){return this._type}get name(){return this._name}get model(){return{id:this.id,kernel:this.kernel&&{id:this.kernel.id,name:this.kernel.name},path:this._path,type:this._type,name:this._name}}get isDisposed(){return this._isDisposed}update(e){const t=this.model;if(this._path=e.path,this._name=e.name,this._type=e.type,null===this._kernel&&null!==e.kernel||null!==this._kernel&&null===e.kernel||null!==this._kernel&&null!==e.kernel&&this._kernel.id!==e.kernel.id){null!==this._kernel&&this._kernel.dispose();const t=this._kernel||null;this.setupKernel(e.kernel);const n=this._kernel||null;this._kernelChanged.emit({name:"kernel",oldValue:t,newValue:n})}this._handleModelChange(t)}dispose(){if(!this.isDisposed){if(this._isDisposed=!0,this._disposed.emit(),this._kernel){this._kernel.dispose();const e=this._kernel;this._kernel=null;const t=this._kernel;this._kernelChanged.emit({name:"kernel",oldValue:e,newValue:t})}i.Signal.clearData(this)}}async setPath(e){if(this.isDisposed)throw new Error("Session is disposed");await this._patch({path:e})}async setName(e){if(this.isDisposed)throw new Error("Session is disposed");await this._patch({name:e})}async setType(e){if(this.isDisposed)throw new Error("Session is disposed");await this._patch({type:e})}async changeKernel(e){if(this.isDisposed)throw new Error("Session is disposed");return await this._patch({kernel:e}),this.kernel}async shutdown(){if(this.isDisposed)throw new Error("Session is disposed");await(0,s.shutdownSession)(this.id,this.serverSettings),this.dispose()}setupKernel(e){if(null===e)return void(this._kernel=null);const t=this._connectToKernel({...this._kernelConnectionOptions,model:e,username:this._username,clientId:this._clientId,serverSettings:this.serverSettings});this._kernel=t,t.statusChanged.connect(this.onKernelStatus,this),t.connectionStatusChanged.connect(this.onKernelConnectionStatus,this),t.pendingInput.connect(this.onPendingInput,this),t.unhandledMessage.connect(this.onUnhandledMessage,this),t.iopubMessage.connect(this.onIOPubMessage,this),t.anyMessage.connect(this.onAnyMessage,this)}onKernelStatus(e,t){this._statusChanged.emit(t)}onKernelConnectionStatus(e,t){this._connectionStatusChanged.emit(t)}onPendingInput(e,t){this._pendingInput.emit(t)}onIOPubMessage(e,t){this._iopubMessage.emit(t)}onUnhandledMessage(e,t){this._unhandledMessage.emit(t)}onAnyMessage(e,t){this._anyMessage.emit(t)}async _patch(e){const t=await(0,s.updateSession)({...e,id:this._id},this.serverSettings);return this.update(t),t}_handleModelChange(e){e.name!==this._name&&this._propertyChanged.emit("name"),e.type!==this._type&&this._propertyChanged.emit("type"),e.path!==this._path&&this._propertyChanged.emit("path")}}},67054:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t},o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.SessionAPI=t.Session=void 0;const a=s(n(90658));t.Session=a;const l=s(n(28351));t.SessionAPI=l,o(n(6699),t)},6699:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SessionManager=void 0;const i=n(59033),r=n(60544),s=n(22700),o=n(92918),a=n(75575),l=n(28351);class u extends o.BaseManager{constructor(e){var t;super(e),this._isReady=!1,this._sessionConnections=new Set,this._models=new Map,this._runningChanged=new r.Signal(this),this._connectionFailure=new r.Signal(this),this._connectToKernel=e=>this._kernelManager.connectTo(e),this._kernelManager=e.kernelManager,this._pollModels=new i.Poll({auto:!1,factory:()=>this.requestRunning(),frequency:{interval:1e4,backoff:!0,max:3e5},name:"@jupyterlab/services:SessionManager#models",standby:null!==(t=e.standby)&&void 0!==t?t:"when-hidden"}),this._ready=(async()=>{await this._pollModels.start(),await this._pollModels.tick,this._kernelManager.isActive&&await this._kernelManager.ready,this._isReady=!0})()}get isReady(){return this._isReady}get ready(){return this._ready}get runningChanged(){return this._runningChanged}get connectionFailure(){return this._connectionFailure}dispose(){this.isDisposed||(this._models.clear(),this._sessionConnections.forEach((e=>e.dispose())),this._pollModels.dispose(),super.dispose())}connectTo(e){const t=new a.SessionConnection({...e,connectToKernel:this._connectToKernel,serverSettings:this.serverSettings});return this._onStarted(t),this._models.has(e.model.id)||this.refreshRunning().catch((()=>{})),t}running(){return this._models.values()}async refreshRunning(){await this._pollModels.refresh(),await this._pollModels.tick}async startNew(e,t={}){const n=await(0,l.startSession)(e,this.serverSettings);return await this.refreshRunning(),this.connectTo({...t,model:n})}async shutdown(e){await(0,l.shutdownSession)(e,this.serverSettings),await this.refreshRunning()}async shutdownAll(){await this.refreshRunning(),await Promise.all([...this._models.keys()].map((e=>(0,l.shutdownSession)(e,this.serverSettings)))),await this.refreshRunning()}async stopIfNeeded(e){try{const t=(await(0,l.listRunning)(this.serverSettings)).filter((t=>t.path===e));if(1===t.length){const e=t[0].id;await this.shutdown(e)}}catch(e){}}async findById(e){return this._models.has(e)||await this.refreshRunning(),this._models.get(e)}async findByPath(e){for(const t of this._models.values())if(t.path===e)return t;await this.refreshRunning();for(const t of this._models.values())if(t.path===e)return t}async requestRunning(){var e,t;let n;try{n=await(0,l.listRunning)(this.serverSettings)}catch(n){throw(n instanceof s.ServerConnection.NetworkError||503===(null===(e=n.response)||void 0===e?void 0:e.status)||424===(null===(t=n.response)||void 0===t?void 0:t.status))&&this._connectionFailure.emit(n),n}this.isDisposed||this._models.size===n.length&&n.every((e=>{var t,n,i,r;const s=this._models.get(e.id);return!!s&&(null===(t=s.kernel)||void 0===t?void 0:t.id)===(null===(n=e.kernel)||void 0===n?void 0:n.id)&&(null===(i=s.kernel)||void 0===i?void 0:i.name)===(null===(r=e.kernel)||void 0===r?void 0:r.name)&&s.name===e.name&&s.path===e.path&&s.type===e.type}))||(this._models=new Map(n.map((e=>[e.id,e]))),this._sessionConnections.forEach((e=>{this._models.has(e.id)?e.update(this._models.get(e.id)):e.dispose()})),this._runningChanged.emit(n))}_onStarted(e){this._sessionConnections.add(e),e.disposed.connect(this._onDisposed,this),e.propertyChanged.connect(this._onChanged,this),e.kernelChanged.connect(this._onChanged,this)}_onDisposed(e){this._sessionConnections.delete(e),this.refreshRunning().catch((()=>{}))}_onChanged(){this.refreshRunning().catch((()=>{}))}}t.SessionManager=u,function(e){e.NoopManager=class extends e{constructor(){super(...arguments),this._readyPromise=new Promise((()=>{}))}get isActive(){return!1}get parentReady(){return super.ready}async startNew(e,t={}){return Promise.reject(new Error("Not implemented in no-op Session Manager"))}connectTo(e){throw Error("Not implemented in no-op Session Manager")}get ready(){return this.parentReady.then((()=>this._readyPromise))}async shutdown(e){return Promise.reject(new Error("Not implemented in no-op Session Manager"))}async requestRunning(){return Promise.resolve()}}}(u=t.SessionManager||(t.SessionManager={}))},28351:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateSession=t.startSession=t.getSessionModel=t.shutdownSession=t.getSessionUrl=t.listRunning=t.SESSION_SERVICE_URL=void 0;const i=n(22700),r=n(18920),s=n(48775);function o(e,n){return r.URLExt.join(e,t.SESSION_SERVICE_URL,n)}t.SESSION_SERVICE_URL="api/sessions",t.listRunning=async function(e=i.ServerConnection.makeSettings()){const n=r.URLExt.join(e.baseUrl,t.SESSION_SERVICE_URL),o=await i.ServerConnection.makeRequest(n,{},e);if(200!==o.status)throw await i.ServerConnection.ResponseError.create(o);const a=await o.json();if(!Array.isArray(a))throw new Error("Invalid Session list");return a.forEach((e=>{(0,s.updateLegacySessionModel)(e),(0,s.validateModel)(e)})),a},t.getSessionUrl=o,t.shutdownSession=async function(e,t=i.ServerConnection.makeSettings()){var n;const r=o(t.baseUrl,e),s=await i.ServerConnection.makeRequest(r,{method:"DELETE"},t);if(404===s.status){const t=null!==(n=(await s.json()).message)&&void 0!==n?n:`The session "${e}"" does not exist on the server`;console.warn(t)}else{if(410===s.status)throw new i.ServerConnection.ResponseError(s,"The kernel was deleted but the session was not");if(204!==s.status)throw await i.ServerConnection.ResponseError.create(s)}},t.getSessionModel=async function(e,t=i.ServerConnection.makeSettings()){const n=o(t.baseUrl,e),r=await i.ServerConnection.makeRequest(n,{},t);if(200!==r.status)throw await i.ServerConnection.ResponseError.create(r);const a=await r.json();return(0,s.updateLegacySessionModel)(a),(0,s.validateModel)(a),a},t.startSession=async function(e,n=i.ServerConnection.makeSettings()){const o=r.URLExt.join(n.baseUrl,t.SESSION_SERVICE_URL),a={method:"POST",body:JSON.stringify(e)},l=await i.ServerConnection.makeRequest(o,a,n);if(201!==l.status)throw await i.ServerConnection.ResponseError.create(l);const u=await l.json();return(0,s.updateLegacySessionModel)(u),(0,s.validateModel)(u),u},t.updateSession=async function(e,t=i.ServerConnection.makeSettings()){const n=o(t.baseUrl,e.id),r={method:"PATCH",body:JSON.stringify(e)},a=await i.ServerConnection.makeRequest(n,r,t);if(200!==a.status)throw await i.ServerConnection.ResponseError.create(a);const l=await a.json();return(0,s.updateLegacySessionModel)(l),(0,s.validateModel)(l),l}},90658:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},48775:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateModels=t.updateLegacySessionModel=t.validateModel=void 0;const i=n(95537),r=n(68193);function s(e){(0,r.validateProperty)(e,"id","string"),(0,r.validateProperty)(e,"type","string"),(0,r.validateProperty)(e,"name","string"),(0,r.validateProperty)(e,"path","string"),(0,r.validateProperty)(e,"kernel","object"),(0,i.validateModel)(e.kernel)}t.validateModel=s,t.updateLegacySessionModel=function(e){void 0===e.path&&void 0!==e.notebook&&(e.path=e.notebook.path,e.type="notebook",e.name="")},t.validateModels=function(e){if(!Array.isArray(e))throw new Error("Invalid session list");e.forEach((e=>s(e)))}},6052:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingManager=void 0;const i=n(18920),r=n(34116),s=n(22700);class o extends r.DataConnector{constructor(e={}){var t;super(),this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:s.ServerConnection.makeSettings()}async fetch(e){if(!e)throw new Error("Plugin `id` parameter is required for settings fetch.");const{serverSettings:t}=this,{baseUrl:n,appUrl:i}=t,{makeRequest:r,ResponseError:o}=s.ServerConnection,l=n+i,u=a.url(l,e),d=await r(u,{},t);if(200!==d.status)throw await o.create(d);return d.json()}async list(e){var t,n,i,r;const{serverSettings:o}=this,{baseUrl:l,appUrl:u}=o,{makeRequest:d,ResponseError:c}=s.ServerConnection,h=l+u,p=a.url(h,"","ids"===e),g=await d(p,{},o);if(200!==g.status)throw new c(g);const f=await g.json(),m=null!==(n=null===(t=null==f?void 0:f.settings)||void 0===t?void 0:t.map((e=>e.id)))&&void 0!==n?n:[];let v=[];return e||(v=null!==(r=null===(i=null==f?void 0:f.settings)||void 0===i?void 0:i.map((e=>(e.data={composite:{},user:{}},e))))&&void 0!==r?r:[]),{ids:m,values:v}}async save(e,t){const{serverSettings:n}=this,{baseUrl:i,appUrl:r}=n,{makeRequest:o,ResponseError:l}=s.ServerConnection,u=i+r,d=a.url(u,e),c={body:JSON.stringify({raw:t}),method:"PUT"},h=await o(d,c,n);if(204!==h.status)throw new l(h)}}var a;t.SettingManager=o,function(e){e.url=function(e,t,n){const r=n?i.URLExt.objectToQueryString({ids_only:!0}):"";return`${i.URLExt.join(e,"api/settings",t)}${r}`}}(a||(a={}))},32195:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=WebSocket},98235:(e,t)=>{},67523:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserManager=void 0;const i=n(18920),r=n(65168),s=n(59033),o=n(60544),a=n(22700),l=n(92918),u="@jupyterlab/services:UserManager#user";class d extends l.BaseManager{constructor(e={}){var t;super(e),this._isReady=!1,this._userChanged=new o.Signal(this),this._connectionFailure=new o.Signal(this),this._ready=this.requestUser().then((()=>{this.isDisposed||(this._isReady=!0)})).catch((e=>new Promise((()=>{})))),this._pollSpecs=new s.Poll({auto:!1,factory:()=>this.requestUser(),frequency:{interval:61e3,backoff:!0,max:3e5},name:u,standby:null!==(t=e.standby)&&void 0!==t?t:"when-hidden"}),this.ready.then((()=>{this._pollSpecs.start()}))}get isReady(){return this._isReady}get ready(){return this._ready}get identity(){return this._identity}get permissions(){return this._permissions}get userChanged(){return this._userChanged}get connectionFailure(){return this._connectionFailure}dispose(){this._pollSpecs.dispose(),super.dispose()}async refreshUser(){await this._pollSpecs.refresh(),await this._pollSpecs.tick}async requestUser(){if(this.isDisposed)return;const{baseUrl:e}=this.serverSettings,{makeRequest:t,ResponseError:n}=a.ServerConnection,s=i.URLExt.join(e,"api/me"),o=await t(s,{},this.serverSettings);if(200!==o.status)throw await n.create(o);const l={identity:this._identity,permissions:this._permissions},d=await o.json(),h=d.identity,{localStorage:p}=window,g=p.getItem(u);if(g&&(!h.initials||!h.color)){const e=JSON.parse(g);h.initials=h.initials||e.initials||h.name.substring(0,1),h.color=h.color||e.color||c.getRandomColor()}r.JSONExt.deepEqual(d,l)||(this._identity=h,this._permissions=d.permissions,p.setItem(u,JSON.stringify(h)),this._userChanged.emit(d))}}var c;t.UserManager=d,function(e){const t=["var(--jp-collaborator-color1)","var(--jp-collaborator-color2)","var(--jp-collaborator-color3)","var(--jp-collaborator-color4)","var(--jp-collaborator-color5)","var(--jp-collaborator-color6)","var(--jp-collaborator-color7)"];e.getRandomColor=()=>t[Math.floor(Math.random()*t.length)]}(c||(c={}))},68193:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateProperty=void 0,t.validateProperty=function(e,t,n,i=[]){if(!e.hasOwnProperty(t))throw Error(`Missing property '${t}'`);const r=e[t];if(void 0!==n){let e=!0;switch(n){case"array":e=Array.isArray(r);break;case"object":e=void 0!==r;break;default:e=typeof r===n}if(!e)throw new Error(`Property '${t}' is not of type '${n}'`);if(i.length>0){let e=!0;switch(n){case"string":case"number":case"boolean":e=i.includes(r);break;default:e=i.findIndex((e=>e===r))>=0}if(!e)throw new Error(`Property '${t}' is not one of the valid values ${JSON.stringify(i)}`)}}}},10087:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WorkspaceManager=void 0;const i=n(18920),r=n(34116),s=n(22700);class o extends r.DataConnector{constructor(e={}){var t;super(),this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:s.ServerConnection.makeSettings()}async fetch(e){const{serverSettings:t}=this,{baseUrl:n,appUrl:i}=t,{makeRequest:r,ResponseError:o}=s.ServerConnection,l=n+i,u=a.url(l,e),d=await r(u,{},t);if(200!==d.status)throw await o.create(d);return d.json()}async list(){const{serverSettings:e}=this,{baseUrl:t,appUrl:n}=e,{makeRequest:i,ResponseError:r}=s.ServerConnection,o=t+n,l=a.url(o,""),u=await i(l,{},e);if(200!==u.status)throw await r.create(u);return(await u.json()).workspaces}async remove(e){const{serverSettings:t}=this,{baseUrl:n,appUrl:i}=t,{makeRequest:r,ResponseError:o}=s.ServerConnection,l=n+i,u=a.url(l,e),d=await r(u,{method:"DELETE"},t);if(204!==d.status)throw await o.create(d)}async save(e,t){const{serverSettings:n}=this,{baseUrl:i,appUrl:r}=n,{makeRequest:o,ResponseError:l}=s.ServerConnection,u=i+r,d=a.url(u,e),c={body:JSON.stringify(t),method:"PUT"},h=await o(d,c,n);if(204!==h.status)throw await l.create(h)}}var a;t.WorkspaceManager=o,function(e){e.url=function(e,t){return i.URLExt.join(e,"api/workspaces",t)}}(a||(a={}))},75619:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ActivityMonitor=void 0;const i=n(60544);t.ActivityMonitor=class{constructor(e){this._timer=-1,this._timeout=-1,this._isDisposed=!1,this._activityStopped=new i.Signal(this),e.signal.connect(this._onSignalFired,this),this._timeout=e.timeout||1e3}get activityStopped(){return this._activityStopped}get timeout(){return this._timeout}set timeout(e){this._timeout=e}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,i.Signal.clearData(this))}_onSignalFired(e,t){clearTimeout(this._timer),this._sender=e,this._args=t,this._timer=setTimeout((()=>{this._activityStopped.emit({sender:this._sender,args:this._args})}),this._timeout)}}},18920:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),r(n(75619),t),r(n(58769),t),r(n(54612),t),r(n(49230),t),r(n(77034),t),r(n(902),t),r(n(6400),t),r(n(41718),t),r(n(78305),t)},58769:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},54612:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MarkdownCodeBlocks=void 0,function(e){e.CODE_BLOCK_MARKER="```";const t=[".markdown",".mdown",".mkdn",".md",".mkd",".mdwn",".mdtxt",".mdtext",".text",".txt",".Rmd"];class n{constructor(e){this.startLine=e,this.code="",this.endLine=-1}}e.MarkdownCodeBlock=n,e.isMarkdown=function(e){return t.indexOf(e)>-1},e.findMarkdownCodeBlocks=function(t){if(!t||""===t)return[];const i=t.split("\n"),r=[];let s=null;for(let t=0;te===t||i&&e===i))},e.isDisabled=function(t){const n=t.indexOf(":");let i="";return-1!==n&&(i=t.slice(0,n)),e.disabled.some((e=>e===t||i&&e===i))}}(Extension=PageConfig.Extension||(PageConfig.Extension={}))})(PageConfig=exports.PageConfig||(exports.PageConfig={}))},77034:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PathExt=void 0;const i=n(21023);!function(e){function t(e){return 0===e.indexOf("/")&&(e=e.slice(1)),e}e.join=function(...e){const n=i.posix.join(...e);return"."===n?"":t(n)},e.basename=function(e,t){return i.posix.basename(e,t)},e.dirname=function(e){const n=t(i.posix.dirname(e));return"."===n?"":n},e.extname=function(e){return i.posix.extname(e)},e.normalize=function(e){return""===e?"":t(i.posix.normalize(e))},e.resolve=function(...e){return t(i.posix.resolve(...e))},e.relative=function(e,n){return t(i.posix.relative(e,n))},e.normalizeExtension=function(e){return e.length>0&&0!==e.indexOf(".")&&(e=`.${e}`),e},e.removeSlash=t}(t.PathExt||(t.PathExt={}))},902:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.signalToPromise=void 0;const i=n(65168);t.signalToPromise=function(e,t){const n=new i.PromiseDelegate;function r(){e.disconnect(s)}function s(e,t){r(),n.resolve([e,t])}return e.connect(s),(null!=t?t:0)>0&&setTimeout((()=>{r(),n.reject(`Signal not emitted within ${t} ms.`)}),t),n.promise}},6400:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Text=void 0,function(e){const t="𝐚".length>1;e.jsIndexToCharIndex=function(e,n){if(t)return e;let i=e;for(let t=0;t+1=55296&&e<=56319){const e=n.charCodeAt(t+1);e>=56320&&e<=57343&&(i--,t++)}}return i},e.charIndexToJsIndex=function(e,n){if(t)return e;let i=e;for(let e=0;e+1=55296&&t<=56319){const t=n.charCodeAt(e+1);t>=56320&&t<=57343&&(i++,e++)}}return i},e.camelCase=function(e,t=!1){return e.replace(/^(\w)|[\s-_:]+(\w)/g,(function(e,n,i){return i?i.toUpperCase():t?n.toUpperCase():n.toLowerCase()}))},e.titleCase=function(e){return(e||"").toLowerCase().split(" ").map((e=>e.charAt(0).toUpperCase()+e.slice(1))).join(" ")}}(t.Text||(t.Text={}))},41718:(e,t)=>{},78305:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.URLExt=void 0;const r=n(21023),s=i(n(64846));!function(e){function t(e){if("undefined"!=typeof document&&document){const t=document.createElement("a");return t.href=e,t}return(0,s.default)(e)}function n(...e){let t=(0,s.default)(e[0],{});const n=""===t.protocol&&t.slashes;n&&(t=(0,s.default)(e[0],"https:"+e[0]));const i=`${n?"":t.protocol}${t.slashes?"//":""}${t.auth}${t.auth?"@":""}${t.host}`,o=r.posix.join(`${i&&"/"!==t.pathname[0]?"/":""}${t.pathname}`,...e.slice(1));return`${i}${"."===o?"":o}`}e.parse=t,e.getHostName=function(e){return(0,s.default)(e).hostname},e.normalize=function(e){return e&&t(e).toString()},e.join=n,e.encodeParts=function(e){return n(...e.split("/").map(encodeURIComponent))},e.objectToQueryString=function(e){const t=Object.keys(e).filter((e=>e.length>0));return t.length?"?"+t.map((t=>{const n=encodeURIComponent(String(e[t]));return t+(n?"="+n:"")})).join("&"):""},e.queryStringToObject=function(e){return e.replace(/^\?/,"").split("&").reduce(((e,t)=>{const[n,i]=t.split("=");return n.length>0&&(e[n]=decodeURIComponent(i||"")),e}),{})},e.isLocal=function(e){const{protocol:n}=t(e);return(!n||0!==e.toLowerCase().indexOf(n))&&0!==e.indexOf("/")}}(t.URLExt||(t.URLExt={}))},32845:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DataConnector=void 0,t.DataConnector=class{async list(e){throw new Error("DataConnector#list method has not been implemented.")}async remove(e){throw new Error("DataConnector#remove method has not been implemented.")}async save(e,t){throw new Error("DataConnector#save method has not been implemented.")}}},34116:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),r(n(32845),t),r(n(33288),t),r(n(34803),t),r(n(26165),t),r(n(59329),t)},33288:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},34803:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RestorablePool=void 0;const i=n(65168),r=n(12571),s=n(60544);var o;t.RestorablePool=class{constructor(e){this._added=new s.Signal(this),this._current=null,this._currentChanged=new s.Signal(this),this._hasRestored=!1,this._isDisposed=!1,this._objects=new Set,this._restore=null,this._restored=new i.PromiseDelegate,this._updated=new s.Signal(this),this.namespace=e.namespace}get added(){return this._added}get current(){return this._current}set current(e){this._current!==e&&null!==e&&this._objects.has(e)&&(this._current=e,this._currentChanged.emit(this._current))}get currentChanged(){return this._currentChanged}get isDisposed(){return this._isDisposed}get restored(){return this._restored.promise}get size(){return this._objects.size}get updated(){return this._updated}async add(e){var t,n;if(e.isDisposed){const t="A disposed object cannot be added.";throw console.warn(t,e),new Error(t)}if(this._objects.has(e)){const t="This object already exists in the pool.";throw console.warn(t,e),new Error(t)}if(this._objects.add(e),e.disposed.connect(this._onInstanceDisposed,this),!o.injectedProperty.get(e)){if(this._restore){const{connector:i}=this._restore,r=this._restore.name(e);if(r){const s=`${this.namespace}:${r}`,a=null===(n=(t=this._restore).args)||void 0===n?void 0:n.call(t,e);o.nameProperty.set(e,s),await i.save(s,{data:a})}}this._added.emit(e)}}dispose(){this.isDisposed||(this._current=null,this._isDisposed=!0,this._objects.clear(),s.Signal.clearData(this))}find(e){const t=this._objects.values();for(const n of t)if(e(n))return n}forEach(e){this._objects.forEach(e)}filter(e){const t=[];return this.forEach((n=>{e(n)&&t.push(n)})),t}inject(e){return o.injectedProperty.set(e,!0),this.add(e)}has(e){return this._objects.has(e)}async restore(e){if(this._hasRestored)throw new Error("This pool has already been restored.");this._hasRestored=!0;const{command:t,connector:n,registry:i,when:r}=e,s=this.namespace,o=r?[n.list(s)].concat(r):[n.list(s)];this._restore=e;const[a]=await Promise.all(o),l=await Promise.all(a.ids.map((async(e,r)=>{const s=a.values[r],o=s&&s.data;return void 0===o?n.remove(e):i.execute(t,o).catch((()=>n.remove(e)))})));return this._restored.resolve(),l}async save(e){var t,n;const i=o.injectedProperty.get(e);if(!this._restore||!this.has(e)||i)return;const{connector:r}=this._restore,s=this._restore.name(e),a=o.nameProperty.get(e),l=s?`${this.namespace}:${s}`:"";if(a&&a!==l&&await r.remove(a),o.nameProperty.set(e,l),l){const i=null===(n=(t=this._restore).args)||void 0===n?void 0:n.call(t,e);await r.save(l,{data:i})}a!==l&&this._updated.emit(e)}_onInstanceDisposed(e){if(this._objects.delete(e),e===this._current&&(this._current=null,this._currentChanged.emit(this._current)),o.injectedProperty.get(e))return;if(!this._restore)return;const{connector:t}=this._restore,n=o.nameProperty.get(e);n&&t.remove(n)}},function(e){e.injectedProperty=new r.AttachedProperty({name:"injected",create:()=>!1}),e.nameProperty=new r.AttachedProperty({name:"name",create:()=>""})}(o||(o={}))},26165:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StateDB=void 0;const i=n(60544);class r{constructor(e={}){this._changed=new i.Signal(this);const{connector:t,transform:n}=e;this._connector=t||new r.Connector,this._ready=n?n.then((e=>{const{contents:t,type:n}=e;switch(n){case"cancel":default:return;case"clear":return this._clear();case"merge":return this._merge(t||{});case"overwrite":return this._overwrite(t||{})}})):Promise.resolve(void 0)}get changed(){return this._changed}async clear(){await this._ready,await this._clear()}async fetch(e){return await this._ready,this._fetch(e)}async list(e){return await this._ready,this._list(e)}async remove(e){await this._ready,await this._remove(e),this._changed.emit({id:e,type:"remove"})}async save(e,t){await this._ready,await this._save(e,t),this._changed.emit({id:e,type:"save"})}async toJSON(){await this._ready;const{ids:e,values:t}=await this._list();return t.reduce(((t,n,i)=>(t[e[i]]=n,t)),{})}async _clear(){await Promise.all((await this._list()).ids.map((e=>this._remove(e))))}async _fetch(e){const t=await this._connector.fetch(e);if(t)return JSON.parse(t).v}async _list(e=""){const{ids:t,values:n}=await this._connector.list(e);return{ids:t,values:n.map((e=>JSON.parse(e).v))}}async _merge(e){await Promise.all(Object.keys(e).map((t=>e[t]&&this._save(t,e[t]))))}async _overwrite(e){await this._clear(),await this._merge(e)}async _remove(e){return this._connector.remove(e)}async _save(e,t){return this._connector.save(e,JSON.stringify({v:t}))}}t.StateDB=r,function(e){e.Connector=class{constructor(){this._storage={}}async fetch(e){return this._storage[e]}async list(e=""){return Object.keys(this._storage).reduce(((t,n)=>(""!==e&&e!==n.split(":")[0]||(t.ids.push(n),t.values.push(this._storage[n])),t)),{ids:[],values:[]})}async remove(e){delete this._storage[e]}async save(e,t){this._storage[e]=t}}}(r=t.StateDB||(t.StateDB={}))},59329:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IStateDB=void 0;const i=n(65168);t.IStateDB=new i.Token("@jupyterlab/coreutils:IStateDB",'A service for the JupyterLab state database.\n Use this if you want to store data that will persist across page loads.\n See "state database" for more information.')},65168:function(e,t){!function(e){"use strict";e.JSONExt=void 0,function(e){function t(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e}function n(e){return Array.isArray(e)}function i(e,r){if(e===r)return!0;if(t(e)||t(r))return!1;let s=n(e),o=n(r);return s===o&&(s&&o?function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0,r=e.length;n>>0),e[n]=255&t,t>>>=8}e.Random=void 0,(e.Random||(e.Random={})).getRandomValues=(()=>{const e="undefined"!=typeof window&&(window.crypto||window.msCrypto)||null;return e&&"function"==typeof e.getRandomValues?function(t){return e.getRandomValues(t)}:t})(),e.UUID=void 0,(e.UUID||(e.UUID={})).uuid4=function(e){const t=new Uint8Array(16),n=new Array(256);for(let e=0;e<16;++e)n[e]="0"+e.toString(16);for(let e=16;e<256;++e)n[e]=e.toString(16);return function(){return e(t),t[6]=64|15&t[6],t[8]=128|63&t[8],n[t[0]]+n[t[1]]+n[t[2]]+n[t[3]]+"-"+n[t[4]]+n[t[5]]+"-"+n[t[6]]+n[t[7]]+"-"+n[t[8]]+n[t[9]]+"-"+n[t[10]]+n[t[11]]+n[t[12]]+n[t[13]]+n[t[14]]+n[t[15]]}}(e.Random.getRandomValues),e.MimeData=class{constructor(){this._types=[],this._values=[]}types(){return this._types.slice()}hasData(e){return-1!==this._types.indexOf(e)}getData(e){let t=this._types.indexOf(e);return-1!==t?this._values[t]:void 0}setData(e,t){this.clearData(e),this._types.push(e),this._values.push(t)}clearData(e){let t=this._types.indexOf(e);-1!==t&&(this._types.splice(t,1),this._values.splice(t,1))}clear(){this._types.length=0,this._values.length=0}},e.PromiseDelegate=class{constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}resolve(e){(0,this._resolve)(e)}reject(e){(0,this._reject)(e)}},e.Token=class{constructor(e,t){this.name=e,this.description=null!=t?t:"",this._tokenStructuralPropertyT=null}}}(t)},34643:(e,t,n)=>{"use strict";n.r(t),n.d(t,{DisposableDelegate:()=>r,DisposableSet:()=>o,ObservableDisposableDelegate:()=>s,ObservableDisposableSet:()=>a});var i=n(60544);class r{constructor(e){this._fn=e}get isDisposed(){return!this._fn}dispose(){if(!this._fn)return;let e=this._fn;this._fn=null,e()}}class s extends r{constructor(){super(...arguments),this._disposed=new i.Signal(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),i.Signal.clearData(this))}}class o{constructor(){this._isDisposed=!1,this._items=new Set}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,this._items.forEach((e=>{e.dispose()})),this._items.clear())}contains(e){return this._items.has(e)}add(e){this._items.add(e)}remove(e){this._items.delete(e)}clear(){this._items.clear()}}!function(e){e.from=function(t){let n=new e;for(const e of t)n.add(e);return n}}(o||(o={}));class a extends o{constructor(){super(...arguments),this._disposed=new i.Signal(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),i.Signal.clearData(this))}}!function(e){e.from=function(t){let n=new e;for(const e of t)n.add(e);return n}}(a||(a={}))},59033:(e,t,n)=>{"use strict";n.r(t),n.d(t,{Debouncer:()=>l,Poll:()=>o,RateLimiter:()=>a,Throttler:()=>u});var i,r=n(65168),s=n(60544);class o{constructor(e){var t;this._disposed=new s.Signal(this),this._lingered=0,this._tick=new r.PromiseDelegate,this._ticked=new s.Signal(this),this._factory=e.factory,this._linger=null!==(t=e.linger)&&void 0!==t?t:i.DEFAULT_LINGER,this._standby=e.standby||i.DEFAULT_STANDBY,this._state={...i.DEFAULT_STATE,timestamp:(new Date).getTime()};const n=e.frequency||{},o=Math.max(n.interval||0,n.max||0,i.DEFAULT_FREQUENCY.max);this.frequency={...i.DEFAULT_FREQUENCY,...n,max:o},this.name=e.name||i.DEFAULT_NAME,"auto"in e&&!e.auto||setTimeout((()=>this.start()))}get disposed(){return this._disposed}get frequency(){return this._frequency}set frequency(e){if(this.isDisposed||r.JSONExt.deepEqual(e,this.frequency||{}))return;let{backoff:t,interval:n,max:i}=e;if(n=Math.round(n),i=Math.round(i),"number"==typeof t&&t<1)throw new Error("Poll backoff growth factor must be at least 1");if((n<0||n>i)&&n!==o.NEVER)throw new Error("Poll interval must be between 0 and max");if(i>o.MAX_INTERVAL&&i!==o.NEVER)throw new Error(`Max interval must be less than ${o.MAX_INTERVAL}`);this._frequency={backoff:t,interval:n,max:i}}get isDisposed(){return"disposed"===this.state.phase}get standby(){return this._standby}set standby(e){this.isDisposed||this.standby===e||(this._standby=e)}get state(){return this._state}get tick(){return this._tick.promise}get ticked(){return this._ticked}async*[Symbol.asyncIterator](){for(;!this.isDisposed;)yield this.state,await this.tick.catch((()=>{}))}dispose(){this.isDisposed||(this._state={...i.DISPOSED_STATE,timestamp:(new Date).getTime()},this._tick.promise.catch((e=>{})),this._tick.reject(new Error(`Poll (${this.name}) is disposed.`)),this._disposed.emit(void 0),s.Signal.clearData(this))}refresh(){return this.schedule({cancel:({phase:e})=>"refreshed"===e,interval:o.IMMEDIATE,phase:"refreshed"})}async schedule(e={}){if(this.isDisposed)return;if(e.cancel&&e.cancel(this.state))return;const t=this._tick,n=new r.PromiseDelegate,i={interval:this.frequency.interval,payload:null,phase:"standby",timestamp:(new Date).getTime(),...e};this._state=i,this._tick=n,clearTimeout(this._timeout),this._ticked.emit(this.state),t.resolve(this),await t.promise,i.interval!==o.NEVER?this._timeout=setTimeout((()=>{this.isDisposed||this.tick!==n.promise||this._execute()}),i.interval):this._timeout=void 0}start(){return this.schedule({cancel:({phase:e})=>"constructed"!==e&&"standby"!==e&&"stopped"!==e,interval:o.IMMEDIATE,phase:"started"})}stop(){return this.schedule({cancel:({phase:e})=>"stopped"===e,interval:o.NEVER,phase:"stopped"})}get hidden(){return i.hidden}_execute(){let e="function"==typeof this.standby?this.standby():this.standby;if("never"===e?e=!1:"when-hidden"===e&&(this.hidden?e=++this._lingered>this._linger:(this._lingered=0,e=!1)),e)return void this.schedule();const t=this.tick;this._factory(this.state).then((e=>{this.isDisposed||this.tick!==t||this.schedule({payload:e,phase:"rejected"===this.state.phase?"reconnected":"resolved"})})).catch((e=>{this.isDisposed||this.tick!==t||this.schedule({interval:i.sleep(this.frequency,this.state),payload:e,phase:"rejected"})}))}}!function(e){e.IMMEDIATE=0,e.MAX_INTERVAL=2147483647,e.NEVER=1/0}(o||(o={})),function(e){e.DEFAULT_BACKOFF=3,e.DEFAULT_FREQUENCY={backoff:!0,interval:1e3,max:3e4},e.DEFAULT_LINGER=1,e.DEFAULT_NAME="unknown",e.DEFAULT_STANDBY="when-hidden",e.DEFAULT_STATE={interval:o.NEVER,payload:null,phase:"constructed",timestamp:new Date(0).getTime()},e.DISPOSED_STATE={interval:o.NEVER,payload:null,phase:"disposed",timestamp:new Date(0).getTime()},e.sleep=function(t,n){const{backoff:i,interval:r,max:s}=t;if(r===o.NEVER)return r;const a=!0===i?e.DEFAULT_BACKOFF:!1===i?1:i,l=function(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e}(r,n.interval*a);return Math.min(s,l)},e.hidden="undefined"!=typeof document&&(document.addEventListener("visibilitychange",(()=>{e.hidden="hidden"===document.visibilityState})),document.addEventListener("pagehide",(()=>{e.hidden="hidden"===document.visibilityState})),"hidden"===document.visibilityState)}(i||(i={}));class a{constructor(e,t=500){this.args=void 0,this.payload=null,this.limit=t,this.poll=new o({auto:!1,factory:async()=>{const{args:t}=this;return this.args=void 0,e(...t)},frequency:{backoff:!1,interval:o.NEVER,max:o.NEVER},standby:"never"}),this.payload=new r.PromiseDelegate,this.poll.ticked.connect(((e,t)=>{const{payload:n}=this;return"resolved"===t.phase?(this.payload=new r.PromiseDelegate,void n.resolve(t.payload)):"rejected"===t.phase||"stopped"===t.phase?(this.payload=new r.PromiseDelegate,n.promise.catch((e=>{})),void n.reject(t.payload)):void 0}),this)}get isDisposed(){return null===this.payload}dispose(){this.isDisposed||(this.args=void 0,this.payload=null,this.poll.dispose())}async stop(){return this.poll.stop()}}class l extends a{invoke(...e){return this.args=e,this.poll.schedule({interval:this.limit,phase:"invoked"}),this.payload.promise}}class u extends a{constructor(e,t){super(e,"number"==typeof t?t:t&&t.limit),this._trailing=!1,"number"!=typeof t&&t&&"trailing"===t.edge&&(this._trailing=!0),this._interval=this._trailing?this.limit:o.IMMEDIATE}invoke(...e){const t="invoked"!==this.poll.state.phase;return(t||this._trailing)&&(this.args=e),t&&this.poll.schedule({interval:this._interval,phase:"invoked"}),this.payload.promise}}},12571:(e,t,n)=>{"use strict";n.r(t),n.d(t,{AttachedProperty:()=>i});class i{constructor(e){this._pid=r.nextPID(),this.name=e.name,this._create=e.create,this._coerce=e.coerce||null,this._compare=e.compare||null,this._changed=e.changed||null}get(e){let t,n=r.ensureMap(e);return t=this._pid in n?n[this._pid]:n[this._pid]=this._createValue(e),t}set(e,t){let n,i=r.ensureMap(e);n=this._pid in i?i[this._pid]:i[this._pid]=this._createValue(e);let s=this._coerceValue(e,t);this._maybeNotify(e,n,i[this._pid]=s)}coerce(e){let t,n=r.ensureMap(e);t=this._pid in n?n[this._pid]:n[this._pid]=this._createValue(e);let i=this._coerceValue(e,t);this._maybeNotify(e,t,n[this._pid]=i)}_createValue(e){return(0,this._create)(e)}_coerceValue(e,t){let n=this._coerce;return n?n(e,t):t}_compareValue(e,t){let n=this._compare;return n?n(e,t):e===t}_maybeNotify(e,t,n){let i=this._changed;i&&!this._compareValue(t,n)&&i(e,t,n)}}var r;!function(e){e.clearData=function(e){r.ownerData.delete(e)}}(i||(i={})),function(e){e.ownerData=new WeakMap,e.nextPID=(()=>{let e=0;return()=>`pid-${`${Math.random()}`.slice(2)}-${e++}`})(),e.ensureMap=function(t){let n=e.ownerData.get(t);return n||(n=Object.create(null),e.ownerData.set(t,n),n)}}(r||(r={}))},60544:(e,t,n)=>{"use strict";var i,r,s;n.r(t),n.d(t,{Signal:()=>l,Stream:()=>u}),function(e){function t(e,t,n=0,i=-1){let r,s=e.length;if(0===s)return-1;n=n<0?Math.max(0,n+s):Math.min(n,s-1),r=(i=i<0?Math.max(0,i+s):Math.min(i,s-1))=n)return;let i=e[t];for(let i=t+1;i0;){let i=a>>1,r=o+i;n(e[r],t)<0?(o=r+1,a-=i+1):a=i}return o},e.upperBound=function(e,t,n,i=0,r=-1){let s=e.length;if(0===s)return 0;let o=i=i<0?Math.max(0,i+s):Math.min(i,s-1),a=(r=r<0?Math.max(0,r+s):Math.min(r,s-1))-i+1;for(;a>0;){let i=a>>1,r=o+i;n(e[r],t)>0?a=i:(o=r+1,a-=i+1)}return o},e.shallowEqual=function(e,t,n){if(e===t)return!0;if(e.length!==t.length)return!1;for(let i=0,r=e.length;i=o&&(n=r<0?o-1:o),void 0===i?i=r<0?-1:o:i<0?i=Math.max(i+o,r<0?-1:0):i>=o&&(i=r<0?o-1:o),s=r<0&&i>=n||r>0&&n>=i?0:r<0?Math.floor((i-n+1)/r+1):Math.floor((i-n-1)/r+1);let a=[];for(let t=0;t=(i=i<0?Math.max(0,i+r):Math.min(i,r-1)))return;let o=i-n+1;if(t>0?t%=o:t<0&&(t=(t%o+o)%o),0===t)return;let a=n+t;s(e,n,a-1),s(e,a,i),s(e,n,i)},e.fill=function(e,t,n=0,i=-1){let r,s=e.length;if(0!==s){n=n<0?Math.max(0,n+s):Math.min(n,s-1),r=(i=i<0?Math.max(0,i+s):Math.min(i,s-1))t;--n)e[n]=e[n-1];e[t]=n},e.removeAt=o,e.removeFirstOf=function(e,n,i=0,r=-1){let s=t(e,n,i,r);return-1!==s&&o(e,s),s},e.removeLastOf=function(e,t,i=-1,r=0){let s=n(e,t,i,r);return-1!==s&&o(e,s),s},e.removeAllOf=function(e,t,n=0,i=-1){let r=e.length;if(0===r)return 0;n=n<0?Math.max(0,n+r):Math.min(n,r-1),i=i<0?Math.max(0,i+r):Math.min(i,r-1);let s=0;for(let o=0;o=n&&o<=i&&e[o]===t||i=n)&&e[o]===t?s++:s>0&&(e[o-s]=e[o]);return s>0&&(e.length=r-s),s},e.removeFirstWhere=function(e,t,n=0,r=-1){let s,a=i(e,t,n,r);return-1!==a&&(s=o(e,a)),{index:a,value:s}},e.removeLastWhere=function(e,t,n=-1,i=0){let s,a=r(e,t,n,i);return-1!==a&&(s=o(e,a)),{index:a,value:s}},e.removeAllWhere=function(e,t,n=0,i=-1){let r=e.length;if(0===r)return 0;n=n<0?Math.max(0,n+r):Math.min(n,r-1),i=i<0?Math.max(0,i+r):Math.min(i,r-1);let s=0;for(let o=0;o=n&&o<=i&&t(e[o],o)||i=n)&&t(e[o],o)?s++:s>0&&(e[o-s]=e[o]);return s>0&&(e.length=r-s),s}}(i||(i={})),function(e){e.rangeLength=function(e,t,n){return 0===n?1/0:e>t&&n>0||et?1:0}}(s||(s={}));var o,a=n(65168);class l{constructor(e){this.sender=e}connect(e,t){return o.connect(this,e,t)}disconnect(e,t){return o.disconnect(this,e,t)}emit(e){o.emit(this,e)}}!function(e){e.disconnectBetween=function(e,t){o.disconnectBetween(e,t)},e.disconnectSender=function(e){o.disconnectSender(e)},e.disconnectReceiver=function(e){o.disconnectReceiver(e)},e.disconnectAll=function(e){o.disconnectAll(e)},e.clearData=function(e){o.disconnectAll(e)},e.getExceptionHandler=function(){return o.exceptionHandler},e.setExceptionHandler=function(e){let t=o.exceptionHandler;return o.exceptionHandler=e,t}}(l||(l={}));class u extends l{constructor(){super(...arguments),this._pending=new a.PromiseDelegate}async*[Symbol.asyncIterator](){let e=this._pending;for(;;)try{const{args:t,next:n}=await e.promise;e=n,yield t}catch(e){return}}emit(e){const t=this._pending,n=this._pending=new a.PromiseDelegate;t.resolve({args:e,next:n}),super.emit(e)}stop(){this._pending.promise.catch((()=>{})),this._pending.reject("stop"),this._pending=new a.PromiseDelegate}}!function(e){function t(e){let t=r.get(e);if(t&&0!==t.length){for(const e of t){if(!e.signal)continue;let t=e.thisArg||e.slot;e.signal=null,d(s.get(t))}d(t)}}function n(e){let t=s.get(e);if(t&&0!==t.length){for(const e of t){if(!e.signal)continue;let t=e.signal.sender;e.signal=null,d(r.get(t))}d(t)}}e.exceptionHandler=e=>{console.error(e)},e.connect=function(e,t,n){n=n||void 0;let i=r.get(e.sender);if(i||(i=[],r.set(e.sender,i)),l(i,e,t,n))return!1;let o=n||t,a=s.get(o);a||(a=[],s.set(o,a));let u={signal:e,slot:t,thisArg:n};return i.push(u),a.push(u),!0},e.disconnect=function(e,t,n){n=n||void 0;let i=r.get(e.sender);if(!i||0===i.length)return!1;let o=l(i,e,t,n);if(!o)return!1;let a=n||t,u=s.get(a);return o.signal=null,d(i),d(u),!0},e.disconnectBetween=function(e,t){let n=r.get(e);if(!n||0===n.length)return;let i=s.get(t);if(i&&0!==i.length){for(const t of i)t.signal&&t.signal.sender===e&&(t.signal=null);d(n),d(i)}},e.disconnectSender=t,e.disconnectReceiver=n,e.disconnectAll=function(e){t(e),n(e)},e.emit=function(e,t){let n=r.get(e.sender);if(n&&0!==n.length)for(let i=0,r=n.length;i{"use strict";var i;function r(e){return"function"==typeof e.iter?e.iter():new l(e)}function s(e,t){for(var n,i=0,s=r(e);void 0!==(n=s.next());)if(!1===t(n,i++))return}function o(e,t){for(var n,i=0,s=r(e);void 0!==(n=s.next());)if(!t(n,i++))return!1;return!0}function a(e,t){for(var n,i=0,s=r(e);void 0!==(n=s.next());)if(t(n,i++))return!0;return!1}n.d(t,{G:()=>a,RO:()=>i,S6:()=>s,cS:()=>u,kh:()=>h,yW:()=>o}),function(e){function t(e,t,n,i){void 0===n&&(n=0),void 0===i&&(i=-1);var r,s=e.length;if(0===s)return-1;n=n<0?Math.max(0,n+s):Math.min(n,s-1),r=(i=i<0?Math.max(0,i+s):Math.min(i,s-1))=n)){for(var i=e[t],r=t+1;r0;){var l=a>>1,u=o+l;n(e[u],t)<0?(o=u+1,a-=l+1):a=l}return o},e.upperBound=function(e,t,n,i,r){void 0===i&&(i=0),void 0===r&&(r=-1);var s=e.length;if(0===s)return 0;for(var o=i=i<0?Math.max(0,i+s):Math.min(i,s-1),a=(r=r<0?Math.max(0,r+s):Math.min(r,s-1))-i+1;a>0;){var l=a>>1,u=o+l;n(e[u],t)>0?a=l:(o=u+1,a-=l+1)}return o},e.shallowEqual=function(e,t,n){if(e===t)return!0;if(e.length!==t.length)return!1;for(var i=0,r=e.length;i=o&&(n=r<0?o-1:o),void 0===i?i=r<0?-1:o:i<0?i=Math.max(i+o,r<0?-1:0):i>=o&&(i=r<0?o-1:o),s=r<0&&i>=n||r>0&&n>=i?0:r<0?Math.floor((i-n+1)/r+1):Math.floor((i-n-1)/r+1);for(var a=[],l=0;l=(i=i<0?Math.max(0,i+r):Math.min(i,r-1)))){var o=i-n+1;if(t>0?t%=o:t<0&&(t=(t%o+o)%o),0!==t){var a=n+t;s(e,n,a-1),s(e,a,i),s(e,n,i)}}},e.fill=function(e,t,n,i){void 0===n&&(n=0),void 0===i&&(i=-1);var r=e.length;if(0!==r){var s;n=n<0?Math.max(0,n+r):Math.min(n,r-1),s=(i=i<0?Math.max(0,i+r):Math.min(i,r-1))t;--r)e[r]=e[r-1];e[t]=n},e.removeAt=o,e.removeFirstOf=function(e,n,i,r){void 0===i&&(i=0),void 0===r&&(r=-1);var s=t(e,n,i,r);return-1!==s&&o(e,s),s},e.removeLastOf=function(e,t,i,r){void 0===i&&(i=-1),void 0===r&&(r=0);var s=n(e,t,i,r);return-1!==s&&o(e,s),s},e.removeAllOf=function(e,t,n,i){void 0===n&&(n=0),void 0===i&&(i=-1);var r=e.length;if(0===r)return 0;n=n<0?Math.max(0,n+r):Math.min(n,r-1),i=i<0?Math.max(0,i+r):Math.min(i,r-1);for(var s=0,o=0;o=n&&o<=i&&e[o]===t||i=n)&&e[o]===t?s++:s>0&&(e[o-s]=e[o]);return s>0&&(e.length=r-s),s},e.removeFirstWhere=function(e,t,n,r){var s;void 0===n&&(n=0),void 0===r&&(r=-1);var a=i(e,t,n,r);return-1!==a&&(s=o(e,a)),{index:a,value:s}},e.removeLastWhere=function(e,t,n,i){var s;void 0===n&&(n=-1),void 0===i&&(i=0);var a=r(e,t,n,i);return-1!==a&&(s=o(e,a)),{index:a,value:s}},e.removeAllWhere=function(e,t,n,i){void 0===n&&(n=0),void 0===i&&(i=-1);var r=e.length;if(0===r)return 0;n=n<0?Math.max(0,n+r):Math.min(n,r-1),i=i<0?Math.max(0,i+r):Math.min(i,r-1);for(var s=0,o=0;o=n&&o<=i&&t(e[o],o)||i=n)&&t(e[o],o)?s++:s>0&&(e[o-s]=e[o]);return s>0&&(e.length=r-s),s}}(i||(i={}));var l=function(){function e(e){this._index=0,this._source=e}return e.prototype.iter=function(){return this},e.prototype.clone=function(){var t=new e(this._source);return t._index=this._index,t},e.prototype.next=function(){if(!(this._index>=this._source.length))return this._source[this._index++]},e}();function u(){return new c}(function(){function e(e,t){void 0===t&&(t=Object.keys(e)),this._index=0,this._source=e,this._keys=t}e.prototype.iter=function(){return this},e.prototype.clone=function(){var t=new e(this._source,this._keys);return t._index=this._index,t},e.prototype.next=function(){if(!(this._index>=this._keys.length)){var e=this._keys[this._index++];return e in this._source?e:this.next()}}})(),function(){function e(e,t){void 0===t&&(t=Object.keys(e)),this._index=0,this._source=e,this._keys=t}e.prototype.iter=function(){return this},e.prototype.clone=function(){var t=new e(this._source,this._keys);return t._index=this._index,t},e.prototype.next=function(){if(!(this._index>=this._keys.length)){var e=this._keys[this._index++];return e in this._source?this._source[e]:this.next()}}}(),function(){function e(e,t){void 0===t&&(t=Object.keys(e)),this._index=0,this._source=e,this._keys=t}e.prototype.iter=function(){return this},e.prototype.clone=function(){var t=new e(this._source,this._keys);return t._index=this._index,t},e.prototype.next=function(){if(!(this._index>=this._keys.length)){var e=this._keys[this._index++];return e in this._source?[e,this._source[e]]:this.next()}}}(),function(){function e(e){this._fn=e}e.prototype.iter=function(){return this},e.prototype.clone=function(){throw new Error("An `FnIterator` cannot be cloned.")},e.prototype.next=function(){return this._fn.call(void 0)}}(),function(){function e(e){this._cloned=!1,this._source=e,this._active=void 0}e.prototype.iter=function(){return this},e.prototype.clone=function(){var t=new e(this._source.clone());return t._active=this._active&&this._active.clone(),t._cloned=!0,this._cloned=!0,t},e.prototype.next=function(){if(void 0===this._active){var e=this._source.next();if(void 0===e)return;this._active=this._cloned?e.clone():e}var t=this._active.next();return void 0!==t?t:(this._active=void 0,this.next())}}();var d,c=function(){function e(){}return e.prototype.iter=function(){return this},e.prototype.clone=function(){return new e},e.prototype.next=function(){},e}();function h(e){return"function"==typeof e.retro?e.retro():new g(e)}!function(){function e(e,t){this._source=e,this._index=t}e.prototype.iter=function(){return this},e.prototype.clone=function(){return new e(this._source.clone(),this._index)},e.prototype.next=function(){var e=this._source.next();if(void 0!==e)return[this._index++,e]}}(),function(){function e(e,t){this._index=0,this._source=e,this._fn=t}e.prototype.iter=function(){return this},e.prototype.clone=function(){var t=new e(this._source.clone(),this._fn);return t._index=this._index,t},e.prototype.next=function(){for(var e,t=this._fn,n=this._source;void 0!==(e=n.next());)if(t(e,this._index++))return e}}(),function(){function e(e,t){this._index=0,this._source=e,this._fn=t}e.prototype.iter=function(){return this},e.prototype.clone=function(){var t=new e(this._source.clone(),this._fn);return t._index=this._index,t},e.prototype.next=function(){var e=this._source.next();if(void 0!==e)return this._fn.call(void 0,e,this._index++)}}(),function(){function e(e,t,n){this._index=0,this._start=e,this._stop=t,this._step=n,this._length=d.rangeLength(e,t,n)}e.prototype.iter=function(){return this},e.prototype.clone=function(){var t=new e(this._start,this._stop,this._step);return t._index=this._index,t},e.prototype.next=function(){if(!(this._index>=this._length))return this._start+this._step*this._index++}}(),function(e){e.rangeLength=function(e,t,n){return 0===n?1/0:e>t&&n>0||e=this._source.length))return this._source[this._index--]},e}();!function(){function e(e,t){this._source=e,this._step=t}e.prototype.iter=function(){return this},e.prototype.clone=function(){return new e(this._source.clone(),this._step)},e.prototype.next=function(){for(var e=this._source.next(),t=this._step-1;t>0;--t)this._source.next();return e}}(),function(e){function t(e,t,n){void 0===n&&(n=0);for(var i=new Array(t.length),r=0,s=n,o=t.length;rt?1:0}}(p||(p={})),function(){function e(e,t){this._source=e,this._count=t}e.prototype.iter=function(){return this},e.prototype.clone=function(){return new e(this._source.clone(),this._count)},e.prototype.next=function(){if(!(this._count<=0)){var e=this._source.next();if(void 0!==e)return this._count--,e}}}(),function(){function e(e){this._source=e}e.prototype.iter=function(){return this},e.prototype.clone=function(){return new e(this._source.map((function(e){return e.clone()})))},e.prototype.next=function(){for(var e=new Array(this._source.length),t=0,n=this._source.length;t>>0),e[n]=255&t,t>>>=8}e.Random=void 0,(e.Random||(e.Random={})).getRandomValues=function(){var e="undefined"!=typeof window&&(window.crypto||window.msCrypto)||null;return e&&"function"==typeof e.getRandomValues?function(t){return e.getRandomValues(t)}:r}(),e.UUID=void 0,(e.UUID||(e.UUID={})).uuid4=function(e){for(var t=new Uint8Array(16),n=new Array(256),i=0;i<16;++i)n[i]="0"+i.toString(16);for(i=16;i<256;++i)n[i]=i.toString(16);return function(){return e(t),t[6]=64|15&t[6],t[8]=128|63&t[8],n[t[0]]+n[t[1]]+n[t[2]]+n[t[3]]+"-"+n[t[4]]+n[t[5]]+"-"+n[t[6]]+n[t[7]]+"-"+n[t[8]]+n[t[9]]+"-"+n[t[10]]+n[t[11]]+n[t[12]]+n[t[13]]+n[t[14]]+n[t[15]]}}(e.Random.getRandomValues),e.MimeData=t,e.PromiseDelegate=n,e.Token=i,Object.defineProperty(e,"__esModule",{value:!0})}(t)},85403:(e,t,n)=>{"use strict";var i,r,s,o,a;n.d(t,{t4:()=>s}),function(e){e.copyText=function(e){var t=document.body,n=function(i){i.preventDefault(),i.stopPropagation(),i.clipboardData.setData("text",e),t.removeEventListener("copy",n,!0)};t.addEventListener("copy",n,!0),document.execCommand("copy")}}(i||(i={})),function(e){e.boxSizing=function(e){var t=window.getComputedStyle(e),n=parseFloat(t.borderTopWidth)||0,i=parseFloat(t.borderLeftWidth)||0,r=parseFloat(t.borderRightWidth)||0,s=parseFloat(t.borderBottomWidth)||0,o=parseFloat(t.paddingTop)||0,a=parseFloat(t.paddingLeft)||0,l=parseFloat(t.paddingRight)||0,u=parseFloat(t.paddingBottom)||0;return{borderTop:n,borderLeft:i,borderRight:r,borderBottom:s,paddingTop:o,paddingLeft:a,paddingRight:l,paddingBottom:u,horizontalSum:i+a+l+r,verticalSum:n+o+u+s}},e.sizeLimits=function(e){var t=window.getComputedStyle(e),n=parseFloat(t.minWidth)||0,i=parseFloat(t.minHeight)||0,r=parseFloat(t.maxWidth)||1/0,s=parseFloat(t.maxHeight)||1/0;return{minWidth:n,minHeight:i,maxWidth:r=Math.max(n,r),maxHeight:s=Math.max(i,s)}},e.hitTest=function(e,t,n){var i=e.getBoundingClientRect();return t>=i.left&&t=i.top&&n=n.bottom||(i.topn.bottom&&i.height>=n.height?e.scrollTop-=n.top-i.top:(i.topn.height||i.bottom>n.bottom&&i.height0;)if(h(n))t++;else if(h(i))d++;else if(h(r))d++;else if(h(o))c++;else if(h(a))d++;else if(h(s))c++;else if(!h(l))return 0;return(t=Math.min(t,255))<<16|(d=Math.min(d,255))<<8|Math.min(c,255)};var n=/^#[^\s\+>~#\.\[:]+/,i=/^\.[^\s\+>~#\.\[:]+/,r=/^\[[^\]]+\]/,s=/^[^\s\+>~#\.\[:]+/,o=/^(::[^\s\+>~#\.\[:]+|:first-line|:first-letter|:before|:after)/,a=/^:[^\s\+>~#\.\[:]+/,l=/^[\s\+>~\*]+/,u=/:not\(([^\)]+)\)/g}(a||(a={}))},31790:(e,t,n)=>{"use strict";n.d(t,{pB:()=>l});var i,r=n(69060),s=function(){function e(e){this._root=new i.LeafNode,this.cmp=e}return Object.defineProperty(e.prototype,"isEmpty",{get:function(){return 0===this._root.size},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this._root.size},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"first",{get:function(){var e=i.firstLeaf(this._root);return e.size>0?e.items[0]:void 0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"last",{get:function(){var e=i.lastLeaf(this._root);return e.size>0?e.items[e.size-1]:void 0},enumerable:!0,configurable:!0}),e.prototype.iter=function(){return i.iterItems(this._root)},e.prototype.retro=function(){return i.retroItems(this._root)},e.prototype.slice=function(e,t){return i.sliceItems(this._root,e,t)},e.prototype.retroSlice=function(e,t){return i.retroSliceItems(this._root,e,t)},e.prototype.at=function(e){return i.itemAt(this._root,e)},e.prototype.has=function(e,t){return i.hasItem(this._root,e,t)},e.prototype.indexOf=function(e,t){return i.indexOf(this._root,e,t)},e.prototype.get=function(e,t){return i.getItem(this._root,e,t)},e.prototype.assign=function(e){this.clear(),this.update(e)},e.prototype.insert=function(e){var t=i.insertItem(this._root,e,this.cmp);return this._root=i.maybeSplitRoot(this._root),t},e.prototype.update=function(e){var t=this;(0,r.S6)(e,(function(e){t.insert(e)}))},e.prototype.delete=function(e,t){var n=i.deleteItem(this._root,e,t);return this._root=i.maybeExtractRoot(this._root),n},e.prototype.remove=function(e){var t=i.removeItem(this._root,e);return this._root=i.maybeExtractRoot(this._root),t},e.prototype.clear=function(){i.clear(this._root),this._root=new i.LeafNode},e}();!function(e){e.from=function(t,n){var i=new e(n);return i.assign(t),i}}(s||(s={})),function(e){var t=function(){function e(){this.items=[],this.sizes=[],this.children=[]}return Object.defineProperty(e.prototype,"type",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this.sizes[this.sizes.length-1]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"width",{get:function(){return this.children.length},enumerable:!0,configurable:!0}),e}();e.BranchNode=t;var n=function(){function e(){this.next=null,this.prev=null,this.items=[]}return Object.defineProperty(e.prototype,"type",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this.items.length},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"width",{get:function(){return this.items.length},enumerable:!0,configurable:!0}),e}();function i(e){for(;0===e.type;)e=e.children[0];return e}function s(e){for(;0===e.type;)e=e.children[e.children.length-1];return e}function o(e){0===e.type?((0,r.S6)(e.children,o),e.children.length=0,e.sizes.length=0,e.items.length=0):(e.items.length=0,e.next=null,e.prev=null)}e.LeafNode=n,e.firstLeaf=i,e.lastLeaf=s,e.iterItems=function(e){var t=i(e);return new u(t,0,-1)},e.retroItems=function(e){var t=s(e);return new d(t,t.size-1,-1)},e.sliceItems=function(e,t,n){t=void 0===t?0:t<0?Math.max(0,t+e.size):Math.min(t,e.size),n=void 0===n?e.size:n<0?Math.max(0,n+e.size):Math.min(n,e.size);var i=Math.max(0,n-t);if(0===i)return(0,r.cS)();for(;0===e.type;){var s=c(e.sizes,t);s>0&&(t-=e.sizes[s-1]),e=e.children[s]}return new u(e,t,i)},e.retroSliceItems=function(e,t,n){t=void 0===t?e.size-1:t<0?Math.max(-1,t+e.size):Math.min(t,e.size-1),n=void 0===n?-1:n<0?Math.max(-1,n+e.size):Math.min(n,e.size-1);var i=Math.max(0,t-n);if(0===i)return(0,r.cS)();for(;0===e.type;){var s=c(e.sizes,t);s>0&&(t-=e.sizes[s-1]),e=e.children[s]}return new d(e,t,i)},e.itemAt=function(e,t){if(t<0&&(t+=e.size),!(t<0||t>=e.size)){for(;0===e.type;){var n=c(e.sizes,t);n>0&&(t-=e.sizes[n-1]),e=e.children[n]}return e.items[t]}},e.hasItem=function(e,t,n){for(;0===e.type;){var i=h(e.items,t,n);e=e.children[i]}return p(e.items,t,n)>=0},e.indexOf=function(e,t,n){for(var i=0;0===e.type;){var r=h(e.items,t,n);r>0&&(i+=e.sizes[r-1]),e=e.children[r]}var s=p(e.items,t,n);return s>=0?i+s:-i+s},e.getItem=function(e,t,n){for(;0===e.type;){var i=h(e.items,t,n);e=e.children[i]}var r=p(e.items,t,n);return r>=0?e.items[r]:void 0},e.insertItem=function e(t,n,i){if(1===t.type){var s,o=p(t.items,n,i);return o>=0?(s=t.items[o],t.items[o]=n):(s=void 0,r.RO.insert(t.items,-o-1,n)),s}var l=h(t.items,n,i),u=t.children[l],d=u.size,c=e(u,n,i),m=u.size;if(t.items[l]=u.items[0],d===m)return c;if(u.width>a){var v=f(u);r.RO.insert(t.children,l+1,v),r.RO.insert(t.items,l+1,v.items[0])}return g(t,l),c},e.deleteItem=function e(t,n,i){if(1===t.type){var s=p(t.items,n,i);if(s<0)return;return r.RO.removeAt(t.items,s)}var o=h(t.items,n,i),a=t.children[o],u=a.size,d=e(a,n,i);return u===a.size||(t.items[o]=a.items[0],a.width=t.size)){if(1===t.type)return r.RO.removeAt(t.items,n);var i=c(t.sizes,n);i>0&&(n-=t.sizes[i]);var s=t.children[i],o=e(s,n);return t.items[i]=s.items[0],s.width1)return e;var t=e.children.pop();return o(e),t};var a=32,l=a>>1,u=function(){function e(e,t,n){this._node=e,this._index=t,this._count=n}return e.prototype.iter=function(){return this},e.prototype.clone=function(){return new e(this._node,this._index,this._count)},e.prototype.next=function(){if(null!==this._node&&0!==this._count)return this._index>=this._node.size?(this._node=this._node.next,this._index=0,this.next()):(this._count>0&&this._count--,this._node.items[this._index++])},e}(),d=function(){function e(e,t,n){this._node=e,this._index=t,this._count=n}return e.prototype.iter=function(){return this},e.prototype.clone=function(){return new e(this._node,this._index,this._count)},e.prototype.next=function(){if(null!==this._node&&0!==this._count)return this._index>=this._node.size&&(this._index=this._node.size-1),this._index<0?(this._node=this._node.prev,this._index=this._node?this._node.size-1:-1,this.next()):(this._count>0&&this._count--,this._node.items[this._index--])},e}();function c(e,t){for(var n=e.length,i=0;it)return i;return n-1}function h(e,t,n){for(var i=e.length,r=1;r0)return r-1;return i-1}function p(e,t,n){for(var i=e.length,r=0;r0)return-r-1}return-i-1}function g(e,t){for(var n=e.sizes,i=e.children,r=t>0?n[t-1]:0,s=i.length;tl;if(f&&m&&p){var v=h;return(b=c).items.push(v.items.shift()),e.items[t+1]=v.items[0],t}if(f&&m&&!p)return v=h,(b=c).items.unshift(v.items.pop()),e.items[t]=b.items[0],t-1;if(f&&!m&&p){var b=c;return(n=(v=h).items).unshift.apply(n,b.items),r.RO.removeAt(e.children,t),r.RO.removeAt(e.items,t+1),b.prev&&(b.prev.next=v),v.prev=b.prev,o(b),t}if(f&&!m&&!p)return b=c,(i=(v=h).items).push.apply(i,b.items),r.RO.removeAt(e.children,t),r.RO.removeAt(e.items,t),b.next&&(b.next.prev=v),v.next=b.next,o(b),t-1;if(!f&&m&&p)return v=h,(b=c).children.push(v.children.shift()),b.items.push(v.items.shift()),e.items[t+1]=v.items[0],g(b,b.width-1),g(v,0),t;if(!f&&m&&!p)return v=h,(b=c).children.unshift(v.children.pop()),b.items.unshift(v.items.pop()),e.items[t]=b.items[0],g(b,0),g(v,v.width-1),t-1;if(!f&&!m&&p)return b=c,(s=(v=h).children).unshift.apply(s,b.children),(a=v.items).unshift.apply(a,b.items),r.RO.removeAt(e.children,t),r.RO.removeAt(e.items,t+1),g(v,0),b.children.length=0,o(b),t;if(!f&&!m&&!p)return b=c,(u=(v=h).children).push.apply(u,b.children),(d=v.items).push.apply(d,b.items),r.RO.removeAt(e.children,t),r.RO.removeAt(e.items,t),g(v,0),b.children.length=0,o(b),t-1;throw"unreachable"}}(i||(i={}));var o,a=function(){function e(){this._first=null,this._last=null,this._size=0}return Object.defineProperty(e.prototype,"isEmpty",{get:function(){return 0===this._size},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this._size},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return this._size},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"first",{get:function(){return this._first?this._first.value:void 0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"last",{get:function(){return this._last?this._last.value:void 0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"firstNode",{get:function(){return this._first},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lastNode",{get:function(){return this._last},enumerable:!0,configurable:!0}),e.prototype.iter=function(){return new e.ForwardValueIterator(this._first)},e.prototype.retro=function(){return new e.RetroValueIterator(this._last)},e.prototype.nodes=function(){return new e.ForwardNodeIterator(this._first)},e.prototype.retroNodes=function(){return new e.RetroNodeIterator(this._last)},e.prototype.assign=function(e){var t=this;this.clear(),(0,r.S6)(e,(function(e){t.addLast(e)}))},e.prototype.push=function(e){this.addLast(e)},e.prototype.pop=function(){return this.removeLast()},e.prototype.shift=function(e){this.addFirst(e)},e.prototype.unshift=function(){return this.removeFirst()},e.prototype.addFirst=function(e){var t=new o.LinkedListNode(this,e);return this._first?(t.next=this._first,this._first.prev=t,this._first=t):(this._first=t,this._last=t),this._size++,t},e.prototype.addLast=function(e){var t=new o.LinkedListNode(this,e);return this._last?(t.prev=this._last,this._last.next=t,this._last=t):(this._first=t,this._last=t),this._size++,t},e.prototype.insertBefore=function(e,t){if(!t||t===this._first)return this.addFirst(e);if(!(t instanceof o.LinkedListNode)||t.list!==this)throw new Error("Reference node is not owned by the list.");var n=new o.LinkedListNode(this,e),i=t,r=i.prev;return n.next=i,n.prev=r,i.prev=n,r.next=n,this._size++,n},e.prototype.insertAfter=function(e,t){if(!t||t===this._last)return this.addLast(e);if(!(t instanceof o.LinkedListNode)||t.list!==this)throw new Error("Reference node is not owned by the list.");var n=new o.LinkedListNode(this,e),i=t,r=i.next;return n.next=r,n.prev=i,i.next=n,r.prev=n,this._size++,n},e.prototype.removeFirst=function(){var e=this._first;if(e)return e===this._last?(this._first=null,this._last=null):(this._first=e.next,this._first.prev=null),e.list=null,e.next=null,e.prev=null,this._size--,e.value},e.prototype.removeLast=function(){var e=this._last;if(e)return e===this._first?(this._first=null,this._last=null):(this._last=e.prev,this._last.next=null),e.list=null,e.next=null,e.prev=null,this._size--,e.value},e.prototype.removeNode=function(e){if(!(e instanceof o.LinkedListNode)||e.list!==this)throw new Error("Node is not owned by the list.");var t=e;t===this._first&&t===this._last?(this._first=null,this._last=null):t===this._first?(this._first=t.next,this._first.prev=null):t===this._last?(this._last=t.prev,this._last.next=null):(t.next.prev=t.prev,t.prev.next=t.next),t.list=null,t.next=null,t.prev=null,this._size--},e.prototype.clear=function(){for(var e=this._first;e;){var t=e.next;e.list=null,e.prev=null,e.next=null,e=t}this._first=null,this._last=null,this._size=0},e}();!function(e){e.from=function(t){var n=new e;return n.assign(t),n};var t=function(){function e(e){this._node=e}return e.prototype.iter=function(){return this},e.prototype.clone=function(){return new e(this._node)},e.prototype.next=function(){if(this._node){var e=this._node;return this._node=e.next,e.value}},e}();e.ForwardValueIterator=t;var n=function(){function e(e){this._node=e}return e.prototype.iter=function(){return this},e.prototype.clone=function(){return new e(this._node)},e.prototype.next=function(){if(this._node){var e=this._node;return this._node=e.prev,e.value}},e}();e.RetroValueIterator=n;var i=function(){function e(e){this._node=e}return e.prototype.iter=function(){return this},e.prototype.clone=function(){return new e(this._node)},e.prototype.next=function(){if(this._node){var e=this._node;return this._node=e.next,e}},e}();e.ForwardNodeIterator=i;var r=function(){function e(e){this._node=e}return e.prototype.iter=function(){return this},e.prototype.clone=function(){return new e(this._node)},e.prototype.next=function(){if(this._node){var e=this._node;return this._node=e.prev,e}},e}();e.RetroNodeIterator=r}(a||(a={})),function(e){e.LinkedListNode=function(e,t){this.list=null,this.next=null,this.prev=null,this.list=e,this.value=t}}(o||(o={}));var l,u=function(e,t){return u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},u(e,t)};!function(e){function t(){return null!==e&&e.apply(this,arguments)||this}(function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}u(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)})(t,e),Object.defineProperty(t.prototype,"isConflatable",{get:function(){return!0},enumerable:!0,configurable:!0}),t.prototype.conflate=function(e){return!0}}(function(){function e(e){this.type=e}return Object.defineProperty(e.prototype,"isConflatable",{get:function(){return!1},enumerable:!0,configurable:!0}),e.prototype.conflate=function(e){return!1},e}()),function(e){function t(e,t){var n=i.get(e);if(n&&0!==n.length){var s=(0,r.yW)((0,r.kh)(n),(function(n){return!n||function(e,t,n){var i=!0;try{i="function"==typeof e?e(t,n):e.messageHook(t,n)}catch(e){o(e)}return i}(n,e,t)}));s&&h(e,t)}else h(e,t)}e.sendMessage=t,e.postMessage=function(e,t){t.isConflatable&&(0,r.G)(n,(function(n){return n.handler===e&&!!n.msg&&n.msg.type===t.type&&!!n.msg.isConflatable&&n.msg.conflate(t)}))||function(e,t){n.addLast({handler:e,msg:t}),0===l&&(l=d(p))}(e,t)},e.installMessageHook=function(e,t){var n=i.get(e);n&&-1!==n.indexOf(t)||(n?n.push(t):i.set(e,[t]))},e.removeMessageHook=function(e,t){var n=i.get(e);if(n){var r=n.indexOf(t);-1!==r&&(n[r]=null,g(n))}},e.clearData=function(e){var t=i.get(e);t&&t.length>0&&(r.RO.fill(t,null),g(t)),(0,r.S6)(n,(function(t){t.handler===e&&(t.handler=null,t.msg=null)}))},e.flush=function(){u||0===l||(c(l),u=!0,p(),u=!1)},e.getExceptionHandler=function(){return o},e.setExceptionHandler=function(e){var t=o;return o=e,t};var n=new a,i=new WeakMap,s=new Set,o=function(e){console.error(e)},l=0,u=!1,d="function"==typeof requestAnimationFrame?requestAnimationFrame:setImmediate,c="function"==typeof cancelAnimationFrame?cancelAnimationFrame:clearImmediate;function h(e,t){try{e.processMessage(t)}catch(e){o(e)}}function p(){if(l=0,!n.isEmpty){var e={handler:null,msg:null};for(n.addLast(e);;){var i=n.removeFirst();if(i===e)return;i.handler&&i.msg&&t(i.handler,i.msg)}}}function g(e){0===s.size&&d(f),s.add(e)}function f(){s.forEach(m),s.clear()}function m(e){r.RO.removeAllWhere(e,v)}function v(e){return null===e}}(l||(l={}))},60785:(e,t,n)=>{"use strict";var i,r,s;function*o(){}function a(e,t){let n=0;for(const i of e)if(t(i,n++))return i}n.d(t,{Rh:()=>Se,s_:()=>le,LN:()=>K,nj:()=>me,$L:()=>V}),function(e){function t(e,t,n=0,i=-1){let r,s=e.length;if(0===s)return-1;n=n<0?Math.max(0,n+s):Math.min(n,s-1),r=(i=i<0?Math.max(0,i+s):Math.min(i,s-1))=n)return;let i=e[t];for(let i=t+1;i0;){let i=a>>1,r=o+i;n(e[r],t)<0?(o=r+1,a-=i+1):a=i}return o},e.upperBound=function(e,t,n,i=0,r=-1){let s=e.length;if(0===s)return 0;let o=i=i<0?Math.max(0,i+s):Math.min(i,s-1),a=(r=r<0?Math.max(0,r+s):Math.min(r,s-1))-i+1;for(;a>0;){let i=a>>1,r=o+i;n(e[r],t)>0?a=i:(o=r+1,a-=i+1)}return o},e.shallowEqual=function(e,t,n){if(e===t)return!0;if(e.length!==t.length)return!1;for(let i=0,r=e.length;i=o&&(n=r<0?o-1:o),void 0===i?i=r<0?-1:o:i<0?i=Math.max(i+o,r<0?-1:0):i>=o&&(i=r<0?o-1:o),s=r<0&&i>=n||r>0&&n>=i?0:r<0?Math.floor((i-n+1)/r+1):Math.floor((i-n-1)/r+1);let a=[];for(let t=0;t=(i=i<0?Math.max(0,i+r):Math.min(i,r-1)))return;let o=i-n+1;if(t>0?t%=o:t<0&&(t=(t%o+o)%o),0===t)return;let a=n+t;s(e,n,a-1),s(e,a,i),s(e,n,i)},e.fill=function(e,t,n=0,i=-1){let r,s=e.length;if(0!==s){n=n<0?Math.max(0,n+s):Math.min(n,s-1),r=(i=i<0?Math.max(0,i+s):Math.min(i,s-1))t;--n)e[n]=e[n-1];e[t]=n},e.removeAt=o,e.removeFirstOf=function(e,n,i=0,r=-1){let s=t(e,n,i,r);return-1!==s&&o(e,s),s},e.removeLastOf=function(e,t,i=-1,r=0){let s=n(e,t,i,r);return-1!==s&&o(e,s),s},e.removeAllOf=function(e,t,n=0,i=-1){let r=e.length;if(0===r)return 0;n=n<0?Math.max(0,n+r):Math.min(n,r-1),i=i<0?Math.max(0,i+r):Math.min(i,r-1);let s=0;for(let o=0;o=n&&o<=i&&e[o]===t||i=n)&&e[o]===t?s++:s>0&&(e[o-s]=e[o]);return s>0&&(e.length=r-s),s},e.removeFirstWhere=function(e,t,n=0,r=-1){let s,a=i(e,t,n,r);return-1!==a&&(s=o(e,a)),{index:a,value:s}},e.removeLastWhere=function(e,t,n=-1,i=0){let s,a=r(e,t,n,i);return-1!==a&&(s=o(e,a)),{index:a,value:s}},e.removeAllWhere=function(e,t,n=0,i=-1){let r=e.length;if(0===r)return 0;n=n<0?Math.max(0,n+r):Math.min(n,r-1),i=i<0?Math.max(0,i+r):Math.min(i,r-1);let s=0;for(let o=0;o=n&&o<=i&&t(e[o],o)||i=n)&&t(e[o],o)?s++:s>0&&(e[o-s]=e[o]);return s>0&&(e.length=r-s),s}}(i||(i={})),function(e){e.rangeLength=function(e,t,n){return 0===n?1/0:e>t&&n>0||et?1:0}}(s||(s={}));var l,u,d,c,h,p,g,f,m,v,b,_,A=n(68743);!function(e){e.copyText=function(e){const t=document.body,n=i=>{i.preventDefault(),i.stopPropagation(),i.clipboardData.setData("text",e),t.removeEventListener("copy",n,!0)};t.addEventListener("copy",n,!0),document.execCommand("copy")}}(l||(l={})),(b=u||(u={})).boxSizing=function(e){let t=window.getComputedStyle(e),n=parseFloat(t.borderTopWidth)||0,i=parseFloat(t.borderLeftWidth)||0,r=parseFloat(t.borderRightWidth)||0,s=parseFloat(t.borderBottomWidth)||0,o=parseFloat(t.paddingTop)||0,a=parseFloat(t.paddingLeft)||0,l=parseFloat(t.paddingRight)||0,u=parseFloat(t.paddingBottom)||0;return{borderTop:n,borderLeft:i,borderRight:r,borderBottom:s,paddingTop:o,paddingLeft:a,paddingRight:l,paddingBottom:u,horizontalSum:i+a+l+r,verticalSum:n+o+u+s}},b.sizeLimits=function(e){let t=window.getComputedStyle(e),n=parseFloat(t.minWidth)||0,i=parseFloat(t.minHeight)||0,r=parseFloat(t.maxWidth)||1/0,s=parseFloat(t.maxHeight)||1/0;return r=Math.max(n,r),s=Math.max(i,s),{minWidth:n,minHeight:i,maxWidth:r,maxHeight:s}},b.hitTest=function(e,t,n){let i=e.getBoundingClientRect();return t>=i.left&&t=i.top&&n=n.bottom||(i.topn.bottom&&i.height>=n.height?e.scrollTop-=n.top-i.top:(i.topn.height||i.bottom>n.bottom&&i.height{let e=Element.prototype;return e.matches||e.matchesSelector||e.mozMatchesSelector||e.msMatchesSelector||e.oMatchesSelector||e.webkitMatchesSelector||function(e){let t=this,n=t.ownerDocument?t.ownerDocument.querySelectorAll(e):[];return-1!==Array.prototype.indexOf.call(n,t)}})(),e.calculateSingle=function(e){let u=0,d=0,c=0;function h(t){let n=e.match(t);return null!==n&&(e=e.slice(n[0].length),!0)}for(e=(e=e.split(",",1)[0]).replace(l," $1 ");e.length>0;)if(h(t))u++;else if(h(n))d++;else if(h(i))d++;else if(h(s))c++;else if(h(o))d++;else if(h(r))c++;else if(!h(a))return 0;return u=Math.min(u,255),d=Math.min(d,255),c=Math.min(c,255),u<<16|d<<8|c};const t=/^#[^\s\+>~#\.\[:]+/,n=/^\.[^\s\+>~#\.\[:]+/,i=/^\[[^\]]+\]/,r=/^[^\s\+>~#\.\[:]+/,s=/^(::[^\s\+>~#\.\[:]+|:first-line|:first-letter|:before|:after)/,o=/^:[^\s\+>~#\.\[:]+/,a=/^[\s\+>~\*]+/,l=/:not\(([^\)]+)\)/g}(h||(h={}));class y{constructor(){this._first=null,this._last=null,this._size=0}get isEmpty(){return 0===this._size}get size(){return this._size}get length(){return this._size}get first(){return this._first?this._first.value:void 0}get last(){return this._last?this._last.value:void 0}get firstNode(){return this._first}get lastNode(){return this._last}*[Symbol.iterator](){let e=this._first;for(;e;)yield e.value,e=e.next}*retro(){let e=this._last;for(;e;)yield e.value,e=e.prev}*nodes(){let e=this._first;for(;e;)yield e,e=e.next}*retroNodes(){let e=this._last;for(;e;)yield e,e=e.prev}assign(e){this.clear();for(const t of e)this.addLast(t)}push(e){this.addLast(e)}pop(){return this.removeLast()}shift(e){this.addFirst(e)}unshift(){return this.removeFirst()}addFirst(e){let t=new p.LinkedListNode(this,e);return this._first?(t.next=this._first,this._first.prev=t,this._first=t):(this._first=t,this._last=t),this._size++,t}addLast(e){let t=new p.LinkedListNode(this,e);return this._last?(t.prev=this._last,this._last.next=t,this._last=t):(this._first=t,this._last=t),this._size++,t}insertBefore(e,t){if(!t||t===this._first)return this.addFirst(e);if(!(t instanceof p.LinkedListNode)||t.list!==this)throw new Error("Reference node is not owned by the list.");let n=new p.LinkedListNode(this,e),i=t,r=i.prev;return n.next=i,n.prev=r,i.prev=n,r.next=n,this._size++,n}insertAfter(e,t){if(!t||t===this._last)return this.addLast(e);if(!(t instanceof p.LinkedListNode)||t.list!==this)throw new Error("Reference node is not owned by the list.");let n=new p.LinkedListNode(this,e),i=t,r=i.next;return n.next=r,n.prev=i,i.next=n,r.prev=n,this._size++,n}removeFirst(){let e=this._first;if(e)return e===this._last?(this._first=null,this._last=null):(this._first=e.next,this._first.prev=null),e.list=null,e.next=null,e.prev=null,this._size--,e.value}removeLast(){let e=this._last;if(e)return e===this._first?(this._first=null,this._last=null):(this._last=e.prev,this._last.next=null),e.list=null,e.next=null,e.prev=null,this._size--,e.value}removeNode(e){if(!(e instanceof p.LinkedListNode)||e.list!==this)throw new Error("Node is not owned by the list.");let t=e;t===this._first&&t===this._last?(this._first=null,this._last=null):t===this._first?(this._first=t.next,this._first.prev=null):t===this._last?(this._last=t.prev,this._last.next=null):(t.next.prev=t.prev,t.prev.next=t.next),t.list=null,t.next=null,t.prev=null,this._size--}clear(){let e=this._first;for(;e;){let t=e.next;e.list=null,e.prev=null,e.next=null,e=t}this._first=null,this._last=null,this._size=0}}!function(e){e.from=function(t){let n=new e;return n.assign(t),n}}(y||(y={})),function(e){e.LinkedListNode=class{constructor(e,t){this.list=null,this.next=null,this.prev=null,this.list=e,this.value=t}}}(p||(p={}));class w{constructor(e){this.type=e}get isConflatable(){return!1}conflate(e){return!1}}class C extends w{get isConflatable(){return!0}conflate(e){return!0}}!function(e){let t=null;const n=(r=Promise.resolve(),e=>{let t=!1;return r.then((()=>!t&&e())),()=>{t=!0}});var r;function s(e,t){let n=a.get(e);if(!n||0===n.length)return void c(e,t);let i=function(e,t){let n=0;for(const i of e)if(!1===t(i,n++))return!1;return!0}(function*(e){if("function"==typeof e.retro)yield*e.retro();else for(let t=e.length-1;t>-1;t--)yield e[t]}(n),(n=>!n||function(e,t,n){let i=!0;try{i="function"==typeof e?e(t,n):e.messageHook(t,n)}catch(e){u(e)}return i}(n,e,t)));i&&c(e,t)}e.sendMessage=s,e.postMessage=function(e,t){t.isConflatable&&function(n,i){for(const i of n)if((r=i).handler===e&&r.msg&&r.msg.type===t.type&&r.msg.isConflatable&&r.msg.conflate(t))return!0;var r;return!1}(o)||h(e,t)},e.installMessageHook=function(e,t){let n=a.get(e);n&&-1!==n.indexOf(t)||(n?n.push(t):a.set(e,[t]))},e.removeMessageHook=function(e,t){let n=a.get(e);if(!n)return;let i=n.indexOf(t);-1!==i&&(n[i]=null,g(n))},e.clearData=function(e){let t=a.get(e);t&&t.length>0&&(i.fill(t,null),g(t));for(const t of o)t.handler===e&&(t.handler=null,t.msg=null)},e.flush=function(){d||null===t||(t(),t=null,d=!0,p(),d=!1)},e.getExceptionHandler=function(){return u},e.setExceptionHandler=function(e){let t=u;return u=e,t};const o=new y,a=new WeakMap,l=new Set;let u=e=>{console.error(e)},d=!1;function c(e,t){try{e.processMessage(t)}catch(e){u(e)}}function h(e,i){o.addLast({handler:e,msg:i}),null===t&&(t=n(p))}function p(){if(t=null,o.isEmpty)return;let e={handler:null,msg:null};for(o.addLast(e);;){let t=o.removeFirst();if(t===e)return;t.handler&&t.msg&&s(t.handler,t.msg)}}function g(e){0===l.size&&n(f),l.add(e)}function f(){l.forEach(m),l.clear()}function m(e){i.removeAllWhere(e,v)}function v(e){return null===e}}(g||(g={}));class E{constructor(e){this._pid=f.nextPID(),this.name=e.name,this._create=e.create,this._coerce=e.coerce||null,this._compare=e.compare||null,this._changed=e.changed||null}get(e){let t,n=f.ensureMap(e);return t=this._pid in n?n[this._pid]:n[this._pid]=this._createValue(e),t}set(e,t){let n,i=f.ensureMap(e);n=this._pid in i?i[this._pid]:i[this._pid]=this._createValue(e);let r=this._coerceValue(e,t);this._maybeNotify(e,n,i[this._pid]=r)}coerce(e){let t,n=f.ensureMap(e);t=this._pid in n?n[this._pid]:n[this._pid]=this._createValue(e);let i=this._coerceValue(e,t);this._maybeNotify(e,t,n[this._pid]=i)}_createValue(e){return(0,this._create)(e)}_coerceValue(e,t){let n=this._coerce;return n?n(e,t):t}_compareValue(e,t){let n=this._compare;return n?n(e,t):e===t}_maybeNotify(e,t,n){let i=this._changed;i&&!this._compareValue(t,n)&&i(e,t,n)}}!function(e){e.clearData=function(e){f.ownerData.delete(e)}}(E||(E={})),function(e){e.ownerData=new WeakMap,e.nextPID=(()=>{let e=0;return()=>`pid-${`${Math.random()}`.slice(2)}-${e++}`})(),e.ensureMap=function(t){let n=e.ownerData.get(t);return n||(n=Object.create(null),e.ownerData.set(t,n),n)}}(f||(f={}));class x{constructor(e){this.sender=e}connect(e,t){return m.connect(this,e,t)}disconnect(e,t){return m.disconnect(this,e,t)}emit(e){m.emit(this,e)}}(_=x||(x={})).disconnectBetween=function(e,t){m.disconnectBetween(e,t)},_.disconnectSender=function(e){m.disconnectSender(e)},_.disconnectReceiver=function(e){m.disconnectReceiver(e)},_.disconnectAll=function(e){m.disconnectAll(e)},_.clearData=function(e){m.disconnectAll(e)},_.getExceptionHandler=function(){return m.exceptionHandler},_.setExceptionHandler=function(e){let t=m.exceptionHandler;return m.exceptionHandler=e,t};class D extends(null){constructor(){super(...arguments),this._pending=new PromiseDelegate}async*[Symbol.asyncIterator](){let e=this._pending;for(;;)try{const{args:t,next:n}=await e.promise;e=n,yield t}catch(e){return}}emit(e){const t=this._pending,n=this._pending=new PromiseDelegate;t.resolve({args:e,next:n}),super.emit(e)}stop(){this._pending.promise.catch((()=>{})),this._pending.reject("stop"),this._pending=new PromiseDelegate}}!function(e){function t(e){let t=r.get(e);if(t&&0!==t.length){for(const e of t){if(!e.signal)continue;let t=e.thisArg||e.slot;e.signal=null,c(s.get(t))}c(t)}}function n(e){let t=s.get(e);if(t&&0!==t.length){for(const e of t){if(!e.signal)continue;let t=e.signal.sender;e.signal=null,c(r.get(t))}c(t)}}e.exceptionHandler=e=>{console.error(e)},e.connect=function(e,t,n){n=n||void 0;let i=r.get(e.sender);if(i||(i=[],r.set(e.sender,i)),u(i,e,t,n))return!1;let o=n||t,a=s.get(o);a||(a=[],s.set(o,a));let l={signal:e,slot:t,thisArg:n};return i.push(l),a.push(l),!0},e.disconnect=function(e,t,n){n=n||void 0;let i=r.get(e.sender);if(!i||0===i.length)return!1;let o=u(i,e,t,n);if(!o)return!1;let a=n||t,l=s.get(a);return o.signal=null,c(i),c(l),!0},e.disconnectBetween=function(e,t){let n=r.get(e);if(!n||0===n.length)return;let i=s.get(t);if(i&&0!==i.length){for(const t of i)t.signal&&t.signal.sender===e&&(t.signal=null);c(n),c(i)}},e.disconnectSender=t,e.disconnectReceiver=n,e.disconnectAll=function(e){t(e),n(e)},e.emit=function(e,t){let n=r.get(e.sender);if(n&&0!==n.length)for(let i=0,r=n.length;ie.signal===t&&e.slot===n&&e.thisArg===i))}function d(t,n){let{signal:i,slot:r,thisArg:s}=t;try{r.call(s,i.sender,n)}catch(t){e.exceptionHandler(t)}}function c(e){0===o.size&&l(h),o.add(e)}function h(){o.forEach(p),o.clear()}function p(e){i.removeAllWhere(e,g)}function g(e){return null===e.signal}}(m||(m={}));var S,T,M=n(64604);class k{constructor(e){this.type="text",this.content=e}}class j{constructor(e,t,n,i){this.type="element",this.tag=e,this.attrs=t,this.children=n,this.renderer=i}}function B(e){let t,n={},i=[];for(let e=1,s=arguments.length;e=i;--s){const i=t[s],o=r?e.lastChild:e.childNodes[s];"text"===i.type||(i.renderer&&i.renderer.unrender?i.renderer.unrender(o,{attrs:i.attrs,children:i.children}):n(o,i.children,0,!1)),r&&e.removeChild(o)}}e.hostMap=new WeakMap,e.asContentArray=function(e){return e?e instanceof Array?e:[e]:[]},e.createDOMNode=t,e.updateContent=function e(r,o,a){if(o===a)return;let l=function(e,t){let n=e.firstChild,i=Object.create(null);for(let e of t)"element"===e.type&&e.attrs.key&&(i[e.attrs.key]={vNode:e,element:n}),n=n.nextSibling;return i}(r,o),u=o.slice(),d=r.firstChild,c=a.length;for(let n=0;n=u.length){t(a[n],r);continue}let o=u[n],c=a[n];if(o===c){d=d.nextSibling;continue}if("text"===o.type&&"text"===c.type){d.textContent!==c.content&&(d.textContent=c.content),d=d.nextSibling;continue}if("text"===o.type||"text"===c.type){i.insert(u,n,c),t(c,r,d);continue}if(!o.renderer!=!c.renderer){i.insert(u,n,c),t(c,r,d);continue}let h=c.attrs.key;if(h&&h in l){let e=l[h];e.vNode!==o&&(i.move(u,u.indexOf(e.vNode,n+1),n),r.insertBefore(e.element,d),o=e.vNode,d=e.element)}if(o===c){d=d.nextSibling;continue}let p=o.attrs.key;p&&p!==h?(i.insert(u,n,c),t(c,r,d)):o.tag===c.tag?(s(d,o.attrs,c.attrs),c.renderer?c.renderer.render(d,{attrs:c.attrs,children:c.children}):e(d,o.children,c.children),d=d.nextSibling):(i.insert(u,n,c),t(c,r,d))}n(r,u,c,!0)};const r={key:!0,className:!0,htmlFor:!0,dataset:!0,style:!0};function s(e,t,n){if(t===n)return;let i;for(i in t)i in r||i in n||("on"===i.substr(0,2)?e[i]=null:e.removeAttribute(i));for(i in n)i in r||t[i]===n[i]||("on"===i.substr(0,2)?e[i]=n[i]:e.setAttribute(i,n[i]));t.className!==n.className&&(void 0!==n.className?e.setAttribute("class",n.className):e.removeAttribute("class")),t.htmlFor!==n.htmlFor&&(void 0!==n.htmlFor?e.setAttribute("for",n.htmlFor):e.removeAttribute("for")),t.dataset!==n.dataset&&function(e,t,n){for(let i in t)i in n||e.removeAttribute(`data-${i}`);for(let i in n)t[i]!==n[i]&&e.setAttribute(`data-${i}`,n[i])}(e,t.dataset||{},n.dataset||{}),t.style!==n.style&&function(e,t,n){let i,r=e.style;for(i in t)i in n||(r[i]="");for(i in n)t[i]!==n[i]&&(r[i]=n[i])}(e,t.style||{},n.style||{})}}(T||(T={}));class O{constructor(){this._isDisposed=!1,this._items=new Set}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,this._items.forEach((e=>{e.dispose()})),this._items.clear())}contains(e){return this._items.has(e)}add(e){this._items.add(e)}remove(e){this._items.delete(e)}clear(){this._items.clear()}}!function(e){e.from=function(t){let n=new e;for(const e of t)n.add(e);return n}}(O||(O={}));class I extends O{constructor(){super(...arguments),this._disposed=new x(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),x.clearData(this))}}function R(){return N.keyboardLayout}!function(e){e.from=function(t){let n=new e;for(const e of t)n.add(e);return n}}(I||(I={}));class P{constructor(e,t,n=[]){this.name=e,this._codes=t,this._keys=P.extractKeys(t),this._modifierKeys=P.convertToKeySet(n)}keys(){return Object.keys(this._keys)}isValidKey(e){return e in this._keys}isModifierKey(e){return e in this._modifierKeys}keyForKeydownEvent(e){return this._codes[e.keyCode]||""}}!function(e){e.extractKeys=function(e){let t=Object.create(null);for(let n in e)t[e[n]]=!0;return t},e.convertToKeySet=function(e){let t=Object(null);for(let n=0,i=e.length;n0&&(o+=n.stretch,a++)}if(t===s)return 0;if(t<=i){for(let t=0;t=r){for(let t=0;t0&&i>l;){let t=i,r=o;for(let s=0;s0&&i>l;){let t=i/u;for(let r=0;r0&&i>l;){let t=i,r=o;for(let s=0;s=n.maxSize?(i-=n.maxSize-n.size,o-=n.stretch,n.size=n.maxSize,n.done=!0,u--,a--):(i-=l,n.size+=l)}}for(;u>0&&i>l;){let t=i/u;for(let r=0;r=n.maxSize?(i-=n.maxSize-n.size,n.size=n.maxSize,n.done=!0,u--):(i-=t,n.size+=t))}}}return 0},e.adjust=function(e,t,n){0!==e.length&&0!==n&&(n>0?function(e,t,n){let i=0;for(let n=0;n<=t;++n){let t=e[n];i+=t.maxSize-t.size}let r=0;for(let n=t+1,i=e.length;n=0&&s>0;--n){let t=e[n],i=t.maxSize-t.size;i>=s?(t.sizeHint=t.size+s,s=0):(t.sizeHint=t.size+i,s-=i)}let o=n;for(let n=t+1,i=e.length;n0;++n){let t=e[n],i=t.size-t.minSize;i>=o?(t.sizeHint=t.size-o,o=0):(t.sizeHint=t.size-i,o-=i)}}(e,t,n):function(e,t,n){let i=0;for(let n=t+1,r=e.length;n0;++n){let t=e[n],i=t.maxSize-t.size;i>=s?(t.sizeHint=t.size+s,s=0):(t.sizeHint=t.size+i,s-=i)}let o=n;for(let n=t;n>=0&&o>0;--n){let t=e[n],i=t.size-t.minSize;i>=o?(t.sizeHint=t.size-o,o=0):(t.sizeHint=t.size-i,o-=i)}}(e,t,-n))}}(F||(F={}));class H{constructor(e){this._label="",this._caption="",this._mnemonic=-1,this._icon=void 0,this._iconClass="",this._iconLabel="",this._className="",this._closable=!1,this._changed=new x(this),this._isDisposed=!1,this.owner=e.owner,void 0!==e.label&&(this._label=e.label),void 0!==e.mnemonic&&(this._mnemonic=e.mnemonic),void 0!==e.icon&&(this._icon=e.icon),void 0!==e.iconClass&&(this._iconClass=e.iconClass),void 0!==e.iconLabel&&(this._iconLabel=e.iconLabel),void 0!==e.caption&&(this._caption=e.caption),void 0!==e.className&&(this._className=e.className),void 0!==e.closable&&(this._closable=e.closable),this._dataset=e.dataset||{}}get changed(){return this._changed}get label(){return this._label}set label(e){this._label!==e&&(this._label=e,this._changed.emit(void 0))}get mnemonic(){return this._mnemonic}set mnemonic(e){this._mnemonic!==e&&(this._mnemonic=e,this._changed.emit(void 0))}get icon(){return this._icon}set icon(e){this._icon!==e&&(this._icon=e,this._changed.emit(void 0))}get iconClass(){return this._iconClass}set iconClass(e){this._iconClass!==e&&(this._iconClass=e,this._changed.emit(void 0))}get iconLabel(){return this._iconLabel}set iconLabel(e){this._iconLabel!==e&&(this._iconLabel=e,this._changed.emit(void 0))}get caption(){return this._caption}set caption(e){this._caption!==e&&(this._caption=e,this._changed.emit(void 0))}get className(){return this._className}set className(e){this._className!==e&&(this._className=e,this._changed.emit(void 0))}get closable(){return this._closable}set closable(e){this._closable!==e&&(this._closable=e,this._changed.emit(void 0))}get dataset(){return this._dataset}set dataset(e){this._dataset!==e&&(this._dataset=e,this._changed.emit(void 0))}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,x.clearData(this))}}class V{constructor(e={}){this._flags=0,this._layout=null,this._parent=null,this._disposed=new x(this),this._hiddenMode=V.HiddenMode.Display,this.node=z.createNode(e),this.addClass("lm-Widget")}dispose(){this.isDisposed||(this.setFlag(V.Flag.IsDisposed),this._disposed.emit(void 0),this.parent?this.parent=null:this.isAttached&&V.detach(this),this._layout&&(this._layout.dispose(),this._layout=null),this.title.dispose(),x.clearData(this),g.clearData(this),E.clearData(this))}get disposed(){return this._disposed}get isDisposed(){return this.testFlag(V.Flag.IsDisposed)}get isAttached(){return this.testFlag(V.Flag.IsAttached)}get isHidden(){return this.testFlag(V.Flag.IsHidden)}get isVisible(){return this.testFlag(V.Flag.IsVisible)}get title(){return z.titleProperty.get(this)}get id(){return this.node.id}set id(e){this.node.id=e}get dataset(){return this.node.dataset}get hiddenMode(){return this._hiddenMode}set hiddenMode(e){this._hiddenMode!==e&&(this.isHidden&&this._toggleHidden(!1),e==V.HiddenMode.Scale?this.node.style.willChange="transform":this.node.style.willChange="auto",this._hiddenMode=e,this.isHidden&&this._toggleHidden(!0))}get parent(){return this._parent}set parent(e){if(this._parent!==e){if(e&&this.contains(e))throw new Error("Invalid parent widget.");if(this._parent&&!this._parent.isDisposed){let e=new V.ChildMessage("child-removed",this);g.sendMessage(this._parent,e)}if(this._parent=e,this._parent&&!this._parent.isDisposed){let e=new V.ChildMessage("child-added",this);g.sendMessage(this._parent,e)}this.isDisposed||g.sendMessage(this,V.Msg.ParentChanged)}}get layout(){return this._layout}set layout(e){if(this._layout!==e){if(this.testFlag(V.Flag.DisallowLayout))throw new Error("Cannot set widget layout.");if(this._layout)throw new Error("Cannot change widget layout.");if(e.parent)throw new Error("Cannot change layout parent.");this._layout=e,e.parent=this}}*children(){this._layout&&(yield*this._layout)}contains(e){for(let t=e;t;t=t._parent)if(t===this)return!0;return!1}hasClass(e){return this.node.classList.contains(e)}addClass(e){this.node.classList.add(e)}removeClass(e){this.node.classList.remove(e)}toggleClass(e,t){return!0===t?(this.node.classList.add(e),!0):!1===t?(this.node.classList.remove(e),!1):this.node.classList.toggle(e)}update(){g.postMessage(this,V.Msg.UpdateRequest)}fit(){g.postMessage(this,V.Msg.FitRequest)}activate(){g.postMessage(this,V.Msg.ActivateRequest)}close(){g.sendMessage(this,V.Msg.CloseRequest)}show(){if(this.testFlag(V.Flag.IsHidden)&&(!this.isAttached||this.parent&&!this.parent.isVisible||g.sendMessage(this,V.Msg.BeforeShow),this.clearFlag(V.Flag.IsHidden),this._toggleHidden(!1),!this.isAttached||this.parent&&!this.parent.isVisible||g.sendMessage(this,V.Msg.AfterShow),this.parent)){let e=new V.ChildMessage("child-shown",this);g.sendMessage(this.parent,e)}}hide(){if(!this.testFlag(V.Flag.IsHidden)&&(!this.isAttached||this.parent&&!this.parent.isVisible||g.sendMessage(this,V.Msg.BeforeHide),this.setFlag(V.Flag.IsHidden),this._toggleHidden(!0),!this.isAttached||this.parent&&!this.parent.isVisible||g.sendMessage(this,V.Msg.AfterHide),this.parent)){let e=new V.ChildMessage("child-hidden",this);g.sendMessage(this.parent,e)}}setHidden(e){e?this.hide():this.show()}testFlag(e){return 0!=(this._flags&e)}setFlag(e){this._flags|=e}clearFlag(e){this._flags&=~e}processMessage(e){switch(e.type){case"resize":this.notifyLayout(e),this.onResize(e);break;case"update-request":this.notifyLayout(e),this.onUpdateRequest(e);break;case"fit-request":this.notifyLayout(e),this.onFitRequest(e);break;case"before-show":this.notifyLayout(e),this.onBeforeShow(e);break;case"after-show":this.setFlag(V.Flag.IsVisible),this.notifyLayout(e),this.onAfterShow(e);break;case"before-hide":this.notifyLayout(e),this.onBeforeHide(e);break;case"after-hide":this.clearFlag(V.Flag.IsVisible),this.notifyLayout(e),this.onAfterHide(e);break;case"before-attach":this.notifyLayout(e),this.onBeforeAttach(e);break;case"after-attach":this.isHidden||this.parent&&!this.parent.isVisible||this.setFlag(V.Flag.IsVisible),this.setFlag(V.Flag.IsAttached),this.notifyLayout(e),this.onAfterAttach(e);break;case"before-detach":this.notifyLayout(e),this.onBeforeDetach(e);break;case"after-detach":this.clearFlag(V.Flag.IsVisible),this.clearFlag(V.Flag.IsAttached),this.notifyLayout(e),this.onAfterDetach(e);break;case"activate-request":this.notifyLayout(e),this.onActivateRequest(e);break;case"close-request":this.notifyLayout(e),this.onCloseRequest(e);break;case"child-added":this.notifyLayout(e),this.onChildAdded(e);break;case"child-removed":this.notifyLayout(e),this.onChildRemoved(e);break;default:this.notifyLayout(e)}}notifyLayout(e){this._layout&&this._layout.processParentMessage(e)}onCloseRequest(e){this.parent?this.parent=null:this.isAttached&&V.detach(this)}onResize(e){}onUpdateRequest(e){}onFitRequest(e){}onActivateRequest(e){}onBeforeShow(e){}onAfterShow(e){}onBeforeHide(e){}onAfterHide(e){}onBeforeAttach(e){}onAfterAttach(e){}onBeforeDetach(e){}onAfterDetach(e){}onChildAdded(e){}onChildRemoved(e){}_toggleHidden(e){if(e)switch(this._hiddenMode){case V.HiddenMode.Display:this.addClass("lm-mod-hidden");break;case V.HiddenMode.Scale:this.node.style.transform="scale(0)",this.node.setAttribute("aria-hidden","true");break;case V.HiddenMode.ContentVisibility:this.node.style.contentVisibility="hidden",this.node.style.zIndex="-1"}else switch(this._hiddenMode){case V.HiddenMode.Display:this.removeClass("lm-mod-hidden");break;case V.HiddenMode.Scale:this.node.style.transform="",this.node.removeAttribute("aria-hidden");break;case V.HiddenMode.ContentVisibility:this.node.style.contentVisibility="",this.node.style.zIndex=""}}}!function(e){var t,n,i;(t=e.HiddenMode||(e.HiddenMode={}))[t.Display=0]="Display",t[t.Scale=1]="Scale",t[t.ContentVisibility=2]="ContentVisibility",(n=e.Flag||(e.Flag={}))[n.IsDisposed=1]="IsDisposed",n[n.IsAttached=2]="IsAttached",n[n.IsHidden=4]="IsHidden",n[n.IsVisible=8]="IsVisible",n[n.DisallowLayout=16]="DisallowLayout",(i=e.Msg||(e.Msg={})).BeforeShow=new w("before-show"),i.AfterShow=new w("after-show"),i.BeforeHide=new w("before-hide"),i.AfterHide=new w("after-hide"),i.BeforeAttach=new w("before-attach"),i.AfterAttach=new w("after-attach"),i.BeforeDetach=new w("before-detach"),i.AfterDetach=new w("after-detach"),i.ParentChanged=new w("parent-changed"),i.UpdateRequest=new C("update-request"),i.FitRequest=new C("fit-request"),i.ActivateRequest=new C("activate-request"),i.CloseRequest=new C("close-request"),e.ChildMessage=class extends w{constructor(e,t){super(e),this.child=t}};class r extends w{constructor(e,t){super("resize"),this.width=e,this.height=t}}e.ResizeMessage=r,function(e){e.UnknownSize=new e(-1,-1)}(r=e.ResizeMessage||(e.ResizeMessage={})),e.attach=function(t,n,i=null){if(t.parent)throw new Error("Cannot attach a child widget.");if(t.isAttached||t.node.isConnected)throw new Error("Widget is already attached.");if(!n.isConnected)throw new Error("Host is not attached.");g.sendMessage(t,e.Msg.BeforeAttach),n.insertBefore(t.node,i),g.sendMessage(t,e.Msg.AfterAttach)},e.detach=function(t){if(t.parent)throw new Error("Cannot detach a child widget.");if(!t.isAttached||!t.node.isConnected)throw new Error("Widget is not attached.");g.sendMessage(t,e.Msg.BeforeDetach),t.node.parentNode.removeChild(t.node),g.sendMessage(t,e.Msg.AfterDetach)}}(V||(V={})),function(e){e.titleProperty=new E({name:"title",create:e=>new H({owner:e})}),e.createNode=function(e){return e.node||document.createElement(e.tag||"div")}}(z||(z={}));class q{constructor(e={}){this._disposed=!1,this._parent=null,this._fitPolicy=e.fitPolicy||"set-min-size"}dispose(){this._parent=null,this._disposed=!0,x.clearData(this),E.clearData(this)}get isDisposed(){return this._disposed}get parent(){return this._parent}set parent(e){if(this._parent!==e){if(this._parent)throw new Error("Cannot change parent widget.");if(e.layout!==this)throw new Error("Invalid parent widget.");this._parent=e,this.init()}}get fitPolicy(){return this._fitPolicy}set fitPolicy(e){if(this._fitPolicy!==e&&(this._fitPolicy=e,this._parent)){let e=this._parent.node.style;e.minWidth="",e.minHeight="",e.maxWidth="",e.maxHeight="",this._parent.fit()}}processParentMessage(e){switch(e.type){case"resize":this.onResize(e);break;case"update-request":this.onUpdateRequest(e);break;case"fit-request":this.onFitRequest(e);break;case"before-show":this.onBeforeShow(e);break;case"after-show":this.onAfterShow(e);break;case"before-hide":this.onBeforeHide(e);break;case"after-hide":this.onAfterHide(e);break;case"before-attach":this.onBeforeAttach(e);break;case"after-attach":this.onAfterAttach(e);break;case"before-detach":this.onBeforeDetach(e);break;case"after-detach":this.onAfterDetach(e);break;case"child-removed":this.onChildRemoved(e);break;case"child-shown":this.onChildShown(e);break;case"child-hidden":this.onChildHidden(e)}}init(){for(const e of this)e.parent=this.parent}onResize(e){for(const e of this)g.sendMessage(e,V.ResizeMessage.UnknownSize)}onUpdateRequest(e){for(const e of this)g.sendMessage(e,V.ResizeMessage.UnknownSize)}onBeforeAttach(e){for(const t of this)g.sendMessage(t,e)}onAfterAttach(e){for(const t of this)g.sendMessage(t,e)}onBeforeDetach(e){for(const t of this)g.sendMessage(t,e)}onAfterDetach(e){for(const t of this)g.sendMessage(t,e)}onBeforeShow(e){for(const t of this)t.isHidden||g.sendMessage(t,e)}onAfterShow(e){for(const t of this)t.isHidden||g.sendMessage(t,e)}onBeforeHide(e){for(const t of this)t.isHidden||g.sendMessage(t,e)}onAfterHide(e){for(const t of this)t.isHidden||g.sendMessage(t,e)}onChildRemoved(e){this.removeWidget(e.child)}onFitRequest(e){}onChildShown(e){}onChildHidden(e){}}!function(e){e.getHorizontalAlignment=function(e){return U.horizontalAlignmentProperty.get(e)},e.setHorizontalAlignment=function(e,t){U.horizontalAlignmentProperty.set(e,t)},e.getVerticalAlignment=function(e){return U.verticalAlignmentProperty.get(e)},e.setVerticalAlignment=function(e,t){U.verticalAlignmentProperty.set(e,t)}}(q||(q={}));class G{constructor(e){this._top=NaN,this._left=NaN,this._width=NaN,this._height=NaN,this._minWidth=0,this._minHeight=0,this._maxWidth=1/0,this._maxHeight=1/0,this._disposed=!1,this.widget=e,this.widget.node.style.position="absolute",this.widget.node.style.contain="strict"}dispose(){if(this._disposed)return;this._disposed=!0;let e=this.widget.node.style;e.position="",e.top="",e.left="",e.width="",e.height="",e.contain=""}get minWidth(){return this._minWidth}get minHeight(){return this._minHeight}get maxWidth(){return this._maxWidth}get maxHeight(){return this._maxHeight}get isDisposed(){return this._disposed}get isHidden(){return this.widget.isHidden}get isVisible(){return this.widget.isVisible}get isAttached(){return this.widget.isAttached}fit(){let e=u.sizeLimits(this.widget.node);this._minWidth=e.minWidth,this._minHeight=e.minHeight,this._maxWidth=e.maxWidth,this._maxHeight=e.maxHeight}update(e,t,n,i){let r=Math.max(this._minWidth,Math.min(n,this._maxWidth)),s=Math.max(this._minHeight,Math.min(i,this._maxHeight));if(r"center",changed:t}),e.verticalAlignmentProperty=new E({name:"verticalAlignment",create:()=>"top",changed:t})}(U||(U={}));class K extends q{constructor(){super(...arguments),this._widgets=[]}dispose(){for(;this._widgets.length>0;)this._widgets.pop().dispose();super.dispose()}get widgets(){return this._widgets}*[Symbol.iterator](){yield*this._widgets}addWidget(e){this.insertWidget(this._widgets.length,e)}insertWidget(e,t){t.parent=this.parent;let n=this._widgets.indexOf(t),r=Math.max(0,Math.min(e,this._widgets.length));if(-1===n)return i.insert(this._widgets,r,t),void(this.parent&&this.attachWidget(r,t));r===this._widgets.length&&r--,n!==r&&(i.move(this._widgets,n,r),this.parent&&this.moveWidget(n,r,t))}removeWidget(e){this.removeWidgetAt(this._widgets.indexOf(e))}removeWidgetAt(e){let t=i.removeAt(this._widgets,e);t&&this.parent&&this.detachWidget(e,t)}init(){super.init();let e=0;for(const t of this)this.attachWidget(e++,t)}attachWidget(e,t){let n=this.parent.node.children[e];this.parent.isAttached&&g.sendMessage(t,V.Msg.BeforeAttach),this.parent.node.insertBefore(t.node,n),this.parent.isAttached&&g.sendMessage(t,V.Msg.AfterAttach)}moveWidget(e,t,n){this.parent.isAttached&&g.sendMessage(n,V.Msg.BeforeDetach),this.parent.node.removeChild(n.node),this.parent.isAttached&&g.sendMessage(n,V.Msg.AfterDetach);let i=this.parent.node.children[t];this.parent.isAttached&&g.sendMessage(n,V.Msg.BeforeAttach),this.parent.node.insertBefore(n.node,i),this.parent.isAttached&&g.sendMessage(n,V.Msg.AfterAttach)}detachWidget(e,t){this.parent.isAttached&&g.sendMessage(t,V.Msg.BeforeDetach),this.parent.node.removeChild(t.node),this.parent.isAttached&&g.sendMessage(t,V.Msg.AfterDetach)}}!function(e){e.clampDimension=function(e){return Math.max(0,Math.floor(e))}}($||($={}));var Y,J,X,Z,Q,ee,te,ne,ie,re,se=$;class oe extends K{constructor(e){super(),this.widgetOffset=0,this._fixed=0,this._spacing=4,this._dirty=!1,this._hasNormedSizes=!1,this._sizers=[],this._items=[],this._handles=[],this._box=null,this._alignment="start",this._orientation="horizontal",this.renderer=e.renderer,void 0!==e.orientation&&(this._orientation=e.orientation),void 0!==e.alignment&&(this._alignment=e.alignment),void 0!==e.spacing&&(this._spacing=$.clampDimension(e.spacing))}dispose(){for(const e of this._items)e.dispose();this._box=null,this._items.length=0,this._sizers.length=0,this._handles.length=0,super.dispose()}get orientation(){return this._orientation}set orientation(e){this._orientation!==e&&(this._orientation=e,this.parent&&(this.parent.dataset.orientation=e,this.parent.fit()))}get alignment(){return this._alignment}set alignment(e){this._alignment!==e&&(this._alignment=e,this.parent&&(this.parent.dataset.alignment=e,this.parent.update()))}get spacing(){return this._spacing}set spacing(e){e=$.clampDimension(e),this._spacing!==e&&(this._spacing=e,this.parent&&this.parent.fit())}get handles(){return this._handles}absoluteSizes(){return this._sizers.map((e=>e.size))}relativeSizes(){return Y.normalize(this._sizers.map((e=>e.size)))}setRelativeSizes(e,t=!0){let n=this._sizers.length,i=e.slice(0,n);for(;i.length0&&(e.sizeHint=e.size);F.adjust(this._sizers,e,n),this.parent&&this.parent.update()}}init(){this.parent.dataset.orientation=this.orientation,this.parent.dataset.alignment=this.alignment,super.init()}attachWidget(e,t){let n=new G(t),r=Y.createHandle(this.renderer),s=Y.averageSize(this._sizers),o=Y.createSizer(s);i.insert(this._items,e,n),i.insert(this._sizers,e,o),i.insert(this._handles,e,r),this.parent.isAttached&&g.sendMessage(t,V.Msg.BeforeAttach),this.parent.node.appendChild(t.node),this.parent.node.appendChild(r),this.parent.isAttached&&g.sendMessage(t,V.Msg.AfterAttach),this.parent.fit()}moveWidget(e,t,n){i.move(this._items,e,t),i.move(this._sizers,e,t),i.move(this._handles,e,t),this.parent.fit()}detachWidget(e,t){let n=i.removeAt(this._items,e),r=i.removeAt(this._handles,e);i.removeAt(this._sizers,e),this.parent.isAttached&&g.sendMessage(t,V.Msg.BeforeDetach),this.parent.node.removeChild(t.node),this.parent.node.removeChild(r),this.parent.isAttached&&g.sendMessage(t,V.Msg.AfterDetach),n.dispose(),this.parent.fit()}onBeforeShow(e){super.onBeforeShow(e),this.parent.update()}onBeforeAttach(e){super.onBeforeAttach(e),this.parent.fit()}onChildShown(e){this.parent.fit()}onChildHidden(e){this.parent.fit()}onResize(e){this.parent.isVisible&&this._update(e.width,e.height)}onUpdateRequest(e){this.parent.isVisible&&this._update(-1,-1)}onFitRequest(e){this.parent.isAttached&&this._fit()}updateItemPosition(e,t,n,i,r,s,o){const a=this._items[e];if(a.isHidden)return;let l=this._handles[e].style;t?(n+=this.widgetOffset,a.update(n,i,o,r),n+=o,l.top=`${i}px`,l.left=`${n}px`,l.width=`${this._spacing}px`,l.height=`${r}px`):(i+=this.widgetOffset,a.update(n,i,s,o),i+=o,l.top=`${i}px`,l.left=`${n}px`,l.width=`${s}px`,l.height=`${this._spacing}px`)}_fit(){let e=0,t=-1;for(let n=0,i=this._items.length;n0&&(s.sizeHint=s.size),t.isHidden?(s.minSize=0,s.maxSize=0):(t.fit(),s.stretch=oe.getStretch(t.widget),n?(s.minSize=t.minWidth,s.maxSize=t.maxWidth,i+=t.minWidth,r=Math.max(r,t.minHeight)):(s.minSize=t.minHeight,s.maxSize=t.maxHeight,r+=t.minHeight,i=Math.max(i,t.minWidth)))}let s=this._box=u.boxSizing(this.parent.node);i+=s.horizontalSum,r+=s.verticalSum;let o=this.parent.node.style;o.minWidth=`${i}px`,o.minHeight=`${r}px`,this._dirty=!0,this.parent.parent&&g.sendMessage(this.parent.parent,V.Msg.FitRequest),this._dirty&&g.sendMessage(this.parent,V.Msg.UpdateRequest)}_update(e,t){this._dirty=!1;let n=0;for(let e=0,t=this._items.length;e0){let e;if(e=d?Math.max(0,s-this._fixed):Math.max(0,o-this._fixed),this._hasNormedSizes){for(let t of this._sizers)t.sizeHint*=e;this._hasNormedSizes=!1}let t=F.calc(this._sizers,e);if(t>0)switch(this._alignment){case"start":break;case"center":a=0,l=t/2;break;case"end":a=0,l=t;break;case"justify":a=t/n,l=0;break;default:throw"unreachable"}}for(let e=0,t=this._items.length;e0,coerce:(e,t)=>Math.max(0,Math.floor(t)),changed:function(e){e.parent&&e.parent.layout instanceof oe&&e.parent.fit()}}),e.createSizer=function(e){let t=new W;return t.sizeHint=Math.floor(e),t},e.createHandle=function(e){let t=e.createHandle();return t.style.position="absolute",t.style.contain="style",t},e.averageSize=function(e){return e.reduce(((e,t)=>e+t.size),0)/e.length||0},e.normalize=function(e){let t=e.length;if(0===t)return[];let n=e.reduce(((e,t)=>e+Math.abs(t)),0);return 0===n?e.map((e=>1/t)):e.map((e=>e/n))}}(Y||(Y={}));class ae extends oe{constructor(e){super({...e,orientation:e.orientation||"vertical"}),this._titles=[],this.titleSpace=e.titleSpace||22}get titleSpace(){return this.widgetOffset}set titleSpace(e){e=se.clampDimension(e),this.widgetOffset!==e&&(this.widgetOffset=e,this.parent&&this.parent.fit())}get titles(){return this._titles}dispose(){this.isDisposed||(this._titles.length=0,super.dispose())}updateTitle(e,t){const n=this._titles[e],i=n.classList.contains("lm-mod-expanded"),r=J.createTitle(this.renderer,t.title,i);this._titles[e]=r,this.parent.node.replaceChild(r,n)}insertWidget(e,t){t.id||(t.id=`id-${A.UUID.uuid4()}`),super.insertWidget(e,t)}attachWidget(e,t){const n=J.createTitle(this.renderer,t.title);i.insert(this._titles,e,n),this.parent.node.appendChild(n),t.node.setAttribute("role","region"),t.node.setAttribute("aria-labelledby",n.id),super.attachWidget(e,t)}moveWidget(e,t,n){i.move(this._titles,e,t),super.moveWidget(e,t,n)}detachWidget(e,t){const n=i.removeAt(this._titles,e);this.parent.node.removeChild(n),super.detachWidget(e,t)}updateItemPosition(e,t,n,i,r,s,o){const a=this._titles[e].style;a.top=`${i}px`,a.left=`${n}px`,a.height=`${this.widgetOffset}px`,a.width=t?`${r}px`:`${s}px`,super.updateItemPosition(e,t,n,i,r,s,o)}}!function(e){e.createTitle=function(e,t,n=!0){const i=e.createSectionTitle(t);return i.style.position="absolute",i.style.contain="strict",i.setAttribute("aria-label",`${t.label} Section`),i.setAttribute("aria-expanded",n?"true":"false"),i.setAttribute("aria-controls",t.owner.id),n&&i.classList.add("lm-mod-expanded"),i}}(J||(J={}));class le extends V{constructor(e={}){super(),this.addClass("lm-Panel"),this.layout=X.createLayout(e)}get widgets(){return this.layout.widgets}addWidget(e){this.layout.addWidget(e)}insertWidget(e,t){this.layout.insertWidget(e,t)}}!function(e){e.createLayout=function(e){return e.layout||new K}}(X||(X={}));class ue extends le{constructor(e={}){super({layout:Z.createLayout(e)}),this._handleMoved=new x(this),this._pressData=null,this.addClass("lm-SplitPanel")}dispose(){this._releaseMouse(),super.dispose()}get orientation(){return this.layout.orientation}set orientation(e){this.layout.orientation=e}get alignment(){return this.layout.alignment}set alignment(e){this.layout.alignment=e}get spacing(){return this.layout.spacing}set spacing(e){this.layout.spacing=e}get renderer(){return this.layout.renderer}get handleMoved(){return this._handleMoved}get handles(){return this.layout.handles}relativeSizes(){return this.layout.relativeSizes()}setRelativeSizes(e,t=!0){this.layout.setRelativeSizes(e,t)}handleEvent(e){switch(e.type){case"pointerdown":this._evtPointerDown(e);break;case"pointermove":this._evtPointerMove(e);break;case"pointerup":this._evtPointerUp(e);break;case"keydown":this._evtKeyDown(e);break;case"contextmenu":e.preventDefault(),e.stopPropagation()}}onBeforeAttach(e){this.node.addEventListener("pointerdown",this)}onAfterDetach(e){this.node.removeEventListener("pointerdown",this),this._releaseMouse()}onChildAdded(e){e.child.addClass("lm-SplitPanel-child"),this._releaseMouse()}onChildRemoved(e){e.child.removeClass("lm-SplitPanel-child"),this._releaseMouse()}_evtKeyDown(e){this._pressData&&(e.preventDefault(),e.stopPropagation()),27===e.keyCode&&this._releaseMouse()}_evtPointerDown(e){if(0!==e.button)return;let t,n=this.layout,r=i.findFirstIndex(n.handles,(t=>t.contains(e.target)));if(-1===r)return;e.preventDefault(),e.stopPropagation(),document.addEventListener("pointerup",this,!0),document.addEventListener("pointermove",this,!0),document.addEventListener("keydown",this,!0),document.addEventListener("contextmenu",this,!0);let s=n.handles[r],o=s.getBoundingClientRect();t="horizontal"===n.orientation?e.clientX-o.left:e.clientY-o.top;let a=window.getComputedStyle(s),l=M.Drag.overrideCursor(a.cursor);this._pressData={index:r,delta:t,override:l}}_evtPointerMove(e){let t;e.preventDefault(),e.stopPropagation();let n=this.layout,i=this.node.getBoundingClientRect();t="horizontal"===n.orientation?e.clientX-i.left-this._pressData.delta:e.clientY-i.top-this._pressData.delta,n.moveHandle(this._pressData.index,t)}_evtPointerUp(e){0===e.button&&(e.preventDefault(),e.stopPropagation(),this._releaseMouse())}_releaseMouse(){this._pressData&&(this._pressData.override.dispose(),this._pressData=null,this._handleMoved.emit(),document.removeEventListener("keydown",this,!0),document.removeEventListener("pointerup",this,!0),document.removeEventListener("pointermove",this,!0),document.removeEventListener("contextmenu",this,!0))}}!function(e){class t{createHandle(){let e=document.createElement("div");return e.className="lm-SplitPanel-handle",e}}e.Renderer=t,e.defaultRenderer=new t,e.getStretch=function(e){return oe.getStretch(e)},e.setStretch=function(e,t){oe.setStretch(e,t)}}(ue||(ue={})),function(e){e.createLayout=function(e){return e.layout||new oe({renderer:e.renderer||ue.defaultRenderer,orientation:e.orientation,alignment:e.alignment,spacing:e.spacing})}}(Z||(Z={}));class de extends ue{constructor(e={}){super({...e,layout:Q.createLayout(e)}),this._widgetSizesCache=new WeakMap,this._expansionToggled=new x(this),this.addClass("lm-AccordionPanel")}get renderer(){return this.layout.renderer}get titleSpace(){return this.layout.titleSpace}set titleSpace(e){this.layout.titleSpace=e}get titles(){return this.layout.titles}get expansionToggled(){return this._expansionToggled}addWidget(e){super.addWidget(e),e.title.changed.connect(this._onTitleChanged,this)}collapse(e){const t=this.layout.widgets[e];t&&!t.isHidden&&this._toggleExpansion(e)}expand(e){const t=this.layout.widgets[e];t&&t.isHidden&&this._toggleExpansion(e)}insertWidget(e,t){super.insertWidget(e,t),t.title.changed.connect(this._onTitleChanged,this)}handleEvent(e){switch(super.handleEvent(e),e.type){case"click":this._evtClick(e);break;case"keydown":this._eventKeyDown(e)}}onBeforeAttach(e){this.node.addEventListener("click",this),this.node.addEventListener("keydown",this),super.onBeforeAttach(e)}onAfterDetach(e){super.onAfterDetach(e),this.node.removeEventListener("click",this),this.node.removeEventListener("keydown",this)}_onTitleChanged(e){const t=i.findFirstIndex(this.widgets,(t=>t.contains(e.owner)));t>=0&&(this.layout.updateTitle(t,e.owner),this.update())}_computeWidgetSize(e){const t=this.layout,n=t.widgets[e];if(!n)return;const i=n.isHidden,r=t.absoluteSizes(),s=(i?-1:1)*this.spacing,o=r.reduce(((e,t)=>e+t));let a=[...r];if(i){const t=this._widgetSizesCache.get(n);if(!t)return;a[e]+=t;const i=a.map((e=>e-t>0)).lastIndexOf(!0);-1===i?a.forEach(((n,i)=>{i!==e&&(a[i]-=r[i]/o*(t-s))})):a[i]-=t-s}else{const t=r[e];this._widgetSizesCache.set(n,t),a[e]=0;const i=a.map((e=>e>0)).lastIndexOf(!0);if(-1===i)return;a[i]=r[i]+t+s}return a.map((e=>e/(o+s)))}_evtClick(e){const t=e.target;if(t){const n=i.findFirstIndex(this.titles,(e=>e.contains(t)));n>=0&&(e.preventDefault(),e.stopPropagation(),this._toggleExpansion(n))}}_eventKeyDown(e){if(e.defaultPrevented)return;const t=e.target;let n=!1;if(t){const r=i.findFirstIndex(this.titles,(e=>e.contains(t)));if(r>=0){const i=e.keyCode.toString();if(e.key.match(/Space|Enter/)||i.match(/13|32/))t.click(),n=!0;else if("horizontal"===this.orientation?e.key.match(/ArrowLeft|ArrowRight/)||i.match(/37|39/):e.key.match(/ArrowUp|ArrowDown/)||i.match(/38|40/)){const t=e.key.match(/ArrowLeft|ArrowUp/)||i.match(/37|38/)?-1:1,s=this.titles.length,o=(r+s+t)%s;this.titles[o].focus(),n=!0}else"End"===e.key||"35"===i?(this.titles[this.titles.length-1].focus(),n=!0):"Home"!==e.key&&"36"!==i||(this.titles[0].focus(),n=!0)}n&&e.preventDefault()}}_toggleExpansion(e){const t=this.titles[e],n=this.layout.widgets[e],i=this._computeWidgetSize(e);i&&this.setRelativeSizes(i,!1),n.isHidden?(t.classList.add("lm-mod-expanded"),t.setAttribute("aria-expanded","true"),n.show()):(t.classList.remove("lm-mod-expanded"),t.setAttribute("aria-expanded","false"),n.hide()),this._expansionToggled.emit(e)}}!function(e){class t extends ue.Renderer{constructor(){super(),this.titleClassName="lm-AccordionPanel-title",this._titleID=0,this._titleKeys=new WeakMap,this._uuid=++t._nInstance}createCollapseIcon(e){return document.createElement("span")}createSectionTitle(e){const t=document.createElement("h3");t.setAttribute("tabindex","0"),t.id=this.createTitleKey(e),t.className=this.titleClassName;for(const n in e.dataset)t.dataset[n]=e.dataset[n];t.appendChild(this.createCollapseIcon(e)).className="lm-AccordionPanel-titleCollapser";const n=t.appendChild(document.createElement("span"));return n.className="lm-AccordionPanel-titleLabel",n.textContent=e.label,n.title=e.caption||e.label,t}createTitleKey(e){let t=this._titleKeys.get(e);return void 0===t&&(t=`title-key-${this._uuid}-${this._titleID++}`,this._titleKeys.set(e,t)),t}}t._nInstance=0,e.Renderer=t,e.defaultRenderer=new t}(de||(de={})),function(e){e.createLayout=function(e){return e.layout||new ae({renderer:e.renderer||de.defaultRenderer,orientation:e.orientation,alignment:e.alignment,spacing:e.spacing,titleSpace:e.titleSpace})}}(Q||(Q={}));class ce extends K{constructor(e={}){super(),this._fixed=0,this._spacing=4,this._dirty=!1,this._sizers=[],this._items=[],this._box=null,this._alignment="start",this._direction="top-to-bottom",void 0!==e.direction&&(this._direction=e.direction),void 0!==e.alignment&&(this._alignment=e.alignment),void 0!==e.spacing&&(this._spacing=se.clampDimension(e.spacing))}dispose(){for(const e of this._items)e.dispose();this._box=null,this._items.length=0,this._sizers.length=0,super.dispose()}get direction(){return this._direction}set direction(e){this._direction!==e&&(this._direction=e,this.parent&&(this.parent.dataset.direction=e,this.parent.fit()))}get alignment(){return this._alignment}set alignment(e){this._alignment!==e&&(this._alignment=e,this.parent&&(this.parent.dataset.alignment=e,this.parent.update()))}get spacing(){return this._spacing}set spacing(e){e=se.clampDimension(e),this._spacing!==e&&(this._spacing=e,this.parent&&this.parent.fit())}init(){this.parent.dataset.direction=this.direction,this.parent.dataset.alignment=this.alignment,super.init()}attachWidget(e,t){i.insert(this._items,e,new G(t)),i.insert(this._sizers,e,new W),this.parent.isAttached&&g.sendMessage(t,V.Msg.BeforeAttach),this.parent.node.appendChild(t.node),this.parent.isAttached&&g.sendMessage(t,V.Msg.AfterAttach),this.parent.fit()}moveWidget(e,t,n){i.move(this._items,e,t),i.move(this._sizers,e,t),this.parent.update()}detachWidget(e,t){let n=i.removeAt(this._items,e);i.removeAt(this._sizers,e),this.parent.isAttached&&g.sendMessage(t,V.Msg.BeforeDetach),this.parent.node.removeChild(t.node),this.parent.isAttached&&g.sendMessage(t,V.Msg.AfterDetach),n.dispose(),this.parent.fit()}onBeforeShow(e){super.onBeforeShow(e),this.parent.update()}onBeforeAttach(e){super.onBeforeAttach(e),this.parent.fit()}onChildShown(e){this.parent.fit()}onChildHidden(e){this.parent.fit()}onResize(e){this.parent.isVisible&&this._update(e.width,e.height)}onUpdateRequest(e){this.parent.isVisible&&this._update(-1,-1)}onFitRequest(e){this.parent.isAttached&&this._fit()}_fit(){let e=0;for(let t=0,n=this._items.length;t0)switch(this._alignment){case"start":break;case"center":l=0,d=i/2;break;case"end":l=0,d=i;break;case"justify":l=i/n,d=0;break;default:throw"unreachable"}for(let e=0,t=this._items.length;e0,coerce:(e,t)=>Math.max(0,Math.floor(t)),changed:t}),e.sizeBasisProperty=new E({name:"sizeBasis",create:()=>0,coerce:(e,t)=>Math.max(0,Math.floor(t)),changed:t}),e.isHorizontal=function(e){return"left-to-right"===e||"right-to-left"===e},e.clampSpacing=function(e){return Math.max(0,Math.floor(e))}}(ee||(ee={}));class he extends le{constructor(e={}){super({layout:te.createLayout(e)}),this.addClass("lm-BoxPanel")}get direction(){return this.layout.direction}set direction(e){this.layout.direction=e}get alignment(){return this.layout.alignment}set alignment(e){this.layout.alignment=e}get spacing(){return this.layout.spacing}set spacing(e){this.layout.spacing=e}onChildAdded(e){e.child.addClass("lm-BoxPanel-child")}onChildRemoved(e){e.child.removeClass("lm-BoxPanel-child")}}!function(e){e.getStretch=function(e){return ce.getStretch(e)},e.setStretch=function(e,t){ce.setStretch(e,t)},e.getSizeBasis=function(e){return ce.getSizeBasis(e)},e.setSizeBasis=function(e,t){ce.setSizeBasis(e,t)}}(he||(he={})),function(e){e.createLayout=function(e){return e.layout||new ce(e)}}(te||(te={}));class pe extends V{constructor(e){super({node:ne.createNode()}),this._activeIndex=-1,this._items=[],this._results=null,this.addClass("lm-CommandPalette"),this.setFlag(V.Flag.DisallowLayout),this.commands=e.commands,this.renderer=e.renderer||pe.defaultRenderer,this.commands.commandChanged.connect(this._onGenericChange,this),this.commands.keyBindingChanged.connect(this._onGenericChange,this)}dispose(){this._items.length=0,this._results=null,super.dispose()}get searchNode(){return this.node.getElementsByClassName("lm-CommandPalette-search")[0]}get inputNode(){return this.node.getElementsByClassName("lm-CommandPalette-input")[0]}get contentNode(){return this.node.getElementsByClassName("lm-CommandPalette-content")[0]}get items(){return this._items}addItem(e){let t=ne.createItem(this.commands,e);return this._items.push(t),this.refresh(),t}addItems(e){const t=e.map((e=>ne.createItem(this.commands,e)));return t.forEach((e=>this._items.push(e))),this.refresh(),t}removeItem(e){this.removeItemAt(this._items.indexOf(e))}removeItemAt(e){i.removeAt(this._items,e)&&this.refresh()}clearItems(){0!==this._items.length&&(this._items.length=0,this.refresh())}refresh(){this._results=null,""!==this.inputNode.value?this.node.getElementsByClassName("lm-close-icon")[0].style.display="inherit":this.node.getElementsByClassName("lm-close-icon")[0].style.display="none",this.update()}handleEvent(e){switch(e.type){case"click":this._evtClick(e);break;case"keydown":this._evtKeyDown(e);break;case"input":this.refresh();break;case"focus":case"blur":this._toggleFocused()}}onBeforeAttach(e){this.node.addEventListener("click",this),this.node.addEventListener("keydown",this),this.node.addEventListener("input",this),this.node.addEventListener("focus",this,!0),this.node.addEventListener("blur",this,!0)}onAfterDetach(e){this.node.removeEventListener("click",this),this.node.removeEventListener("keydown",this),this.node.removeEventListener("input",this),this.node.removeEventListener("focus",this,!0),this.node.removeEventListener("blur",this,!0)}onAfterShow(e){this.update(),super.onAfterShow(e)}onActivateRequest(e){if(this.isAttached){let e=this.inputNode;e.focus(),e.select()}}onUpdateRequest(e){if(this.isHidden)return;let t=this.inputNode.value,n=this.contentNode,r=this._results;if(r||(r=this._results=ne.search(this._items,t),this._activeIndex=t?i.findFirstIndex(r,ne.canActivate):-1),!t&&0===r.length)return void S.render(null,n);if(t&&0===r.length){let e=this.renderer.renderEmptyMessage({query:t});return void S.render(e,n)}let s=this.renderer,o=this._activeIndex,a=new Array(r.length);for(let e=0,t=r.length;e=r.length)n.scrollTop=0;else{let e=n.children[o];u.scrollIntoViewIfNeeded(n,e)}}_evtClick(e){if(0!==e.button)return;if(e.target.classList.contains("lm-close-icon"))return this.inputNode.value="",void this.refresh();let t=i.findFirstIndex(this.contentNode.children,(t=>t.contains(e.target)));-1!==t&&(e.preventDefault(),e.stopPropagation(),this._execute(t))}_evtKeyDown(e){if(!(e.altKey||e.ctrlKey||e.metaKey||e.shiftKey))switch(e.keyCode){case 13:e.preventDefault(),e.stopPropagation(),this._execute(this._activeIndex);break;case 38:e.preventDefault(),e.stopPropagation(),this._activatePreviousItem();break;case 40:e.preventDefault(),e.stopPropagation(),this._activateNextItem()}}_activateNextItem(){if(!this._results||0===this._results.length)return;let e=this._activeIndex,t=this._results.length,n=ee-t)),c=a.slice(0,d),h=a.slice(d);for(let e=0,t=h.length;en.command===e&&A.JSONExt.deepEqual(n.args,t)))||null}}}(ne||(ne={}));class ge extends V{constructor(e){super({node:ie.createNode()}),this._childIndex=-1,this._activeIndex=-1,this._openTimerID=0,this._closeTimerID=0,this._items=[],this._childMenu=null,this._parentMenu=null,this._aboutToClose=new x(this),this._menuRequested=new x(this),this.addClass("lm-Menu"),this.setFlag(V.Flag.DisallowLayout),this.commands=e.commands,this.renderer=e.renderer||ge.defaultRenderer}dispose(){this.close(),this._items.length=0,super.dispose()}get aboutToClose(){return this._aboutToClose}get menuRequested(){return this._menuRequested}get parentMenu(){return this._parentMenu}get childMenu(){return this._childMenu}get rootMenu(){let e=this;for(;e._parentMenu;)e=e._parentMenu;return e}get leafMenu(){let e=this;for(;e._childMenu;)e=e._childMenu;return e}get contentNode(){return this.node.getElementsByClassName("lm-Menu-content")[0]}get activeItem(){return this._items[this._activeIndex]||null}set activeItem(e){this.activeIndex=e?this._items.indexOf(e):-1}get activeIndex(){return this._activeIndex}set activeIndex(e){(e<0||e>=this._items.length)&&(e=-1),-1===e||ie.canActivate(this._items[e])||(e=-1),this._activeIndex!==e&&(this._activeIndex=e,this._activeIndex>=0&&this.contentNode.childNodes[this._activeIndex]&&this.contentNode.childNodes[this._activeIndex].focus(),this.update())}get items(){return this._items}activateNextItem(){let e=this._items.length,t=this._activeIndex,n=t{this.activeIndex=e}})}S.render(s,this.contentNode)}onCloseRequest(e){this._cancelOpenTimer(),this._cancelCloseTimer(),this.activeIndex=-1;let t=this._childMenu;t&&(this._childIndex=-1,this._childMenu=null,t._parentMenu=null,t.close());let n=this._parentMenu;n&&(this._parentMenu=null,n._childIndex=-1,n._childMenu=null,n.activate()),this.isAttached&&this._aboutToClose.emit(void 0),super.onCloseRequest(e)}_evtKeyDown(e){e.preventDefault(),e.stopPropagation();let t=e.keyCode;if(13===t)return void this.triggerActiveItem();if(27===t)return void this.close();if(37===t)return void(this._parentMenu?this.close():this._menuRequested.emit("previous"));if(38===t)return void this.activatePreviousItem();if(39===t){let e=this.activeItem;return void(e&&"submenu"===e.type?this.triggerActiveItem():this.rootMenu._menuRequested.emit("next"))}if(40===t)return void this.activateNextItem();let n=R().keyForKeydownEvent(e);if(!n)return;let i=this._activeIndex+1,r=ie.findMnemonic(this._items,n,i);-1===r.index||r.multiple?-1!==r.index?this.activeIndex=r.index:-1!==r.auto&&(this.activeIndex=r.auto):(this.activeIndex=r.index,this.triggerActiveItem())}_evtMouseUp(e){0===e.button&&(e.preventDefault(),e.stopPropagation(),this.triggerActiveItem())}_evtMouseMove(e){let t=i.findFirstIndex(this.contentNode.children,(t=>u.hitTest(t,e.clientX,e.clientY)));if(t===this._activeIndex)return;if(this.activeIndex=t,t=this.activeIndex,t===this._childIndex)return this._cancelOpenTimer(),void this._cancelCloseTimer();-1!==this._childIndex&&this._startCloseTimer(),this._cancelOpenTimer();let n=this.activeItem;n&&"submenu"===n.type&&n.submenu&&this._startOpenTimer()}_evtMouseEnter(e){for(let e=this._parentMenu;e;e=e._parentMenu)e._cancelOpenTimer(),e._cancelCloseTimer(),e.activeIndex=e._childIndex}_evtMouseLeave(e){if(this._cancelOpenTimer(),!this._childMenu)return void(this.activeIndex=-1);let{clientX:t,clientY:n}=e;u.hitTest(this._childMenu.node,t,n)?this._cancelCloseTimer():(this.activeIndex=-1,this._startCloseTimer())}_evtMouseDown(e){this._parentMenu||(ie.hitTestMenus(this,e.clientX,e.clientY)?(e.preventDefault(),e.stopPropagation()):this.close())}_openChildMenu(e=!1){let t=this.activeItem;if(!t||"submenu"!==t.type||!t.submenu)return void this._closeChildMenu();let n=t.submenu;if(n===this._childMenu)return;ge.saveWindowData(),this._closeChildMenu(),this._childMenu=n,this._childIndex=this._activeIndex,n._parentMenu=this,g.sendMessage(this,V.Msg.UpdateRequest);let i=this.contentNode.children[this._activeIndex];ie.openSubmenu(n,i),e&&(n.activeIndex=-1,n.activateNextItem()),n.activate()}_closeChildMenu(){this._childMenu&&this._childMenu.close()}_startOpenTimer(){0===this._openTimerID&&(this._openTimerID=window.setTimeout((()=>{this._openTimerID=0,this._openChildMenu()}),ie.TIMER_DELAY))}_startCloseTimer(){0===this._closeTimerID&&(this._closeTimerID=window.setTimeout((()=>{this._closeTimerID=0,this._closeChildMenu()}),ie.TIMER_DELAY))}_cancelOpenTimer(){0!==this._openTimerID&&(clearTimeout(this._openTimerID),this._openTimerID=0)}_cancelCloseTimer(){0!==this._closeTimerID&&(clearTimeout(this._closeTimerID),this._closeTimerID=0)}static saveWindowData(){ie.saveWindowData()}}!function(e){class t{renderItem(e){let t=this.createItemClass(e),n=this.createItemDataset(e),i=this.createItemARIA(e);return B.li({className:t,dataset:n,tabindex:"0",onfocus:e.onfocus,...i},this.renderIcon(e),this.renderLabel(e),this.renderShortcut(e),this.renderSubmenu(e))}renderIcon(e){let t=this.createIconClass(e);return B.div({className:t},e.item.icon,e.item.iconLabel)}renderLabel(e){let t=this.formatLabel(e);return B.div({className:"lm-Menu-itemLabel"},t)}renderShortcut(e){let t=this.formatShortcut(e);return B.div({className:"lm-Menu-itemShortcut"},t)}renderSubmenu(e){return B.div({className:"lm-Menu-itemSubmenuIcon"})}createItemClass(e){let t="lm-Menu-item";e.item.isEnabled||(t+=" lm-mod-disabled"),e.item.isToggled&&(t+=" lm-mod-toggled"),e.item.isVisible||(t+=" lm-mod-hidden"),e.active&&(t+=" lm-mod-active"),e.collapsed&&(t+=" lm-mod-collapsed");let n=e.item.className;return n&&(t+=` ${n}`),t}createItemDataset(e){let t,{type:n,command:i,dataset:r}=e.item;return t="command"===n?{...r,type:n,command:i}:{...r,type:n},t}createIconClass(e){let t="lm-Menu-itemIcon",n=e.item.iconClass;return n?`${t} ${n}`:t}createItemARIA(e){let t={};switch(e.item.type){case"separator":t.role="presentation";break;case"submenu":t["aria-haspopup"]="true",e.item.isEnabled||(t["aria-disabled"]="true");break;default:e.item.isEnabled||(t["aria-disabled"]="true"),t.role="menuitem"}return t}formatLabel(e){let{label:t,mnemonic:n}=e.item;if(n<0||n>=t.length)return t;let i=t.slice(0,n),r=t.slice(n+1),s=t[n];return[i,B.span({className:"lm-Menu-itemMnemonic"},s),r]}formatShortcut(e){let t=e.item.keyBinding;return t?M.CommandRegistry.formatKeystroke(t.keys):null}}e.Renderer=t,e.defaultRenderer=new t}(ge||(ge={})),function(e){e.TIMER_DELAY=300,e.SUBMENU_OVERLAP=3;let t=null,n=0;function r(){return n>0?(n--,t):o()}function s(e){return"separator"!==e.type&&e.isEnabled&&e.isVisible}function o(){return{pageXOffset:window.pageXOffset,pageYOffset:window.pageYOffset,clientWidth:document.documentElement.clientWidth,clientHeight:document.documentElement.clientHeight}}e.saveWindowData=function(){t=o(),n++},e.createNode=function(){let e=document.createElement("div"),t=document.createElement("ul");return t.className="lm-Menu-content",e.appendChild(t),t.setAttribute("role","menu"),e.tabIndex=0,e},e.canActivate=s,e.createItem=function(e,t){return new a(e.commands,t)},e.hitTestMenus=function(e,t,n){for(let i=e;i;i=i.childMenu)if(u.hitTest(i.node,t,n))return!0;return!1},e.computeCollapsed=function(e){let t=new Array(e.length);i.fill(t,!1);let n=0,r=e.length;for(;n=0;--s){let n=e[s];if(n.isVisible){if("separator"!==n.type)break;t[s]=!0}}let o=!1;for(;++na+u&&(t=a+u-f),!s&&n+m>l+d&&(n>l+d?n=l+d-m:n-=m),p.transform=`translate(${Math.max(0,t)}px, ${Math.max(0,n)}px`,p.opacity="1"},e.openSubmenu=function(t,n){const i=r();let s=i.pageXOffset,o=i.pageYOffset,a=i.clientWidth,l=i.clientHeight;g.sendMessage(t,V.Msg.UpdateRequest);let d=l,c=t.node,h=c.style;h.opacity="0",h.maxHeight=`${d}px`,V.attach(t,document.body);let{width:p,height:f}=c.getBoundingClientRect(),m=u.boxSizing(t.node),v=n.getBoundingClientRect(),b=v.right-e.SUBMENU_OVERLAP;b+p>s+a&&(b=v.left+e.SUBMENU_OVERLAP-p);let _=v.top-m.borderTop-m.paddingTop;_+f>o+l&&(_=v.bottom+m.borderBottom+m.paddingBottom-f),h.transform=`translate(${Math.max(0,b)}px, ${Math.max(0,_)}px`,h.opacity="1"},e.findMnemonic=function(e,t,n){let i=-1,r=-1,o=!1,a=t.toUpperCase();for(let t=0,l=e.length;t=0&&hn.command===e&&A.JSONExt.deepEqual(n.args,t)))||null}return null}}}(ie||(ie={})),function(e){function t(e,t){let n=e.rank,i=t.rank;return n!==i?n=this._titles.length)&&(e=-1),this._currentIndex===e)return;let t=this._currentIndex,n=this._titles[t]||null,i=e,r=this._titles[i]||null;this._currentIndex=i,this._previousTitle=n,this.update(),this._currentChanged.emit({previousIndex:t,previousTitle:n,currentIndex:i,currentTitle:r})}get name(){return this._name}set name(e){this._name=e,e?this.contentNode.setAttribute("aria-label",e):this.contentNode.removeAttribute("aria-label")}get orientation(){return this._orientation}set orientation(e){this._orientation!==e&&(this._releaseMouse(),this._orientation=e,this.dataset.orientation=e,this.contentNode.setAttribute("aria-orientation",e))}get addButtonEnabled(){return this._addButtonEnabled}set addButtonEnabled(e){this._addButtonEnabled!==e&&(this._addButtonEnabled=e,e?this.addButtonNode.classList.remove("lm-mod-hidden"):this.addButtonNode.classList.add("lm-mod-hidden"))}get titles(){return this._titles}get contentNode(){return this.node.getElementsByClassName("lm-TabBar-content")[0]}get addButtonNode(){return this.node.getElementsByClassName("lm-TabBar-addButton")[0]}addTab(e){return this.insertTab(this._titles.length,e)}insertTab(e,t){this._releaseMouse();let n=ve.asTitle(t),r=this._titles.indexOf(n),s=Math.max(0,Math.min(e,this._titles.length));return-1===r?(i.insert(this._titles,s,n),n.changed.connect(this._onTitleChanged,this),this.update(),this._adjustCurrentForInsert(s,n),n):(s===this._titles.length&&s--,r===s||(i.move(this._titles,r,s),this.update(),this._adjustCurrentForMove(r,s)),n)}removeTab(e){this.removeTabAt(this._titles.indexOf(e))}removeTabAt(e){this._releaseMouse();let t=i.removeAt(this._titles,e);t&&(t.changed.disconnect(this._onTitleChanged,this),t===this._previousTitle&&(this._previousTitle=null),this.update(),this._adjustCurrentForRemove(e,t))}clearTabs(){if(0===this._titles.length)return;this._releaseMouse();for(let e of this._titles)e.changed.disconnect(this._onTitleChanged,this);let e=this.currentIndex,t=this.currentTitle;this._currentIndex=-1,this._previousTitle=null,this._titles.length=0,this.update(),-1!==e&&this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:-1,currentTitle:null})}releaseMouse(){this._releaseMouse()}handleEvent(e){switch(e.type){case"pointerdown":this._evtPointerDown(e);break;case"pointermove":this._evtPointerMove(e);break;case"pointerup":this._evtPointerUp(e);break;case"dblclick":this._evtDblClick(e);break;case"keydown":e.eventPhase===Event.CAPTURING_PHASE?this._evtKeyDownCapturing(e):this._evtKeyDown(e);break;case"contextmenu":e.preventDefault(),e.stopPropagation()}}onBeforeAttach(e){this.node.addEventListener("pointerdown",this),this.node.addEventListener("dblclick",this),this.node.addEventListener("keydown",this)}onAfterDetach(e){this.node.removeEventListener("pointerdown",this),this.node.removeEventListener("dblclick",this),this.node.removeEventListener("keydown",this),this._releaseMouse()}onUpdateRequest(e){var t;let n=this._titles,i=this.renderer,r=this.currentTitle,s=new Array(n.length);const o=null!==(t=this._getCurrentTabindex())&&void 0!==t?t:this._currentIndex>-1?this._currentIndex:0;for(let e=0,t=n.length;eu.hitTest(t,e.clientX,e.clientY)));if(-1===n)return;let r=this.titles[n],s=t[n].querySelector(".lm-TabBar-tabLabel");if(s&&s.contains(e.target)){let e=r.label||"",t=s.innerHTML;s.innerHTML="";let n=document.createElement("input");n.classList.add("lm-TabBar-tabInput"),n.value=e,s.appendChild(n);let i=()=>{n.removeEventListener("blur",i),s.innerHTML=t,this.node.addEventListener("keydown",this)};n.addEventListener("dblclick",(e=>e.stopPropagation())),n.addEventListener("blur",i),n.addEventListener("keydown",(e=>{"Enter"===e.key?(""!==n.value&&(r.label=r.caption=n.value),i()):"Escape"===e.key&&i()})),this.node.removeEventListener("keydown",this),n.select(),n.focus(),s.children.length>0&&s.children[0].focus()}}_evtKeyDownCapturing(e){e.eventPhase===Event.CAPTURING_PHASE&&(e.preventDefault(),e.stopPropagation(),"Escape"===e.key&&this._releaseMouse())}_evtKeyDown(e){var t,n,r;if("Tab"!==e.key&&e.eventPhase!==Event.CAPTURING_PHASE)if("Enter"===e.key||"Spacebar"===e.key||" "===e.key){const t=document.activeElement;if(this.addButtonEnabled&&this.addButtonNode.contains(t))e.preventDefault(),e.stopPropagation(),this._addRequested.emit();else{const n=i.findFirstIndex(this.contentNode.children,(e=>e.contains(t)));n>=0&&(e.preventDefault(),e.stopPropagation(),this.currentIndex=n)}}else if(fe.includes(e.key)){const i=[...this.contentNode.children];if(this.addButtonEnabled&&i.push(this.addButtonNode),i.length<=1)return;e.preventDefault(),e.stopPropagation();let s,o=i.indexOf(document.activeElement);-1===o&&(o=this._currentIndex),"ArrowRight"===e.key&&"horizontal"===this._orientation||"ArrowDown"===e.key&&"vertical"===this._orientation?s=null!==(t=i[o+1])&&void 0!==t?t:i[0]:"ArrowLeft"===e.key&&"horizontal"===this._orientation||"ArrowUp"===e.key&&"vertical"===this._orientation?s=null!==(n=i[o-1])&&void 0!==n?n:i[i.length-1]:"Home"===e.key?s=i[0]:"End"===e.key&&(s=i[i.length-1]),s&&(null===(r=i[o])||void 0===r||r.setAttribute("tabindex","-1"),null==s||s.setAttribute("tabindex","0"),s.focus())}}_evtPointerDown(e){if(0!==e.button&&1!==e.button)return;if(this._dragData)return;if(e.target.classList.contains("lm-TabBar-tabInput"))return;let t=this.addButtonEnabled&&this.addButtonNode.contains(e.target),n=this.contentNode.children,r=i.findFirstIndex(n,(t=>u.hitTest(t,e.clientX,e.clientY)));if(-1===r&&!t)return;if(e.preventDefault(),e.stopPropagation(),this._dragData={tab:n[r],index:r,pressX:e.clientX,pressY:e.clientY,tabPos:-1,tabSize:-1,tabPressPos:-1,targetIndex:-1,tabLayout:null,contentRect:null,override:null,dragActive:!1,dragAborted:!1,detachRequested:!1},this.document.addEventListener("pointerup",this,!0),1===e.button||t)return;let s=n[r].querySelector(this.renderer.closeIconSelector);s&&s.contains(e.target)||(this.tabsMovable&&(this.document.addEventListener("pointermove",this,!0),this.document.addEventListener("keydown",this,!0),this.document.addEventListener("contextmenu",this,!0)),this.allowDeselect&&this.currentIndex===r?this.currentIndex=-1:this.currentIndex=r,-1!==this.currentIndex&&this._tabActivateRequested.emit({index:this.currentIndex,title:this.currentTitle}))}_evtPointerMove(e){let t=this._dragData;if(!t)return;e.preventDefault(),e.stopPropagation();let n=this.contentNode.children;if(t.dragActive||ve.dragExceeded(t,e)){if(!t.dragActive){let e=t.tab.getBoundingClientRect();"horizontal"===this._orientation?(t.tabPos=t.tab.offsetLeft,t.tabSize=e.width,t.tabPressPos=t.pressX-e.left):(t.tabPos=t.tab.offsetTop,t.tabSize=e.height,t.tabPressPos=t.pressY-e.top),t.tabPressOffset={x:t.pressX-e.left,y:t.pressY-e.top},t.tabLayout=ve.snapTabLayout(n,this._orientation),t.contentRect=this.contentNode.getBoundingClientRect(),t.override=M.Drag.overrideCursor("default"),t.tab.classList.add("lm-mod-dragging"),this.addClass("lm-mod-dragging"),t.dragActive=!0}if(!t.detachRequested&&ve.detachExceeded(t,e)){t.detachRequested=!0;let i=t.index,r=e.clientX,s=e.clientY,o=n[i],a=this._titles[i];if(this._tabDetachRequested.emit({index:i,title:a,tab:o,clientX:r,clientY:s,offset:t.tabPressOffset}),t.dragAborted)return}ve.layoutTabs(n,t,e,this._orientation)}}_evtPointerUp(e){if(0!==e.button&&1!==e.button)return;const t=this._dragData;if(!t)return;if(e.preventDefault(),e.stopPropagation(),this.document.removeEventListener("pointermove",this,!0),this.document.removeEventListener("pointerup",this,!0),this.document.removeEventListener("keydown",this,!0),this.document.removeEventListener("contextmenu",this,!0),!t.dragActive){if(this._dragData=null,this.addButtonEnabled&&this.addButtonNode.contains(e.target))return void this._addRequested.emit(void 0);let n=this.contentNode.children,r=i.findFirstIndex(n,(t=>u.hitTest(t,e.clientX,e.clientY)));if(r!==t.index)return;let s=this._titles[r];if(!s.closable)return;if(1===e.button)return void this._tabCloseRequested.emit({index:r,title:s});let o=n[r].querySelector(this.renderer.closeIconSelector);return o&&o.contains(e.target)?void this._tabCloseRequested.emit({index:r,title:s}):void 0}if(0!==e.button)return;ve.finalizeTabPosition(t,this._orientation),t.tab.classList.remove("lm-mod-dragging");let n=ve.parseTransitionDuration(t.tab);setTimeout((()=>{if(t.dragAborted)return;this._dragData=null,ve.resetTabPositions(this.contentNode.children,this._orientation),t.override.dispose(),this.removeClass("lm-mod-dragging");let e=t.index,n=t.targetIndex;-1!==n&&e!==n&&(i.move(this._titles,e,n),this._adjustCurrentForMove(e,n),this._tabMoved.emit({fromIndex:e,toIndex:n,title:this._titles[n]}),g.sendMessage(this,V.Msg.UpdateRequest))}),n)}_releaseMouse(){let e=this._dragData;e&&(this._dragData=null,this.document.removeEventListener("pointermove",this,!0),this.document.removeEventListener("pointerup",this,!0),this.document.removeEventListener("keydown",this,!0),this.document.removeEventListener("contextmenu",this,!0),e.dragAborted=!0,e.dragActive&&(ve.resetTabPositions(this.contentNode.children,this._orientation),e.override.dispose(),e.tab.classList.remove("lm-mod-dragging"),this.removeClass("lm-mod-dragging")))}_adjustCurrentForInsert(e,t){let n=this.currentTitle,i=this._currentIndex,r=this.insertBehavior;if("select-tab"===r||"select-tab-if-needed"===r&&-1===i)return this._currentIndex=e,this._previousTitle=n,void this._currentChanged.emit({previousIndex:i,previousTitle:n,currentIndex:e,currentTitle:t});i>=e&&this._currentIndex++}_adjustCurrentForMove(e,t){this._currentIndex===e?this._currentIndex=t:this._currentIndex=t?this._currentIndex++:this._currentIndex>e&&this._currentIndex<=t&&this._currentIndex--}_adjustCurrentForRemove(e,t){let n=this._currentIndex,i=this.removeBehavior;if(n===e){if(0===this._titles.length)return this._currentIndex=-1,void this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:-1,currentTitle:null});if("select-tab-after"===i)return this._currentIndex=Math.min(e,this._titles.length-1),void this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:this._currentIndex,currentTitle:this.currentTitle});if("select-tab-before"===i)return this._currentIndex=Math.max(0,e-1),void this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:this._currentIndex,currentTitle:this.currentTitle});if("select-previous-tab"===i)return this._previousTitle?(this._currentIndex=this._titles.indexOf(this._previousTitle),this._previousTitle=null):this._currentIndex=Math.min(e,this._titles.length-1),void this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:this._currentIndex,currentTitle:this.currentTitle});this._currentIndex=-1,this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:-1,currentTitle:null})}else n>e&&this._currentIndex--}_onTitleChanged(e){this.update()}}var ve,be,_e,Ae,ye,we,Ce,Ee;!function(e){class t{constructor(){this.closeIconSelector=".lm-TabBar-tabCloseIcon",this._tabID=0,this._tabKeys=new WeakMap,this._uuid=++t._nInstance}renderTab(e){let t=e.title.caption,n=this.createTabKey(e),i=n,r=this.createTabStyle(e),s=this.createTabClass(e),o=this.createTabDataset(e),a=this.createTabARIA(e);return e.title.closable?B.li({id:i,key:n,className:s,title:t,style:r,dataset:o,...a},this.renderIcon(e),this.renderLabel(e),this.renderCloseIcon(e)):B.li({id:i,key:n,className:s,title:t,style:r,dataset:o,...a},this.renderIcon(e),this.renderLabel(e))}renderIcon(e){const{title:t}=e;let n=this.createIconClass(e);return B.div({className:n},t.icon,t.iconLabel)}renderLabel(e){return B.div({className:"lm-TabBar-tabLabel"},e.title.label)}renderCloseIcon(e){return B.div({className:"lm-TabBar-tabCloseIcon"})}createTabKey(e){let t=this._tabKeys.get(e.title);return void 0===t&&(t=`tab-key-${this._uuid}-${this._tabID++}`,this._tabKeys.set(e.title,t)),t}createTabStyle(e){return{zIndex:`${e.zIndex}`}}createTabClass(e){let t="lm-TabBar-tab";return e.title.className&&(t+=` ${e.title.className}`),e.title.closable&&(t+=" lm-mod-closable"),e.current&&(t+=" lm-mod-current"),t}createTabDataset(e){return e.title.dataset}createTabARIA(e){var t;return{role:"tab","aria-selected":e.current.toString(),tabindex:`${null!==(t=e.tabIndex)&&void 0!==t?t:"-1"}`}}createIconClass(e){let t="lm-TabBar-tabIcon",n=e.title.iconClass;return n?`${t} ${n}`:t}}t._nInstance=0,e.Renderer=t,e.defaultRenderer=new t,e.addButtonSelector=".lm-TabBar-addButton"}(me||(me={})),function(e){e.DRAG_THRESHOLD=5,e.DETACH_THRESHOLD=20,e.createNode=function(){let e=document.createElement("div"),t=document.createElement("ul");t.setAttribute("role","tablist"),t.className="lm-TabBar-content",e.appendChild(t);let n=document.createElement("div");return n.className="lm-TabBar-addButton lm-mod-hidden",n.setAttribute("tabindex","-1"),n.setAttribute("role","button"),e.appendChild(n),e},e.asTitle=function(e){return e instanceof H?e:new H(e)},e.parseTransitionDuration=function(e){let t=window.getComputedStyle(e);return 1e3*(parseFloat(t.transitionDuration)||0)},e.snapTabLayout=function(e,t){let n=new Array(e.length);for(let i=0,r=e.length;i=e.DRAG_THRESHOLD||r>=e.DRAG_THRESHOLD},e.detachExceeded=function(t,n){let i=t.contentRect;return n.clientX=i.right+e.DETACH_THRESHOLD||n.clientY=i.bottom+e.DETACH_THRESHOLD},e.layoutTabs=function(e,t,n,i){let r,s,o,a;"horizontal"===i?(r=t.pressX,s=n.clientX-t.contentRect.left,o=n.clientX,a=t.contentRect.width):(r=t.pressY,s=n.clientY-t.contentRect.top,o=n.clientY,a=t.contentRect.height);let l=t.index,u=s-t.tabPressPos,d=u+t.tabSize;for(let n=0,s=e.length;n>1);if(nt.index&&d>h)s=-t.tabSize-c.margin+"px",l=Math.max(l,n);else if(n===t.index){let e=o-r,n=a-(t.tabPos+t.tabSize);s=`${Math.max(-t.tabPos,Math.min(e,n))}px`}else s="";"horizontal"===i?e[n].style.left=s:e[n].style.top=s}t.targetIndex=l},e.finalizeTabPosition=function(e,t){let n,i;if(n="horizontal"===t?e.contentRect.width:e.contentRect.height,e.targetIndex===e.index)i=0;else if(e.targetIndex>e.index){let t=e.tabLayout[e.targetIndex];i=t.pos+t.size-e.tabSize-e.tabPos}else i=e.tabLayout[e.targetIndex].pos-e.tabPos;let r=n-(e.tabPos+e.tabSize),s=Math.max(-e.tabPos,Math.min(i,r));"horizontal"===t?e.tab.style.left=`${s}px`:e.tab.style.top=`${s}px`},e.resetTabPositions=function(e,t){for(const n of e)"horizontal"===t?n.style.left="":n.style.top=""}}(ve||(ve={}));class xe extends q{constructor(e){super(),this._spacing=4,this._dirty=!1,this._root=null,this._box=null,this._items=new Map,this.renderer=e.renderer,void 0!==e.spacing&&(this._spacing=se.clampDimension(e.spacing)),this._document=e.document||document,this._hiddenMode=void 0!==e.hiddenMode?e.hiddenMode:V.HiddenMode.Display}dispose(){let e=this[Symbol.iterator]();this._items.forEach((e=>{e.dispose()})),this._box=null,this._root=null,this._items.clear();for(const t of e)t.dispose();super.dispose()}get hiddenMode(){return this._hiddenMode}set hiddenMode(e){if(this._hiddenMode!==e){this._hiddenMode=e;for(const e of this.tabBars())if(e.titles.length>1)for(const t of e.titles)t.owner.hiddenMode=this._hiddenMode}}get spacing(){return this._spacing}set spacing(e){e=se.clampDimension(e),this._spacing!==e&&(this._spacing=e,this.parent&&this.parent.fit())}get isEmpty(){return null===this._root}[Symbol.iterator](){return this._root?this._root.iterAllWidgets():o()}widgets(){return this._root?this._root.iterUserWidgets():o()}selectedWidgets(){return this._root?this._root.iterSelectedWidgets():o()}tabBars(){return this._root?this._root.iterTabBars():o()}handles(){return this._root?this._root.iterHandles():o()}moveHandle(e,t,n){let i=e.classList.contains("lm-mod-hidden");if(!this._root||i)return;let r,s=this._root.findSplitNode(e);s&&(r="horizontal"===s.node.orientation?t-e.offsetLeft:n-e.offsetTop,0!==r&&(s.node.holdSizes(),F.adjust(s.node.sizers,s.index,r),this.parent&&this.parent.update()))}saveLayout(){return this._root?(this._root.holdAllSizes(),{main:this._root.createConfig()}):{main:null}}restoreLayout(e){let t,n=new Set;t=e.main?be.normalizeAreaConfig(e.main,n):null;let i=this.widgets(),r=this.tabBars(),s=this.handles();this._root=null;for(const e of i)n.has(e)||(e.parent=null);for(const e of r)e.dispose();for(const e of s)e.parentNode&&e.parentNode.removeChild(e);for(const e of n)e.parent=this.parent;this._root=t?be.realizeAreaConfig(t,{createTabBar:e=>this._createTabBar(),createHandle:()=>this._createHandle()},this._document):null,this.parent&&(n.forEach((e=>{this.attachWidget(e)})),this.parent.fit())}addWidget(e,t={}){let n=t.ref||null,i=t.mode||"tab-after",r=null;if(this._root&&n&&(r=this._root.findTabNode(n)),n&&!r)throw new Error("Reference widget is not in the layout.");switch(e.parent=this.parent,i){case"tab-after":this._insertTab(e,n,r,!0);break;case"tab-before":this._insertTab(e,n,r,!1);break;case"split-top":this._insertSplit(e,n,r,"vertical",!1);break;case"split-left":this._insertSplit(e,n,r,"horizontal",!1);break;case"split-right":this._insertSplit(e,n,r,"horizontal",!0);break;case"split-bottom":this._insertSplit(e,n,r,"vertical",!0);break;case"merge-top":this._insertSplit(e,n,r,"vertical",!1,!0);break;case"merge-left":this._insertSplit(e,n,r,"horizontal",!1,!0);break;case"merge-right":this._insertSplit(e,n,r,"horizontal",!0,!0);break;case"merge-bottom":this._insertSplit(e,n,r,"vertical",!0,!0)}this.parent&&(this.attachWidget(e),this.parent.fit())}removeWidget(e){this._removeWidget(e),this.parent&&(this.detachWidget(e),this.parent.fit())}hitTestTabAreas(e,t){if(!this._root||!this.parent||!this.parent.isVisible)return null;this._box||(this._box=u.boxSizing(this.parent.node));let n=this.parent.node.getBoundingClientRect(),i=e-n.left-this._box.borderLeft,r=t-n.top-this._box.borderTop,s=this._root.hitTestTabNodes(i,r);if(!s)return null;let{tabBar:o,top:a,left:l,width:d,height:c}=s,h=this._box.borderLeft+this._box.borderRight,p=this._box.borderTop+this._box.borderBottom;return{tabBar:o,x:i,y:r,top:a,left:l,right:n.width-h-(l+d),bottom:n.height-p-(a+c),width:d,height:c}}init(){super.init();for(const e of this)this.attachWidget(e);for(const e of this.handles())this.parent.node.appendChild(e);this.parent.fit()}attachWidget(e){this.parent.node!==e.node.parentNode&&(this._items.set(e,new G(e)),this.parent.isAttached&&g.sendMessage(e,V.Msg.BeforeAttach),this.parent.node.appendChild(e.node),this.parent.isAttached&&g.sendMessage(e,V.Msg.AfterAttach))}detachWidget(e){if(this.parent.node!==e.node.parentNode)return;this.parent.isAttached&&g.sendMessage(e,V.Msg.BeforeDetach),this.parent.node.removeChild(e.node),this.parent.isAttached&&g.sendMessage(e,V.Msg.AfterDetach);let t=this._items.get(e);t&&(this._items.delete(e),t.dispose())}onBeforeShow(e){super.onBeforeShow(e),this.parent.update()}onBeforeAttach(e){super.onBeforeAttach(e),this.parent.fit()}onChildShown(e){this.parent.fit()}onChildHidden(e){this.parent.fit()}onResize(e){this.parent.isVisible&&this._update(e.width,e.height)}onUpdateRequest(e){this.parent.isVisible&&this._update(-1,-1)}onFitRequest(e){this.parent.isAttached&&this._fit()}_removeWidget(e){if(!this._root)return;let t=this._root.findTabNode(e);if(!t)return;if(be.removeAria(e),t.tabBar.titles.length>1)return t.tabBar.removeTab(e.title),void(this._hiddenMode===V.HiddenMode.Scale&&1==t.tabBar.titles.length&&(t.tabBar.titles[0].owner.hiddenMode=V.HiddenMode.Display));if(t.tabBar.dispose(),this._root===t)return void(this._root=null);this._root.holdAllSizes();let n=t.parent;t.parent=null;let r=i.removeFirstOf(n.children,t),s=i.removeAt(n.handles,r);if(i.removeAt(n.sizers,r),s.parentNode&&s.parentNode.removeChild(s),n.children.length>1)return void n.syncHandles();let o=n.parent;n.parent=null;let a=n.children[0],l=n.handles[0];if(n.children.length=0,n.handles.length=0,n.sizers.length=0,l.parentNode&&l.parentNode.removeChild(l),this._root===n)return a.parent=null,void(this._root=a);let u=o,d=u.children.indexOf(n);if(a instanceof be.TabLayoutNode)return a.parent=u,void(u.children[d]=a);let c=i.removeAt(u.handles,d);i.removeAt(u.children,d),i.removeAt(u.sizers,d),c.parentNode&&c.parentNode.removeChild(c);for(let e=0,t=a.children.length;e=n.length)&&(i=0),{type:"tab-area",widgets:n,currentIndex:i}}(t,n):function(t,n){let i=t.orientation,r=[],s=[];for(let o=0,a=t.children.length;o{let l=r(i,n,s),u=t(e.sizes[a]),d=n.createHandle();o.children.push(l),o.handles.push(d),o.sizers.push(u),l.parent=o})),o.syncHandles(),o.normalizeSizes(),o}(s,o,a),l};class n{constructor(e){this.parent=null,this._top=0,this._left=0,this._width=0,this._height=0;let t=new W,n=new W;t.stretch=0,n.stretch=1,this.tabBar=e,this.sizers=[t,n]}get top(){return this._top}get left(){return this._left}get width(){return this._width}get height(){return this._height}*iterAllWidgets(){yield this.tabBar,yield*this.iterUserWidgets()}*iterUserWidgets(){for(const e of this.tabBar.titles)yield e.owner}*iterSelectedWidgets(){let e=this.tabBar.currentTitle;e&&(yield e.owner)}*iterTabBars(){yield this.tabBar}*iterHandles(){}findTabNode(e){return-1!==this.tabBar.titles.indexOf(e.title)?this:null}findSplitNode(e){return null}findFirstTabNode(){return this}hitTestTabNodes(e,t){return e=this._left+this._width||t=this._top+this._height?null:this}createConfig(){return{type:"tab-area",widgets:this.tabBar.titles.map((e=>e.owner)),currentIndex:this.tabBar.currentIndex}}holdAllSizes(){}fit(e,t){let n=0,i=0,r=t.get(this.tabBar),s=this.tabBar.currentTitle,o=s?t.get(s.owner):void 0,[a,l]=this.sizers;return r&&r.fit(),o&&o.fit(),r&&!r.isHidden?(n=Math.max(n,r.minWidth),i+=r.minHeight,a.minSize=r.minHeight,a.maxSize=r.maxHeight):(a.minSize=0,a.maxSize=0),o&&!o.isHidden?(n=Math.max(n,o.minWidth),i+=o.minHeight,l.minSize=o.minHeight,l.maxSize=1/0):(l.minSize=0,l.maxSize=1/0),{minWidth:n,minHeight:i,maxWidth:1/0,maxHeight:1/0}}update(e,t,n,i,r,s){this._top=t,this._left=e,this._width=n,this._height=i;let o=s.get(this.tabBar),a=this.tabBar.currentTitle,l=a?s.get(a.owner):void 0;if(F.calc(this.sizers,i),o&&!o.isHidden){let i=this.sizers[0].size;o.update(e,t,n,i),t+=i}if(l&&!l.isHidden){let i=this.sizers[1].size;l.update(e,t,n,i)}}}e.TabLayoutNode=n;class i{constructor(e){this.parent=null,this.normalized=!1,this.children=[],this.sizers=[],this.handles=[],this.orientation=e}*iterAllWidgets(){for(const e of this.children)yield*e.iterAllWidgets()}*iterUserWidgets(){for(const e of this.children)yield*e.iterUserWidgets()}*iterSelectedWidgets(){for(const e of this.children)yield*e.iterSelectedWidgets()}*iterTabBars(){for(const e of this.children)yield*e.iterTabBars()}*iterHandles(){yield*this.handles;for(const e of this.children)yield*e.iterHandles()}findTabNode(e){for(let t=0,n=this.children.length;te.createConfig())),sizes:t}}syncHandles(){this.handles.forEach(((e,t)=>{e.setAttribute("data-orientation",this.orientation),t===this.handles.length-1?e.classList.add("lm-mod-hidden"):e.classList.remove("lm-mod-hidden")}))}holdSizes(){for(const e of this.sizers)e.sizeHint=e.size}holdAllSizes(){for(const e of this.children)e.holdAllSizes();this.holdSizes()}normalizeSizes(){let e=this.sizers.length;if(0===e)return;this.holdSizes();let t=this.sizers.reduce(((e,t)=>e+t.sizeHint),0);if(0===t)for(const t of this.sizers)t.size=t.sizeHint=1/e;else for(const e of this.sizers)e.size=e.sizeHint/=t;this.normalized=!0}createNormalizedSizes(){let e=this.sizers.length;if(0===e)return[];let t=this.sizers.map((e=>e.size)),n=t.reduce(((e,t)=>e+t),0);if(0===n)for(let n=t.length-1;n>-1;n--)t[n]=1/e;else for(let e=t.length-1;e>-1;e--)t[e]/=n;return t}fit(e,t){let n="horizontal"===this.orientation,i=Math.max(0,this.children.length-1)*e,r=n?i:0,s=n?0:i;for(let i=0,o=this.children.length;ithis._createTabBar(),createHandle:()=>this._createHandle()};this.layout=new xe({document:this._document,renderer:t,spacing:e.spacing,hiddenMode:e.hiddenMode}),this.overlay=e.overlay||new De.Overlay,this.node.appendChild(this.overlay.node)}dispose(){this._releaseMouse(),this.overlay.hide(0),this._drag&&this._drag.dispose(),super.dispose()}get hiddenMode(){return this.layout.hiddenMode}set hiddenMode(e){this.layout.hiddenMode=e}get layoutModified(){return this._layoutModified}get addRequested(){return this._addRequested}get renderer(){return this.layout.renderer}get spacing(){return this.layout.spacing}set spacing(e){this.layout.spacing=e}get mode(){return this._mode}set mode(e){if(this._mode===e)return;this._mode=e,this.dataset.mode=e;let t=this.layout;switch(e){case"multiple-document":for(const e of t.tabBars())e.show();break;case"single-document":t.restoreLayout(_e.createSingleDocumentConfig(this));break;default:throw"unreachable"}g.postMessage(this,_e.LayoutModified)}get tabsMovable(){return this._tabsMovable}set tabsMovable(e){this._tabsMovable=e;for(const t of this.tabBars())t.tabsMovable=e}get tabsConstrained(){return this._tabsConstrained}set tabsConstrained(e){this._tabsConstrained=e}get addButtonEnabled(){return this._addButtonEnabled}set addButtonEnabled(e){this._addButtonEnabled=e;for(const t of this.tabBars())t.addButtonEnabled=e}get isEmpty(){return this.layout.isEmpty}*widgets(){yield*this.layout.widgets()}*selectedWidgets(){yield*this.layout.selectedWidgets()}*tabBars(){yield*this.layout.tabBars()}*handles(){yield*this.layout.handles()}selectWidget(e){let t=a(this.tabBars(),(t=>-1!==t.titles.indexOf(e.title)));if(!t)throw new Error("Widget is not contained in the dock panel.");t.currentTitle=e.title}activateWidget(e){this.selectWidget(e),e.activate()}saveLayout(){return this.layout.saveLayout()}restoreLayout(e){this._mode="multiple-document",this.layout.restoreLayout(e),(d.IS_EDGE||d.IS_IE)&&g.flush(),g.postMessage(this,_e.LayoutModified)}addWidget(e,t={}){"single-document"===this._mode?this.layout.addWidget(e):this.layout.addWidget(e,t),g.postMessage(this,_e.LayoutModified)}processMessage(e){"layout-modified"===e.type?this._layoutModified.emit(void 0):super.processMessage(e)}handleEvent(e){switch(e.type){case"lm-dragenter":this._evtDragEnter(e);break;case"lm-dragleave":this._evtDragLeave(e);break;case"lm-dragover":this._evtDragOver(e);break;case"lm-drop":this._evtDrop(e);break;case"pointerdown":this._evtPointerDown(e);break;case"pointermove":this._evtPointerMove(e);break;case"pointerup":this._evtPointerUp(e);break;case"keydown":this._evtKeyDown(e);break;case"contextmenu":e.preventDefault(),e.stopPropagation()}}onBeforeAttach(e){this.node.addEventListener("lm-dragenter",this),this.node.addEventListener("lm-dragleave",this),this.node.addEventListener("lm-dragover",this),this.node.addEventListener("lm-drop",this),this.node.addEventListener("pointerdown",this)}onAfterDetach(e){this.node.removeEventListener("lm-dragenter",this),this.node.removeEventListener("lm-dragleave",this),this.node.removeEventListener("lm-dragover",this),this.node.removeEventListener("lm-drop",this),this.node.removeEventListener("pointerdown",this),this._releaseMouse()}onChildAdded(e){_e.isGeneratedTabBarProperty.get(e.child)||e.child.addClass("lm-DockPanel-widget")}onChildRemoved(e){_e.isGeneratedTabBarProperty.get(e.child)||(e.child.removeClass("lm-DockPanel-widget"),g.postMessage(this,_e.LayoutModified))}_evtDragEnter(e){e.mimeData.hasData("application/vnd.lumino.widget-factory")&&(e.preventDefault(),e.stopPropagation())}_evtDragLeave(e){e.preventDefault(),this._tabsConstrained&&e.source!==this||(e.stopPropagation(),this.overlay.hide(1))}_evtDragOver(e){e.preventDefault(),this._tabsConstrained&&e.source!==this||"invalid"===this._showOverlay(e.clientX,e.clientY)?e.dropAction="none":(e.stopPropagation(),e.dropAction=e.proposedAction)}_evtDrop(e){if(e.preventDefault(),this.overlay.hide(0),"none"===e.proposedAction)return void(e.dropAction="none");let{clientX:t,clientY:n}=e,{zone:i,target:r}=_e.findDropTarget(this,t,n,this._edges);if(this._tabsConstrained&&e.source!==this||"invalid"===i)return void(e.dropAction="none");let s=e.mimeData.getData("application/vnd.lumino.widget-factory");if("function"!=typeof s)return void(e.dropAction="none");let o=s();if(!(o instanceof V))return void(e.dropAction="none");if(o.contains(this))return void(e.dropAction="none");let a=r?_e.getDropRef(r.tabBar):null;switch(i){case"root-all":this.addWidget(o);break;case"root-top":this.addWidget(o,{mode:"split-top"});break;case"root-left":this.addWidget(o,{mode:"split-left"});break;case"root-right":this.addWidget(o,{mode:"split-right"});break;case"root-bottom":this.addWidget(o,{mode:"split-bottom"});break;case"widget-all":case"widget-tab":this.addWidget(o,{mode:"tab-after",ref:a});break;case"widget-top":this.addWidget(o,{mode:"split-top",ref:a});break;case"widget-left":this.addWidget(o,{mode:"split-left",ref:a});break;case"widget-right":this.addWidget(o,{mode:"split-right",ref:a});break;case"widget-bottom":this.addWidget(o,{mode:"split-bottom",ref:a});break;default:throw"unreachable"}e.dropAction=e.proposedAction,e.stopPropagation(),this.activateWidget(o)}_evtKeyDown(e){e.preventDefault(),e.stopPropagation(),27===e.keyCode&&(this._releaseMouse(),g.postMessage(this,_e.LayoutModified))}_evtPointerDown(e){if(0!==e.button)return;let t=this.layout,n=e.target,i=a(t.handles(),(e=>e.contains(n)));if(!i)return;e.preventDefault(),e.stopPropagation(),this._document.addEventListener("keydown",this,!0),this._document.addEventListener("pointerup",this,!0),this._document.addEventListener("pointermove",this,!0),this._document.addEventListener("contextmenu",this,!0);let r=i.getBoundingClientRect(),s=e.clientX-r.left,o=e.clientY-r.top,l=window.getComputedStyle(i),u=M.Drag.overrideCursor(l.cursor,this._document);this._pressData={handle:i,deltaX:s,deltaY:o,override:u}}_evtPointerMove(e){if(!this._pressData)return;e.preventDefault(),e.stopPropagation();let t=this.node.getBoundingClientRect(),n=e.clientX-t.left-this._pressData.deltaX,i=e.clientY-t.top-this._pressData.deltaY;this.layout.moveHandle(this._pressData.handle,n,i)}_evtPointerUp(e){0===e.button&&(e.preventDefault(),e.stopPropagation(),this._releaseMouse(),g.postMessage(this,_e.LayoutModified))}_releaseMouse(){this._pressData&&(this._pressData.override.dispose(),this._pressData=null,this._document.removeEventListener("keydown",this,!0),this._document.removeEventListener("pointerup",this,!0),this._document.removeEventListener("pointermove",this,!0),this._document.removeEventListener("contextmenu",this,!0))}_showOverlay(e,t){let n,i,r,s,{zone:o,target:a}=_e.findDropTarget(this,e,t,this._edges);if("invalid"===o)return this.overlay.hide(100),o;let l=u.boxSizing(this.node),d=this.node.getBoundingClientRect();switch(o){case"root-all":n=l.paddingTop,i=l.paddingLeft,r=l.paddingRight,s=l.paddingBottom;break;case"root-top":n=l.paddingTop,i=l.paddingLeft,r=l.paddingRight,s=d.height*_e.GOLDEN_RATIO;break;case"root-left":n=l.paddingTop,i=l.paddingLeft,r=d.width*_e.GOLDEN_RATIO,s=l.paddingBottom;break;case"root-right":n=l.paddingTop,i=d.width*_e.GOLDEN_RATIO,r=l.paddingRight,s=l.paddingBottom;break;case"root-bottom":n=d.height*_e.GOLDEN_RATIO,i=l.paddingLeft,r=l.paddingRight,s=l.paddingBottom;break;case"widget-all":n=a.top,i=a.left,r=a.right,s=a.bottom;break;case"widget-top":n=a.top,i=a.left,r=a.right,s=a.bottom+a.height/2;break;case"widget-left":n=a.top,i=a.left,r=a.right+a.width/2,s=a.bottom;break;case"widget-right":n=a.top,i=a.left+a.width/2,r=a.right,s=a.bottom;break;case"widget-bottom":n=a.top+a.height/2,i=a.left,r=a.right,s=a.bottom;break;case"widget-tab":{const e=a.tabBar.node.getBoundingClientRect().height;n=a.top,i=a.left,r=a.right,s=a.bottom+a.height-e;break}default:throw"unreachable"}return this.overlay.show({top:n,left:i,right:r,bottom:s}),o}_createTabBar(){let e=this._renderer.createTabBar(this._document);return _e.isGeneratedTabBarProperty.set(e,!0),"single-document"===this._mode&&e.hide(),e.tabsMovable=this._tabsMovable,e.allowDeselect=!1,e.addButtonEnabled=this._addButtonEnabled,e.removeBehavior="select-previous-tab",e.insertBehavior="select-tab-if-needed",e.tabMoved.connect(this._onTabMoved,this),e.currentChanged.connect(this._onCurrentChanged,this),e.tabCloseRequested.connect(this._onTabCloseRequested,this),e.tabDetachRequested.connect(this._onTabDetachRequested,this),e.tabActivateRequested.connect(this._onTabActivateRequested,this),e.addRequested.connect(this._onTabAddRequested,this),e}_createHandle(){return this._renderer.createHandle()}_onTabMoved(){g.postMessage(this,_e.LayoutModified)}_onCurrentChanged(e,t){let{previousTitle:n,currentTitle:i}=t;n&&n.owner.hide(),i&&i.owner.show(),(d.IS_EDGE||d.IS_IE)&&g.flush(),g.postMessage(this,_e.LayoutModified)}_onTabAddRequested(e){this._addRequested.emit(e)}_onTabActivateRequested(e,t){t.title.owner.activate()}_onTabCloseRequested(e,t){t.title.owner.close()}_onTabDetachRequested(e,t){if(this._drag)return;e.releaseMouse();let{title:n,tab:i,clientX:r,clientY:s,offset:o}=t,a=new A.MimeData;a.setData("application/vnd.lumino.widget-factory",(()=>n.owner));let l=i.cloneNode(!0);o&&(l.style.top=`-${o.y}px`,l.style.left=`-${o.x}px`),this._drag=new M.Drag({document:this._document,mimeData:a,dragImage:l,proposedAction:"move",supportedActions:"move",source:this}),i.classList.add("lm-mod-hidden"),this._drag.start(r,s).then((()=>{this._drag=null,i.classList.remove("lm-mod-hidden")}))}}!function(e){e.Overlay=class{constructor(){this._timer=-1,this._hidden=!0,this.node=document.createElement("div"),this.node.classList.add("lm-DockPanel-overlay"),this.node.classList.add("lm-mod-hidden"),this.node.style.position="absolute",this.node.style.contain="strict"}show(e){let t=this.node.style;t.top=`${e.top}px`,t.left=`${e.left}px`,t.right=`${e.right}px`,t.bottom=`${e.bottom}px`,clearTimeout(this._timer),this._timer=-1,this._hidden&&(this._hidden=!1,this.node.classList.remove("lm-mod-hidden"))}hide(e){if(!this._hidden)return e<=0?(clearTimeout(this._timer),this._timer=-1,this._hidden=!0,void this.node.classList.add("lm-mod-hidden")):void(-1===this._timer&&(this._timer=window.setTimeout((()=>{this._timer=-1,this._hidden=!0,this.node.classList.add("lm-mod-hidden")}),e)))}};class t{createTabBar(e){let t=new me({document:e});return t.addClass("lm-DockPanel-tabBar"),t}createHandle(){let e=document.createElement("div");return e.className="lm-DockPanel-handle",e}}e.Renderer=t,e.defaultRenderer=new t}(De||(De={})),function(e){e.GOLDEN_RATIO=.618,e.DEFAULT_EDGES={top:12,right:40,bottom:40,left:40},e.LayoutModified=new C("layout-modified"),e.isGeneratedTabBarProperty=new E({name:"isGeneratedTabBar",create:()=>!1}),e.createSingleDocumentConfig=function(e){if(e.isEmpty)return{main:null};let t=Array.from(e.widgets()),n=e.selectedWidgets().next().value,i=n?t.indexOf(n):-1;return{main:{type:"tab-area",widgets:t,currentIndex:i}}},e.findDropTarget=function(e,t,n,i){if(!u.hitTest(e.node,t,n))return{zone:"invalid",target:null};let r=e.layout;if(r.isEmpty)return{zone:"root-all",target:null};if("multiple-document"===e.mode){let r=e.node.getBoundingClientRect(),s=t-r.left+1,o=n-r.top+1,a=r.right-t,l=r.bottom-n;switch(Math.min(o,a,l,s)){case o:if(oh&&l>h&&a>p&&d>p)return{zone:"widget-all",target:s};switch(o/=h,a/=p,l/=h,d/=p,Math.min(o,a,l,d)){case o:c="widget-left";break;case a:c="widget-top";break;case l:c="widget-right";break;case d:c="widget-bottom";break;default:throw"unreachable"}return{zone:c,target:s}},e.getDropRef=function(e){return 0===e.titles.length?null:e.currentTitle?e.currentTitle.owner:e.titles[e.titles.length-1].owner}}(_e||(_e={}));class Se{constructor(){this._counter=0,this._widgets=[],this._activeWidget=null,this._currentWidget=null,this._numbers=new Map,this._nodes=new Map,this._activeChanged=new x(this),this._currentChanged=new x(this)}dispose(){if(!(this._counter<0)){this._counter=-1,x.clearData(this);for(const e of this._widgets)e.node.removeEventListener("focus",this,!0),e.node.removeEventListener("blur",this,!0);this._activeWidget=null,this._currentWidget=null,this._nodes.clear(),this._numbers.clear(),this._widgets.length=0}}get currentChanged(){return this._currentChanged}get activeChanged(){return this._activeChanged}get isDisposed(){return this._counter<0}get currentWidget(){return this._currentWidget}get activeWidget(){return this._activeWidget}get widgets(){return this._widgets}focusNumber(e){let t=this._numbers.get(e);return void 0===t?-1:t}has(e){return this._numbers.has(e)}add(e){if(this._numbers.has(e))return;let t=e.node.contains(document.activeElement),n=t?this._counter++:-1;this._widgets.push(e),this._numbers.set(e,n),this._nodes.set(e.node,e),e.node.addEventListener("focus",this,!0),e.node.addEventListener("blur",this,!0),e.disposed.connect(this._onWidgetDisposed,this),t&&this._setWidgets(e,e)}remove(e){if(!this._numbers.has(e))return;if(e.disposed.disconnect(this._onWidgetDisposed,this),e.node.removeEventListener("focus",this,!0),e.node.removeEventListener("blur",this,!0),i.removeFirstOf(this._widgets,e),this._nodes.delete(e.node),this._numbers.delete(e),this._currentWidget!==e)return;let t=function(e,t){let n;for(const i of e)void 0!==n?t(i,n)>0&&(n=i):n=i;return n}(this._widgets.filter((e=>-1!==this._numbers.get(e))),((e,t)=>this._numbers.get(e)-this._numbers.get(t)))||null;this._setWidgets(t,null)}handleEvent(e){switch(e.type){case"focus":this._evtFocus(e);break;case"blur":this._evtBlur(e)}}_setWidgets(e,t){let n=this._currentWidget;this._currentWidget=e;let i=this._activeWidget;this._activeWidget=t,n!==e&&this._currentChanged.emit({oldValue:n,newValue:e}),i!==t&&this._activeChanged.emit({oldValue:i,newValue:t})}_evtFocus(e){let t=this._nodes.get(e.currentTarget);t!==this._currentWidget&&this._numbers.set(t,this._counter++),this._setWidgets(t,t)}_evtBlur(e){let t=this._nodes.get(e.currentTarget),n=e.relatedTarget;n&&(t.node.contains(n)||a(this._widgets,(e=>e.node.contains(n))))||this._setWidgets(this._currentWidget,null)}_onWidgetDisposed(e){this.remove(e)}}class Te extends q{constructor(e={}){super(e),this._dirty=!1,this._rowSpacing=4,this._columnSpacing=4,this._items=[],this._rowStarts=[],this._columnStarts=[],this._rowSizers=[new W],this._columnSizers=[new W],this._box=null,void 0!==e.rowCount&&Ae.reallocSizers(this._rowSizers,e.rowCount),void 0!==e.columnCount&&Ae.reallocSizers(this._columnSizers,e.columnCount),void 0!==e.rowSpacing&&(this._rowSpacing=Ae.clampValue(e.rowSpacing)),void 0!==e.columnSpacing&&(this._columnSpacing=Ae.clampValue(e.columnSpacing))}dispose(){for(const e of this._items){let t=e.widget;e.dispose(),t.dispose()}this._box=null,this._items.length=0,this._rowStarts.length=0,this._rowSizers.length=0,this._columnStarts.length=0,this._columnSizers.length=0,super.dispose()}get rowCount(){return this._rowSizers.length}set rowCount(e){e!==this.rowCount&&(Ae.reallocSizers(this._rowSizers,e),this.parent&&this.parent.fit())}get columnCount(){return this._columnSizers.length}set columnCount(e){e!==this.columnCount&&(Ae.reallocSizers(this._columnSizers,e),this.parent&&this.parent.fit())}get rowSpacing(){return this._rowSpacing}set rowSpacing(e){e=Ae.clampValue(e),this._rowSpacing!==e&&(this._rowSpacing=e,this.parent&&this.parent.fit())}get columnSpacing(){return this._columnSpacing}set columnSpacing(e){e=Ae.clampValue(e),this._columnSpacing!==e&&(this._columnSpacing=e,this.parent&&this.parent.fit())}rowStretch(e){let t=this._rowSizers[e];return t?t.stretch:-1}setRowStretch(e,t){let n=this._rowSizers[e];n&&(t=Ae.clampValue(t),n.stretch!==t&&(n.stretch=t,this.parent&&this.parent.update()))}columnStretch(e){let t=this._columnSizers[e];return t?t.stretch:-1}setColumnStretch(e,t){let n=this._columnSizers[e];n&&(t=Ae.clampValue(t),n.stretch!==t&&(n.stretch=t,this.parent&&this.parent.update()))}*[Symbol.iterator](){for(const e of this._items)yield e.widget}addWidget(e){-1===i.findFirstIndex(this._items,(t=>t.widget===e))&&(this._items.push(new G(e)),this.parent&&this.attachWidget(e))}removeWidget(e){let t=i.findFirstIndex(this._items,(t=>t.widget===e));if(-1===t)return;let n=i.removeAt(this._items,t);this.parent&&this.detachWidget(e),n.dispose()}init(){super.init();for(const e of this)this.attachWidget(e)}attachWidget(e){this.parent.isAttached&&g.sendMessage(e,V.Msg.BeforeAttach),this.parent.node.appendChild(e.node),this.parent.isAttached&&g.sendMessage(e,V.Msg.AfterAttach),this.parent.fit()}detachWidget(e){this.parent.isAttached&&g.sendMessage(e,V.Msg.BeforeDetach),this.parent.node.removeChild(e.node),this.parent.isAttached&&g.sendMessage(e,V.Msg.AfterDetach),this.parent.fit()}onBeforeShow(e){super.onBeforeShow(e),this.parent.update()}onBeforeAttach(e){super.onBeforeAttach(e),this.parent.fit()}onChildShown(e){this.parent.fit()}onChildHidden(e){this.parent.fit()}onResize(e){this.parent.isVisible&&this._update(e.width,e.height)}onUpdateRequest(e){this.parent.isVisible&&this._update(-1,-1)}onFitRequest(e){this.parent.isAttached&&this._fit()}_fit(){for(let e=0,t=this.rowCount;e!e.isHidden));for(let t=0,n=e.length;t({row:0,column:0,rowSpan:1,columnSpan:1}),changed:function(e){e.parent&&e.parent.layout instanceof Te&&e.parent.fit()}}),e.normalizeConfig=function(e){return{row:Math.max(0,Math.floor(e.row||0)),column:Math.max(0,Math.floor(e.column||0)),rowSpan:Math.max(1,Math.floor(e.rowSpan||0)),columnSpan:Math.max(1,Math.floor(e.columnSpan||0))}},e.clampValue=function(e){return Math.max(0,Math.floor(e))},e.rowSpanCmp=function(t,n){let i=e.cellConfigProperty.get(t.widget),r=e.cellConfigProperty.get(n.widget);return i.rowSpan-r.rowSpan},e.columnSpanCmp=function(t,n){let i=e.cellConfigProperty.get(t.widget),r=e.cellConfigProperty.get(n.widget);return i.columnSpan-r.columnSpan},e.reallocSizers=function(e,t){for(t=Math.max(1,Math.floor(t));e.lengtht&&(e.length=t)},e.distributeMin=function(e,t,n,i){if(n=i)return;let s=(i-r)/(n-t+1);for(let i=t;i<=n;++i)e[i].minSize+=s}}(Ae||(Ae={}));class Me extends V{constructor(e={}){super({node:ye.createNode()}),this._activeIndex=-1,this._tabFocusIndex=0,this._menus=[],this._childMenu=null,this._overflowMenu=null,this._menuItemSizes=[],this._overflowIndex=-1,this.addClass("lm-MenuBar"),this.setFlag(V.Flag.DisallowLayout),this.renderer=e.renderer||Me.defaultRenderer,this._forceItemsPosition=e.forceItemsPosition||{forceX:!0,forceY:!0},this._overflowMenuOptions=e.overflowMenuOptions||{isVisible:!0}}dispose(){this._closeChildMenu(),this._menus.length=0,super.dispose()}get childMenu(){return this._childMenu}get overflowIndex(){return this._overflowIndex}get overflowMenu(){return this._overflowMenu}get contentNode(){return this.node.getElementsByClassName("lm-MenuBar-content")[0]}get activeMenu(){return this._menus[this._activeIndex]||null}set activeMenu(e){this.activeIndex=e?this._menus.indexOf(e):-1}get activeIndex(){return this._activeIndex}set activeIndex(e){(e<0||e>=this._menus.length)&&(e=-1),e>-1&&0===this._menus[e].items.length&&(e=-1),this._activeIndex!==e&&(this._activeIndex=e,this.update())}get menus(){return this._menus}openActiveMenu(){-1!==this._activeIndex&&(this._openChildMenu(),this._childMenu&&(this._childMenu.activeIndex=-1,this._childMenu.activateNextItem()))}addMenu(e,t=!0){this.insertMenu(this._menus.length,e,t)}insertMenu(e,t,n=!0){this._closeChildMenu();let r=this._menus.indexOf(t),s=Math.max(0,Math.min(e,this._menus.length));if(-1===r)return i.insert(this._menus,s,t),t.addClass("lm-MenuBar-menu"),t.aboutToClose.connect(this._onMenuAboutToClose,this),t.menuRequested.connect(this._onMenuMenuRequested,this),t.title.changed.connect(this._onTitleChanged,this),void(n&&this.update());s===this._menus.length&&s--,r!==s&&(i.move(this._menus,r,s),n&&this.update())}removeMenu(e,t=!0){this.removeMenuAt(this._menus.indexOf(e),t)}removeMenuAt(e,t=!0){this._closeChildMenu();let n=i.removeAt(this._menus,e);n&&(n.aboutToClose.disconnect(this._onMenuAboutToClose,this),n.menuRequested.disconnect(this._onMenuMenuRequested,this),n.title.changed.disconnect(this._onTitleChanged,this),n.removeClass("lm-MenuBar-menu"),t&&this.update())}clearMenus(){if(0!==this._menus.length){this._closeChildMenu();for(let e of this._menus)e.aboutToClose.disconnect(this._onMenuAboutToClose,this),e.menuRequested.disconnect(this._onMenuMenuRequested,this),e.title.changed.disconnect(this._onTitleChanged,this),e.removeClass("lm-MenuBar-menu");this._menus.length=0,this.update()}}handleEvent(e){switch(e.type){case"keydown":this._evtKeyDown(e);break;case"mousedown":this._evtMouseDown(e);break;case"mousemove":this._evtMouseMove(e);break;case"focusout":this._evtFocusOut(e);break;case"contextmenu":e.preventDefault(),e.stopPropagation()}}onBeforeAttach(e){this.node.addEventListener("keydown",this),this.node.addEventListener("mousedown",this),this.node.addEventListener("mousemove",this),this.node.addEventListener("focusout",this),this.node.addEventListener("contextmenu",this)}onAfterDetach(e){this.node.removeEventListener("keydown",this),this.node.removeEventListener("mousedown",this),this.node.removeEventListener("mousemove",this),this.node.removeEventListener("focusout",this),this.node.removeEventListener("contextmenu",this),this._closeChildMenu()}onActivateRequest(e){this.isAttached&&this._focusItemAt(0)}onResize(e){this.update(),super.onResize(e)}onUpdateRequest(e){var t;let n=this._menus,i=this.renderer,r=this._activeIndex,s=this._tabFocusIndex>=0&&this._tabFocusIndex-1?this._overflowIndex:n.length,a=0,l=!1;o=null!==this._overflowMenu?o-1:o;let u=new Array(o);for(let e=0;e{this._tabFocusIndex=e,this.activeIndex=e}}),a+=this._menuItemSizes[e],n[e].title.label===this._overflowMenuOptions.title&&(l=!0,o--);if(this._overflowMenuOptions.isVisible)if(this._overflowIndex>-1&&!l){if(null===this._overflowMenu){const e=null!==(t=this._overflowMenuOptions.title)&&void 0!==t?t:"...";this._overflowMenu=new ge({commands:new M.CommandRegistry}),this._overflowMenu.title.label=e,this._overflowMenu.title.mnemonic=0,this.addMenu(this._overflowMenu,!1)}for(let e=n.length-2;e>=o;e--){const t=this.menus[e];t.title.mnemonic=0,this._overflowMenu.insertItem(0,{type:"submenu",submenu:t}),this.removeMenu(t,!1)}u[o]=i.renderItem({title:this._overflowMenu.title,active:o===r&&0!==n[o].items.length,tabbable:o===s,disabled:0===n[o].items.length,onfocus:()=>{this._tabFocusIndex=o,this.activeIndex=o}}),o++}else if(null!==this._overflowMenu){let e=this._overflowMenu.items,t=this.node.offsetWidth,r=this._overflowMenu.items.length;for(let l=0;lthis._menuItemSizes[r]){let t=e[0].submenu;this._overflowMenu.removeItemAt(0),this.insertMenu(o,t,!1),u[o]=i.renderItem({title:t.title,active:!1,tabbable:o===s,disabled:0===n[o].items.length,onfocus:()=>{this._tabFocusIndex=o,this.activeIndex=o}}),o++}}0===this._overflowMenu.items.length&&(this.removeMenu(this._overflowMenu,!1),u.pop(),this._overflowMenu=null,this._overflowIndex=-1)}S.render(u,this.contentNode),this._updateOverflowIndex()}_updateOverflowIndex(){if(!this._overflowMenuOptions.isVisible)return;const e=this.contentNode.childNodes;let t=this.node.offsetWidth,n=0,i=-1,r=e.length;if(0==this._menuItemSizes.length)for(let s=0;st&&-1===i&&(i=s)}else for(let e=0;et){i=e;break}this._overflowIndex=i}_evtKeyDown(e){let t=e.keyCode;if(9===t)return void(this.activeIndex=-1);if(e.preventDefault(),e.stopPropagation(),13===t||32===t||38===t||40===t){if(this.activeIndex=this._tabFocusIndex,this.activeIndex!==this._tabFocusIndex)return;return void this.openActiveMenu()}if(27===t)return this._closeChildMenu(),void this._focusItemAt(this.activeIndex);if(37===t||39===t){let e=37===t?-1:1,n=this._tabFocusIndex+e,i=this._menus.length;for(let t=0;tu.hitTest(t,e.clientX,e.clientY)));if(-1!==t){if(0===e.button)if(this._childMenu)this._closeChildMenu(),this.activeIndex=t;else{e.preventDefault();const n=this._positionForMenu(t);ge.saveWindowData(),this.activeIndex=t,this._openChildMenu(n)}}else this._closeChildMenu()}_evtMouseMove(e){let t=i.findFirstIndex(this.contentNode.children,(t=>u.hitTest(t,e.clientX,e.clientY)));if(t===this._activeIndex)return;if(-1===t&&this._childMenu)return;const n=t>=0&&this._childMenu?this._positionForMenu(t):null;ge.saveWindowData(),this.activeIndex=t,n&&this._openChildMenu(n)}_positionForMenu(e){let t=this.contentNode.children[e],{left:n,bottom:i}=t.getBoundingClientRect();return{top:i,left:n}}_evtFocusOut(e){this._childMenu||this.node.contains(e.relatedTarget)||(this.activeIndex=-1)}_focusItemAt(e){const t=this.contentNode.childNodes[e];t&&t.focus()}_openChildMenu(e={}){let t=this.activeMenu;if(!t)return void this._closeChildMenu();let n=this._childMenu;if(n===t)return;this._childMenu=t,n?n.close():document.addEventListener("mousedown",this,!0),this._tabFocusIndex=this.activeIndex,g.sendMessage(this,V.Msg.UpdateRequest);let{left:i,top:r}=e;void 0!==i&&void 0!==r||({left:i,top:r}=this._positionForMenu(this._activeIndex)),n||this.addClass("lm-mod-active"),t.items.length>0&&t.open(i,r,this._forceItemsPosition)}_closeChildMenu(){if(!this._childMenu)return;this.removeClass("lm-mod-active"),document.removeEventListener("mousedown",this,!0);let e=this._childMenu;this._childMenu=null,e.close(),this.activeIndex=-1}_onMenuAboutToClose(e){e===this._childMenu&&(this.removeClass("lm-mod-active"),document.removeEventListener("mousedown",this,!0),this._childMenu=null,this.activeIndex=-1)}_onMenuMenuRequested(e,t){if(e!==this._childMenu)return;let n=this._activeIndex,i=this._menus.length;switch(t){case"next":this.activeIndex=n===i-1?0:n+1;break;case"previous":this.activeIndex=0===n?i-1:n-1}this.openActiveMenu()}_onTitleChanged(){this.update()}}!function(e){class t{renderItem(e){let t=this.createItemClass(e),n=this.createItemDataset(e),i=this.createItemARIA(e);return B.li({className:t,dataset:n,...e.disabled?{}:{tabindex:e.tabbable?"0":"-1"},onfocus:e.onfocus,...i},this.renderIcon(e),this.renderLabel(e))}renderIcon(e){let t=this.createIconClass(e);return B.div({className:t},e.title.icon,e.title.iconLabel)}renderLabel(e){let t=this.formatLabel(e);return B.div({className:"lm-MenuBar-itemLabel"},t)}createItemClass(e){let t="lm-MenuBar-item";return e.title.className&&(t+=` ${e.title.className}`),e.active&&!e.disabled&&(t+=" lm-mod-active"),t}createItemDataset(e){return e.title.dataset}createItemARIA(e){return{role:"menuitem","aria-haspopup":"true","aria-disabled":e.disabled?"true":"false"}}createIconClass(e){let t="lm-MenuBar-itemIcon",n=e.title.iconClass;return n?`${t} ${n}`:t}formatLabel(e){let{label:t,mnemonic:n}=e.title;if(n<0||n>=t.length)return t;let i=t.slice(0,n),r=t.slice(n+1),s=t[n];return[i,B.span({className:"lm-MenuBar-itemMnemonic"},s),r]}}e.Renderer=t,e.defaultRenderer=new t}(Me||(Me={})),function(e){e.createNode=function(){let e=document.createElement("div"),t=document.createElement("ul");return t.className="lm-MenuBar-content",e.appendChild(t),t.setAttribute("role","menubar"),e},e.findMnemonic=function(e,t,n){let i=-1,r=-1,s=!1,o=t.toUpperCase();for(let t=0,a=e.length;t=0&&d1&&this.widgets.forEach((e=>{e.hiddenMode=this._hiddenMode})))}dispose(){for(const e of this._items)e.dispose();this._box=null,this._items.length=0,super.dispose()}attachWidget(e,t){this._hiddenMode===V.HiddenMode.Scale&&this._items.length>0?(1===this._items.length&&(this.widgets[0].hiddenMode=V.HiddenMode.Scale),t.hiddenMode=V.HiddenMode.Scale):t.hiddenMode=V.HiddenMode.Display,i.insert(this._items,e,new G(t)),this.parent.isAttached&&g.sendMessage(t,V.Msg.BeforeAttach),this.parent.node.appendChild(t.node),this.parent.isAttached&&g.sendMessage(t,V.Msg.AfterAttach),this.parent.fit()}moveWidget(e,t,n){i.move(this._items,e,t),this.parent.update()}detachWidget(e,t){let n=i.removeAt(this._items,e);this.parent.isAttached&&g.sendMessage(t,V.Msg.BeforeDetach),this.parent.node.removeChild(t.node),this.parent.isAttached&&g.sendMessage(t,V.Msg.AfterDetach),n.widget.node.style.zIndex="",this._hiddenMode===V.HiddenMode.Scale&&(t.hiddenMode=V.HiddenMode.Display,1===this._items.length&&(this._items[0].widget.hiddenMode=V.HiddenMode.Display)),n.dispose(),this.parent.fit()}onBeforeShow(e){super.onBeforeShow(e),this.parent.update()}onBeforeAttach(e){super.onBeforeAttach(e),this.parent.fit()}onChildShown(e){this.parent.fit()}onChildHidden(e){this.parent.fit()}onResize(e){this.parent.isVisible&&this._update(e.width,e.height)}onUpdateRequest(e){this.parent.isVisible&&this._update(-1,-1)}onFitRequest(e){this.parent.isAttached&&this._fit()}_fit(){let e=0,t=0;for(let n=0,i=this._items.length;n>>0),e[n]=255&t,t>>>=8}e.Random=void 0,(e.Random||(e.Random={})).getRandomValues=(()=>{const e="undefined"!=typeof window&&(window.crypto||window.msCrypto)||null;return e&&"function"==typeof e.getRandomValues?function(t){return e.getRandomValues(t)}:t})(),e.UUID=void 0,(e.UUID||(e.UUID={})).uuid4=function(e){const t=new Uint8Array(16),n=new Array(256);for(let e=0;e<16;++e)n[e]="0"+e.toString(16);for(let e=16;e<256;++e)n[e]=e.toString(16);return function(){return e(t),t[6]=64|15&t[6],t[8]=128|63&t[8],n[t[0]]+n[t[1]]+n[t[2]]+n[t[3]]+"-"+n[t[4]]+n[t[5]]+"-"+n[t[6]]+n[t[7]]+"-"+n[t[8]]+n[t[9]]+"-"+n[t[10]]+n[t[11]]+n[t[12]]+n[t[13]]+n[t[14]]+n[t[15]]}}(e.Random.getRandomValues),e.MimeData=class{constructor(){this._types=[],this._values=[]}types(){return this._types.slice()}hasData(e){return-1!==this._types.indexOf(e)}getData(e){let t=this._types.indexOf(e);return-1!==t?this._values[t]:void 0}setData(e,t){this.clearData(e),this._types.push(e),this._values.push(t)}clearData(e){let t=this._types.indexOf(e);-1!==t&&(this._types.splice(t,1),this._values.splice(t,1))}clear(){this._types.length=0,this._values.length=0}},e.PromiseDelegate=class{constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}resolve(e){(0,this._resolve)(e)}reject(e){(0,this._reject)(e)}},e.Token=class{constructor(e,t){this.name=e,this.description=null!=t?t:"",this._tokenStructuralPropertyT=null}}}(t)},7298:(e,t,n)=>{var i,r,s;s="object"==typeof self&&self.self===self&&self||"object"==typeof n.g&&n.g.global===n.g&&n.g,i=[n(70405),n(38291),t],r=function(e,t,n){s.Backbone=function(e,t,n,i){var r=e.Backbone,s=Array.prototype.slice;t.VERSION="1.4.0",t.$=i,t.noConflict=function(){return e.Backbone=r,this},t.emulateHTTP=!1,t.emulateJSON=!1;var o,a=t.Events={},l=/\s+/,u=function(e,t,i,r,s){var o,a=0;if(i&&"object"==typeof i){void 0!==r&&"context"in s&&void 0===s.context&&(s.context=r);for(o=n.keys(i);athis.length&&(r=this.length),r<0&&(r+=this.length+1);var s,o,a=[],l=[],u=[],d=[],c={},h=t.add,p=t.merge,g=t.remove,f=!1,m=this.comparator&&null==r&&!1!==t.sort,v=n.isString(this.comparator)?this.comparator:null;for(o=0;o7),this._useHashChange=this._wantsHashChange&&this._hasHashChange,this._wantsPushState=!!this.options.pushState,this._hasPushState=!(!this.history||!this.history.pushState),this._usePushState=this._wantsPushState&&this._hasPushState,this.fragment=this.getFragment(),this.root=("/"+this.root+"/").replace(U,"/"),this._wantsHashChange&&this._wantsPushState){if(!this._hasPushState&&!this.atRoot()){var t=this.root.slice(0,-1)||"/";return this.location.replace(t+"#"+this.getPath()),!0}this._hasPushState&&this.atRoot()&&this.navigate(this.getHash(),{replace:!0})}if(!this._hasHashChange&&this._wantsHashChange&&!this._usePushState){this.iframe=document.createElement("iframe"),this.iframe.src="javascript:0",this.iframe.style.display="none",this.iframe.tabIndex=-1;var i=document.body,r=i.insertBefore(this.iframe,i.firstChild).contentWindow;r.document.open(),r.document.close(),r.location.hash="#"+this.fragment}var s=window.addEventListener||function(e,t){return attachEvent("on"+e,t)};if(this._usePushState?s("popstate",this.checkUrl,!1):this._useHashChange&&!this.iframe?s("hashchange",this.checkUrl,!1):this._wantsHashChange&&(this._checkUrlInterval=setInterval(this.checkUrl,this.interval)),!this.options.silent)return this.loadUrl()},stop:function(){var e=window.removeEventListener||function(e,t){return detachEvent("on"+e,t)};this._usePushState?e("popstate",this.checkUrl,!1):this._useHashChange&&!this.iframe&&e("hashchange",this.checkUrl,!1),this.iframe&&(document.body.removeChild(this.iframe),this.iframe=null),this._checkUrlInterval&&clearInterval(this._checkUrlInterval),F.started=!1},route:function(e,t){this.handlers.unshift({route:e,callback:t})},checkUrl:function(e){var t=this.getFragment();if(t===this.fragment&&this.iframe&&(t=this.getHash(this.iframe.contentWindow)),t===this.fragment)return!1;this.iframe&&this.navigate(t),this.loadUrl()},loadUrl:function(e){return!!this.matchRoot()&&(e=this.fragment=this.getFragment(e),n.some(this.handlers,(function(t){if(t.route.test(e))return t.callback(e),!0})))},navigate:function(e,t){if(!F.started)return!1;t&&!0!==t||(t={trigger:!!t}),e=this.getFragment(e||"");var n=this.root;""!==e&&"?"!==e.charAt(0)||(n=n.slice(0,-1)||"/");var i=n+e;e=e.replace($,"");var r=this.decodeFragment(e);if(this.fragment!==r){if(this.fragment=r,this._usePushState)this.history[t.replace?"replaceState":"pushState"]({},document.title,i);else{if(!this._wantsHashChange)return this.location.assign(i);if(this._updateHash(this.location,e,t.replace),this.iframe&&e!==this.getHash(this.iframe.contentWindow)){var s=this.iframe.contentWindow;t.replace||(s.document.open(),s.document.close()),this._updateHash(s.location,e,t.replace)}}return t.trigger?this.loadUrl(e):void 0}},_updateHash:function(e,t,n){if(n){var i=e.href.replace(/(javascript:|#).*$/,"");e.replace(i+"#"+t)}else e.hash="#"+t}}),t.history=new F;v.extend=b.extend=I.extend=S.extend=F.extend=function(e,t){var i,r=this;return i=e&&n.has(e,"constructor")?e.constructor:function(){return r.apply(this,arguments)},n.extend(i,r,t),i.prototype=n.create(r.prototype,e),i.prototype.constructor=i,i.__super__=r.prototype,i};var W=function(){throw new Error('A "url" property or function must be specified')},H=function(e,t){var n=t.error;t.error=function(i){n&&n.call(t.context,e,i,t),e.trigger("error",e,i,t)}};return t}(s,n,e,t)}.apply(t,i),void 0===r||(e.exports=r)},95766:(e,t)=>{"use strict";t.b$=function(e){var t,n,s=function(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}(e),o=s[0],a=s[1],l=new r(function(e,t,n){return 3*(t+n)/4-n}(0,o,a)),u=0,d=a>0?o-4:o;for(n=0;n>16&255,l[u++]=t>>8&255,l[u++]=255&t;return 2===a&&(t=i[e.charCodeAt(n)]<<2|i[e.charCodeAt(n+1)]>>4,l[u++]=255&t),1===a&&(t=i[e.charCodeAt(n)]<<10|i[e.charCodeAt(n+1)]<<4|i[e.charCodeAt(n+2)]>>2,l[u++]=t>>8&255,l[u++]=255&t),l},t.JQ=function(e){for(var t,i=e.length,r=i%3,s=[],o=16383,a=0,u=i-r;au?u:a+o));return 1===r?(t=e[i-1],s.push(n[t>>2]+n[t<<4&63]+"==")):2===r&&(t=(e[i-2]<<8)+e[i-1],s.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),s.join("")};for(var n=[],i=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,a=s.length;o>18&63]+n[s>>12&63]+n[s>>6&63]+n[63&s]);return o.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},51590:(e,t,n)=>{!function(e){"use strict";function t(t,n){clearTimeout(n.timeout),e.off(window,"mouseup",n.hurry),e.off(window,"keyup",n.hurry)}e.defineOption("autoRefresh",!1,(function(n,i){n.state.autoRefresh&&(t(0,n.state.autoRefresh),n.state.autoRefresh=null),i&&0==n.display.wrapper.offsetHeight&&function(n,i){function r(){n.display.wrapper.offsetHeight?(t(0,i),n.display.lastWrapHeight!=n.display.wrapper.clientHeight&&n.refresh()):i.timeout=setTimeout(r,i.delay)}i.timeout=setTimeout(r,i.delay),i.hurry=function(){clearTimeout(i.timeout),i.timeout=setTimeout(r,50)},e.on(window,"mouseup",i.hurry),e.on(window,"keyup",i.hurry)}(n,n.state.autoRefresh={delay:i.delay||250})}))}(n(23326))},22130:(e,t,n)=>{!function(e){"use strict";var t="CodeMirror-hint",n="CodeMirror-hint-active";function i(e,t){if(this.cm=e,this.options=t,this.widget=null,this.debounce=0,this.tick=0,this.startPos=this.cm.getCursor("start"),this.startLen=this.cm.getLine(this.startPos.line).length-this.cm.getSelection().length,this.options.updateOnCursorActivity){var n=this;e.on("cursorActivity",this.activityFunc=function(){n.cursorActivity()})}}e.showHint=function(e,t,n){if(!t)return e.showHint(n);n&&n.async&&(t.async=!0);var i={hint:t};if(n)for(var r in n)i[r]=n[r];return e.showHint(i)},e.defineExtension("showHint",(function(t){t=function(e,t,n){var i=e.options.hintOptions,r={};for(var s in d)r[s]=d[s];if(i)for(var s in i)void 0!==i[s]&&(r[s]=i[s]);if(n)for(var s in n)void 0!==n[s]&&(r[s]=n[s]);return r.hint.resolve&&(r.hint=r.hint.resolve(e,t)),r}(this,this.getCursor("start"),t);var n=this.listSelections();if(!(n.length>1)){if(this.somethingSelected()){if(!t.hint.supportsSelection)return;for(var r=0;rc.clientHeight+1;if(setTimeout((function(){k=l.getScrollInfo()})),j.bottom-M>0){var O=j.bottom-j.top;if(_.top-(_.bottom-j.top)-O>0)c.style.top=(y=_.top-O-E)+"px",w=!1;else if(O>M){c.style.height=M-5+"px",c.style.top=(y=_.bottom-j.top-E)+"px";var I=l.getCursor();r.from.ch!=I.ch&&(_=l.cursorCoords(I),c.style.left=(A=_.left-C)+"px",j=c.getBoundingClientRect())}}var R,P=j.right-T;if(B&&(P+=l.display.nativeBarWidth),P>0&&(j.right-j.left>T&&(c.style.width=T-5+"px",P-=j.right-j.left-T),c.style.left=(A=_.left-P-C)+"px"),B)for(var L=c.firstChild;L;L=L.nextSibling)L.style.paddingRight=l.display.nativeBarWidth+"px";l.addKeyMap(this.keyMap=function(e,t){var n={Up:function(){t.moveFocus(-1)},Down:function(){t.moveFocus(1)},PageUp:function(){t.moveFocus(1-t.menuSize(),!0)},PageDown:function(){t.moveFocus(t.menuSize()-1,!0)},Home:function(){t.setFocus(0)},End:function(){t.setFocus(t.length-1)},Enter:t.pick,Tab:t.pick,Esc:t.close};/Mac/.test(navigator.platform)&&(n["Ctrl-P"]=function(){t.moveFocus(-1)},n["Ctrl-N"]=function(){t.moveFocus(1)});var i=e.options.customKeys,r=i?{}:n;function s(e,i){var s;s="string"!=typeof i?function(e){return i(e,t)}:n.hasOwnProperty(i)?n[i]:i,r[e]=s}if(i)for(var o in i)i.hasOwnProperty(o)&&s(o,i[o]);var a=e.options.extraKeys;if(a)for(var o in a)a.hasOwnProperty(o)&&s(o,a[o]);return r}(i,{moveFocus:function(e,t){s.changeActive(s.selectedHint+e,t)},setFocus:function(e){s.changeActive(e)},menuSize:function(){return s.screenAmount()},length:p.length,close:function(){i.close()},pick:function(){s.pick()},data:r})),i.options.closeOnUnfocus&&(l.on("blur",this.onBlur=function(){R=setTimeout((function(){i.close()}),100)}),l.on("focus",this.onFocus=function(){clearTimeout(R)})),l.on("scroll",this.onScroll=function(){var e=l.getScrollInfo(),t=l.getWrapperElement().getBoundingClientRect();k||(k=l.getScrollInfo());var n=y+k.top-e.top,r=n-(d.pageYOffset||(u.documentElement||u.body).scrollTop);if(w||(r+=c.offsetHeight),r<=t.top||r>=t.bottom)return i.close();c.style.top=n+"px",c.style.left=A+k.left-e.left+"px"}),e.on(c,"dblclick",(function(e){var t=a(c,e.target||e.srcElement);t&&null!=t.hintId&&(s.changeActive(t.hintId),s.pick())})),e.on(c,"click",(function(e){var t=a(c,e.target||e.srcElement);t&&null!=t.hintId&&(s.changeActive(t.hintId),i.options.completeOnSingleClick&&s.pick())})),e.on(c,"mousedown",(function(){setTimeout((function(){l.focus()}),20)}));var N=this.getSelectedHintRange();return 0===N.from&&0===N.to||this.scrollToActive(),e.signal(r,"select",p[this.selectedHint],c.childNodes[this.selectedHint]),!0}function u(e,t,n,i){if(e.async)e(t,i,n);else{var r=e(t,n);r&&r.then?r.then(i):i(r)}}i.prototype={close:function(){this.active()&&(this.cm.state.completionActive=null,this.tick=null,this.options.updateOnCursorActivity&&this.cm.off("cursorActivity",this.activityFunc),this.widget&&this.data&&e.signal(this.data,"close"),this.widget&&this.widget.close(),e.signal(this.cm,"endCompletion",this.cm))},active:function(){return this.cm.state.completionActive==this},pick:function(t,n){var i=t.list[n],r=this;this.cm.operation((function(){i.hint?i.hint(r.cm,t,i):r.cm.replaceRange(o(i),i.from||t.from,i.to||t.to,"complete"),e.signal(t,"pick",i),r.cm.scrollIntoView()})),this.options.closeOnPick&&this.close()},cursorActivity:function(){this.debounce&&(s(this.debounce),this.debounce=0);var e=this.startPos;this.data&&(e=this.data.from);var t=this.cm.getCursor(),n=this.cm.getLine(t.line);if(t.line!=this.startPos.line||n.length-t.ch!=this.startLen-this.startPos.ch||t.ch=this.data.list.length?t=i?this.data.list.length-1:0:t<0&&(t=i?0:this.data.list.length-1),this.selectedHint!=t){var r=this.hints.childNodes[this.selectedHint];r&&(r.className=r.className.replace(" "+n,"")),(r=this.hints.childNodes[this.selectedHint=t]).className+=" "+n,this.scrollToActive(),e.signal(this.data,"select",this.data.list[this.selectedHint],r)}},scrollToActive:function(){var e=this.getSelectedHintRange(),t=this.hints.childNodes[e.from],n=this.hints.childNodes[e.to],i=this.hints.firstChild;t.offsetTopthis.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=n.offsetTop+n.offsetHeight-this.hints.clientHeight+i.offsetTop)},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1},getSelectedHintRange:function(){var e=this.completion.options.scrollMargin||0;return{from:Math.max(0,this.selectedHint-e),to:Math.min(this.data.list.length-1,this.selectedHint+e)}}},e.registerHelper("hint","auto",{resolve:function(t,n){var i,r=t.getHelpers(n,"hint");if(r.length){var s=function(e,t,n){var i=function(e,t){if(!e.somethingSelected())return t;for(var n=[],i=0;i0?t(e):r(s+1)}))}(0)};return s.async=!0,s.supportsSelection=!0,s}return(i=t.getHelper(t.getCursor(),"hintWords"))?function(t){return e.hint.fromList(t,{words:i})}:e.hint.anyword?function(t,n){return e.hint.anyword(t,n)}:function(){}}}),e.registerHelper("hint","fromList",(function(t,n){var i,r=t.getCursor(),s=t.getTokenAt(r),o=e.Pos(r.line,s.start),a=r;s.start,]/,closeOnPick:!0,closeOnUnfocus:!0,updateOnCursorActivity:!0,completeOnSingleClick:!0,container:null,customKeys:null,extraKeys:null,paddingForScrollbar:!0,moveOnOverlap:!0};e.defineOption("hintOptions",null)}(n(23326))},23326:function(e){e.exports=function(){"use strict";var e=navigator.userAgent,t=navigator.platform,n=/gecko\/\d/i.test(e),i=/MSIE \d/.test(e),r=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(e),s=/Edge\/(\d+)/.exec(e),o=i||r||s,a=o&&(i?document.documentMode||6:+(s||r)[1]),l=!s&&/WebKit\//.test(e),u=l&&/Qt\/\d+\.\d+/.test(e),d=!s&&/Chrome\//.test(e),c=/Opera\//.test(e),h=/Apple Computer/.test(navigator.vendor),p=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(e),g=/PhantomJS/.test(e),f=h&&(/Mobile\/\w+/.test(e)||navigator.maxTouchPoints>2),m=/Android/.test(e),v=f||m||/webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(e),b=f||/Mac/.test(t),_=/\bCrOS\b/.test(e),A=/win/i.test(t),y=c&&e.match(/Version\/(\d*\.\d*)/);y&&(y=Number(y[1])),y&&y>=15&&(c=!1,l=!0);var w=b&&(u||c&&(null==y||y<12.11)),C=n||o&&a>=9;function E(e){return new RegExp("(^|\\s)"+e+"(?:$|\\s)\\s*")}var x,D=function(e,t){var n=e.className,i=E(t).exec(n);if(i){var r=n.slice(i.index+i[0].length);e.className=n.slice(0,i.index)+(r?i[1]+r:"")}};function S(e){for(var t=e.childNodes.length;t>0;--t)e.removeChild(e.firstChild);return e}function T(e,t){return S(e).appendChild(t)}function M(e,t,n,i){var r=document.createElement(e);if(n&&(r.className=n),i&&(r.style.cssText=i),"string"==typeof t)r.appendChild(document.createTextNode(t));else if(t)for(var s=0;s=t)return o+(t-s);o+=a-s,o+=n-o%n,s=a+1}}f?R=function(e){e.selectionStart=0,e.selectionEnd=e.value.length}:o&&(R=function(e){try{e.select()}catch(e){}});var F=function(){this.id=null,this.f=null,this.time=0,this.handler=P(this.onTimeout,this)};function z(e,t){for(var n=0;n=t)return i+Math.min(o,t-r);if(r+=s-i,i=s+1,(r+=n-r%n)>=t)return i}}var G=[""];function K(e){for(;G.length<=e;)G.push(Y(G)+" ");return G[e]}function Y(e){return e[e.length-1]}function J(e,t){for(var n=[],i=0;i"€"&&(e.toUpperCase()!=e.toLowerCase()||Q.test(e))}function te(e,t){return t?!!(t.source.indexOf("\\w")>-1&&ee(e))||t.test(e):ee(e)}function ne(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}var ie=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;function re(e){return e.charCodeAt(0)>=768&&ie.test(e)}function se(e,t,n){for(;(n<0?t>0:tn?-1:1;;){if(t==n)return t;var r=(t+n)/2,s=i<0?Math.ceil(r):Math.floor(r);if(s==t)return e(s)?t:n;e(s)?n=s:t=s+i}}var ae=null;function le(e,t,n){var i;ae=null;for(var r=0;rt)return r;s.to==t&&(s.from!=s.to&&"before"==n?i=r:ae=r),s.from==t&&(s.from!=s.to&&"before"!=n?i=r:ae=r)}return null!=i?i:ae}var ue=function(){var e="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",t="nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";var n=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,i=/[stwN]/,r=/[LRr]/,s=/[Lb1n]/,o=/[1n]/;function a(e,t,n){this.level=e,this.from=t,this.to=n}return function(l,u){var d,c="ltr"==u?"L":"R";if(0==l.length||"ltr"==u&&!n.test(l))return!1;for(var h=l.length,p=[],g=0;g-1&&(i[t]=r.slice(0,s).concat(r.slice(s+1)))}}}function fe(e,t){var n=pe(e,t);if(n.length)for(var i=Array.prototype.slice.call(arguments,2),r=0;r0}function _e(e){e.prototype.on=function(e,t){he(this,e,t)},e.prototype.off=function(e,t){ge(this,e,t)}}function Ae(e){e.preventDefault?e.preventDefault():e.returnValue=!1}function ye(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0}function we(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function Ce(e){Ae(e),ye(e)}function Ee(e){return e.target||e.srcElement}function xe(e){var t=e.which;return null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2)),b&&e.ctrlKey&&1==t&&(t=3),t}var De,Se,Te=function(){if(o&&a<9)return!1;var e=M("div");return"draggable"in e||"dragDrop"in e}();function Me(e){if(null==De){var t=M("span","​");T(e,M("span",[t,document.createTextNode("x")])),0!=e.firstChild.offsetHeight&&(De=t.offsetWidth<=1&&t.offsetHeight>2&&!(o&&a<8))}var n=De?M("span","​"):M("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px");return n.setAttribute("cm-text",""),n}function ke(e){if(null!=Se)return Se;var t=T(e,document.createTextNode("AخA")),n=x(t,0,1).getBoundingClientRect(),i=x(t,1,2).getBoundingClientRect();return S(e),!(!n||n.left==n.right)&&(Se=i.right-n.right<3)}var je,Be=3!="\n\nb".split(/\n/).length?function(e){for(var t=0,n=[],i=e.length;t<=i;){var r=e.indexOf("\n",t);-1==r&&(r=e.length);var s=e.slice(t,"\r"==e.charAt(r-1)?r-1:r),o=s.indexOf("\r");-1!=o?(n.push(s.slice(0,o)),t+=o+1):(n.push(s),t=r+1)}return n}:function(e){return e.split(/\r\n?|\n/)},Oe=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(e){return!1}}:function(e){var t;try{t=e.ownerDocument.selection.createRange()}catch(e){}return!(!t||t.parentElement()!=e)&&0!=t.compareEndPoints("StartToEnd",t)},Ie="oncopy"in(je=M("div"))||(je.setAttribute("oncopy","return;"),"function"==typeof je.oncopy),Re=null;var Pe={},Le={};function Ne(e,t){arguments.length>2&&(t.dependencies=Array.prototype.slice.call(arguments,2)),Pe[e]=t}function Fe(e){if("string"==typeof e&&Le.hasOwnProperty(e))e=Le[e];else if(e&&"string"==typeof e.name&&Le.hasOwnProperty(e.name)){var t=Le[e.name];"string"==typeof t&&(t={name:t}),(e=Z(t,e)).name=t.name}else{if("string"==typeof e&&/^[\w\-]+\/[\w\-]+\+xml$/.test(e))return Fe("application/xml");if("string"==typeof e&&/^[\w\-]+\/[\w\-]+\+json$/.test(e))return Fe("application/json")}return"string"==typeof e?{name:e}:e||{name:"null"}}function ze(e,t){t=Fe(t);var n=Pe[t.name];if(!n)return ze(e,"text/plain");var i=n(e,t);if(Ue.hasOwnProperty(t.name)){var r=Ue[t.name];for(var s in r)r.hasOwnProperty(s)&&(i.hasOwnProperty(s)&&(i["_"+s]=i[s]),i[s]=r[s])}if(i.name=t.name,t.helperType&&(i.helperType=t.helperType),t.modeProps)for(var o in t.modeProps)i[o]=t.modeProps[o];return i}var Ue={};function $e(e,t){L(t,Ue.hasOwnProperty(e)?Ue[e]:Ue[e]={})}function We(e,t){if(!0===t)return t;if(e.copyState)return e.copyState(t);var n={};for(var i in t){var r=t[i];r instanceof Array&&(r=r.concat([])),n[i]=r}return n}function He(e,t){for(var n;e.innerMode&&(n=e.innerMode(t))&&n.mode!=e;)t=n.state,e=n.mode;return n||{mode:e,state:t}}function Ve(e,t,n){return!e.startState||e.startState(t,n)}var qe=function(e,t,n){this.pos=this.start=0,this.string=e,this.tabSize=t||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0,this.lineOracle=n};function Ge(e,t){if((t-=e.first)<0||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var n=e;!n.lines;)for(var i=0;;++i){var r=n.children[i],s=r.chunkSize();if(t=e.first&&tn?tt(n,Ge(e,n).text.length):function(e,t){var n=e.ch;return null==n||n>t?tt(e.line,t):n<0?tt(e.line,0):e}(t,Ge(e,t.line).text.length)}function ut(e,t){for(var n=[],i=0;i=this.string.length},qe.prototype.sol=function(){return this.pos==this.lineStart},qe.prototype.peek=function(){return this.string.charAt(this.pos)||void 0},qe.prototype.next=function(){if(this.post},qe.prototype.eatSpace=function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},qe.prototype.skipToEnd=function(){this.pos=this.string.length},qe.prototype.skipTo=function(e){var t=this.string.indexOf(e,this.pos);if(t>-1)return this.pos=t,!0},qe.prototype.backUp=function(e){this.pos-=e},qe.prototype.column=function(){return this.lastColumnPos0?null:(i&&!1!==t&&(this.pos+=i[0].length),i)}var r=function(e){return n?e.toLowerCase():e};if(r(this.string.substr(this.pos,e.length))==r(e))return!1!==t&&(this.pos+=e.length),!0},qe.prototype.current=function(){return this.string.slice(this.start,this.pos)},qe.prototype.hideFirstChars=function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}},qe.prototype.lookAhead=function(e){var t=this.lineOracle;return t&&t.lookAhead(e)},qe.prototype.baseToken=function(){var e=this.lineOracle;return e&&e.baseToken(this.pos)};var dt=function(e,t){this.state=e,this.lookAhead=t},ct=function(e,t,n,i){this.state=t,this.doc=e,this.line=n,this.maxLookAhead=i||0,this.baseTokens=null,this.baseTokenPos=1};function ht(e,t,n,i){var r=[e.state.modeGen],s={};yt(e,t.text,e.doc.mode,n,(function(e,t){return r.push(e,t)}),s,i);for(var o=n.state,a=function(i){n.baseTokens=r;var a=e.state.overlays[i],l=1,u=0;n.state=!0,yt(e,t.text,a.mode,n,(function(e,t){for(var n=l;ue&&r.splice(l,1,e,r[l+1],i),l+=2,u=Math.min(e,i)}if(t)if(a.opaque)r.splice(n,l-n,e,"overlay "+t),l=n+2;else for(;ne.options.maxHighlightLength&&We(e.doc.mode,i.state),s=ht(e,t,i);r&&(i.state=r),t.stateAfter=i.save(!r),t.styles=s.styles,s.classes?t.styleClasses=s.classes:t.styleClasses&&(t.styleClasses=null),n===e.doc.highlightFrontier&&(e.doc.modeFrontier=Math.max(e.doc.modeFrontier,++e.doc.highlightFrontier))}return t.styles}function gt(e,t,n){var i=e.doc,r=e.display;if(!i.mode.startState)return new ct(i,!0,t);var s=function(e,t,n){for(var i,r,s=e.doc,o=n?-1:t-(e.doc.mode.innerMode?1e3:100),a=t;a>o;--a){if(a<=s.first)return s.first;var l=Ge(s,a-1),u=l.stateAfter;if(u&&(!n||a+(u instanceof dt?u.lookAhead:0)<=s.modeFrontier))return a;var d=N(l.text,null,e.options.tabSize);(null==r||i>d)&&(r=a-1,i=d)}return r}(e,t,n),o=s>i.first&&Ge(i,s-1).stateAfter,a=o?ct.fromSaved(i,o,s):new ct(i,Ve(i.mode),s);return i.iter(s,t,(function(n){ft(e,n.text,a);var i=a.line;n.stateAfter=i==t-1||i%5==0||i>=r.viewFrom&&it.start)return s}throw new Error("Mode "+e.name+" failed to advance stream.")}ct.prototype.lookAhead=function(e){var t=this.doc.getLine(this.line+e);return null!=t&&e>this.maxLookAhead&&(this.maxLookAhead=e),t},ct.prototype.baseToken=function(e){if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=e;)this.baseTokenPos+=2;var t=this.baseTokens[this.baseTokenPos+1];return{type:t&&t.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-e}},ct.prototype.nextLine=function(){this.line++,this.maxLookAhead>0&&this.maxLookAhead--},ct.fromSaved=function(e,t,n){return t instanceof dt?new ct(e,We(e.mode,t.state),n,t.lookAhead):new ct(e,We(e.mode,t),n)},ct.prototype.save=function(e){var t=!1!==e?We(this.doc.mode,this.state):this.state;return this.maxLookAhead>0?new dt(t,this.maxLookAhead):t};var bt=function(e,t,n){this.start=e.start,this.end=e.pos,this.string=e.current(),this.type=t||null,this.state=n};function _t(e,t,n,i){var r,s,o=e.doc,a=o.mode,l=Ge(o,(t=lt(o,t)).line),u=gt(e,t.line,n),d=new qe(l.text,e.options.tabSize,u);for(i&&(s=[]);(i||d.pose.options.maxHighlightLength?(a=!1,o&&ft(e,t,i,c.pos),c.pos=t.length,l=null):l=At(vt(n,c,i.state,h),s),h){var p=h[0].name;p&&(l="m-"+(l?p+" "+l:p))}if(!a||d!=l){for(;u=t:s.to>t);(i||(i=[])).push(new Et(o,s.from,a?null:s.to))}}return i}(n,r,o),l=function(e,t,n){var i;if(e)for(var r=0;r=t:s.to>t)||s.from==t&&"bookmark"==o.type&&(!n||s.marker.insertLeft)){var a=null==s.from||(o.inclusiveLeft?s.from<=t:s.from0&&a)for(var _=0;_t)&&(!n||Ot(n,s.marker)<0)&&(n=s.marker)}return n}function Nt(e,t,n,i,r){var s=Ge(e,t),o=Ct&&s.markedSpans;if(o)for(var a=0;a=0&&c<=0||d<=0&&c>=0)&&(d<=0&&(l.marker.inclusiveRight&&r.inclusiveLeft?nt(u.to,n)>=0:nt(u.to,n)>0)||d>=0&&(l.marker.inclusiveRight&&r.inclusiveLeft?nt(u.from,i)<=0:nt(u.from,i)<0)))return!0}}}function Ft(e){for(var t;t=Rt(e);)e=t.find(-1,!0).line;return e}function zt(e,t){var n=Ge(e,t),i=Ft(n);return n==i?t:Xe(i)}function Ut(e,t){if(t>e.lastLine())return t;var n,i=Ge(e,t);if(!$t(e,i))return t;for(;n=Pt(i);)i=n.find(1,!0).line;return Xe(i)+1}function $t(e,t){var n=Ct&&t.markedSpans;if(n)for(var i=void 0,r=0;rt.maxLineLength&&(t.maxLineLength=n,t.maxLine=e)}))}var Gt=function(e,t,n){this.text=e,kt(this,t),this.height=n?n(this):1};function Kt(e){e.parent=null,Mt(e)}Gt.prototype.lineNo=function(){return Xe(this)},_e(Gt);var Yt={},Jt={};function Xt(e,t){if(!e||/^\s*$/.test(e))return null;var n=t.addModeClass?Jt:Yt;return n[e]||(n[e]=e.replace(/\S+/g,"cm-$&"))}function Zt(e,t){var n=k("span",null,null,l?"padding-right: .1px":null),i={pre:k("pre",[n],"CodeMirror-line"),content:n,col:0,pos:0,cm:e,trailingSpace:!1,splitSpaces:e.getOption("lineWrapping")};t.measure={};for(var r=0;r<=(t.rest?t.rest.length:0);r++){var s=r?t.rest[r-1]:t.line,o=void 0;i.pos=0,i.addToken=en,ke(e.display.measure)&&(o=de(s,e.doc.direction))&&(i.addToken=tn(i.addToken,o)),i.map=[],rn(s,i,pt(e,s,t!=e.display.externalMeasured&&Xe(s))),s.styleClasses&&(s.styleClasses.bgClass&&(i.bgClass=I(s.styleClasses.bgClass,i.bgClass||"")),s.styleClasses.textClass&&(i.textClass=I(s.styleClasses.textClass,i.textClass||""))),0==i.map.length&&i.map.push(0,0,i.content.appendChild(Me(e.display.measure))),0==r?(t.measure.map=i.map,t.measure.cache={}):((t.measure.maps||(t.measure.maps=[])).push(i.map),(t.measure.caches||(t.measure.caches=[])).push({}))}if(l){var a=i.content.lastChild;(/\bcm-tab\b/.test(a.className)||a.querySelector&&a.querySelector(".cm-tab"))&&(i.content.className="cm-tab-wrap-hack")}return fe(e,"renderLine",e,t.line,i.pre),i.pre.className&&(i.textClass=I(i.pre.className,i.textClass||"")),i}function Qt(e){var t=M("span","•","cm-invalidchar");return t.title="\\u"+e.charCodeAt(0).toString(16),t.setAttribute("aria-label",t.title),t}function en(e,t,n,i,r,s,l){if(t){var u,d=e.splitSpaces?function(e,t){if(e.length>1&&!/ /.test(e))return e;for(var n=t,i="",r=0;ru&&c.from<=u);h++);if(c.to>=d)return e(n,i,r,s,o,a,l);e(n,i.slice(0,c.to-u),r,s,null,a,l),s=null,i=i.slice(c.to-u),u=c.to}}}function nn(e,t,n,i){var r=!i&&n.widgetNode;r&&e.map.push(e.pos,e.pos+t,r),!i&&e.cm.display.input.needsContentAttribute&&(r||(r=e.content.appendChild(document.createElement("span"))),r.setAttribute("cm-marker",n.id)),r&&(e.cm.display.input.setUneditable(r),e.content.appendChild(r)),e.pos+=t,e.trailingSpace=!1}function rn(e,t,n){var i=e.markedSpans,r=e.text,s=0;if(i)for(var o,a,l,u,d,c,h,p=r.length,g=0,f=1,m="",v=0;;){if(v==g){l=u=d=a="",h=null,c=null,v=1/0;for(var b=[],_=void 0,A=0;Ag||w.collapsed&&y.to==g&&y.from==g)){if(null!=y.to&&y.to!=g&&v>y.to&&(v=y.to,u=""),w.className&&(l+=" "+w.className),w.css&&(a=(a?a+";":"")+w.css),w.startStyle&&y.from==g&&(d+=" "+w.startStyle),w.endStyle&&y.to==v&&(_||(_=[])).push(w.endStyle,y.to),w.title&&((h||(h={})).title=w.title),w.attributes)for(var C in w.attributes)(h||(h={}))[C]=w.attributes[C];w.collapsed&&(!c||Ot(c.marker,w)<0)&&(c=y)}else y.from>g&&v>y.from&&(v=y.from)}if(_)for(var E=0;E<_.length;E+=2)_[E+1]==v&&(u+=" "+_[E]);if(!c||c.from==g)for(var x=0;x=p)break;for(var D=Math.min(p,v);;){if(m){var S=g+m.length;if(!c){var T=S>D?m.slice(0,D-g):m;t.addToken(t,T,o?o+l:l,d,g+T.length==v?u:"",a,h)}if(S>=D){m=m.slice(D-g),g=D;break}g=S,d=""}m=r.slice(s,s=n[f++]),o=Xt(n[f++],t.cm.options)}}else for(var M=1;Mn)return{map:e.measure.maps[r],cache:e.measure.caches[r],before:!0}}function jn(e,t,n,i){return In(e,On(e,t),n,i)}function Bn(e,t){if(t>=e.display.viewFrom&&t=n.lineN&&t2&&s.push((l.bottom+u.top)/2-n.top)}}s.push(n.bottom-n.top)}}(e,t.view,t.rect),t.hasHeights=!0),(s=function(e,t,n,i){var r,s=Ln(t.map,n,i),l=s.node,u=s.start,d=s.end,c=s.collapse;if(3==l.nodeType){for(var h=0;h<4;h++){for(;u&&re(t.line.text.charAt(s.coverStart+u));)--u;for(;s.coverStart+d1}(e))return t;var n=screen.logicalXDPI/screen.deviceXDPI,i=screen.logicalYDPI/screen.deviceYDPI;return{left:t.left*n,right:t.right*n,top:t.top*i,bottom:t.bottom*i}}(e.display.measure,r))}else{var p;u>0&&(c=i="right"),r=e.options.lineWrapping&&(p=l.getClientRects()).length>1?p["right"==i?p.length-1:0]:l.getBoundingClientRect()}if(o&&a<9&&!u&&(!r||!r.left&&!r.right)){var g=l.parentNode.getClientRects()[0];r=g?{left:g.left,right:g.left+si(e.display),top:g.top,bottom:g.bottom}:Pn}for(var f=r.top-t.rect.top,m=r.bottom-t.rect.top,v=(f+m)/2,b=t.view.measure.heights,_=0;_t)&&(r=(s=l-a)-1,t>=l&&(o="right")),null!=r){if(i=e[u+2],a==l&&n==(i.insertLeft?"left":"right")&&(o=n),"left"==n&&0==r)for(;u&&e[u-2]==e[u-3]&&e[u-1].insertLeft;)i=e[2+(u-=3)],o="left";if("right"==n&&r==l-a)for(;u=0&&(n=e[r]).left==n.right;r--);return n}function Fn(e){if(e.measure&&(e.measure.cache={},e.measure.heights=null,e.rest))for(var t=0;t=i.text.length?(l=i.text.length,u="before"):l<=0&&(l=0,u="after"),!a)return o("before"==u?l-1:l,"before"==u);function d(e,t,n){return o(n?e-1:e,1==a[t].level!=n)}var c=le(a,l,u),h=ae,p=d(l,c,"before"==u);return null!=h&&(p.other=d(l,h,"before"!=u)),p}function Yn(e,t){var n=0;t=lt(e.doc,t),e.options.lineWrapping||(n=si(e.display)*t.ch);var i=Ge(e.doc,t.line),r=Ht(i)+En(e.display);return{left:n,right:n,top:r,bottom:r+i.height}}function Jn(e,t,n,i,r){var s=tt(e,t,n);return s.xRel=r,i&&(s.outside=i),s}function Xn(e,t,n){var i=e.doc;if((n+=e.display.viewOffset)<0)return Jn(i.first,0,null,-1,-1);var r=Ze(i,n),s=i.first+i.size-1;if(r>s)return Jn(i.first+i.size-1,Ge(i,s).text.length,null,1,1);t<0&&(t=0);for(var o=Ge(i,r);;){var a=ti(e,o,r,t,n),l=Lt(o,a.ch+(a.xRel>0||a.outside>0?1:0));if(!l)return a;var u=l.find(1);if(u.line==r)return u;o=Ge(i,r=u.line)}}function Zn(e,t,n,i){i-=Hn(t);var r=t.text.length,s=oe((function(t){return In(e,n,t-1).bottom<=i}),r,0);return{begin:s,end:r=oe((function(t){return In(e,n,t).top>i}),s,r)}}function Qn(e,t,n,i){return n||(n=On(e,t)),Zn(e,t,n,Vn(e,t,In(e,n,i),"line").top)}function ei(e,t,n,i){return!(e.bottom<=n)&&(e.top>n||(i?e.left:e.right)>t)}function ti(e,t,n,i,r){r-=Ht(t);var s=On(e,t),o=Hn(t),a=0,l=t.text.length,u=!0,d=de(t,e.doc.direction);if(d){var c=(e.options.lineWrapping?ii:ni)(e,t,n,s,d,i,r);a=(u=1!=c.level)?c.from:c.to-1,l=u?c.to:c.from-1}var h,p,g=null,f=null,m=oe((function(t){var n=In(e,s,t);return n.top+=o,n.bottom+=o,!!ei(n,i,r,!1)&&(n.top<=r&&n.left<=i&&(g=t,f=n),!0)}),a,l),v=!1;if(f){var b=i-f.left=A.bottom?1:0}return Jn(n,m=se(t.text,m,1),p,v,i-h)}function ni(e,t,n,i,r,s,o){var a=oe((function(a){var l=r[a],u=1!=l.level;return ei(Kn(e,tt(n,u?l.to:l.from,u?"before":"after"),"line",t,i),s,o,!0)}),0,r.length-1),l=r[a];if(a>0){var u=1!=l.level,d=Kn(e,tt(n,u?l.from:l.to,u?"after":"before"),"line",t,i);ei(d,s,o,!0)&&d.top>o&&(l=r[a-1])}return l}function ii(e,t,n,i,r,s,o){var a=Zn(e,t,i,o),l=a.begin,u=a.end;/\s/.test(t.text.charAt(u-1))&&u--;for(var d=null,c=null,h=0;h=u||p.to<=l)){var g=In(e,i,1!=p.level?Math.min(u,p.to)-1:Math.max(l,p.from)).right,f=gf)&&(d=p,c=f)}}return d||(d=r[r.length-1]),d.fromu&&(d={from:d.from,to:u,level:d.level}),d}function ri(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==Rn){Rn=M("pre",null,"CodeMirror-line-like");for(var t=0;t<49;++t)Rn.appendChild(document.createTextNode("x")),Rn.appendChild(M("br"));Rn.appendChild(document.createTextNode("x"))}T(e.measure,Rn);var n=Rn.offsetHeight/50;return n>3&&(e.cachedTextHeight=n),S(e.measure),n||1}function si(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=M("span","xxxxxxxxxx"),n=M("pre",[t],"CodeMirror-line-like");T(e.measure,n);var i=t.getBoundingClientRect(),r=(i.right-i.left)/10;return r>2&&(e.cachedCharWidth=r),r||10}function oi(e){for(var t=e.display,n={},i={},r=t.gutters.clientLeft,s=t.gutters.firstChild,o=0;s;s=s.nextSibling,++o){var a=e.display.gutterSpecs[o].className;n[a]=s.offsetLeft+s.clientLeft+r,i[a]=s.clientWidth}return{fixedPos:ai(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:n,gutterWidth:i,wrapperWidth:t.wrapper.clientWidth}}function ai(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function li(e){var t=ri(e.display),n=e.options.lineWrapping,i=n&&Math.max(5,e.display.scroller.clientWidth/si(e.display)-3);return function(r){if($t(e.doc,r))return 0;var s=0;if(r.widgets)for(var o=0;o0&&(l=Ge(e.doc,u.line).text).length==u.ch){var d=N(l,l.length,e.options.tabSize)-l.length;u=tt(u.line,Math.max(0,Math.round((s-Dn(e.display).left)/si(e.display))-d))}return u}function ci(e,t){if(t>=e.display.viewTo)return null;if((t-=e.display.viewFrom)<0)return null;for(var n=e.display.view,i=0;it)&&(r.updateLineNumbers=t),e.curOp.viewChanged=!0,t>=r.viewTo)Ct&&zt(e.doc,t)r.viewFrom?gi(e):(r.viewFrom+=i,r.viewTo+=i);else if(t<=r.viewFrom&&n>=r.viewTo)gi(e);else if(t<=r.viewFrom){var s=fi(e,n,n+i,1);s?(r.view=r.view.slice(s.index),r.viewFrom=s.lineN,r.viewTo+=i):gi(e)}else if(n>=r.viewTo){var o=fi(e,t,t,-1);o?(r.view=r.view.slice(0,o.index),r.viewTo=o.lineN):gi(e)}else{var a=fi(e,t,t,-1),l=fi(e,n,n+i,1);a&&l?(r.view=r.view.slice(0,a.index).concat(on(e,a.lineN,l.lineN)).concat(r.view.slice(l.index)),r.viewTo+=i):gi(e)}var u=r.externalMeasured;u&&(n=r.lineN&&t=i.viewTo)){var s=i.view[ci(e,t)];if(null!=s.node){var o=s.changes||(s.changes=[]);-1==z(o,n)&&o.push(n)}}}function gi(e){e.display.viewFrom=e.display.viewTo=e.doc.first,e.display.view=[],e.display.viewOffset=0}function fi(e,t,n,i){var r,s=ci(e,t),o=e.display.view;if(!Ct||n==e.doc.first+e.doc.size)return{index:s,lineN:n};for(var a=e.display.viewFrom,l=0;l0){if(s==o.length-1)return null;r=a+o[s].size-t,s++}else r=a-t;t+=r,n+=r}for(;zt(e.doc,n)!=n;){if(s==(i<0?0:o.length-1))return null;n+=i*o[s-(i<0?1:0)].size,s+=i}return{index:s,lineN:n}}function mi(e){for(var t=e.display.view,n=0,i=0;i=e.display.viewTo||a.to().linet||t==n&&o.to==t)&&(i(Math.max(o.from,t),Math.min(o.to,n),1==o.level?"rtl":"ltr",s),r=!0)}r||i(t,n,"ltr")}(f,n||0,null==i?h:i,(function(e,t,r,c){var m="ltr"==r,v=p(e,m?"left":"right"),b=p(t-1,m?"right":"left"),_=null==n&&0==e,A=null==i&&t==h,y=0==c,w=!f||c==f.length-1;if(b.top-v.top<=3){var C=(u?A:_)&&w,E=(u?_:A)&&y?a:(m?v:b).left,x=C?l:(m?b:v).right;d(E,v.top,x-E,v.bottom)}else{var D,S,T,M;m?(D=u&&_&&y?a:v.left,S=u?l:g(e,r,"before"),T=u?a:g(t,r,"after"),M=u&&A&&w?l:b.right):(D=u?g(e,r,"before"):a,S=!u&&_&&y?l:v.right,T=!u&&A&&w?a:b.left,M=u?g(t,r,"after"):l),d(D,v.top,S-D,v.bottom),v.bottom0?t.blinker=setInterval((function(){e.hasFocus()||Di(e),t.cursorDiv.style.visibility=(n=!n)?"":"hidden"}),e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden")}}function Ci(e){e.hasFocus()||(e.display.input.focus(),e.state.focused||xi(e))}function Ei(e){e.state.delayingBlurEvent=!0,setTimeout((function(){e.state.delayingBlurEvent&&(e.state.delayingBlurEvent=!1,e.state.focused&&Di(e))}),100)}function xi(e,t){e.state.delayingBlurEvent&&!e.state.draggingText&&(e.state.delayingBlurEvent=!1),"nocursor"!=e.options.readOnly&&(e.state.focused||(fe(e,"focus",e,t),e.state.focused=!0,O(e.display.wrapper,"CodeMirror-focused"),e.curOp||e.display.selForContextMenu==e.doc.sel||(e.display.input.reset(),l&&setTimeout((function(){return e.display.input.reset(!0)}),20)),e.display.input.receivedFocus()),wi(e))}function Di(e,t){e.state.delayingBlurEvent||(e.state.focused&&(fe(e,"blur",e,t),e.state.focused=!1,D(e.display.wrapper,"CodeMirror-focused")),clearInterval(e.display.blinker),setTimeout((function(){e.state.focused||(e.display.shift=!1)}),150))}function Si(e){for(var t=e.display,n=t.lineDiv.offsetTop,i=0;i.005||h<-.005)&&(Je(r.line,l),Ti(r.line),r.rest))for(var p=0;pe.display.sizerWidth){var g=Math.ceil(u/si(e.display));g>e.display.maxLineLength&&(e.display.maxLineLength=g,e.display.maxLine=r.line,e.display.maxLineChanged=!0)}}}}function Ti(e){if(e.widgets)for(var t=0;t=o&&(s=Ze(t,Ht(Ge(t,l))-e.wrapper.clientHeight),o=l)}return{from:s,to:Math.max(o,s+1)}}function ki(e,t){var n=e.display,i=ri(e.display);t.top<0&&(t.top=0);var r=e.curOp&&null!=e.curOp.scrollTop?e.curOp.scrollTop:n.scroller.scrollTop,s=Mn(e),o={};t.bottom-t.top>s&&(t.bottom=t.top+s);var a=e.doc.height+xn(n),l=t.topa-i;if(t.topr+s){var d=Math.min(t.top,(u?a:t.bottom)-s);d!=r&&(o.scrollTop=d)}var c=e.options.fixedGutter?0:n.gutters.offsetWidth,h=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:n.scroller.scrollLeft-c,p=Tn(e)-n.gutters.offsetWidth,g=t.right-t.left>p;return g&&(t.right=t.left+p),t.left<10?o.scrollLeft=0:t.leftp+h-3&&(o.scrollLeft=t.right+(g?0:10)-p),o}function ji(e,t){null!=t&&(Ii(e),e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+t)}function Bi(e){Ii(e);var t=e.getCursor();e.curOp.scrollToPos={from:t,to:t,margin:e.options.cursorScrollMargin}}function Oi(e,t,n){null==t&&null==n||Ii(e),null!=t&&(e.curOp.scrollLeft=t),null!=n&&(e.curOp.scrollTop=n)}function Ii(e){var t=e.curOp.scrollToPos;t&&(e.curOp.scrollToPos=null,Ri(e,Yn(e,t.from),Yn(e,t.to),t.margin))}function Ri(e,t,n,i){var r=ki(e,{left:Math.min(t.left,n.left),top:Math.min(t.top,n.top)-i,right:Math.max(t.right,n.right),bottom:Math.max(t.bottom,n.bottom)+i});Oi(e,r.scrollLeft,r.scrollTop)}function Pi(e,t){Math.abs(e.doc.scrollTop-t)<2||(n||ur(e,{top:t}),Li(e,t,!0),n&&ur(e),rr(e,100))}function Li(e,t,n){t=Math.max(0,Math.min(e.display.scroller.scrollHeight-e.display.scroller.clientHeight,t)),(e.display.scroller.scrollTop!=t||n)&&(e.doc.scrollTop=t,e.display.scrollbars.setScrollTop(t),e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t))}function Ni(e,t,n,i){t=Math.max(0,Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth)),(n?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)&&!i||(e.doc.scrollLeft=t,hr(e),e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t),e.display.scrollbars.setScrollLeft(t))}function Fi(e){var t=e.display,n=t.gutters.offsetWidth,i=Math.round(e.doc.height+xn(e.display));return{clientHeight:t.scroller.clientHeight,viewHeight:t.wrapper.clientHeight,scrollWidth:t.scroller.scrollWidth,clientWidth:t.scroller.clientWidth,viewWidth:t.wrapper.clientWidth,barLeft:e.options.fixedGutter?n:0,docHeight:i,scrollHeight:i+Sn(e)+t.barHeight,nativeBarWidth:t.nativeBarWidth,gutterWidth:n}}var zi=function(e,t,n){this.cm=n;var i=this.vert=M("div",[M("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),r=this.horiz=M("div",[M("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");i.tabIndex=r.tabIndex=-1,e(i),e(r),he(i,"scroll",(function(){i.clientHeight&&t(i.scrollTop,"vertical")})),he(r,"scroll",(function(){r.clientWidth&&t(r.scrollLeft,"horizontal")})),this.checkedZeroWidth=!1,o&&a<8&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")};zi.prototype.update=function(e){var t=e.scrollWidth>e.clientWidth+1,n=e.scrollHeight>e.clientHeight+1,i=e.nativeBarWidth;if(n){this.vert.style.display="block",this.vert.style.bottom=t?i+"px":"0";var r=e.viewHeight-(t?i:0);this.vert.firstChild.style.height=Math.max(0,e.scrollHeight-e.clientHeight+r)+"px"}else this.vert.style.display="",this.vert.firstChild.style.height="0";if(t){this.horiz.style.display="block",this.horiz.style.right=n?i+"px":"0",this.horiz.style.left=e.barLeft+"px";var s=e.viewWidth-e.barLeft-(n?i:0);this.horiz.firstChild.style.width=Math.max(0,e.scrollWidth-e.clientWidth+s)+"px"}else this.horiz.style.display="",this.horiz.firstChild.style.width="0";return!this.checkedZeroWidth&&e.clientHeight>0&&(0==i&&this.zeroWidthHack(),this.checkedZeroWidth=!0),{right:n?i:0,bottom:t?i:0}},zi.prototype.setScrollLeft=function(e){this.horiz.scrollLeft!=e&&(this.horiz.scrollLeft=e),this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz,"horiz")},zi.prototype.setScrollTop=function(e){this.vert.scrollTop!=e&&(this.vert.scrollTop=e),this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert,"vert")},zi.prototype.zeroWidthHack=function(){var e=b&&!p?"12px":"18px";this.horiz.style.height=this.vert.style.width=e,this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none",this.disableHoriz=new F,this.disableVert=new F},zi.prototype.enableZeroWidthBar=function(e,t,n){e.style.pointerEvents="auto",t.set(1e3,(function i(){var r=e.getBoundingClientRect();("vert"==n?document.elementFromPoint(r.right-1,(r.top+r.bottom)/2):document.elementFromPoint((r.right+r.left)/2,r.bottom-1))!=e?e.style.pointerEvents="none":t.set(1e3,i)}))},zi.prototype.clear=function(){var e=this.horiz.parentNode;e.removeChild(this.horiz),e.removeChild(this.vert)};var Ui=function(){};function $i(e,t){t||(t=Fi(e));var n=e.display.barWidth,i=e.display.barHeight;Wi(e,t);for(var r=0;r<4&&n!=e.display.barWidth||i!=e.display.barHeight;r++)n!=e.display.barWidth&&e.options.lineWrapping&&Si(e),Wi(e,Fi(e)),n=e.display.barWidth,i=e.display.barHeight}function Wi(e,t){var n=e.display,i=n.scrollbars.update(t);n.sizer.style.paddingRight=(n.barWidth=i.right)+"px",n.sizer.style.paddingBottom=(n.barHeight=i.bottom)+"px",n.heightForcer.style.borderBottom=i.bottom+"px solid transparent",i.right&&i.bottom?(n.scrollbarFiller.style.display="block",n.scrollbarFiller.style.height=i.bottom+"px",n.scrollbarFiller.style.width=i.right+"px"):n.scrollbarFiller.style.display="",i.bottom&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter?(n.gutterFiller.style.display="block",n.gutterFiller.style.height=i.bottom+"px",n.gutterFiller.style.width=t.gutterWidth+"px"):n.gutterFiller.style.display=""}Ui.prototype.update=function(){return{bottom:0,right:0}},Ui.prototype.setScrollLeft=function(){},Ui.prototype.setScrollTop=function(){},Ui.prototype.clear=function(){};var Hi={native:zi,null:Ui};function Vi(e){e.display.scrollbars&&(e.display.scrollbars.clear(),e.display.scrollbars.addClass&&D(e.display.wrapper,e.display.scrollbars.addClass)),e.display.scrollbars=new Hi[e.options.scrollbarStyle]((function(t){e.display.wrapper.insertBefore(t,e.display.scrollbarFiller),he(t,"mousedown",(function(){e.state.focused&&setTimeout((function(){return e.display.input.focus()}),0)})),t.setAttribute("cm-not-content","true")}),(function(t,n){"horizontal"==n?Ni(e,t):Pi(e,t)}),e),e.display.scrollbars.addClass&&O(e.display.wrapper,e.display.scrollbars.addClass)}var qi=0;function Gi(e){var t;e.curOp={cm:e,viewChanged:!1,startHeight:e.doc.height,forceUpdate:!1,updateInput:0,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++qi,markArrays:null},t=e.curOp,an?an.ops.push(t):t.ownsGroup=an={ops:[t],delayedCallbacks:[]}}function Ki(e){var t=e.curOp;t&&function(e,t){var n=e.ownsGroup;if(n)try{!function(e){var t=e.delayedCallbacks,n=0;do{for(;n=n.viewTo)||n.maxLineChanged&&t.options.lineWrapping,e.update=e.mustUpdate&&new or(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function Ji(e){e.updatedDisplay=e.mustUpdate&&ar(e.cm,e.update)}function Xi(e){var t=e.cm,n=t.display;e.updatedDisplay&&Si(t),e.barMeasure=Fi(t),n.maxLineChanged&&!t.options.lineWrapping&&(e.adjustWidthTo=jn(t,n.maxLine,n.maxLine.text.length).left+3,t.display.sizerWidth=e.adjustWidthTo,e.barMeasure.scrollWidth=Math.max(n.scroller.clientWidth,n.sizer.offsetLeft+e.adjustWidthTo+Sn(t)+t.display.barWidth),e.maxScrollLeft=Math.max(0,n.sizer.offsetLeft+e.adjustWidthTo-Tn(t))),(e.updatedDisplay||e.selectionChanged)&&(e.preparedSelection=n.input.prepareSelection())}function Zi(e){var t=e.cm;null!=e.adjustWidthTo&&(t.display.sizer.style.minWidth=e.adjustWidthTo+"px",e.maxScrollLeft(window.innerHeight||document.documentElement.clientHeight)&&(r=!1),null!=r&&!g){var s=M("div","​",null,"position: absolute;\n top: "+(t.top-n.viewOffset-En(e.display))+"px;\n height: "+(t.bottom-t.top+Sn(e)+n.barHeight)+"px;\n left: "+t.left+"px; width: "+Math.max(2,t.right-t.left)+"px;");e.display.lineSpace.appendChild(s),s.scrollIntoView(r),e.display.lineSpace.removeChild(s)}}}(t,function(e,t,n,i){var r;null==i&&(i=0),e.options.lineWrapping||t!=n||(n="before"==t.sticky?tt(t.line,t.ch+1,"before"):t,t=t.ch?tt(t.line,"before"==t.sticky?t.ch-1:t.ch,"after"):t);for(var s=0;s<5;s++){var o=!1,a=Kn(e,t),l=n&&n!=t?Kn(e,n):a,u=ki(e,r={left:Math.min(a.left,l.left),top:Math.min(a.top,l.top)-i,right:Math.max(a.left,l.left),bottom:Math.max(a.bottom,l.bottom)+i}),d=e.doc.scrollTop,c=e.doc.scrollLeft;if(null!=u.scrollTop&&(Pi(e,u.scrollTop),Math.abs(e.doc.scrollTop-d)>1&&(o=!0)),null!=u.scrollLeft&&(Ni(e,u.scrollLeft),Math.abs(e.doc.scrollLeft-c)>1&&(o=!0)),!o)break}return r}(t,lt(i,e.scrollToPos.from),lt(i,e.scrollToPos.to),e.scrollToPos.margin));var r=e.maybeHiddenMarkers,s=e.maybeUnhiddenMarkers;if(r)for(var o=0;o=e.display.viewTo)){var n=+new Date+e.options.workTime,i=gt(e,t.highlightFrontier),r=[];t.iter(i.line,Math.min(t.first+t.size,e.display.viewTo+500),(function(s){if(i.line>=e.display.viewFrom){var o=s.styles,a=s.text.length>e.options.maxHighlightLength?We(t.mode,i.state):null,l=ht(e,s,i,!0);a&&(i.state=a),s.styles=l.styles;var u=s.styleClasses,d=l.classes;d?s.styleClasses=d:u&&(s.styleClasses=null);for(var c=!o||o.length!=s.styles.length||u!=d&&(!u||!d||u.bgClass!=d.bgClass||u.textClass!=d.textClass),h=0;!c&&hn)return rr(e,e.options.workDelay),!0})),t.highlightFrontier=i.line,t.modeFrontier=Math.max(t.modeFrontier,i.line),r.length&&er(e,(function(){for(var t=0;t=n.viewFrom&&t.visible.to<=n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo)&&n.renderedView==n.view&&0==mi(e))return!1;pr(e)&&(gi(e),t.dims=oi(e));var r=i.first+i.size,s=Math.max(t.visible.from-e.options.viewportMargin,i.first),o=Math.min(r,t.visible.to+e.options.viewportMargin);n.viewFromo&&n.viewTo-o<20&&(o=Math.min(r,n.viewTo)),Ct&&(s=zt(e.doc,s),o=Ut(e.doc,o));var a=s!=n.viewFrom||o!=n.viewTo||n.lastWrapHeight!=t.wrapperHeight||n.lastWrapWidth!=t.wrapperWidth;(function(e,t,n){var i=e.display;0==i.view.length||t>=i.viewTo||n<=i.viewFrom?(i.view=on(e,t,n),i.viewFrom=t):(i.viewFrom>t?i.view=on(e,t,i.viewFrom).concat(i.view):i.viewFromn&&(i.view=i.view.slice(0,ci(e,n)))),i.viewTo=n})(e,s,o),n.viewOffset=Ht(Ge(e.doc,n.viewFrom)),e.display.mover.style.top=n.viewOffset+"px";var u=mi(e);if(!a&&0==u&&!t.force&&n.renderedView==n.view&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo))return!1;var d=function(e){if(e.hasFocus())return null;var t=B();if(!t||!j(e.display.lineDiv,t))return null;var n={activeElt:t};if(window.getSelection){var i=window.getSelection();i.anchorNode&&i.extend&&j(e.display.lineDiv,i.anchorNode)&&(n.anchorNode=i.anchorNode,n.anchorOffset=i.anchorOffset,n.focusNode=i.focusNode,n.focusOffset=i.focusOffset)}return n}(e);return u>4&&(n.lineDiv.style.display="none"),function(e,t,n){var i=e.display,r=e.options.lineNumbers,s=i.lineDiv,o=s.firstChild;function a(t){var n=t.nextSibling;return l&&b&&e.display.currentWheelTarget==t?t.style.display="none":t.parentNode.removeChild(t),n}for(var u=i.view,d=i.viewFrom,c=0;c-1&&(p=!1),cn(e,h,d,n)),p&&(S(h.lineNumber),h.lineNumber.appendChild(document.createTextNode(et(e.options,d)))),o=h.node.nextSibling}else{var g=bn(e,h,d,n);s.insertBefore(g,o)}d+=h.size}for(;o;)o=a(o)}(e,n.updateLineNumbers,t.dims),u>4&&(n.lineDiv.style.display=""),n.renderedView=n.view,function(e){if(e&&e.activeElt&&e.activeElt!=B()&&(e.activeElt.focus(),!/^(INPUT|TEXTAREA)$/.test(e.activeElt.nodeName)&&e.anchorNode&&j(document.body,e.anchorNode)&&j(document.body,e.focusNode))){var t=window.getSelection(),n=document.createRange();n.setEnd(e.anchorNode,e.anchorOffset),n.collapse(!1),t.removeAllRanges(),t.addRange(n),t.extend(e.focusNode,e.focusOffset)}}(d),S(n.cursorDiv),S(n.selectionDiv),n.gutters.style.height=n.sizer.style.minHeight=0,a&&(n.lastWrapHeight=t.wrapperHeight,n.lastWrapWidth=t.wrapperWidth,rr(e,400)),n.updateLineNumbers=null,!0}function lr(e,t){for(var n=t.viewport,i=!0;;i=!1){if(i&&e.options.lineWrapping&&t.oldDisplayWidth!=Tn(e))i&&(t.visible=Mi(e.display,e.doc,n));else if(n&&null!=n.top&&(n={top:Math.min(e.doc.height+xn(e.display)-Mn(e),n.top)}),t.visible=Mi(e.display,e.doc,n),t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)break;if(!ar(e,t))break;Si(e);var r=Fi(e);vi(e),$i(e,r),cr(e,r),t.force=!1}t.signal(e,"update",e),e.display.viewFrom==e.display.reportedViewFrom&&e.display.viewTo==e.display.reportedViewTo||(t.signal(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo),e.display.reportedViewFrom=e.display.viewFrom,e.display.reportedViewTo=e.display.viewTo)}function ur(e,t){var n=new or(e,t);if(ar(e,n)){Si(e),lr(e,n);var i=Fi(e);vi(e),$i(e,i),cr(e,i),n.finish()}}function dr(e){var t=e.gutters.offsetWidth;e.sizer.style.marginLeft=t+"px",un(e,"gutterChanged",e)}function cr(e,t){e.display.sizer.style.minHeight=t.docHeight+"px",e.display.heightForcer.style.top=t.docHeight+"px",e.display.gutters.style.height=t.docHeight+e.display.barHeight+Sn(e)+"px"}function hr(e){var t=e.display,n=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var i=ai(t)-t.scroller.scrollLeft+e.doc.scrollLeft,r=t.gutters.offsetWidth,s=i+"px",o=0;oa.clientWidth,d=a.scrollHeight>a.clientHeight;if(r&&u||s&&d){if(s&&b&&l)e:for(var h=t.target,p=o.view;h!=a;h=h.parentNode)for(var g=0;g=0&&nt(e,i.to())<=0)return n}return-1};var Er=function(e,t){this.anchor=e,this.head=t};function xr(e,t,n){var i=e&&e.options.selectionsMayTouch,r=t[n];t.sort((function(e,t){return nt(e.from(),t.from())})),n=z(t,r);for(var s=1;s0:l>=0){var u=ot(a.from(),o.from()),d=st(a.to(),o.to()),c=a.empty()?o.from()==o.head:a.from()==a.head;s<=n&&--n,t.splice(--s,2,new Er(c?d:u,c?u:d))}}return new Cr(t,n)}function Dr(e,t){return new Cr([new Er(e,t||e)],0)}function Sr(e){return e.text?tt(e.from.line+e.text.length-1,Y(e.text).length+(1==e.text.length?e.from.ch:0)):e.to}function Tr(e,t){if(nt(e,t.from)<0)return e;if(nt(e,t.to)<=0)return Sr(t);var n=e.line+t.text.length-(t.to.line-t.from.line)-1,i=e.ch;return e.line==t.to.line&&(i+=Sr(t).ch-t.to.ch),tt(n,i)}function Mr(e,t){for(var n=[],i=0;i1&&e.remove(a.line+1,g-1),e.insert(a.line+1,v)}un(e,"change",e,t)}function Rr(e,t,n){!function e(i,r,s){if(i.linked)for(var o=0;oa-(e.cm?e.cm.options.historyEventDelay:500)||"*"==t.origin.charAt(0)))&&(s=function(e,t){return t?(zr(e.done),Y(e.done)):e.done.length&&!Y(e.done).ranges?Y(e.done):e.done.length>1&&!e.done[e.done.length-2].ranges?(e.done.pop(),Y(e.done)):void 0}(r,r.lastOp==i)))o=Y(s.changes),0==nt(t.from,t.to)&&0==nt(t.from,o.to)?o.to=Sr(t):s.changes.push(Fr(e,t));else{var l=Y(r.done);for(l&&l.ranges||Wr(e.sel,r.done),s={changes:[Fr(e,t)],generation:r.generation},r.done.push(s);r.done.length>r.undoDepth;)r.done.shift(),r.done[0].ranges||r.done.shift()}r.done.push(n),r.generation=++r.maxGeneration,r.lastModTime=r.lastSelTime=a,r.lastOp=r.lastSelOp=i,r.lastOrigin=r.lastSelOrigin=t.origin,o||fe(e,"historyAdded")}function $r(e,t,n,i){var r=e.history,s=i&&i.origin;n==r.lastSelOp||s&&r.lastSelOrigin==s&&(r.lastModTime==r.lastSelTime&&r.lastOrigin==s||function(e,t,n,i){var r=t.charAt(0);return"*"==r||"+"==r&&n.ranges.length==i.ranges.length&&n.somethingSelected()==i.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}(e,s,Y(r.done),t))?r.done[r.done.length-1]=t:Wr(t,r.done),r.lastSelTime=+new Date,r.lastSelOrigin=s,r.lastSelOp=n,i&&!1!==i.clearRedo&&zr(r.undone)}function Wr(e,t){var n=Y(t);n&&n.ranges&&n.equals(e)||t.push(e)}function Hr(e,t,n,i){var r=t["spans_"+e.id],s=0;e.iter(Math.max(e.first,n),Math.min(e.first+e.size,i),(function(n){n.markedSpans&&((r||(r=t["spans_"+e.id]={}))[s]=n.markedSpans),++s}))}function Vr(e){if(!e)return null;for(var t,n=0;n-1&&(Y(a)[c]=u[c],delete u[c])}}}return i}function Kr(e,t,n,i){if(i){var r=e.anchor;if(n){var s=nt(t,r)<0;s!=nt(n,r)<0?(r=t,t=n):s!=nt(t,n)<0&&(t=n)}return new Er(r,t)}return new Er(n||t,t)}function Yr(e,t,n,i,r){null==r&&(r=e.cm&&(e.cm.display.shift||e.extend)),es(e,new Cr([Kr(e.sel.primary(),t,n,r)],0),i)}function Jr(e,t,n){for(var i=[],r=e.cm&&(e.cm.display.shift||e.extend),s=0;s=t.ch:a.to>t.ch))){if(r&&(fe(l,"beforeCursorEnter"),l.explicitlyCleared)){if(s.markedSpans){--o;continue}break}if(!l.atomic)continue;if(n){var c=l.find(i<0?1:-1),h=void 0;if((i<0?d:u)&&(c=as(e,c,-i,c&&c.line==t.line?s:null)),c&&c.line==t.line&&(h=nt(c,n))&&(i<0?h<0:h>0))return ss(e,c,t,i,r)}var p=l.find(i<0?-1:1);return(i<0?u:d)&&(p=as(e,p,i,p.line==t.line?s:null)),p?ss(e,p,t,i,r):null}}return t}function os(e,t,n,i,r){var s=i||1;return ss(e,t,n,s,r)||!r&&ss(e,t,n,s,!0)||ss(e,t,n,-s,r)||!r&&ss(e,t,n,-s,!0)||(e.cantEdit=!0,tt(e.first,0))}function as(e,t,n,i){return n<0&&0==t.ch?t.line>e.first?lt(e,tt(t.line-1)):null:n>0&&t.ch==(i||Ge(e,t.line)).text.length?t.line0)){var d=[l,1],c=nt(u.from,a.from),h=nt(u.to,a.to);(c<0||!o.inclusiveLeft&&!c)&&d.push({from:u.from,to:a.from}),(h>0||!o.inclusiveRight&&!h)&&d.push({from:a.to,to:u.to}),r.splice.apply(r,d),l+=d.length-3}}return r}(e,t.from,t.to);if(i)for(var r=i.length-1;r>=0;--r)cs(e,{from:i[r].from,to:i[r].to,text:r?[""]:t.text,origin:t.origin});else cs(e,t)}}function cs(e,t){if(1!=t.text.length||""!=t.text[0]||0!=nt(t.from,t.to)){var n=Mr(e,t);Ur(e,t,n,e.cm?e.cm.curOp.id:NaN),gs(e,t,n,St(e,t));var i=[];Rr(e,(function(e,n){n||-1!=z(i,e.history)||(bs(e.history,t),i.push(e.history)),gs(e,t,null,St(e,t))}))}}function hs(e,t,n){var i=e.cm&&e.cm.state.suppressEdits;if(!i||n){for(var r,s=e.history,o=e.sel,a="undo"==t?s.done:s.undone,l="undo"==t?s.undone:s.done,u=0;u=0;--p){var g=h(p);if(g)return g.v}}}}function ps(e,t){if(0!=t&&(e.first+=t,e.sel=new Cr(J(e.sel.ranges,(function(e){return new Er(tt(e.anchor.line+t,e.anchor.ch),tt(e.head.line+t,e.head.ch))})),e.sel.primIndex),e.cm)){hi(e.cm,e.first,e.first-t,t);for(var n=e.cm.display,i=n.viewFrom;ie.lastLine())){if(t.from.lines&&(t={from:t.from,to:tt(s,Ge(e,s).text.length),text:[t.text[0]],origin:t.origin}),t.removed=Ke(e,t.from,t.to),n||(n=Mr(e,t)),e.cm?function(e,t,n){var i=e.doc,r=e.display,s=t.from,o=t.to,a=!1,l=s.line;e.options.lineWrapping||(l=Xe(Ft(Ge(i,s.line))),i.iter(l,o.line+1,(function(e){if(e==r.maxLine)return a=!0,!0}))),i.sel.contains(t.from,t.to)>-1&&ve(e),Ir(i,t,n,li(e)),e.options.lineWrapping||(i.iter(l,s.line+t.text.length,(function(e){var t=Vt(e);t>r.maxLineLength&&(r.maxLine=e,r.maxLineLength=t,r.maxLineChanged=!0,a=!1)})),a&&(e.curOp.updateMaxLine=!0)),function(e,t){if(e.modeFrontier=Math.min(e.modeFrontier,t),!(e.highlightFrontiern;i--){var r=Ge(e,i).stateAfter;if(r&&(!(r instanceof dt)||i+r.lookAhead1||!(this.children[0]instanceof As))){var a=[];this.collapse(a),this.children=[new As(a)],this.children[0].parent=this}},collapse:function(e){for(var t=0;t50){for(var o=r.lines.length%25+25,a=o;a10);e.parent.maybeSpill()}},iterN:function(e,t,n){for(var i=0;i0||0==o&&!1!==s.clearWhenEmpty)return s;if(s.replacedWith&&(s.collapsed=!0,s.widgetNode=k("span",[s.replacedWith],"CodeMirror-widget"),i.handleMouseEvents||s.widgetNode.setAttribute("cm-ignore-events","true"),i.insertLeft&&(s.widgetNode.insertLeft=!0)),s.collapsed){if(Nt(e,t.line,t,n,s)||t.line!=n.line&&Nt(e,n.line,t,n,s))throw new Error("Inserting collapsed marker partially overlapping an existing one");Ct=!0}s.addToHistory&&Ur(e,{from:t,to:n,origin:"markText"},e.sel,NaN);var a,l=t.line,u=e.cm;if(e.iter(l,n.line+1,(function(i){u&&s.collapsed&&!u.options.lineWrapping&&Ft(i)==u.display.maxLine&&(a=!0),s.collapsed&&l!=t.line&&Je(i,0),function(e,t,n){var i=n&&window.WeakSet&&(n.markedSpans||(n.markedSpans=new WeakSet));i&&i.has(e.markedSpans)?e.markedSpans.push(t):(e.markedSpans=e.markedSpans?e.markedSpans.concat([t]):[t],i&&i.add(e.markedSpans)),t.marker.attachLine(e)}(i,new Et(s,l==t.line?t.ch:null,l==n.line?n.ch:null),e.cm&&e.cm.curOp),++l})),s.collapsed&&e.iter(t.line,n.line+1,(function(t){$t(e,t)&&Je(t,0)})),s.clearOnEnter&&he(s,"beforeCursorEnter",(function(){return s.clear()})),s.readOnly&&(wt=!0,(e.history.done.length||e.history.undone.length)&&e.clearHistory()),s.collapsed&&(s.id=++Es,s.atomic=!0),u){if(a&&(u.curOp.updateMaxLine=!0),s.collapsed)hi(u,t.line,n.line+1);else if(s.className||s.startStyle||s.endStyle||s.css||s.attributes||s.title)for(var d=t.line;d<=n.line;d++)pi(u,d,"text");s.atomic&&is(u.doc),un(u,"markerAdded",u,s)}return s}xs.prototype.clear=function(){if(!this.explicitlyCleared){var e=this.doc.cm,t=e&&!e.curOp;if(t&&Gi(e),be(this,"clear")){var n=this.find();n&&un(this,"clear",n.from,n.to)}for(var i=null,r=null,s=0;se.display.maxLineLength&&(e.display.maxLine=u,e.display.maxLineLength=d,e.display.maxLineChanged=!0)}null!=i&&e&&this.collapsed&&hi(e,i,r+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,e&&is(e.doc)),e&&un(e,"markerCleared",e,this,i,r),t&&Ki(e),this.parent&&this.parent.clear()}},xs.prototype.find=function(e,t){var n,i;null==e&&"bookmark"==this.type&&(e=1);for(var r=0;r=0;l--)ds(this,i[l]);a?Qr(this,a):this.cm&&Bi(this.cm)})),undo:ir((function(){hs(this,"undo")})),redo:ir((function(){hs(this,"redo")})),undoSelection:ir((function(){hs(this,"undo",!0)})),redoSelection:ir((function(){hs(this,"redo",!0)})),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,n=0,i=0;i=e.ch)&&t.push(r.marker.parent||r.marker)}return t},findMarks:function(e,t,n){e=lt(this,e),t=lt(this,t);var i=[],r=e.line;return this.iter(e.line,t.line+1,(function(s){var o=s.markedSpans;if(o)for(var a=0;a=l.to||null==l.from&&r!=e.line||null!=l.from&&r==t.line&&l.from>=t.ch||n&&!n(l.marker)||i.push(l.marker.parent||l.marker)}++r})),i},getAllMarks:function(){var e=[];return this.iter((function(t){var n=t.markedSpans;if(n)for(var i=0;ie)return t=e,!0;e-=s,++n})),lt(this,tt(n,t))},indexFromPos:function(e){var t=(e=lt(this,e)).ch;if(e.linet&&(t=e.from),null!=e.to&&e.to-1)return t.state.draggingText(e),void setTimeout((function(){return t.display.input.focus()}),20);try{var c=e.dataTransfer.getData("Text");if(c){var h;if(t.state.draggingText&&!t.state.draggingText.copy&&(h=t.listSelections()),ts(t.doc,Dr(n,n)),h)for(var p=0;p=0;t--)fs(e.doc,"",i[t].from,i[t].to,"+delete");Bi(e)}))}function Zs(e,t,n){var i=se(e.text,t+n,n);return i<0||i>e.text.length?null:i}function Qs(e,t,n){var i=Zs(e,t.ch,n);return null==i?null:new tt(t.line,i,n<0?"after":"before")}function eo(e,t,n,i,r){if(e){"rtl"==t.doc.direction&&(r=-r);var s=de(n,t.doc.direction);if(s){var o,a=r<0?Y(s):s[0],l=r<0==(1==a.level)?"after":"before";if(a.level>0||"rtl"==t.doc.direction){var u=On(t,n);o=r<0?n.text.length-1:0;var d=In(t,u,o).top;o=oe((function(e){return In(t,u,e).top==d}),r<0==(1==a.level)?a.from:a.to-1,o),"before"==l&&(o=Zs(n,o,1))}else o=r<0?a.to:a.from;return new tt(i,o,l)}}return new tt(i,r<0?n.text.length:0,r<0?"before":"after")}Ws.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},Ws.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},Ws.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars","Ctrl-O":"openLine"},Ws.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]},Ws.default=b?Ws.macDefault:Ws.pcDefault;var to={selectAll:ls,singleSelection:function(e){return e.setSelection(e.getCursor("anchor"),e.getCursor("head"),W)},killLine:function(e){return Xs(e,(function(t){if(t.empty()){var n=Ge(e.doc,t.head.line).text.length;return t.head.ch==n&&t.head.line0)r=new tt(r.line,r.ch+1),e.replaceRange(s.charAt(r.ch-1)+s.charAt(r.ch-2),tt(r.line,r.ch-2),r,"+transpose");else if(r.line>e.doc.first){var o=Ge(e.doc,r.line-1).text;o&&(r=new tt(r.line,1),e.replaceRange(s.charAt(0)+e.doc.lineSeparator()+o.charAt(o.length-1),tt(r.line-1,o.length-1),r,"+transpose"))}n.push(new Er(r,r))}e.setSelections(n)}))},newlineAndIndent:function(e){return er(e,(function(){for(var t=e.listSelections(),n=t.length-1;n>=0;n--)e.replaceRange(e.doc.lineSeparator(),t[n].anchor,t[n].head,"+input");t=e.listSelections();for(var i=0;i-1&&(nt((r=u.ranges[r]).from(),t)<0||t.xRel>0)&&(nt(r.to(),t)>0||t.xRel<0)?function(e,t,n,i){var r=e.display,s=!1,u=tr(e,(function(t){l&&(r.scroller.draggable=!1),e.state.draggingText=!1,e.state.delayingBlurEvent&&(e.hasFocus()?e.state.delayingBlurEvent=!1:Ei(e)),ge(r.wrapper.ownerDocument,"mouseup",u),ge(r.wrapper.ownerDocument,"mousemove",d),ge(r.scroller,"dragstart",c),ge(r.scroller,"drop",u),s||(Ae(t),i.addNew||Yr(e.doc,n,null,null,i.extend),l&&!h||o&&9==a?setTimeout((function(){r.wrapper.ownerDocument.body.focus({preventScroll:!0}),r.input.focus()}),20):r.input.focus())})),d=function(e){s=s||Math.abs(t.clientX-e.clientX)+Math.abs(t.clientY-e.clientY)>=10},c=function(){return s=!0};l&&(r.scroller.draggable=!0),e.state.draggingText=u,u.copy=!i.moveOnDrag,he(r.wrapper.ownerDocument,"mouseup",u),he(r.wrapper.ownerDocument,"mousemove",d),he(r.scroller,"dragstart",c),he(r.scroller,"drop",u),e.state.delayingBlurEvent=!0,setTimeout((function(){return r.input.focus()}),20),r.scroller.dragDrop&&r.scroller.dragDrop()}(e,i,t,s):function(e,t,n,i){o&&Ei(e);var r=e.display,s=e.doc;Ae(t);var a,l,u=s.sel,d=u.ranges;if(i.addNew&&!i.extend?(l=s.sel.contains(n),a=l>-1?d[l]:new Er(n,n)):(a=s.sel.primary(),l=s.sel.primIndex),"rectangle"==i.unit)i.addNew||(a=new Er(n,n)),n=di(e,t,!0,!0),l=-1;else{var c=bo(e,n,i.unit);a=i.extend?Kr(a,c.anchor,c.head,i.extend):c}i.addNew?-1==l?(l=d.length,es(s,xr(e,d.concat([a]),l),{scroll:!1,origin:"*mouse"})):d.length>1&&d[l].empty()&&"char"==i.unit&&!i.extend?(es(s,xr(e,d.slice(0,l).concat(d.slice(l+1)),0),{scroll:!1,origin:"*mouse"}),u=s.sel):Xr(s,l,a,H):(l=0,es(s,new Cr([a],0),H),u=s.sel);var h=n;function p(t){if(0!=nt(h,t))if(h=t,"rectangle"==i.unit){for(var r=[],o=e.options.tabSize,d=N(Ge(s,n.line).text,n.ch,o),c=N(Ge(s,t.line).text,t.ch,o),p=Math.min(d,c),g=Math.max(d,c),f=Math.min(n.line,t.line),m=Math.min(e.lastLine(),Math.max(n.line,t.line));f<=m;f++){var v=Ge(s,f).text,b=q(v,p,o);p==g?r.push(new Er(tt(f,b),tt(f,b))):v.length>b&&r.push(new Er(tt(f,b),tt(f,q(v,g,o))))}r.length||r.push(new Er(n,n)),es(s,xr(e,u.ranges.slice(0,l).concat(r),l),{origin:"*mouse",scroll:!1}),e.scrollIntoView(t)}else{var _,A=a,y=bo(e,t,i.unit),w=A.anchor;nt(y.anchor,w)>0?(_=y.head,w=ot(A.from(),y.anchor)):(_=y.anchor,w=st(A.to(),y.head));var C=u.ranges.slice(0);C[l]=function(e,t){var n=t.anchor,i=t.head,r=Ge(e.doc,n.line);if(0==nt(n,i)&&n.sticky==i.sticky)return t;var s=de(r);if(!s)return t;var o=le(s,n.ch,n.sticky),a=s[o];if(a.from!=n.ch&&a.to!=n.ch)return t;var l,u=o+(a.from==n.ch==(1!=a.level)?0:1);if(0==u||u==s.length)return t;if(i.line!=n.line)l=(i.line-n.line)*("ltr"==e.doc.direction?1:-1)>0;else{var d=le(s,i.ch,i.sticky),c=d-o||(i.ch-n.ch)*(1==a.level?-1:1);l=d==u-1||d==u?c<0:c>0}var h=s[u+(l?-1:0)],p=l==(1==h.level),g=p?h.from:h.to,f=p?"after":"before";return n.ch==g&&n.sticky==f?t:new Er(new tt(n.line,g,f),i)}(e,new Er(lt(s,w),_)),es(s,xr(e,C,l),H)}}var g=r.wrapper.getBoundingClientRect(),f=0;function m(t){var n=++f,o=di(e,t,!0,"rectangle"==i.unit);if(o)if(0!=nt(o,h)){e.curOp.focus=B(),p(o);var a=Mi(r,s);(o.line>=a.to||o.lineg.bottom?20:0;l&&setTimeout(tr(e,(function(){f==n&&(r.scroller.scrollTop+=l,m(t))})),50)}}function v(t){e.state.selectingText=!1,f=1/0,t&&(Ae(t),r.input.focus()),ge(r.wrapper.ownerDocument,"mousemove",b),ge(r.wrapper.ownerDocument,"mouseup",_),s.history.lastSelOrigin=null}var b=tr(e,(function(e){0!==e.buttons&&xe(e)?m(e):v(e)})),_=tr(e,v);e.state.selectingText=_,he(r.wrapper.ownerDocument,"mousemove",b),he(r.wrapper.ownerDocument,"mouseup",_)}(e,i,t,s)}(t,i,s,e):Ee(e)==n.scroller&&Ae(e):2==r?(i&&Yr(t.doc,i),setTimeout((function(){return n.input.focus()}),20)):3==r&&(C?t.display.input.onContextMenu(e):Ei(t)))}}function bo(e,t,n){if("char"==n)return new Er(t,t);if("word"==n)return e.findWordAt(t);if("line"==n)return new Er(tt(t.line,0),lt(e.doc,tt(t.line+1,0)));var i=n(e,t);return new Er(i.from,i.to)}function _o(e,t,n,i){var r,s;if(t.touches)r=t.touches[0].clientX,s=t.touches[0].clientY;else try{r=t.clientX,s=t.clientY}catch(e){return!1}if(r>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;i&&Ae(t);var o=e.display,a=o.lineDiv.getBoundingClientRect();if(s>a.bottom||!be(e,n))return we(t);s-=a.top-o.viewOffset;for(var l=0;l=r)return fe(e,n,e,Ze(e.doc,s),e.display.gutterSpecs[l].className,t),we(t)}}function Ao(e,t){return _o(e,t,"gutterClick",!0)}function yo(e,t){Cn(e.display,t)||function(e,t){return!!be(e,"gutterContextMenu")&&_o(e,t,"gutterContextMenu",!1)}(e,t)||me(e,t,"contextmenu")||C||e.display.input.onContextMenu(t)}function wo(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-"),Un(e)}mo.prototype.compare=function(e,t,n){return this.time+400>e&&0==nt(t,this.pos)&&n==this.button};var Co={toString:function(){return"CodeMirror.Init"}},Eo={},xo={};function Do(e,t,n){if(!t!=!(n&&n!=Co)){var i=e.display.dragFunctions,r=t?he:ge;r(e.display.scroller,"dragstart",i.start),r(e.display.scroller,"dragenter",i.enter),r(e.display.scroller,"dragover",i.over),r(e.display.scroller,"dragleave",i.leave),r(e.display.scroller,"drop",i.drop)}}function So(e){e.options.lineWrapping?(O(e.display.wrapper,"CodeMirror-wrap"),e.display.sizer.style.minWidth="",e.display.sizerWidth=null):(D(e.display.wrapper,"CodeMirror-wrap"),qt(e)),ui(e),hi(e),Un(e),setTimeout((function(){return $i(e)}),100)}function To(e,t){var n=this;if(!(this instanceof To))return new To(e,t);this.options=t=t?L(t):{},L(Eo,t,!1);var i=t.value;"string"==typeof i?i=new js(i,t.mode,null,t.lineSeparator,t.direction):t.mode&&(i.modeOption=t.mode),this.doc=i;var r=new To.inputStyles[t.inputStyle](this),s=this.display=new vr(e,i,r,t);for(var u in s.wrapper.CodeMirror=this,wo(this),t.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),Vi(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:-1,cutIncoming:-1,selectingText:!1,draggingText:!1,highlight:new F,keySeq:null,specialChars:null},t.autofocus&&!v&&s.input.focus(),o&&a<11&&setTimeout((function(){return n.display.input.reset(!0)}),20),function(e){var t=e.display;he(t.scroller,"mousedown",tr(e,vo)),he(t.scroller,"dblclick",o&&a<11?tr(e,(function(t){if(!me(e,t)){var n=di(e,t);if(n&&!Ao(e,t)&&!Cn(e.display,t)){Ae(t);var i=e.findWordAt(n);Yr(e.doc,i.anchor,i.head)}}})):function(t){return me(e,t)||Ae(t)}),he(t.scroller,"contextmenu",(function(t){return yo(e,t)})),he(t.input.getField(),"contextmenu",(function(n){t.scroller.contains(n.target)||yo(e,n)}));var n,i={end:0};function r(){t.activeTouch&&(n=setTimeout((function(){return t.activeTouch=null}),1e3),(i=t.activeTouch).end=+new Date)}function s(e){if(1!=e.touches.length)return!1;var t=e.touches[0];return t.radiusX<=1&&t.radiusY<=1}function l(e,t){if(null==t.left)return!0;var n=t.left-e.left,i=t.top-e.top;return n*n+i*i>400}he(t.scroller,"touchstart",(function(r){if(!me(e,r)&&!s(r)&&!Ao(e,r)){t.input.ensurePolled(),clearTimeout(n);var o=+new Date;t.activeTouch={start:o,moved:!1,prev:o-i.end<=300?i:null},1==r.touches.length&&(t.activeTouch.left=r.touches[0].pageX,t.activeTouch.top=r.touches[0].pageY)}})),he(t.scroller,"touchmove",(function(){t.activeTouch&&(t.activeTouch.moved=!0)})),he(t.scroller,"touchend",(function(n){var i=t.activeTouch;if(i&&!Cn(t,n)&&null!=i.left&&!i.moved&&new Date-i.start<300){var s,o=e.coordsChar(t.activeTouch,"page");s=!i.prev||l(i,i.prev)?new Er(o,o):!i.prev.prev||l(i,i.prev.prev)?e.findWordAt(o):new Er(tt(o.line,0),lt(e.doc,tt(o.line+1,0))),e.setSelection(s.anchor,s.head),e.focus(),Ae(n)}r()})),he(t.scroller,"touchcancel",r),he(t.scroller,"scroll",(function(){t.scroller.clientHeight&&(Pi(e,t.scroller.scrollTop),Ni(e,t.scroller.scrollLeft,!0),fe(e,"scroll",e))})),he(t.scroller,"mousewheel",(function(t){return wr(e,t)})),he(t.scroller,"DOMMouseScroll",(function(t){return wr(e,t)})),he(t.wrapper,"scroll",(function(){return t.wrapper.scrollTop=t.wrapper.scrollLeft=0})),t.dragFunctions={enter:function(t){me(e,t)||Ce(t)},over:function(t){me(e,t)||(function(e,t){var n=di(e,t);if(n){var i=document.createDocumentFragment();_i(e,n,i),e.display.dragCursor||(e.display.dragCursor=M("div",null,"CodeMirror-cursors CodeMirror-dragcursors"),e.display.lineSpace.insertBefore(e.display.dragCursor,e.display.cursorDiv)),T(e.display.dragCursor,i)}}(e,t),Ce(t))},start:function(t){return function(e,t){if(o&&(!e.state.draggingText||+new Date-Bs<100))Ce(t);else if(!me(e,t)&&!Cn(e.display,t)&&(t.dataTransfer.setData("Text",e.getSelection()),t.dataTransfer.effectAllowed="copyMove",t.dataTransfer.setDragImage&&!h)){var n=M("img",null,null,"position: fixed; left: 0; top: 0;");n.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",c&&(n.width=n.height=1,e.display.wrapper.appendChild(n),n._top=n.offsetTop),t.dataTransfer.setDragImage(n,0,0),c&&n.parentNode.removeChild(n)}}(e,t)},drop:tr(e,Os),leave:function(t){me(e,t)||Is(e)}};var u=t.input.getField();he(u,"keyup",(function(t){return ho.call(e,t)})),he(u,"keydown",tr(e,co)),he(u,"keypress",tr(e,po)),he(u,"focus",(function(t){return xi(e,t)})),he(u,"blur",(function(t){return Di(e,t)}))}(this),Ls(),Gi(this),this.curOp.forceUpdate=!0,Pr(this,i),t.autofocus&&!v||this.hasFocus()?setTimeout((function(){n.hasFocus()&&!n.state.focused&&xi(n)}),20):Di(this),xo)xo.hasOwnProperty(u)&&xo[u](this,t[u],Co);pr(this),t.finishInit&&t.finishInit(this);for(var d=0;d150)){if(!i)return;n="prev"}}else u=0,n="not";"prev"==n?u=t>s.first?N(Ge(s,t-1).text,null,o):0:"add"==n?u=l+e.options.indentUnit:"subtract"==n?u=l-e.options.indentUnit:"number"==typeof n&&(u=l+n),u=Math.max(0,u);var c="",h=0;if(e.options.indentWithTabs)for(var p=Math.floor(u/o);p;--p)h+=o,c+="\t";if(ho,l=Be(t),u=null;if(a&&i.ranges.length>1)if(jo&&jo.text.join("\n")==t){if(i.ranges.length%jo.text.length==0){u=[];for(var d=0;d=0;h--){var p=i.ranges[h],g=p.from(),f=p.to();p.empty()&&(n&&n>0?g=tt(g.line,g.ch-n):e.state.overwrite&&!a?f=tt(f.line,Math.min(Ge(s,f.line).text.length,f.ch+Y(l).length)):a&&jo&&jo.lineWise&&jo.text.join("\n")==l.join("\n")&&(g=f=tt(g.line,0)));var m={from:g,to:f,text:u?u[h%u.length]:l,origin:r||(a?"paste":e.state.cutIncoming>o?"cut":"+input")};ds(e.doc,m),un(e,"inputRead",e,m)}t&&!a&&Ro(e,t),Bi(e),e.curOp.updateInput<2&&(e.curOp.updateInput=c),e.curOp.typing=!0,e.state.pasteIncoming=e.state.cutIncoming=-1}function Io(e,t){var n=e.clipboardData&&e.clipboardData.getData("Text");if(n)return e.preventDefault(),t.isReadOnly()||t.options.disableInput||er(t,(function(){return Oo(t,n,0,null,"paste")})),!0}function Ro(e,t){if(e.options.electricChars&&e.options.smartIndent)for(var n=e.doc.sel,i=n.ranges.length-1;i>=0;i--){var r=n.ranges[i];if(!(r.head.ch>100||i&&n.ranges[i-1].head.line==r.head.line)){var s=e.getModeAt(r.head),o=!1;if(s.electricChars){for(var a=0;a-1){o=ko(e,r.head.line,"smart");break}}else s.electricInput&&s.electricInput.test(Ge(e.doc,r.head.line).text.slice(0,r.head.ch))&&(o=ko(e,r.head.line,"smart"));o&&un(e,"electricInput",e,r.head.line)}}}function Po(e){for(var t=[],n=[],i=0;i0?0:-1));if(isNaN(d))o=null;else{var c=n>0?d>=55296&&d<56320:d>=56320&&d<57343;o=new tt(t.line,Math.max(0,Math.min(a.text.length,t.ch+n*(c?2:1))),-n)}}else o=r?function(e,t,n,i){var r=de(t,e.doc.direction);if(!r)return Qs(t,n,i);n.ch>=t.text.length?(n.ch=t.text.length,n.sticky="before"):n.ch<=0&&(n.ch=0,n.sticky="after");var s=le(r,n.ch,n.sticky),o=r[s];if("ltr"==e.doc.direction&&o.level%2==0&&(i>0?o.to>n.ch:o.from=o.from&&h>=d.begin)){var p=c?"before":"after";return new tt(n.line,h,p)}}var g=function(e,t,i){for(var s=function(e,t){return t?new tt(n.line,l(e,1),"before"):new tt(n.line,e,"after")};e>=0&&e0==(1!=o.level),u=a?i.begin:l(i.end,-1);if(o.from<=u&&u0?d.end:l(d.begin,-1);return null==m||i>0&&m==t.text.length||!(f=g(i>0?0:r.length-1,i,u(m)))?null:f}(e.cm,a,t,n):Qs(a,t,n);if(null==o){if(s||((u=t.line+l)=e.first+e.size||(t=new tt(u,t.ch,t.sticky),!(a=Ge(e,u)))))return!1;t=eo(r,e.cm,a,t.line,l)}else t=o;return!0}if("char"==i||"codepoint"==i)u();else if("column"==i)u(!0);else if("word"==i||"group"==i)for(var d=null,c="group"==i,h=e.cm&&e.cm.getHelper(t,"wordChars"),p=!0;!(n<0)||u(!p);p=!1){var g=a.text.charAt(t.ch)||"\n",f=te(g,h)?"w":c&&"\n"==g?"n":!c||/\s/.test(g)?null:"p";if(!c||p||f||(f="s"),d&&d!=f){n<0&&(n=1,u(),t.sticky="after");break}if(f&&(d=f),n>0&&!u(!p))break}var m=os(e,t,s,o,!0);return it(s,m)&&(m.hitSide=!0),m}function zo(e,t,n,i){var r,s,o=e.doc,a=t.left;if("page"==i){var l=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight),u=Math.max(l-.5*ri(e.display),3);r=(n>0?t.bottom:t.top)+n*u}else"line"==i&&(r=n>0?t.bottom+3:t.top-3);for(;(s=Xn(e,a,r)).outside;){if(n<0?r<=0:r>=o.height){s.hitSide=!0;break}r+=5*n}return s}var Uo=function(e){this.cm=e,this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null,this.polling=new F,this.composing=null,this.gracePeriod=!1,this.readDOMTimeout=null};function $o(e,t){var n=Bn(e,t.line);if(!n||n.hidden)return null;var i=Ge(e.doc,t.line),r=kn(n,i,t.line),s=de(i,e.doc.direction),o="left";s&&(o=le(s,t.ch)%2?"right":"left");var a=Ln(r.map,t.ch,o);return a.offset="right"==a.collapse?a.end:a.start,a}function Wo(e,t){return t&&(e.bad=!0),e}function Ho(e,t,n){var i;if(t==e.display.lineDiv){if(!(i=e.display.lineDiv.childNodes[n]))return Wo(e.clipPos(tt(e.display.viewTo-1)),!0);t=null,n=0}else for(i=t;;i=i.parentNode){if(!i||i==e.display.lineDiv)return null;if(i.parentNode&&i.parentNode==e.display.lineDiv)break}for(var r=0;r=t.display.viewTo||s.line=t.display.viewFrom&&$o(t,r)||{node:l[0].measure.map[2],offset:0},d=s.linei.firstLine()&&(o=tt(o.line-1,Ge(i.doc,o.line-1).length)),a.ch==Ge(i.doc,a.line).text.length&&a.liner.viewTo-1)return!1;o.line==r.viewFrom||0==(e=ci(i,o.line))?(t=Xe(r.view[0].line),n=r.view[0].node):(t=Xe(r.view[e].line),n=r.view[e-1].node.nextSibling);var l,u,d=ci(i,a.line);if(d==r.view.length-1?(l=r.viewTo-1,u=r.lineDiv.lastChild):(l=Xe(r.view[d+1].line)-1,u=r.view[d+1].node.previousSibling),!n)return!1;for(var c=i.doc.splitLines(function(e,t,n,i,r){var s="",o=!1,a=e.doc.lineSeparator(),l=!1;function u(){o&&(s+=a,l&&(s+=a),o=l=!1)}function d(e){e&&(u(),s+=e)}function c(t){if(1==t.nodeType){var n=t.getAttribute("cm-text");if(n)return void d(n);var s,h=t.getAttribute("cm-marker");if(h){var p=e.findMarks(tt(i,0),tt(r+1,0),(m=+h,function(e){return e.id==m}));return void(p.length&&(s=p[0].find(0))&&d(Ke(e.doc,s.from,s.to).join(a)))}if("false"==t.getAttribute("contenteditable"))return;var g=/^(pre|div|p|li|table|br)$/i.test(t.nodeName);if(!/^br$/i.test(t.nodeName)&&0==t.textContent.length)return;g&&u();for(var f=0;f1&&h.length>1;)if(Y(c)==Y(h))c.pop(),h.pop(),l--;else{if(c[0]!=h[0])break;c.shift(),h.shift(),t++}for(var p=0,g=0,f=c[0],m=h[0],v=Math.min(f.length,m.length);po.ch&&b.charCodeAt(b.length-g-1)==_.charCodeAt(_.length-g-1);)p--,g++;c[c.length-1]=b.slice(0,b.length-g).replace(/^\u200b+/,""),c[0]=c[0].slice(p).replace(/\u200b+$/,"");var y=tt(t,p),w=tt(l,h.length?Y(h).length-g:0);return c.length>1||c[0]||nt(y,w)?(fs(i.doc,c,y,w,"+input"),!0):void 0},Uo.prototype.ensurePolled=function(){this.forceCompositionEnd()},Uo.prototype.reset=function(){this.forceCompositionEnd()},Uo.prototype.forceCompositionEnd=function(){this.composing&&(clearTimeout(this.readDOMTimeout),this.composing=null,this.updateFromDOM(),this.div.blur(),this.div.focus())},Uo.prototype.readFromDOMSoon=function(){var e=this;null==this.readDOMTimeout&&(this.readDOMTimeout=setTimeout((function(){if(e.readDOMTimeout=null,e.composing){if(!e.composing.done)return;e.composing=null}e.updateFromDOM()}),80))},Uo.prototype.updateFromDOM=function(){var e=this;!this.cm.isReadOnly()&&this.pollContent()||er(this.cm,(function(){return hi(e.cm)}))},Uo.prototype.setUneditable=function(e){e.contentEditable="false"},Uo.prototype.onKeyPress=function(e){0==e.charCode||this.composing||(e.preventDefault(),this.cm.isReadOnly()||tr(this.cm,Oo)(this.cm,String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),0))},Uo.prototype.readOnlyChanged=function(e){this.div.contentEditable=String("nocursor"!=e)},Uo.prototype.onContextMenu=function(){},Uo.prototype.resetPosition=function(){},Uo.prototype.needsContentAttribute=!0;var qo=function(e){this.cm=e,this.prevInput="",this.pollingFast=!1,this.polling=new F,this.hasSelection=!1,this.composing=null};qo.prototype.init=function(e){var t=this,n=this,i=this.cm;this.createField(e);var r=this.textarea;function s(e){if(!me(i,e)){if(i.somethingSelected())Bo({lineWise:!1,text:i.getSelections()});else{if(!i.options.lineWiseCopyCut)return;var t=Po(i);Bo({lineWise:!0,text:t.text}),"cut"==e.type?i.setSelections(t.ranges,null,W):(n.prevInput="",r.value=t.text.join("\n"),R(r))}"cut"==e.type&&(i.state.cutIncoming=+new Date)}}e.wrapper.insertBefore(this.wrapper,e.wrapper.firstChild),f&&(r.style.width="0px"),he(r,"input",(function(){o&&a>=9&&t.hasSelection&&(t.hasSelection=null),n.poll()})),he(r,"paste",(function(e){me(i,e)||Io(e,i)||(i.state.pasteIncoming=+new Date,n.fastPoll())})),he(r,"cut",s),he(r,"copy",s),he(e.scroller,"paste",(function(t){if(!Cn(e,t)&&!me(i,t)){if(!r.dispatchEvent)return i.state.pasteIncoming=+new Date,void n.focus();var s=new Event("paste");s.clipboardData=t.clipboardData,r.dispatchEvent(s)}})),he(e.lineSpace,"selectstart",(function(t){Cn(e,t)||Ae(t)})),he(r,"compositionstart",(function(){var e=i.getCursor("from");n.composing&&n.composing.range.clear(),n.composing={start:e,range:i.markText(e,i.getCursor("to"),{className:"CodeMirror-composing"})}})),he(r,"compositionend",(function(){n.composing&&(n.poll(),n.composing.range.clear(),n.composing=null)}))},qo.prototype.createField=function(e){this.wrapper=No(),this.textarea=this.wrapper.firstChild},qo.prototype.screenReaderLabelChanged=function(e){e?this.textarea.setAttribute("aria-label",e):this.textarea.removeAttribute("aria-label")},qo.prototype.prepareSelection=function(){var e=this.cm,t=e.display,n=e.doc,i=bi(e);if(e.options.moveInputWithCursor){var r=Kn(e,n.sel.primary().head,"div"),s=t.wrapper.getBoundingClientRect(),o=t.lineDiv.getBoundingClientRect();i.teTop=Math.max(0,Math.min(t.wrapper.clientHeight-10,r.top+o.top-s.top)),i.teLeft=Math.max(0,Math.min(t.wrapper.clientWidth-10,r.left+o.left-s.left))}return i},qo.prototype.showSelection=function(e){var t=this.cm.display;T(t.cursorDiv,e.cursors),T(t.selectionDiv,e.selection),null!=e.teTop&&(this.wrapper.style.top=e.teTop+"px",this.wrapper.style.left=e.teLeft+"px")},qo.prototype.reset=function(e){if(!this.contextMenuPending&&!this.composing){var t=this.cm;if(t.somethingSelected()){this.prevInput="";var n=t.getSelection();this.textarea.value=n,t.state.focused&&R(this.textarea),o&&a>=9&&(this.hasSelection=n)}else e||(this.prevInput=this.textarea.value="",o&&a>=9&&(this.hasSelection=null))}},qo.prototype.getField=function(){return this.textarea},qo.prototype.supportsTouch=function(){return!1},qo.prototype.focus=function(){if("nocursor"!=this.cm.options.readOnly&&(!v||B()!=this.textarea))try{this.textarea.focus()}catch(e){}},qo.prototype.blur=function(){this.textarea.blur()},qo.prototype.resetPosition=function(){this.wrapper.style.top=this.wrapper.style.left=0},qo.prototype.receivedFocus=function(){this.slowPoll()},qo.prototype.slowPoll=function(){var e=this;this.pollingFast||this.polling.set(this.cm.options.pollInterval,(function(){e.poll(),e.cm.state.focused&&e.slowPoll()}))},qo.prototype.fastPoll=function(){var e=!1,t=this;t.pollingFast=!0,t.polling.set(20,(function n(){t.poll()||e?(t.pollingFast=!1,t.slowPoll()):(e=!0,t.polling.set(60,n))}))},qo.prototype.poll=function(){var e=this,t=this.cm,n=this.textarea,i=this.prevInput;if(this.contextMenuPending||!t.state.focused||Oe(n)&&!i&&!this.composing||t.isReadOnly()||t.options.disableInput||t.state.keySeq)return!1;var r=n.value;if(r==i&&!t.somethingSelected())return!1;if(o&&a>=9&&this.hasSelection===r||b&&/[\uf700-\uf7ff]/.test(r))return t.display.input.reset(),!1;if(t.doc.sel==t.display.selForContextMenu){var s=r.charCodeAt(0);if(8203!=s||i||(i="​"),8666==s)return this.reset(),this.cm.execCommand("undo")}for(var l=0,u=Math.min(i.length,r.length);l1e3||r.indexOf("\n")>-1?n.value=e.prevInput="":e.prevInput=r,e.composing&&(e.composing.range.clear(),e.composing.range=t.markText(e.composing.start,t.getCursor("to"),{className:"CodeMirror-composing"}))})),!0},qo.prototype.ensurePolled=function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)},qo.prototype.onKeyPress=function(){o&&a>=9&&(this.hasSelection=null),this.fastPoll()},qo.prototype.onContextMenu=function(e){var t=this,n=t.cm,i=n.display,r=t.textarea;t.contextMenuPending&&t.contextMenuPending();var s=di(n,e),u=i.scroller.scrollTop;if(s&&!c){n.options.resetSelectionOnContextMenu&&-1==n.doc.sel.contains(s)&&tr(n,es)(n.doc,Dr(s),W);var d,h=r.style.cssText,p=t.wrapper.style.cssText,g=t.wrapper.offsetParent.getBoundingClientRect();if(t.wrapper.style.cssText="position: static",r.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(e.clientY-g.top-5)+"px; left: "+(e.clientX-g.left-5)+"px;\n z-index: 1000; background: "+(o?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",l&&(d=window.scrollY),i.input.focus(),l&&window.scrollTo(null,d),i.input.reset(),n.somethingSelected()||(r.value=t.prevInput=" "),t.contextMenuPending=v,i.selForContextMenu=n.doc.sel,clearTimeout(i.detectingSelectAll),o&&a>=9&&m(),C){Ce(e);var f=function(){ge(window,"mouseup",f),setTimeout(v,20)};he(window,"mouseup",f)}else setTimeout(v,50)}function m(){if(null!=r.selectionStart){var e=n.somethingSelected(),s="​"+(e?r.value:"");r.value="⇚",r.value=s,t.prevInput=e?"":"​",r.selectionStart=1,r.selectionEnd=s.length,i.selForContextMenu=n.doc.sel}}function v(){if(t.contextMenuPending==v&&(t.contextMenuPending=!1,t.wrapper.style.cssText=p,r.style.cssText=h,o&&a<9&&i.scrollbars.setScrollTop(i.scroller.scrollTop=u),null!=r.selectionStart)){(!o||o&&a<9)&&m();var e=0,s=function(){i.selForContextMenu==n.doc.sel&&0==r.selectionStart&&r.selectionEnd>0&&"​"==t.prevInput?tr(n,ls)(n):e++<10?i.detectingSelectAll=setTimeout(s,500):(i.selForContextMenu=null,i.input.reset())};i.detectingSelectAll=setTimeout(s,200)}}},qo.prototype.readOnlyChanged=function(e){e||this.reset(),this.textarea.disabled="nocursor"==e,this.textarea.readOnly=!!e},qo.prototype.setUneditable=function(){},qo.prototype.needsContentAttribute=!1,function(e){var t=e.optionHandlers;function n(n,i,r,s){e.defaults[n]=i,r&&(t[n]=s?function(e,t,n){n!=Co&&r(e,t,n)}:r)}e.defineOption=n,e.Init=Co,n("value","",(function(e,t){return e.setValue(t)}),!0),n("mode",null,(function(e,t){e.doc.modeOption=t,jr(e)}),!0),n("indentUnit",2,jr,!0),n("indentWithTabs",!1),n("smartIndent",!0),n("tabSize",4,(function(e){Br(e),Un(e),hi(e)}),!0),n("lineSeparator",null,(function(e,t){if(e.doc.lineSep=t,t){var n=[],i=e.doc.first;e.doc.iter((function(e){for(var r=0;;){var s=e.text.indexOf(t,r);if(-1==s)break;r=s+t.length,n.push(tt(i,s))}i++}));for(var r=n.length-1;r>=0;r--)fs(e.doc,t,n[r],tt(n[r].line,n[r].ch+t.length))}})),n("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g,(function(e,t,n){e.state.specialChars=new RegExp(t.source+(t.test("\t")?"":"|\t"),"g"),n!=Co&&e.refresh()})),n("specialCharPlaceholder",Qt,(function(e){return e.refresh()}),!0),n("electricChars",!0),n("inputStyle",v?"contenteditable":"textarea",(function(){throw new Error("inputStyle can not (yet) be changed in a running editor")}),!0),n("spellcheck",!1,(function(e,t){return e.getInputField().spellcheck=t}),!0),n("autocorrect",!1,(function(e,t){return e.getInputField().autocorrect=t}),!0),n("autocapitalize",!1,(function(e,t){return e.getInputField().autocapitalize=t}),!0),n("rtlMoveVisually",!A),n("wholeLineUpdateBefore",!0),n("theme","default",(function(e){wo(e),mr(e)}),!0),n("keyMap","default",(function(e,t,n){var i=Js(t),r=n!=Co&&Js(n);r&&r.detach&&r.detach(e,i),i.attach&&i.attach(e,r||null)})),n("extraKeys",null),n("configureMouse",null),n("lineWrapping",!1,So,!0),n("gutters",[],(function(e,t){e.display.gutterSpecs=gr(t,e.options.lineNumbers),mr(e)}),!0),n("fixedGutter",!0,(function(e,t){e.display.gutters.style.left=t?ai(e.display)+"px":"0",e.refresh()}),!0),n("coverGutterNextToScrollbar",!1,(function(e){return $i(e)}),!0),n("scrollbarStyle","native",(function(e){Vi(e),$i(e),e.display.scrollbars.setScrollTop(e.doc.scrollTop),e.display.scrollbars.setScrollLeft(e.doc.scrollLeft)}),!0),n("lineNumbers",!1,(function(e,t){e.display.gutterSpecs=gr(e.options.gutters,t),mr(e)}),!0),n("firstLineNumber",1,mr,!0),n("lineNumberFormatter",(function(e){return e}),mr,!0),n("showCursorWhenSelecting",!1,vi,!0),n("resetSelectionOnContextMenu",!0),n("lineWiseCopyCut",!0),n("pasteLinesPerSelection",!0),n("selectionsMayTouch",!1),n("readOnly",!1,(function(e,t){"nocursor"==t&&(Di(e),e.display.input.blur()),e.display.input.readOnlyChanged(t)})),n("screenReaderLabel",null,(function(e,t){t=""===t?null:t,e.display.input.screenReaderLabelChanged(t)})),n("disableInput",!1,(function(e,t){t||e.display.input.reset()}),!0),n("dragDrop",!0,Do),n("allowDropFileTypes",null),n("cursorBlinkRate",530),n("cursorScrollMargin",0),n("cursorHeight",1,vi,!0),n("singleCursorHeightPerLine",!0,vi,!0),n("workTime",100),n("workDelay",100),n("flattenSpans",!0,Br,!0),n("addModeClass",!1,Br,!0),n("pollInterval",100),n("undoDepth",200,(function(e,t){return e.doc.history.undoDepth=t})),n("historyEventDelay",1250),n("viewportMargin",10,(function(e){return e.refresh()}),!0),n("maxHighlightLength",1e4,Br,!0),n("moveInputWithCursor",!0,(function(e,t){t||e.display.input.resetPosition()})),n("tabindex",null,(function(e,t){return e.display.input.getField().tabIndex=t||""})),n("autofocus",null),n("direction","ltr",(function(e,t){return e.doc.setDirection(t)}),!0),n("phrases",null)}(To),function(e){var t=e.optionHandlers,n=e.helpers={};e.prototype={constructor:e,focus:function(){window.focus(),this.display.input.focus()},setOption:function(e,n){var i=this.options,r=i[e];i[e]==n&&"mode"!=e||(i[e]=n,t.hasOwnProperty(e)&&tr(this,t[e])(this,n,r),fe(this,"optionChange",this,e))},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](Js(e))},removeKeyMap:function(e){for(var t=this.state.keyMaps,n=0;nn&&(ko(this,r.head.line,e,!0),n=r.head.line,i==this.doc.sel.primIndex&&Bi(this));else{var s=r.from(),o=r.to(),a=Math.max(n,s.line);n=Math.min(this.lastLine(),o.line-(o.ch?0:1))+1;for(var l=a;l0&&Xr(this.doc,i,new Er(s,u[i].to()),W)}}})),getTokenAt:function(e,t){return _t(this,e,t)},getLineTokens:function(e,t){return _t(this,tt(e),t,!0)},getTokenTypeAt:function(e){e=lt(this.doc,e);var t,n=pt(this,Ge(this.doc,e.line)),i=0,r=(n.length-1)/2,s=e.ch;if(0==s)t=n[2];else for(;;){var o=i+r>>1;if((o?n[2*o-1]:0)>=s)r=o;else{if(!(n[2*o+1]s&&(e=s,r=!0),i=Ge(this.doc,e)}else i=e;return Vn(this,i,{top:0,left:0},t||"page",n||r).top+(r?this.doc.height-Ht(i):0)},defaultTextHeight:function(){return ri(this.display)},defaultCharWidth:function(){return si(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,n,i,r){var s,o,a,l=this.display,u=(e=Kn(this,lt(this.doc,e))).bottom,d=e.left;if(t.style.position="absolute",t.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(t),l.sizer.appendChild(t),"over"==i)u=e.top;else if("above"==i||"near"==i){var c=Math.max(l.wrapper.clientHeight,this.doc.height),h=Math.max(l.sizer.clientWidth,l.lineSpace.clientWidth);("above"==i||e.bottom+t.offsetHeight>c)&&e.top>t.offsetHeight?u=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=c&&(u=e.bottom),d+t.offsetWidth>h&&(d=h-t.offsetWidth)}t.style.top=u+"px",t.style.left=t.style.right="","right"==r?(d=l.sizer.clientWidth-t.offsetWidth,t.style.right="0px"):("left"==r?d=0:"middle"==r&&(d=(l.sizer.clientWidth-t.offsetWidth)/2),t.style.left=d+"px"),n&&(s=this,o={left:d,top:u,right:d+t.offsetWidth,bottom:u+t.offsetHeight},null!=(a=ki(s,o)).scrollTop&&Pi(s,a.scrollTop),null!=a.scrollLeft&&Ni(s,a.scrollLeft))},triggerOnKeyDown:nr(co),triggerOnKeyPress:nr(po),triggerOnKeyUp:ho,triggerOnMouseDown:nr(vo),execCommand:function(e){if(to.hasOwnProperty(e))return to[e].call(null,this)},triggerElectric:nr((function(e){Ro(this,e)})),findPosH:function(e,t,n,i){var r=1;t<0&&(r=-1,t=-t);for(var s=lt(this.doc,e),o=0;o0&&o(t.charAt(n-1));)--n;for(;i.5||this.options.lineWrapping)&&ui(this),fe(this,"refresh",this)})),swapDoc:nr((function(e){var t=this.doc;return t.cm=null,this.state.selectingText&&this.state.selectingText(),Pr(this,e),Un(this),this.display.input.reset(),Oi(this,e.scrollLeft,e.scrollTop),this.curOp.forceScroll=!0,un(this,"swapDoc",this,t),t})),phrase:function(e){var t=this.options.phrases;return t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]:e},getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},_e(e),e.registerHelper=function(t,i,r){n.hasOwnProperty(t)||(n[t]=e[t]={_global:[]}),n[t][i]=r},e.registerGlobalHelper=function(t,i,r,s){e.registerHelper(t,i,s),n[t]._global.push({pred:r,val:s})}}(To);var Go="iter insert remove copy getEditor constructor".split(" ");for(var Ko in js.prototype)js.prototype.hasOwnProperty(Ko)&&z(Go,Ko)<0&&(To.prototype[Ko]=function(e){return function(){return e.apply(this.doc,arguments)}}(js.prototype[Ko]));return _e(js),To.inputStyles={textarea:qo,contenteditable:Uo},To.defineMode=function(e){To.defaults.mode||"null"==e||(To.defaults.mode=e),Ne.apply(this,arguments)},To.defineMIME=function(e,t){Le[e]=t},To.defineMode("null",(function(){return{token:function(e){return e.skipToEnd()}}})),To.defineMIME("text/plain","null"),To.defineExtension=function(e,t){To.prototype[e]=t},To.defineDocExtension=function(e,t){js.prototype[e]=t},To.fromTextArea=function(e,t){if((t=t?L(t):{}).value=e.value,!t.tabindex&&e.tabIndex&&(t.tabindex=e.tabIndex),!t.placeholder&&e.placeholder&&(t.placeholder=e.placeholder),null==t.autofocus){var n=B();t.autofocus=n==e||null!=e.getAttribute("autofocus")&&n==document.body}function i(){e.value=a.getValue()}var r;if(e.form&&(he(e.form,"submit",i),!t.leaveSubmitMethodAlone)){var s=e.form;r=s.submit;try{var o=s.submit=function(){i(),s.submit=r,s.submit(),s.submit=o}}catch(e){}}t.finishInit=function(n){n.save=i,n.getTextArea=function(){return e},n.toTextArea=function(){n.toTextArea=isNaN,i(),e.parentNode.removeChild(n.getWrapperElement()),e.style.display="",e.form&&(ge(e.form,"submit",i),t.leaveSubmitMethodAlone||"function"!=typeof e.form.submit||(e.form.submit=r))}},e.style.display="none";var a=To((function(t){return e.parentNode.insertBefore(t,e.nextSibling)}),t);return a},function(e){e.off=ge,e.on=he,e.wheelEventPixels=yr,e.Doc=js,e.splitLines=Be,e.countColumn=N,e.findColumn=q,e.isWordChar=ee,e.Pass=$,e.signal=fe,e.Line=Gt,e.changeEnd=Sr,e.scrollbarModel=Hi,e.Pos=tt,e.cmpPos=nt,e.modes=Pe,e.mimeModes=Le,e.resolveMode=Fe,e.getMode=ze,e.modeExtensions=Ue,e.extendMode=$e,e.copyState=We,e.startState=Ve,e.innerMode=He,e.commands=to,e.keyMap=Ws,e.keyName=Ys,e.isModifierKey=Gs,e.lookupKey=qs,e.normalizeKeyMap=Vs,e.StringStream=qe,e.SharedTextMarker=Ss,e.TextMarker=xs,e.LineWidget=ws,e.e_preventDefault=Ae,e.e_stopPropagation=ye,e.e_stop=Ce,e.addClass=O,e.contains=j,e.rmClass=D,e.keyNames=Fs}(To),To.version="5.61.1",To}()},56141:(e,t,n)=>{!function(e){"use strict";function t(e){return new RegExp("^(("+e.join(")|(")+"))\\b")}var n=t(["and","or","not","is"]),i=["as","assert","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","lambda","pass","raise","return","try","while","with","yield","in"],r=["abs","all","any","bin","bool","bytearray","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip","__import__","NotImplemented","Ellipsis","__debug__"];function s(e){return e.scopes[e.scopes.length-1]}e.registerHelper("hintWords","python",i.concat(r)),e.defineMode("python",(function(o,a){for(var l="error",u=a.delimiters||a.singleDelimiters||/^[\(\)\[\]\{\}@,:`=;\.\\]/,d=[a.singleOperators,a.doubleOperators,a.doubleDelimiters,a.tripleDelimiters,a.operators||/^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@]|\.\.\.)/],c=0;ci?w(t):r0&&C(e,t)&&(o+=" "+l),o}return y(e,t)}function y(e,t,i){if(e.eatSpace())return null;if(!i&&e.match(/^#.*/))return"comment";if(e.match(/^[0-9\.]/,!1)){var r=!1;if(e.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)&&(r=!0),e.match(/^[\d_]+\.\d*/)&&(r=!0),e.match(/^\.\d+/)&&(r=!0),r)return e.eat(/J/i),"number";var s=!1;if(e.match(/^0x[0-9a-f_]+/i)&&(s=!0),e.match(/^0b[01_]+/i)&&(s=!0),e.match(/^0o[0-7_]+/i)&&(s=!0),e.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)&&(e.eat(/J/i),s=!0),e.match(/^0(?![\dx])/i)&&(s=!0),s)return e.eat(/L/i),"number"}if(e.match(v))return-1!==e.current().toLowerCase().indexOf("f")?(t.tokenize=function(e,t){for(;"rubf".indexOf(e.charAt(0).toLowerCase())>=0;)e=e.substr(1);var n=1==e.length,i="string";function r(e){return function(t,n){var i=y(t,n,!0);return"punctuation"==i&&("{"==t.current()?n.tokenize=r(e+1):"}"==t.current()&&(n.tokenize=e>1?r(e-1):s)),i}}function s(s,o){for(;!s.eol();)if(s.eatWhile(/[^'"\{\}\\]/),s.eat("\\")){if(s.next(),n&&s.eol())return i}else{if(s.match(e))return o.tokenize=t,i;if(s.match("{{"))return i;if(s.match("{",!1))return o.tokenize=r(0),s.current()?i:o.tokenize(s,o);if(s.match("}}"))return i;if(s.match("}"))return l;s.eat(/['"]/)}if(n){if(a.singleLineStringErrors)return l;o.tokenize=t}return i}return s.isString=!0,s}(e.current(),t.tokenize),t.tokenize(e,t)):(t.tokenize=function(e,t){for(;"rubf".indexOf(e.charAt(0).toLowerCase())>=0;)e=e.substr(1);var n=1==e.length,i="string";function r(r,s){for(;!r.eol();)if(r.eatWhile(/[^'"\\]/),r.eat("\\")){if(r.next(),n&&r.eol())return i}else{if(r.match(e))return s.tokenize=t,i;r.eat(/['"]/)}if(n){if(a.singleLineStringErrors)return l;s.tokenize=t}return i}return r.isString=!0,r}(e.current(),t.tokenize),t.tokenize(e,t));for(var o=0;o1&&s(t).offset>n;){if("py"!=s(t).type)return!0;t.scopes.pop()}return s(t).offset!=n}function E(e,t){e.sol()&&(t.beginningOfLine=!0);var n=t.tokenize(e,t),i=e.current();if(t.beginningOfLine&&"@"==i)return e.match(m,!1)?"meta":f?"operator":l;if(/\S/.test(i)&&(t.beginningOfLine=!1),"variable"!=n&&"builtin"!=n||"meta"!=t.lastToken||(n="meta"),"pass"!=i&&"return"!=i||(t.dedent+=1),"lambda"==i&&(t.lambda=!0),":"==i&&!t.lambda&&"py"==s(t).type&&e.match(/^\s*(?:#|$)/,!1)&&w(t),1==i.length&&!/string|comment/.test(n)){var r="[({".indexOf(i);if(-1!=r&&function(e,t,n){var i=e.match(/^[\s\[\{\(]*(?:#|$)/,!1)?null:e.column()+1;t.scopes.push({offset:t.indent+h,type:n,align:i})}(e,t,"])}".slice(r,r+1)),-1!=(r="])}".indexOf(i))){if(s(t).type!=i)return l;t.indent=t.scopes.pop().offset-h}}return t.dedent>0&&e.eol()&&"py"==s(t).type&&(t.scopes.length>1&&t.scopes.pop(),t.dedent-=1),n}return{startState:function(e){return{tokenize:A,scopes:[{offset:e||0,type:"py",align:null}],indent:e||0,lastToken:null,lambda:!1,dedent:0}},token:function(e,t){var n=t.errorToken;n&&(t.errorToken=!1);var i=E(e,t);return i&&"comment"!=i&&(t.lastToken="keyword"==i||"punctuation"==i?e.current():i),"punctuation"==i&&(i=null),e.eol()&&t.lambda&&(t.lambda=!1),n?i+" "+l:i},indent:function(t,n){if(t.tokenize!=A)return t.tokenize.isString?e.Pass:0;var i=s(t),r=i.type==n.charAt(0);return null!=i.align?i.align-(r?1:0):i.offset-(r?h:0)},electricInput:/^\s*[\}\]\)]$/,closeBrackets:{triples:"'\""},lineComment:"#",fold:"indent"}})),e.defineMIME("text/x-python","python");var o;e.defineMIME("text/x-cython",{name:"python",extra_keywords:(o="by cdef cimport cpdef ctypedef enum except extern gil include nogil property public readonly struct union DEF IF ELIF ELSE",o.split(" "))})}(n(23326))},39714:e=>{"use strict";var t=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||function(e){return e.$$typeof===n}(e)}(e)},n="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function i(e,t){return!1!==t.clone&&t.isMergeableObject(e)?a((n=e,Array.isArray(n)?[]:{}),e,t):e;var n}function r(e,t,n){return e.concat(t).map((function(e){return i(e,n)}))}function s(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter((function(t){return Object.propertyIsEnumerable.call(e,t)})):[]}(e))}function o(e,t){try{return t in e}catch(e){return!1}}function a(e,n,l){(l=l||{}).arrayMerge=l.arrayMerge||r,l.isMergeableObject=l.isMergeableObject||t,l.cloneUnlessOtherwiseSpecified=i;var u=Array.isArray(n);return u===Array.isArray(e)?u?l.arrayMerge(e,n,l):function(e,t,n){var r={};return n.isMergeableObject(e)&&s(e).forEach((function(t){r[t]=i(e[t],n)})),s(t).forEach((function(s){(function(e,t){return o(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,s)||(o(e,s)&&n.isMergeableObject(t[s])?r[s]=function(e,t){if(!t.customMerge)return a;var n=t.customMerge(e);return"function"==typeof n?n:a}(s,n)(e[s],t[s],n):r[s]=i(t[s],n))})),r}(e,n,l):i(n,l)}a.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce((function(e,n){return a(e,n,t)}),{})};var l=a;e.exports=l},16594:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.attributeNames=t.elementNames=void 0,t.elementNames=new Map([["altglyph","altGlyph"],["altglyphdef","altGlyphDef"],["altglyphitem","altGlyphItem"],["animatecolor","animateColor"],["animatemotion","animateMotion"],["animatetransform","animateTransform"],["clippath","clipPath"],["feblend","feBlend"],["fecolormatrix","feColorMatrix"],["fecomponenttransfer","feComponentTransfer"],["fecomposite","feComposite"],["feconvolvematrix","feConvolveMatrix"],["fediffuselighting","feDiffuseLighting"],["fedisplacementmap","feDisplacementMap"],["fedistantlight","feDistantLight"],["fedropshadow","feDropShadow"],["feflood","feFlood"],["fefunca","feFuncA"],["fefuncb","feFuncB"],["fefuncg","feFuncG"],["fefuncr","feFuncR"],["fegaussianblur","feGaussianBlur"],["feimage","feImage"],["femerge","feMerge"],["femergenode","feMergeNode"],["femorphology","feMorphology"],["feoffset","feOffset"],["fepointlight","fePointLight"],["fespecularlighting","feSpecularLighting"],["fespotlight","feSpotLight"],["fetile","feTile"],["feturbulence","feTurbulence"],["foreignobject","foreignObject"],["glyphref","glyphRef"],["lineargradient","linearGradient"],["radialgradient","radialGradient"],["textpath","textPath"]]),t.attributeNames=new Map([["definitionurl","definitionURL"],["attributename","attributeName"],["attributetype","attributeType"],["basefrequency","baseFrequency"],["baseprofile","baseProfile"],["calcmode","calcMode"],["clippathunits","clipPathUnits"],["diffuseconstant","diffuseConstant"],["edgemode","edgeMode"],["filterunits","filterUnits"],["glyphref","glyphRef"],["gradienttransform","gradientTransform"],["gradientunits","gradientUnits"],["kernelmatrix","kernelMatrix"],["kernelunitlength","kernelUnitLength"],["keypoints","keyPoints"],["keysplines","keySplines"],["keytimes","keyTimes"],["lengthadjust","lengthAdjust"],["limitingconeangle","limitingConeAngle"],["markerheight","markerHeight"],["markerunits","markerUnits"],["markerwidth","markerWidth"],["maskcontentunits","maskContentUnits"],["maskunits","maskUnits"],["numoctaves","numOctaves"],["pathlength","pathLength"],["patterncontentunits","patternContentUnits"],["patterntransform","patternTransform"],["patternunits","patternUnits"],["pointsatx","pointsAtX"],["pointsaty","pointsAtY"],["pointsatz","pointsAtZ"],["preservealpha","preserveAlpha"],["preserveaspectratio","preserveAspectRatio"],["primitiveunits","primitiveUnits"],["refx","refX"],["refy","refY"],["repeatcount","repeatCount"],["repeatdur","repeatDur"],["requiredextensions","requiredExtensions"],["requiredfeatures","requiredFeatures"],["specularconstant","specularConstant"],["specularexponent","specularExponent"],["spreadmethod","spreadMethod"],["startoffset","startOffset"],["stddeviation","stdDeviation"],["stitchtiles","stitchTiles"],["surfacescale","surfaceScale"],["systemlanguage","systemLanguage"],["tablevalues","tableValues"],["targetx","targetX"],["targety","targetY"],["textlength","textLength"],["viewbox","viewBox"],["viewtarget","viewTarget"],["xchannelselector","xChannelSelector"],["ychannelselector","yChannelSelector"],["zoomandpan","zoomAndPan"]])},50606:function(e,t,n){"use strict";var i=this&&this.__assign||function(){return i=Object.assign||function(e){for(var t,n=1,i=arguments.length;n";case a.Comment:return"\x3c!--"+e.data+"--\x3e";case a.CDATA:return function(e){return""}(e);case a.Script:case a.Style:case a.Tag:return function(e,t){var n;"foreign"===t.xmlMode&&(e.name=null!==(n=u.elementNames.get(e.name))&&void 0!==n?n:e.name,e.parent&&g.has(e.parent.name)&&(t=i(i({},t),{xmlMode:!1}))),!t.xmlMode&&f.has(e.name)&&(t=i(i({},t),{xmlMode:"foreign"}));var r="<"+e.name,s=function(e,t){if(e)return Object.keys(e).map((function(n){var i,r,s=null!==(i=e[n])&&void 0!==i?i:"";return"foreign"===t.xmlMode&&(n=null!==(r=u.attributeNames.get(n))&&void 0!==r?r:n),t.emptyAttrs||t.xmlMode||""!==s?n+'="'+(!1!==t.decodeEntities?l.encodeXML(s):s.replace(/"/g,"""))+'"':n})).join(" ")}(e.attribs,t);return s&&(r+=" "+s),0===e.children.length&&(t.xmlMode?!1!==t.selfClosingTags:t.selfClosingTags&&c.has(e.name))?(t.xmlMode||(r+=" "),r+="/>"):(r+=">",e.children.length>0&&(r+=h(e.children,t)),!t.xmlMode&&c.has(e.name)||(r+="")),r}(e,t);case a.Text:return function(e,t){var n=e.data||"";return!1===t.decodeEntities||!t.xmlMode&&e.parent&&d.has(e.parent.name)||(n=l.encodeXML(n)),n}(e,t)}}t.default=h;var g=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),f=new Set(["svg","math"])},34821:(e,t)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.Doctype=t.CDATA=t.Tag=t.Style=t.Script=t.Comment=t.Directive=t.Text=t.Root=t.isTag=t.ElementType=void 0,function(e){e.Root="root",e.Text="text",e.Directive="directive",e.Comment="comment",e.Script="script",e.Style="style",e.Tag="tag",e.CDATA="cdata",e.Doctype="doctype"}(n=t.ElementType||(t.ElementType={})),t.isTag=function(e){return e.type===n.Tag||e.type===n.Script||e.type===n.Style},t.Root=n.Root,t.Text=n.Text,t.Directive=n.Directive,t.Comment=n.Comment,t.Script=n.Script,t.Style=n.Style,t.Tag=n.Tag,t.CDATA=n.CDATA,t.Doctype=n.Doctype},79959:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.DomHandler=void 0;var s=n(34821),o=n(75538);r(n(75538),t);var a=/\s+/g,l={normalizeWhitespace:!1,withStartIndices:!1,withEndIndices:!1,xmlMode:!1},u=function(){function e(e,t,n){this.dom=[],this.root=new o.Document(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null,"function"==typeof t&&(n=t,t=l),"object"==typeof e&&(t=e,e=void 0),this.callback=null!=e?e:null,this.options=null!=t?t:l,this.elementCB=null!=n?n:null}return e.prototype.onparserinit=function(e){this.parser=e},e.prototype.onreset=function(){this.dom=[],this.root=new o.Document(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null},e.prototype.onend=function(){this.done||(this.done=!0,this.parser=null,this.handleCallback(null))},e.prototype.onerror=function(e){this.handleCallback(e)},e.prototype.onclosetag=function(){this.lastNode=null;var e=this.tagStack.pop();this.options.withEndIndices&&(e.endIndex=this.parser.endIndex),this.elementCB&&this.elementCB(e)},e.prototype.onopentag=function(e,t){var n=this.options.xmlMode?s.ElementType.Tag:void 0,i=new o.Element(e,t,void 0,n);this.addNode(i),this.tagStack.push(i)},e.prototype.ontext=function(e){var t=this.options.normalizeWhitespace,n=this.lastNode;if(n&&n.type===s.ElementType.Text)t?n.data=(n.data+e).replace(a," "):n.data+=e,this.options.withEndIndices&&(n.endIndex=this.parser.endIndex);else{t&&(e=e.replace(a," "));var i=new o.Text(e);this.addNode(i),this.lastNode=i}},e.prototype.oncomment=function(e){if(this.lastNode&&this.lastNode.type===s.ElementType.Comment)this.lastNode.data+=e;else{var t=new o.Comment(e);this.addNode(t),this.lastNode=t}},e.prototype.oncommentend=function(){this.lastNode=null},e.prototype.oncdatastart=function(){var e=new o.Text(""),t=new o.NodeWithChildren(s.ElementType.CDATA,[e]);this.addNode(t),e.parent=t,this.lastNode=e},e.prototype.oncdataend=function(){this.lastNode=null},e.prototype.onprocessinginstruction=function(e,t){var n=new o.ProcessingInstruction(e,t);this.addNode(n)},e.prototype.handleCallback=function(e){if("function"==typeof this.callback)this.callback(e,this.dom);else if(e)throw e},e.prototype.addNode=function(e){var t=this.tagStack[this.tagStack.length-1],n=t.children[t.children.length-1];this.options.withStartIndices&&(e.startIndex=this.parser.startIndex),this.options.withEndIndices&&(e.endIndex=this.parser.endIndex),t.children.push(e),n&&(e.prev=n,n.next=e),e.parent=t,this.lastNode=null},e}();t.DomHandler=u,t.default=u},75538:function(e,t,n){"use strict";var i,r=this&&this.__extends||(i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},i(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),s=this&&this.__assign||function(){return s=Object.assign||function(e){for(var t,n=1,i=arguments.length;n0?this.children[this.children.length-1]:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"childNodes",{get:function(){return this.children},set:function(e){this.children=e},enumerable:!1,configurable:!0}),t}(l);t.NodeWithChildren=p;var g=function(e){function t(t){return e.call(this,o.ElementType.Root,t)||this}return r(t,e),t}(p);t.Document=g;var f=function(e){function t(t,n,i,r){void 0===i&&(i=[]),void 0===r&&(r="script"===t?o.ElementType.Script:"style"===t?o.ElementType.Style:o.ElementType.Tag);var s=e.call(this,r,i)||this;return s.name=t,s.attribs=n,s}return r(t,e),Object.defineProperty(t.prototype,"tagName",{get:function(){return this.name},set:function(e){this.name=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"attributes",{get:function(){var e=this;return Object.keys(this.attribs).map((function(t){var n,i;return{name:t,value:e.attribs[t],namespace:null===(n=e["x-attribsNamespace"])||void 0===n?void 0:n[t],prefix:null===(i=e["x-attribsPrefix"])||void 0===i?void 0:i[t]}}))},enumerable:!1,configurable:!0}),t}(p);function m(e){return(0,o.isTag)(e)}function v(e){return e.type===o.ElementType.CDATA}function b(e){return e.type===o.ElementType.Text}function _(e){return e.type===o.ElementType.Comment}function A(e){return e.type===o.ElementType.Directive}function y(e){return e.type===o.ElementType.Root}function w(e,t){var n;if(void 0===t&&(t=!1),b(e))n=new d(e.data);else if(_(e))n=new c(e.data);else if(m(e)){var i=t?C(e.children):[],r=new f(e.name,s({},e.attribs),i);i.forEach((function(e){return e.parent=r})),null!=e.namespace&&(r.namespace=e.namespace),e["x-attribsNamespace"]&&(r["x-attribsNamespace"]=s({},e["x-attribsNamespace"])),e["x-attribsPrefix"]&&(r["x-attribsPrefix"]=s({},e["x-attribsPrefix"])),n=r}else if(v(e)){i=t?C(e.children):[];var a=new p(o.ElementType.CDATA,i);i.forEach((function(e){return e.parent=a})),n=a}else if(y(e)){i=t?C(e.children):[];var l=new g(i);i.forEach((function(e){return e.parent=l})),e["x-mode"]&&(l["x-mode"]=e["x-mode"]),n=l}else{if(!A(e))throw new Error("Not implemented yet: ".concat(e.type));var u=new h(e.name,e.data);null!=e["x-name"]&&(u["x-name"]=e["x-name"],u["x-publicId"]=e["x-publicId"],u["x-systemId"]=e["x-systemId"]),n=u}return n.startIndex=e.startIndex,n.endIndex=e.endIndex,null!=e.sourceCodeLocation&&(n.sourceCodeLocation=e.sourceCodeLocation),n}function C(e){for(var t=e.map((function(e){return w(e,!0)})),n=1;n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getFeed=void 0;var i=n(87559),r=n(65310);t.getFeed=function(e){var t=l(c,e);return t?"feed"===t.name?function(e){var t,n=e.children,i={type:"atom",items:(0,r.getElementsByTagName)("entry",n).map((function(e){var t,n=e.children,i={media:a(n)};d(i,"id","id",n),d(i,"title","title",n);var r=null===(t=l("link",n))||void 0===t?void 0:t.attribs.href;r&&(i.link=r);var s=u("summary",n)||u("content",n);s&&(i.description=s);var o=u("updated",n);return o&&(i.pubDate=new Date(o)),i}))};d(i,"id","id",n),d(i,"title","title",n);var s=null===(t=l("link",n))||void 0===t?void 0:t.attribs.href;s&&(i.link=s),d(i,"description","subtitle",n);var o=u("updated",n);return o&&(i.updated=new Date(o)),d(i,"author","email",n,!0),i}(t):function(e){var t,n,i=null!==(n=null===(t=l("channel",e.children))||void 0===t?void 0:t.children)&&void 0!==n?n:[],s={type:e.name.substr(0,3),id:"",items:(0,r.getElementsByTagName)("item",e.children).map((function(e){var t=e.children,n={media:a(t)};d(n,"id","guid",t),d(n,"title","title",t),d(n,"link","link",t),d(n,"description","description",t);var i=u("pubDate",t);return i&&(n.pubDate=new Date(i)),n}))};d(s,"title","title",i),d(s,"link","link",i),d(s,"description","description",i);var o=u("lastBuildDate",i);return o&&(s.updated=new Date(o)),d(s,"author","managingEditor",i,!0),s}(t):null};var s=["url","type","lang"],o=["fileSize","bitrate","framerate","samplingrate","channels","duration","height","width"];function a(e){return(0,r.getElementsByTagName)("media:content",e).map((function(e){for(var t=e.attribs,n={medium:t.medium,isDefault:!!t.isDefault},i=0,r=s;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uniqueSort=t.compareDocumentPosition=t.removeSubsets=void 0;var i=n(79959);function r(e,t){var n=[],r=[];if(e===t)return 0;for(var s=(0,i.hasChildren)(e)?e:e.parent;s;)n.unshift(s),s=s.parent;for(s=(0,i.hasChildren)(t)?t:t.parent;s;)r.unshift(s),s=s.parent;for(var o=Math.min(n.length,r.length),a=0;au.indexOf(c)?l===t?20:4:l===e?10:2}t.removeSubsets=function(e){for(var t=e.length;--t>=0;){var n=e[t];if(t>0&&e.lastIndexOf(n,t-1)>=0)e.splice(t,1);else for(var i=n.parent;i;i=i.parent)if(e.includes(i)){e.splice(t,1);break}}return e},t.compareDocumentPosition=r,t.uniqueSort=function(e){return(e=e.filter((function(e,t,n){return!n.includes(e,t+1)}))).sort((function(e,t){var n=r(e,t);return 2&n?-1:4&n?1:0})),e}},64622:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.hasChildren=t.isDocument=t.isComment=t.isText=t.isCDATA=t.isTag=void 0,r(n(87559),t),r(n(16304),t),r(n(57427),t),r(n(17853),t),r(n(65310),t),r(n(42880),t),r(n(57065),t);var s=n(79959);Object.defineProperty(t,"isTag",{enumerable:!0,get:function(){return s.isTag}}),Object.defineProperty(t,"isCDATA",{enumerable:!0,get:function(){return s.isCDATA}}),Object.defineProperty(t,"isText",{enumerable:!0,get:function(){return s.isText}}),Object.defineProperty(t,"isComment",{enumerable:!0,get:function(){return s.isComment}}),Object.defineProperty(t,"isDocument",{enumerable:!0,get:function(){return s.isDocument}}),Object.defineProperty(t,"hasChildren",{enumerable:!0,get:function(){return s.hasChildren}})},65310:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getElementsByTagType=t.getElementsByTagName=t.getElementById=t.getElements=t.testElement=void 0;var i=n(79959),r=n(17853),s={tag_name:function(e){return"function"==typeof e?function(t){return(0,i.isTag)(t)&&e(t.name)}:"*"===e?i.isTag:function(t){return(0,i.isTag)(t)&&t.name===e}},tag_type:function(e){return"function"==typeof e?function(t){return e(t.type)}:function(t){return t.type===e}},tag_contains:function(e){return"function"==typeof e?function(t){return(0,i.isText)(t)&&e(t.data)}:function(t){return(0,i.isText)(t)&&t.data===e}}};function o(e,t){return"function"==typeof t?function(n){return(0,i.isTag)(n)&&t(n.attribs[e])}:function(n){return(0,i.isTag)(n)&&n.attribs[e]===t}}function a(e,t){return function(n){return e(n)||t(n)}}function l(e){var t=Object.keys(e).map((function(t){var n=e[t];return Object.prototype.hasOwnProperty.call(s,t)?s[t](n):o(t,n)}));return 0===t.length?null:t.reduce(a)}t.testElement=function(e,t){var n=l(e);return!n||n(t)},t.getElements=function(e,t,n,i){void 0===i&&(i=1/0);var s=l(e);return s?(0,r.filter)(s,t,n,i):[]},t.getElementById=function(e,t,n){return void 0===n&&(n=!0),Array.isArray(t)||(t=[t]),(0,r.findOne)(o("id",e),t,n)},t.getElementsByTagName=function(e,t,n,i){return void 0===n&&(n=!0),void 0===i&&(i=1/0),(0,r.filter)(s.tag_name(e),t,n,i)},t.getElementsByTagType=function(e,t,n,i){return void 0===n&&(n=!0),void 0===i&&(i=1/0),(0,r.filter)(s.tag_type(e),t,n,i)}},57427:(e,t)=>{"use strict";function n(e){if(e.prev&&(e.prev.next=e.next),e.next&&(e.next.prev=e.prev),e.parent){var t=e.parent.children;t.splice(t.lastIndexOf(e),1)}}Object.defineProperty(t,"__esModule",{value:!0}),t.prepend=t.prependChild=t.append=t.appendChild=t.replaceElement=t.removeElement=void 0,t.removeElement=n,t.replaceElement=function(e,t){var n=t.prev=e.prev;n&&(n.next=t);var i=t.next=e.next;i&&(i.prev=t);var r=t.parent=e.parent;if(r){var s=r.children;s[s.lastIndexOf(e)]=t}},t.appendChild=function(e,t){if(n(t),t.next=null,t.parent=e,e.children.push(t)>1){var i=e.children[e.children.length-2];i.next=t,t.prev=i}else t.prev=null},t.append=function(e,t){n(t);var i=e.parent,r=e.next;if(t.next=r,t.prev=e,e.next=t,t.parent=i,r){if(r.prev=t,i){var s=i.children;s.splice(s.lastIndexOf(r),0,t)}}else i&&i.children.push(t)},t.prependChild=function(e,t){if(n(t),t.parent=e,t.prev=null,1!==e.children.unshift(t)){var i=e.children[1];i.prev=t,t.next=i}else t.next=null},t.prepend=function(e,t){n(t);var i=e.parent;if(i){var r=i.children;r.splice(r.indexOf(e),0,t)}e.prev&&(e.prev.next=t),t.parent=i,t.prev=e.prev,t.next=e,e.prev=t}},17853:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findAll=t.existsOne=t.findOne=t.findOneChild=t.find=t.filter=void 0;var i=n(79959);function r(e,t,n,s){for(var o=[],a=0,l=t;a0){var d=r(e,u.children,n,s);if(o.push.apply(o,d),(s-=d.length)<=0)break}}return o}t.filter=function(e,t,n,i){return void 0===n&&(n=!0),void 0===i&&(i=1/0),Array.isArray(t)||(t=[t]),r(e,t,n,i)},t.find=r,t.findOneChild=function(e,t){return t.find(e)},t.findOne=function e(t,n,r){void 0===r&&(r=!0);for(var s=null,o=0;o0&&(s=e(t,a.children)))}return s},t.existsOne=function e(t,n){return n.some((function(n){return(0,i.isTag)(n)&&(t(n)||n.children.length>0&&e(t,n.children))}))},t.findAll=function(e,t){for(var n,r,s=[],o=t.filter(i.isTag);r=o.shift();){var a=null===(n=r.children)||void 0===n?void 0:n.filter(i.isTag);a&&a.length>0&&o.unshift.apply(o,a),e(r)&&s.push(r)}return s}},87559:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.innerText=t.textContent=t.getText=t.getInnerHTML=t.getOuterHTML=void 0;var r=n(79959),s=i(n(50606)),o=n(34821);function a(e,t){return(0,s.default)(e,t)}t.getOuterHTML=a,t.getInnerHTML=function(e,t){return(0,r.hasChildren)(e)?e.children.map((function(e){return a(e,t)})).join(""):""},t.getText=function e(t){return Array.isArray(t)?t.map(e).join(""):(0,r.isTag)(t)?"br"===t.name?"\n":e(t.children):(0,r.isCDATA)(t)?e(t.children):(0,r.isText)(t)?t.data:""},t.textContent=function e(t){return Array.isArray(t)?t.map(e).join(""):(0,r.hasChildren)(t)&&!(0,r.isComment)(t)?e(t.children):(0,r.isText)(t)?t.data:""},t.innerText=function e(t){return Array.isArray(t)?t.map(e).join(""):(0,r.hasChildren)(t)&&(t.type===o.ElementType.Tag||(0,r.isCDATA)(t))?e(t.children):(0,r.isText)(t)?t.data:""}},16304:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prevElementSibling=t.nextElementSibling=t.getName=t.hasAttrib=t.getAttributeValue=t.getSiblings=t.getParent=t.getChildren=void 0;var i=n(79959),r=[];function s(e){var t;return null!==(t=e.children)&&void 0!==t?t:r}function o(e){return e.parent||null}t.getChildren=s,t.getParent=o,t.getSiblings=function(e){var t=o(e);if(null!=t)return s(t);for(var n=[e],i=e.prev,r=e.next;null!=i;)n.unshift(i),i=i.prev;for(;null!=r;)n.push(r),r=r.next;return n},t.getAttributeValue=function(e,t){var n;return null===(n=e.attribs)||void 0===n?void 0:n[t]},t.hasAttrib=function(e,t){return null!=e.attribs&&Object.prototype.hasOwnProperty.call(e.attribs,t)&&null!=e.attribs[t]},t.getName=function(e){return e.name},t.nextElementSibling=function(e){for(var t=e.next;null!==t&&!(0,i.isTag)(t);)t=t.next;return t},t.prevElementSibling=function(e){for(var t=e.prev;null!==t&&!(0,i.isTag)(t);)t=t.prev;return t}},73094:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.decodeHTML=t.decodeHTMLStrict=t.decodeXML=void 0;var r=i(n(72059)),s=i(n(62184)),o=i(n(81542)),a=i(n(70105)),l=/&(?:[a-zA-Z0-9]+|#[xX][\da-fA-F]+|#\d+);/g;function u(e){var t=c(e);return function(e){return String(e).replace(l,t)}}t.decodeXML=u(o.default),t.decodeHTMLStrict=u(r.default);var d=function(e,t){return e65535&&(e-=65536,t+=String.fromCharCode(e>>>10&1023|55296),e=56320|1023&e),t+String.fromCharCode(e)};t.default=function(e){return e>=55296&&e<=57343||e>1114111?"�":(e in r.default&&(e=r.default[e]),s(e))}},41029:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.escapeUTF8=t.escape=t.encodeNonAsciiHTML=t.encodeHTML=t.encodeXML=void 0;var r=d(i(n(81542)).default),s=c(r);t.encodeXML=m(r);var o,a,l=d(i(n(72059)).default),u=c(l);function d(e){return Object.keys(e).sort().reduce((function(t,n){return t[e[n]]="&"+n+";",t}),{})}function c(e){for(var t=[],n=[],i=0,r=Object.keys(e);i1?p(e):e.charCodeAt(0)).toString(16).toUpperCase()+";"}var f=new RegExp(s.source+"|"+h.source,"g");function m(e){return function(t){return t.replace(f,(function(t){return e[t]||g(t)}))}}t.escape=function(e){return e.replace(f,g)},t.escapeUTF8=function(e){return e.replace(s,g)}},75924:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decodeXMLStrict=t.decodeHTML5Strict=t.decodeHTML4Strict=t.decodeHTML5=t.decodeHTML4=t.decodeHTMLStrict=t.decodeHTML=t.decodeXML=t.encodeHTML5=t.encodeHTML4=t.escapeUTF8=t.escape=t.encodeNonAsciiHTML=t.encodeHTML=t.encodeXML=t.encode=t.decodeStrict=t.decode=void 0;var i=n(73094),r=n(41029);t.decode=function(e,t){return(!t||t<=0?i.decodeXML:i.decodeHTML)(e)},t.decodeStrict=function(e,t){return(!t||t<=0?i.decodeXML:i.decodeHTMLStrict)(e)},t.encode=function(e,t){return(!t||t<=0?r.encodeXML:r.encodeHTML)(e)};var s=n(41029);Object.defineProperty(t,"encodeXML",{enumerable:!0,get:function(){return s.encodeXML}}),Object.defineProperty(t,"encodeHTML",{enumerable:!0,get:function(){return s.encodeHTML}}),Object.defineProperty(t,"encodeNonAsciiHTML",{enumerable:!0,get:function(){return s.encodeNonAsciiHTML}}),Object.defineProperty(t,"escape",{enumerable:!0,get:function(){return s.escape}}),Object.defineProperty(t,"escapeUTF8",{enumerable:!0,get:function(){return s.escapeUTF8}}),Object.defineProperty(t,"encodeHTML4",{enumerable:!0,get:function(){return s.encodeHTML}}),Object.defineProperty(t,"encodeHTML5",{enumerable:!0,get:function(){return s.encodeHTML}});var o=n(73094);Object.defineProperty(t,"decodeXML",{enumerable:!0,get:function(){return o.decodeXML}}),Object.defineProperty(t,"decodeHTML",{enumerable:!0,get:function(){return o.decodeHTML}}),Object.defineProperty(t,"decodeHTMLStrict",{enumerable:!0,get:function(){return o.decodeHTMLStrict}}),Object.defineProperty(t,"decodeHTML4",{enumerable:!0,get:function(){return o.decodeHTML}}),Object.defineProperty(t,"decodeHTML5",{enumerable:!0,get:function(){return o.decodeHTML}}),Object.defineProperty(t,"decodeHTML4Strict",{enumerable:!0,get:function(){return o.decodeHTMLStrict}}),Object.defineProperty(t,"decodeHTML5Strict",{enumerable:!0,get:function(){return o.decodeHTMLStrict}}),Object.defineProperty(t,"decodeXMLStrict",{enumerable:!0,get:function(){return o.decodeXML}})},84163:function(e,t,n){"use strict";var i,r=this&&this.__extends||(i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},i(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),s=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&s(t,e,n);return o(t,e),t},l=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.parseFeed=t.FeedHandler=void 0;var u,d,c=l(n(79959)),h=a(n(64622)),p=n(75233);!function(e){e[e.image=0]="image",e[e.audio=1]="audio",e[e.video=2]="video",e[e.document=3]="document",e[e.executable=4]="executable"}(u||(u={})),function(e){e[e.sample=0]="sample",e[e.full=1]="full",e[e.nonstop=2]="nonstop"}(d||(d={}));var g=function(e){function t(t,n){return"object"==typeof t&&(n=t=void 0),e.call(this,t,n)||this}return r(t,e),t.prototype.onend=function(){var e,t,n=v(y,this.dom);if(n){var i={};if("feed"===n.name){var r=n.children;i.type="atom",A(i,"id","id",r),A(i,"title","title",r);var s=_("href",v("link",r));s&&(i.link=s),A(i,"description","subtitle",r),(o=b("updated",r))&&(i.updated=new Date(o)),A(i,"author","email",r,!0),i.items=m("entry",r).map((function(e){var t={},n=e.children;A(t,"id","id",n),A(t,"title","title",n);var i=_("href",v("link",n));i&&(t.link=i);var r=b("summary",n)||b("content",n);r&&(t.description=r);var s=b("updated",n);return s&&(t.pubDate=new Date(s)),t.media=f(n),t}))}else{var o;r=null!==(t=null===(e=v("channel",n.children))||void 0===e?void 0:e.children)&&void 0!==t?t:[],i.type=n.name.substr(0,3),i.id="",A(i,"title","title",r),A(i,"link","link",r),A(i,"description","description",r),(o=b("lastBuildDate",r))&&(i.updated=new Date(o)),A(i,"author","managingEditor",r,!0),i.items=m("item",n.children).map((function(e){var t={},n=e.children;A(t,"id","guid",n),A(t,"title","title",n),A(t,"link","link",n),A(t,"description","description",n);var i=b("pubDate",n);return i&&(t.pubDate=new Date(i)),t.media=f(n),t}))}this.feed=i,this.handleCallback(null)}else this.handleCallback(new Error("couldn't find root of feed"))},t}(c.default);function f(e){return m("media:content",e).map((function(e){var t={medium:e.attribs.medium,isDefault:!!e.attribs.isDefault};return e.attribs.url&&(t.url=e.attribs.url),e.attribs.fileSize&&(t.fileSize=parseInt(e.attribs.fileSize,10)),e.attribs.type&&(t.type=e.attribs.type),e.attribs.expression&&(t.expression=e.attribs.expression),e.attribs.bitrate&&(t.bitrate=parseInt(e.attribs.bitrate,10)),e.attribs.framerate&&(t.framerate=parseInt(e.attribs.framerate,10)),e.attribs.samplingrate&&(t.samplingrate=parseInt(e.attribs.samplingrate,10)),e.attribs.channels&&(t.channels=parseInt(e.attribs.channels,10)),e.attribs.duration&&(t.duration=parseInt(e.attribs.duration,10)),e.attribs.height&&(t.height=parseInt(e.attribs.height,10)),e.attribs.width&&(t.width=parseInt(e.attribs.width,10)),e.attribs.lang&&(t.lang=e.attribs.lang),t}))}function m(e,t){return h.getElementsByTagName(e,t,!0)}function v(e,t){return h.getElementsByTagName(e,t,!0,1)[0]}function b(e,t,n){return void 0===n&&(n=!1),h.getText(h.getElementsByTagName(e,t,n,1)).trim()}function _(e,t){return t?t.attribs[e]:null}function A(e,t,n,i,r){void 0===r&&(r=!1);var s=b(n,i,r);s&&(e[t]=s)}function y(e){return"rss"===e||"feed"===e||"rdf:RDF"===e}t.FeedHandler=g,t.parseFeed=function(e,t){void 0===t&&(t={xmlMode:!0});var n=new g(t);return new p.Parser(n,t).end(e),n.feed}},75233:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Parser=void 0;var r=i(n(59636)),s=new Set(["input","option","optgroup","select","button","datalist","textarea"]),o=new Set(["p"]),a={tr:new Set(["tr","th","td"]),th:new Set(["th"]),td:new Set(["thead","th","td"]),body:new Set(["head","link","script"]),li:new Set(["li"]),p:o,h1:o,h2:o,h3:o,h4:o,h5:o,h6:o,select:s,input:s,output:s,button:s,datalist:s,textarea:s,option:new Set(["option"]),optgroup:new Set(["optgroup","option"]),dd:new Set(["dt","dd"]),dt:new Set(["dt","dd"]),address:o,article:o,aside:o,blockquote:o,details:o,div:o,dl:o,fieldset:o,figcaption:o,figure:o,footer:o,form:o,header:o,hr:o,main:o,nav:o,ol:o,pre:o,section:o,table:o,ul:o,rt:new Set(["rt","rp"]),rp:new Set(["rt","rp"]),tbody:new Set(["thead","tbody"]),tfoot:new Set(["thead","tbody"])},l=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),u=new Set(["math","svg"]),d=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),c=/\s|\//,h=function(){function e(e,t){var n,i,s,o,a;void 0===t&&(t={}),this.startIndex=0,this.endIndex=null,this.tagname="",this.attribname="",this.attribvalue="",this.attribs=null,this.stack=[],this.foreignContext=[],this.options=t,this.cbs=null!=e?e:{},this.lowerCaseTagNames=null!==(n=t.lowerCaseTags)&&void 0!==n?n:!t.xmlMode,this.lowerCaseAttributeNames=null!==(i=t.lowerCaseAttributeNames)&&void 0!==i?i:!t.xmlMode,this.tokenizer=new(null!==(s=t.Tokenizer)&&void 0!==s?s:r.default)(this.options,this),null===(a=(o=this.cbs).onparserinit)||void 0===a||a.call(o,this)}return e.prototype.updatePosition=function(e){null===this.endIndex?this.tokenizer.sectionStart<=e?this.startIndex=0:this.startIndex=this.tokenizer.sectionStart-e:this.startIndex=this.endIndex+1,this.endIndex=this.tokenizer.getAbsoluteIndex()},e.prototype.ontext=function(e){var t,n;this.updatePosition(1),this.endIndex--,null===(n=(t=this.cbs).ontext)||void 0===n||n.call(t,e)},e.prototype.onopentagname=function(e){var t,n;if(this.lowerCaseTagNames&&(e=e.toLowerCase()),this.tagname=e,!this.options.xmlMode&&Object.prototype.hasOwnProperty.call(a,e))for(var i=void 0;this.stack.length>0&&a[e].has(i=this.stack[this.stack.length-1]);)this.onclosetag(i);!this.options.xmlMode&&l.has(e)||(this.stack.push(e),u.has(e)?this.foreignContext.push(!0):d.has(e)&&this.foreignContext.push(!1)),null===(n=(t=this.cbs).onopentagname)||void 0===n||n.call(t,e),this.cbs.onopentag&&(this.attribs={})},e.prototype.onopentagend=function(){var e,t;this.updatePosition(1),this.attribs&&(null===(t=(e=this.cbs).onopentag)||void 0===t||t.call(e,this.tagname,this.attribs),this.attribs=null),!this.options.xmlMode&&this.cbs.onclosetag&&l.has(this.tagname)&&this.cbs.onclosetag(this.tagname),this.tagname=""},e.prototype.onclosetag=function(e){if(this.updatePosition(1),this.lowerCaseTagNames&&(e=e.toLowerCase()),(u.has(e)||d.has(e))&&this.foreignContext.pop(),!this.stack.length||!this.options.xmlMode&&l.has(e))this.options.xmlMode||"br"!==e&&"p"!==e||(this.onopentagname(e),this.closeCurrentTag());else{var t=this.stack.lastIndexOf(e);if(-1!==t)if(this.cbs.onclosetag)for(t=this.stack.length-t;t--;)this.cbs.onclosetag(this.stack.pop());else this.stack.length=t;else"p"!==e||this.options.xmlMode||(this.onopentagname(e),this.closeCurrentTag())}},e.prototype.onselfclosingtag=function(){this.options.xmlMode||this.options.recognizeSelfClosing||this.foreignContext[this.foreignContext.length-1]?this.closeCurrentTag():this.onopentagend()},e.prototype.closeCurrentTag=function(){var e,t,n=this.tagname;this.onopentagend(),this.stack[this.stack.length-1]===n&&(null===(t=(e=this.cbs).onclosetag)||void 0===t||t.call(e,n),this.stack.pop())},e.prototype.onattribname=function(e){this.lowerCaseAttributeNames&&(e=e.toLowerCase()),this.attribname=e},e.prototype.onattribdata=function(e){this.attribvalue+=e},e.prototype.onattribend=function(e){var t,n;null===(n=(t=this.cbs).onattribute)||void 0===n||n.call(t,this.attribname,this.attribvalue,e),this.attribs&&!Object.prototype.hasOwnProperty.call(this.attribs,this.attribname)&&(this.attribs[this.attribname]=this.attribvalue),this.attribname="",this.attribvalue=""},e.prototype.getInstructionName=function(e){var t=e.search(c),n=t<0?e:e.substr(0,t);return this.lowerCaseTagNames&&(n=n.toLowerCase()),n},e.prototype.ondeclaration=function(e){if(this.cbs.onprocessinginstruction){var t=this.getInstructionName(e);this.cbs.onprocessinginstruction("!"+t,"!"+e)}},e.prototype.onprocessinginstruction=function(e){if(this.cbs.onprocessinginstruction){var t=this.getInstructionName(e);this.cbs.onprocessinginstruction("?"+t,"?"+e)}},e.prototype.oncomment=function(e){var t,n,i,r;this.updatePosition(4),null===(n=(t=this.cbs).oncomment)||void 0===n||n.call(t,e),null===(r=(i=this.cbs).oncommentend)||void 0===r||r.call(i)},e.prototype.oncdata=function(e){var t,n,i,r,s,o;this.updatePosition(1),this.options.xmlMode||this.options.recognizeCDATA?(null===(n=(t=this.cbs).oncdatastart)||void 0===n||n.call(t),null===(r=(i=this.cbs).ontext)||void 0===r||r.call(i,e),null===(o=(s=this.cbs).oncdataend)||void 0===o||o.call(s)):this.oncomment("[CDATA["+e+"]]")},e.prototype.onerror=function(e){var t,n;null===(n=(t=this.cbs).onerror)||void 0===n||n.call(t,e)},e.prototype.onend=function(){var e,t;if(this.cbs.onclosetag)for(var n=this.stack.length;n>0;this.cbs.onclosetag(this.stack[--n]));null===(t=(e=this.cbs).onend)||void 0===t||t.call(e)},e.prototype.reset=function(){var e,t,n,i;null===(t=(e=this.cbs).onreset)||void 0===t||t.call(e),this.tokenizer.reset(),this.tagname="",this.attribname="",this.attribs=null,this.stack=[],null===(i=(n=this.cbs).onparserinit)||void 0===i||i.call(n,this)},e.prototype.parseComplete=function(e){this.reset(),this.end(e)},e.prototype.write=function(e){this.tokenizer.write(e)},e.prototype.end=function(e){this.tokenizer.end(e)},e.prototype.pause=function(){this.tokenizer.pause()},e.prototype.resume=function(){this.tokenizer.resume()},e.prototype.parseChunk=function(e){this.write(e)},e.prototype.done=function(e){this.end(e)},e}();t.Parser=h},59636:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var r=i(n(70105)),s=i(n(72059)),o=i(n(62184)),a=i(n(81542));function l(e){return" "===e||"\n"===e||"\t"===e||"\f"===e||"\r"===e}function u(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}function d(e,t,n){var i=e.toLowerCase();return e===i?function(e,r){r===i?e._state=t:(e._state=n,e._index--)}:function(r,s){s===i||s===e?r._state=t:(r._state=n,r._index--)}}function c(e,t){var n=e.toLowerCase();return function(i,r){r===n||r===e?i._state=t:(i._state=3,i._index--)}}var h=d("C",24,16),p=d("D",25,16),g=d("A",26,16),f=d("T",27,16),m=d("A",28,16),v=c("R",35),b=c("I",36),_=c("P",37),A=c("T",38),y=d("R",40,1),w=d("I",41,1),C=d("P",42,1),E=d("T",43,1),x=c("Y",45),D=c("L",46),S=c("E",47),T=d("Y",49,1),M=d("L",50,1),k=d("E",51,1),j=c("I",54),B=c("T",55),O=c("L",56),I=c("E",57),R=d("I",58,1),P=d("T",59,1),L=d("L",60,1),N=d("E",61,1),F=d("#",63,64),z=d("X",66,65),U=function(){function e(e,t){var n;this._state=1,this.buffer="",this.sectionStart=0,this._index=0,this.bufferOffset=0,this.baseState=1,this.special=1,this.running=!0,this.ended=!1,this.cbs=t,this.xmlMode=!!(null==e?void 0:e.xmlMode),this.decodeEntities=null===(n=null==e?void 0:e.decodeEntities)||void 0===n||n}return e.prototype.reset=function(){this._state=1,this.buffer="",this.sectionStart=0,this._index=0,this.bufferOffset=0,this.baseState=1,this.special=1,this.running=!0,this.ended=!1},e.prototype.write=function(e){this.ended&&this.cbs.onerror(Error(".write() after done!")),this.buffer+=e,this.parse()},e.prototype.end=function(e){this.ended&&this.cbs.onerror(Error(".end() after done!")),e&&this.write(e),this.ended=!0,this.running&&this.finish()},e.prototype.pause=function(){this.running=!1},e.prototype.resume=function(){this.running=!0,this._indexthis.sectionStart&&this.cbs.ontext(this.getSection()),this._state=2,this.sectionStart=this._index):!this.decodeEntities||"&"!==e||1!==this.special&&4!==this.special||(this._index>this.sectionStart&&this.cbs.ontext(this.getSection()),this.baseState=1,this._state=62,this.sectionStart=this._index)},e.prototype.isTagStartChar=function(e){return u(e)||this.xmlMode&&!l(e)&&"/"!==e&&">"!==e},e.prototype.stateBeforeTagName=function(e){"/"===e?this._state=5:"<"===e?(this.cbs.ontext(this.getSection()),this.sectionStart=this._index):">"===e||1!==this.special||l(e)?this._state=1:"!"===e?(this._state=15,this.sectionStart=this._index+1):"?"===e?(this._state=17,this.sectionStart=this._index+1):this.isTagStartChar(e)?(this._state=this.xmlMode||"s"!==e&&"S"!==e?this.xmlMode||"t"!==e&&"T"!==e?3:52:32,this.sectionStart=this._index):this._state=1},e.prototype.stateInTagName=function(e){("/"===e||">"===e||l(e))&&(this.emitToken("onopentagname"),this._state=8,this._index--)},e.prototype.stateBeforeClosingTagName=function(e){l(e)||(">"===e?this._state=1:1!==this.special?4===this.special||"s"!==e&&"S"!==e?4!==this.special||"t"!==e&&"T"!==e?(this._state=1,this._index--):this._state=53:this._state=33:this.isTagStartChar(e)?(this._state=6,this.sectionStart=this._index):(this._state=20,this.sectionStart=this._index))},e.prototype.stateInClosingTagName=function(e){(">"===e||l(e))&&(this.emitToken("onclosetag"),this._state=7,this._index--)},e.prototype.stateAfterClosingTagName=function(e){">"===e&&(this._state=1,this.sectionStart=this._index+1)},e.prototype.stateBeforeAttributeName=function(e){">"===e?(this.cbs.onopentagend(),this._state=1,this.sectionStart=this._index+1):"/"===e?this._state=4:l(e)||(this._state=9,this.sectionStart=this._index)},e.prototype.stateInSelfClosingTag=function(e){">"===e?(this.cbs.onselfclosingtag(),this._state=1,this.sectionStart=this._index+1,this.special=1):l(e)||(this._state=8,this._index--)},e.prototype.stateInAttributeName=function(e){("="===e||"/"===e||">"===e||l(e))&&(this.cbs.onattribname(this.getSection()),this.sectionStart=-1,this._state=10,this._index--)},e.prototype.stateAfterAttributeName=function(e){"="===e?this._state=11:"/"===e||">"===e?(this.cbs.onattribend(void 0),this._state=8,this._index--):l(e)||(this.cbs.onattribend(void 0),this._state=9,this.sectionStart=this._index)},e.prototype.stateBeforeAttributeValue=function(e){'"'===e?(this._state=12,this.sectionStart=this._index+1):"'"===e?(this._state=13,this.sectionStart=this._index+1):l(e)||(this._state=14,this.sectionStart=this._index,this._index--)},e.prototype.handleInAttributeValue=function(e,t){e===t?(this.emitToken("onattribdata"),this.cbs.onattribend(t),this._state=8):this.decodeEntities&&"&"===e&&(this.emitToken("onattribdata"),this.baseState=this._state,this._state=62,this.sectionStart=this._index)},e.prototype.stateInAttributeValueDoubleQuotes=function(e){this.handleInAttributeValue(e,'"')},e.prototype.stateInAttributeValueSingleQuotes=function(e){this.handleInAttributeValue(e,"'")},e.prototype.stateInAttributeValueNoQuotes=function(e){l(e)||">"===e?(this.emitToken("onattribdata"),this.cbs.onattribend(null),this._state=8,this._index--):this.decodeEntities&&"&"===e&&(this.emitToken("onattribdata"),this.baseState=this._state,this._state=62,this.sectionStart=this._index)},e.prototype.stateBeforeDeclaration=function(e){this._state="["===e?23:"-"===e?18:16},e.prototype.stateInDeclaration=function(e){">"===e&&(this.cbs.ondeclaration(this.getSection()),this._state=1,this.sectionStart=this._index+1)},e.prototype.stateInProcessingInstruction=function(e){">"===e&&(this.cbs.onprocessinginstruction(this.getSection()),this._state=1,this.sectionStart=this._index+1)},e.prototype.stateBeforeComment=function(e){"-"===e?(this._state=19,this.sectionStart=this._index+1):this._state=16},e.prototype.stateInComment=function(e){"-"===e&&(this._state=21)},e.prototype.stateInSpecialComment=function(e){">"===e&&(this.cbs.oncomment(this.buffer.substring(this.sectionStart,this._index)),this._state=1,this.sectionStart=this._index+1)},e.prototype.stateAfterComment1=function(e){this._state="-"===e?22:19},e.prototype.stateAfterComment2=function(e){">"===e?(this.cbs.oncomment(this.buffer.substring(this.sectionStart,this._index-2)),this._state=1,this.sectionStart=this._index+1):"-"!==e&&(this._state=19)},e.prototype.stateBeforeCdata6=function(e){"["===e?(this._state=29,this.sectionStart=this._index+1):(this._state=16,this._index--)},e.prototype.stateInCdata=function(e){"]"===e&&(this._state=30)},e.prototype.stateAfterCdata1=function(e){this._state="]"===e?31:29},e.prototype.stateAfterCdata2=function(e){">"===e?(this.cbs.oncdata(this.buffer.substring(this.sectionStart,this._index-2)),this._state=1,this.sectionStart=this._index+1):"]"!==e&&(this._state=29)},e.prototype.stateBeforeSpecialS=function(e){"c"===e||"C"===e?this._state=34:"t"===e||"T"===e?this._state=44:(this._state=3,this._index--)},e.prototype.stateBeforeSpecialSEnd=function(e){2!==this.special||"c"!==e&&"C"!==e?3!==this.special||"t"!==e&&"T"!==e?this._state=1:this._state=48:this._state=39},e.prototype.stateBeforeSpecialLast=function(e,t){("/"===e||">"===e||l(e))&&(this.special=t),this._state=3,this._index--},e.prototype.stateAfterSpecialLast=function(e,t){">"===e||l(e)?(this.special=1,this._state=6,this.sectionStart=this._index-t,this._index--):this._state=1},e.prototype.parseFixedEntity=function(e){if(void 0===e&&(e=this.xmlMode?a.default:s.default),this.sectionStart+1=2;){var n=this.buffer.substr(e,t);if(Object.prototype.hasOwnProperty.call(o.default,n))return this.emitPartial(o.default[n]),void(this.sectionStart+=t+1);t--}},e.prototype.stateInNamedEntity=function(e){";"===e?(this.parseFixedEntity(),1===this.baseState&&this.sectionStart+1"9")&&!u(e)&&(this.xmlMode||this.sectionStart+1===this._index||(1!==this.baseState?"="!==e&&this.parseFixedEntity(o.default):this.parseLegacyEntity()),this._state=this.baseState,this._index--)},e.prototype.decodeNumericEntity=function(e,t,n){var i=this.sectionStart+e;if(i!==this._index){var s=this.buffer.substring(i,this._index),o=parseInt(s,t);this.emitPartial(r.default(o)),this.sectionStart=n?this._index+1:this._index}this._state=this.baseState},e.prototype.stateInNumericEntity=function(e){";"===e?this.decodeNumericEntity(2,10,!0):(e<"0"||e>"9")&&(this.xmlMode?this._state=this.baseState:this.decodeNumericEntity(2,10,!1),this._index--)},e.prototype.stateInHexEntity=function(e){";"===e?this.decodeNumericEntity(3,16,!0):(e<"a"||e>"f")&&(e<"A"||e>"F")&&(e<"0"||e>"9")&&(this.xmlMode?this._state=this.baseState:this.decodeNumericEntity(3,16,!1),this._index--)},e.prototype.cleanup=function(){this.sectionStart<0?(this.buffer="",this.bufferOffset+=this._index,this._index=0):this.running&&(1===this._state?(this.sectionStart!==this._index&&this.cbs.ontext(this.buffer.substr(this.sectionStart)),this.buffer="",this.bufferOffset+=this._index,this._index=0):this.sectionStart===this._index?(this.buffer="",this.bufferOffset+=this._index,this._index=0):(this.buffer=this.buffer.substr(this.sectionStart),this._index-=this.sectionStart,this.bufferOffset+=this.sectionStart),this.sectionStart=0)},e.prototype.parse=function(){for(;this._index0&&t-1 in e)}E.fn=E.prototype={jquery:C,constructor:E,length:0,toArray:function(){return a.call(this)},get:function(e){return null==e?a.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=E.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return E.each(this,e)},map:function(e){return this.pushStack(E.map(this,(function(t,n){return e.call(t,n,t)})))},slice:function(){return this.pushStack(a.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},even:function(){return this.pushStack(E.grep(this,(function(e,t){return(t+1)%2})))},odd:function(){return this.pushStack(E.grep(this,(function(e,t){return t%2})))},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(n>=0&&n+~]|"+L+")"+L+"*"),V=new RegExp(L+"|>"),q=new RegExp(z),G=new RegExp("^"+N+"$"),K={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N+"|[*])"),ATTR:new RegExp("^"+F),PSEUDO:new RegExp("^"+z),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+P+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,J=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,Q=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+L+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},ie=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,re=function(e,t){return t?"\0"===e?"�":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},se=function(){h()},oe=Ae((function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()}),{dir:"parentNode",next:"legend"});try{O.apply(k=I.call(y.childNodes),y.childNodes),k[y.childNodes.length].nodeType}catch(e){O={apply:k.length?function(e,t){B.apply(e,I.call(t))}:function(e,t){for(var n=e.length,i=0;e[n++]=t[i++];);e.length=n-1}}}function ae(e,t,i,r){var s,a,u,d,c,g,v,b=t&&t.ownerDocument,y=t?t.nodeType:9;if(i=i||[],"string"!=typeof e||!e||1!==y&&9!==y&&11!==y)return i;if(!r&&(h(t),t=t||p,f)){if(11!==y&&(c=Q.exec(e)))if(s=c[1]){if(9===y){if(!(u=t.getElementById(s)))return i;if(u.id===s)return i.push(u),i}else if(b&&(u=b.getElementById(s))&&_(t,u)&&u.id===s)return i.push(u),i}else{if(c[2])return O.apply(i,t.getElementsByTagName(e)),i;if((s=c[3])&&n.getElementsByClassName&&t.getElementsByClassName)return O.apply(i,t.getElementsByClassName(s)),i}if(n.qsa&&!S[e+" "]&&(!m||!m.test(e))&&(1!==y||"object"!==t.nodeName.toLowerCase())){if(v=e,b=t,1===y&&(V.test(e)||H.test(e))){for((b=ee.test(e)&&ve(t.parentNode)||t)===t&&n.scope||((d=t.getAttribute("id"))?d=d.replace(ie,re):t.setAttribute("id",d=A)),a=(g=o(e)).length;a--;)g[a]=(d?"#"+d:":scope")+" "+_e(g[a]);v=g.join(",")}try{return O.apply(i,b.querySelectorAll(v)),i}catch(t){S(e,!0)}finally{d===A&&t.removeAttribute("id")}}}return l(e.replace($,"$1"),t,i,r)}function le(){var e=[];return function t(n,r){return e.push(n+" ")>i.cacheLength&&delete t[e.shift()],t[n+" "]=r}}function ue(e){return e[A]=!0,e}function de(e){var t=p.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ce(e,t){for(var n=e.split("|"),r=n.length;r--;)i.attrHandle[n[r]]=t}function he(e,t){var n=t&&e,i=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(i)return i;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function pe(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}function ge(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function fe(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&oe(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function me(e){return ue((function(t){return t=+t,ue((function(n,i){for(var r,s=e([],n.length,t),o=s.length;o--;)n[r=s[o]]&&(n[r]=!(i[r]=n[r]))}))}))}function ve(e){return e&&void 0!==e.getElementsByTagName&&e}for(t in n=ae.support={},s=ae.isXML=function(e){var t=e&&e.namespaceURI,n=e&&(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},h=ae.setDocument=function(e){var t,r,o=e?e.ownerDocument||e:y;return o!=p&&9===o.nodeType&&o.documentElement?(g=(p=o).documentElement,f=!s(p),y!=p&&(r=p.defaultView)&&r.top!==r&&(r.addEventListener?r.addEventListener("unload",se,!1):r.attachEvent&&r.attachEvent("onunload",se)),n.scope=de((function(e){return g.appendChild(e).appendChild(p.createElement("div")),void 0!==e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length})),n.cssHas=de((function(){try{return p.querySelector(":has(*,:jqfake)"),!1}catch(e){return!0}})),n.attributes=de((function(e){return e.className="i",!e.getAttribute("className")})),n.getElementsByTagName=de((function(e){return e.appendChild(p.createComment("")),!e.getElementsByTagName("*").length})),n.getElementsByClassName=Z.test(p.getElementsByClassName),n.getById=de((function(e){return g.appendChild(e).id=A,!p.getElementsByName||!p.getElementsByName(A).length})),n.getById?(i.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},i.find.ID=function(e,t){if(void 0!==t.getElementById&&f){var n=t.getElementById(e);return n?[n]:[]}}):(i.filter.ID=function(e){var t=e.replace(te,ne);return function(e){var n=void 0!==e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},i.find.ID=function(e,t){if(void 0!==t.getElementById&&f){var n,i,r,s=t.getElementById(e);if(s){if((n=s.getAttributeNode("id"))&&n.value===e)return[s];for(r=t.getElementsByName(e),i=0;s=r[i++];)if((n=s.getAttributeNode("id"))&&n.value===e)return[s]}return[]}}),i.find.TAG=n.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,i=[],r=0,s=t.getElementsByTagName(e);if("*"===e){for(;n=s[r++];)1===n.nodeType&&i.push(n);return i}return s},i.find.CLASS=n.getElementsByClassName&&function(e,t){if(void 0!==t.getElementsByClassName&&f)return t.getElementsByClassName(e)},v=[],m=[],(n.qsa=Z.test(p.querySelectorAll))&&(de((function(e){var t;g.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&m.push("[*^$]="+L+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||m.push("\\["+L+"*(?:value|"+P+")"),e.querySelectorAll("[id~="+A+"-]").length||m.push("~="),(t=p.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||m.push("\\["+L+"*name"+L+"*="+L+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||m.push(":checked"),e.querySelectorAll("a#"+A+"+*").length||m.push(".#.+[+~]"),e.querySelectorAll("\\\f"),m.push("[\\r\\n\\f]")})),de((function(e){e.innerHTML="";var t=p.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&m.push("name"+L+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&m.push(":enabled",":disabled"),g.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&m.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),m.push(",.*:")}))),(n.matchesSelector=Z.test(b=g.matches||g.webkitMatchesSelector||g.mozMatchesSelector||g.oMatchesSelector||g.msMatchesSelector))&&de((function(e){n.disconnectedMatch=b.call(e,"*"),b.call(e,"[s!='']:x"),v.push("!=",z)})),n.cssHas||m.push(":has"),m=m.length&&new RegExp(m.join("|")),v=v.length&&new RegExp(v.join("|")),t=Z.test(g.compareDocumentPosition),_=t||Z.test(g.contains)?function(e,t){var n=9===e.nodeType&&e.documentElement||e,i=t&&t.parentNode;return e===i||!(!i||1!==i.nodeType||!(n.contains?n.contains(i):e.compareDocumentPosition&&16&e.compareDocumentPosition(i)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},T=t?function(e,t){if(e===t)return c=!0,0;var i=!e.compareDocumentPosition-!t.compareDocumentPosition;return i||(1&(i=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===i?e==p||e.ownerDocument==y&&_(y,e)?-1:t==p||t.ownerDocument==y&&_(y,t)?1:d?R(d,e)-R(d,t):0:4&i?-1:1)}:function(e,t){if(e===t)return c=!0,0;var n,i=0,r=e.parentNode,s=t.parentNode,o=[e],a=[t];if(!r||!s)return e==p?-1:t==p?1:r?-1:s?1:d?R(d,e)-R(d,t):0;if(r===s)return he(e,t);for(n=e;n=n.parentNode;)o.unshift(n);for(n=t;n=n.parentNode;)a.unshift(n);for(;o[i]===a[i];)i++;return i?he(o[i],a[i]):o[i]==y?-1:a[i]==y?1:0},p):p},ae.matches=function(e,t){return ae(e,null,null,t)},ae.matchesSelector=function(e,t){if(h(e),n.matchesSelector&&f&&!S[t+" "]&&(!v||!v.test(t))&&(!m||!m.test(t)))try{var i=b.call(e,t);if(i||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return i}catch(e){S(t,!0)}return ae(t,p,null,[e]).length>0},ae.contains=function(e,t){return(e.ownerDocument||e)!=p&&h(e),_(e,t)},ae.attr=function(e,t){(e.ownerDocument||e)!=p&&h(e);var r=i.attrHandle[t.toLowerCase()],s=r&&M.call(i.attrHandle,t.toLowerCase())?r(e,t,!f):void 0;return void 0!==s?s:n.attributes||!f?e.getAttribute(t):(s=e.getAttributeNode(t))&&s.specified?s.value:null},ae.escape=function(e){return(e+"").replace(ie,re)},ae.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},ae.uniqueSort=function(e){var t,i=[],r=0,s=0;if(c=!n.detectDuplicates,d=!n.sortStable&&e.slice(0),e.sort(T),c){for(;t=e[s++];)t===e[s]&&(r=i.push(s));for(;r--;)e.splice(i[r],1)}return d=null,e},r=ae.getText=function(e){var t,n="",i=0,s=e.nodeType;if(s){if(1===s||9===s||11===s){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=r(e)}else if(3===s||4===s)return e.nodeValue}else for(;t=e[i++];)n+=r(t);return n},i=ae.selectors={cacheLength:50,createPseudo:ue,match:K,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||ae.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&ae.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return K.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&q.test(n)&&(t=o(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+L+")"+e+"("+L+"|$)"))&&E(e,(function(e){return t.test("string"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute("class")||"")}))},ATTR:function(e,t,n){return function(i){var r=ae.attr(i,e);return null==r?"!="===t:!t||(r+="","="===t?r===n:"!="===t?r!==n:"^="===t?n&&0===r.indexOf(n):"*="===t?n&&r.indexOf(n)>-1:"$="===t?n&&r.slice(-n.length)===n:"~="===t?(" "+r.replace(U," ")+" ").indexOf(n)>-1:"|="===t&&(r===n||r.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,i,r){var s="nth"!==e.slice(0,3),o="last"!==e.slice(-4),a="of-type"===t;return 1===i&&0===r?function(e){return!!e.parentNode}:function(t,n,l){var u,d,c,h,p,g,f=s!==o?"nextSibling":"previousSibling",m=t.parentNode,v=a&&t.nodeName.toLowerCase(),b=!l&&!a,_=!1;if(m){if(s){for(;f;){for(h=t;h=h[f];)if(a?h.nodeName.toLowerCase()===v:1===h.nodeType)return!1;g=f="only"===e&&!g&&"nextSibling"}return!0}if(g=[o?m.firstChild:m.lastChild],o&&b){for(_=(p=(u=(d=(c=(h=m)[A]||(h[A]={}))[h.uniqueID]||(c[h.uniqueID]={}))[e]||[])[0]===w&&u[1])&&u[2],h=p&&m.childNodes[p];h=++p&&h&&h[f]||(_=p=0)||g.pop();)if(1===h.nodeType&&++_&&h===t){d[e]=[w,p,_];break}}else if(b&&(_=p=(u=(d=(c=(h=t)[A]||(h[A]={}))[h.uniqueID]||(c[h.uniqueID]={}))[e]||[])[0]===w&&u[1]),!1===_)for(;(h=++p&&h&&h[f]||(_=p=0)||g.pop())&&((a?h.nodeName.toLowerCase()!==v:1!==h.nodeType)||!++_||(b&&((d=(c=h[A]||(h[A]={}))[h.uniqueID]||(c[h.uniqueID]={}))[e]=[w,_]),h!==t)););return(_-=r)===i||_%i==0&&_/i>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||ae.error("unsupported pseudo: "+e);return r[A]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ue((function(e,n){for(var i,s=r(e,t),o=s.length;o--;)e[i=R(e,s[o])]=!(n[i]=s[o])})):function(e){return r(e,0,n)}):r}},pseudos:{not:ue((function(e){var t=[],n=[],i=a(e.replace($,"$1"));return i[A]?ue((function(e,t,n,r){for(var s,o=i(e,null,r,[]),a=e.length;a--;)(s=o[a])&&(e[a]=!(t[a]=s))})):function(e,r,s){return t[0]=e,i(t,null,s,n),t[0]=null,!n.pop()}})),has:ue((function(e){return function(t){return ae(e,t).length>0}})),contains:ue((function(e){return e=e.replace(te,ne),function(t){return(t.textContent||r(t)).indexOf(e)>-1}})),lang:ue((function(e){return G.test(e||"")||ae.error("unsupported lang: "+e),e=e.replace(te,ne).toLowerCase(),function(t){var n;do{if(n=f?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}})),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===g},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:fe(!1),disabled:fe(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return X.test(e.nodeName)},input:function(e){return J.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:me((function(){return[0]})),last:me((function(e,t){return[t-1]})),eq:me((function(e,t,n){return[n<0?n+t:n]})),even:me((function(e,t){for(var n=0;nt?t:n;--i>=0;)e.push(i);return e})),gt:me((function(e,t,n){for(var i=n<0?n+t:n;++i1?function(t,n,i){for(var r=e.length;r--;)if(!e[r](t,n,i))return!1;return!0}:e[0]}function we(e,t,n,i,r){for(var s,o=[],a=0,l=e.length,u=null!=t;a-1&&(s[u]=!(o[u]=c))}}else v=we(v===o?v.splice(g,v.length):v),r?r(null,o,v,l):O.apply(o,v)}))}function Ee(e){for(var t,n,r,s=e.length,o=i.relative[e[0].type],a=o||i.relative[" "],l=o?1:0,d=Ae((function(e){return e===t}),a,!0),c=Ae((function(e){return R(t,e)>-1}),a,!0),h=[function(e,n,i){var r=!o&&(i||n!==u)||((t=n).nodeType?d(e,n,i):c(e,n,i));return t=null,r}];l1&&ye(h),l>1&&_e(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace($,"$1"),n,l0,r=e.length>0,s=function(s,o,a,l,d){var c,g,m,v=0,b="0",_=s&&[],A=[],y=u,C=s||r&&i.find.TAG("*",d),E=w+=null==y?1:Math.random()||.1,x=C.length;for(d&&(u=o==p||o||d);b!==x&&null!=(c=C[b]);b++){if(r&&c){for(g=0,o||c.ownerDocument==p||(h(c),a=!f);m=e[g++];)if(m(c,o||p,a)){l.push(c);break}d&&(w=E)}n&&((c=!m&&c)&&v--,s&&_.push(c))}if(v+=b,n&&b!==v){for(g=0;m=t[g++];)m(_,A,o,a);if(s){if(v>0)for(;b--;)_[b]||A[b]||(A[b]=j.call(l));A=we(A)}O.apply(l,A),d&&!s&&A.length>0&&v+t.length>1&&ae.uniqueSort(l)}return d&&(w=E,u=y),_};return n?ue(s):s}(s,r)),a.selector=e}return a},l=ae.select=function(e,t,n,r){var s,l,u,d,c,h="function"==typeof e&&e,p=!r&&o(e=h.selector||e);if(n=n||[],1===p.length){if((l=p[0]=p[0].slice(0)).length>2&&"ID"===(u=l[0]).type&&9===t.nodeType&&f&&i.relative[l[1].type]){if(!(t=(i.find.ID(u.matches[0].replace(te,ne),t)||[])[0]))return n;h&&(t=t.parentNode),e=e.slice(l.shift().value.length)}for(s=K.needsContext.test(e)?0:l.length;s--&&(u=l[s],!i.relative[d=u.type]);)if((c=i.find[d])&&(r=c(u.matches[0].replace(te,ne),ee.test(l[0].type)&&ve(t.parentNode)||t))){if(l.splice(s,1),!(e=r.length&&_e(l)))return O.apply(n,r),n;break}}return(h||a(e,p))(r,t,!f,n,!t||ee.test(e)&&ve(t.parentNode)||t),n},n.sortStable=A.split("").sort(T).join("")===A,n.detectDuplicates=!!c,h(),n.sortDetached=de((function(e){return 1&e.compareDocumentPosition(p.createElement("fieldset"))})),de((function(e){return e.innerHTML="","#"===e.firstChild.getAttribute("href")}))||ce("type|href|height|width",(function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)})),n.attributes&&de((function(e){return e.innerHTML="",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")}))||ce("value",(function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue})),de((function(e){return null==e.getAttribute("disabled")}))||ce(P,(function(e,t,n){var i;if(!n)return!0===e[t]?t.toLowerCase():(i=e.getAttributeNode(t))&&i.specified?i.value:null})),ae}(i);E.find=D,E.expr=D.selectors,E.expr[":"]=E.expr.pseudos,E.uniqueSort=E.unique=D.uniqueSort,E.text=D.getText,E.isXMLDoc=D.isXML,E.contains=D.contains,E.escapeSelector=D.escape;var S=function(e,t,n){for(var i=[],r=void 0!==n;(e=e[t])&&9!==e.nodeType;)if(1===e.nodeType){if(r&&E(e).is(n))break;i.push(e)}return i},T=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},M=E.expr.match.needsContext;function k(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var j=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function B(e,t,n){return v(t)?E.grep(e,(function(e,i){return!!t.call(e,i,e)!==n})):t.nodeType?E.grep(e,(function(e){return e===t!==n})):"string"!=typeof t?E.grep(e,(function(e){return d.call(t,e)>-1!==n})):E.filter(t,e,n)}E.filter=function(e,t,n){var i=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===i.nodeType?E.find.matchesSelector(i,e)?[i]:[]:E.find.matches(e,E.grep(t,(function(e){return 1===e.nodeType})))},E.fn.extend({find:function(e){var t,n,i=this.length,r=this;if("string"!=typeof e)return this.pushStack(E(e).filter((function(){for(t=0;t1?E.uniqueSort(n):n},filter:function(e){return this.pushStack(B(this,e||[],!1))},not:function(e){return this.pushStack(B(this,e||[],!0))},is:function(e){return!!B(this,"string"==typeof e&&M.test(e)?E(e):e||[],!1).length}});var O,I=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(E.fn.init=function(e,t,n){var i,r;if(!e)return this;if(n=n||O,"string"==typeof e){if(!(i="<"===e[0]&&">"===e[e.length-1]&&e.length>=3?[null,e,null]:I.exec(e))||!i[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(i[1]){if(t=t instanceof E?t[0]:t,E.merge(this,E.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:_,!0)),j.test(i[1])&&E.isPlainObject(t))for(i in t)v(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}return(r=_.getElementById(i[2]))&&(this[0]=r,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):v(e)?void 0!==n.ready?n.ready(e):e(E):E.makeArray(e,this)}).prototype=E.fn,O=E(_);var R=/^(?:parents|prev(?:Until|All))/,P={children:!0,contents:!0,next:!0,prev:!0};function L(e,t){for(;(e=e[t])&&1!==e.nodeType;);return e}E.fn.extend({has:function(e){var t=E(e,this),n=t.length;return this.filter((function(){for(var e=0;e-1:1===n.nodeType&&E.find.matchesSelector(n,e))){s.push(n);break}return this.pushStack(s.length>1?E.uniqueSort(s):s)},index:function(e){return e?"string"==typeof e?d.call(E(e),this[0]):d.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(E.uniqueSort(E.merge(this.get(),E(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),E.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return S(e,"parentNode")},parentsUntil:function(e,t,n){return S(e,"parentNode",n)},next:function(e){return L(e,"nextSibling")},prev:function(e){return L(e,"previousSibling")},nextAll:function(e){return S(e,"nextSibling")},prevAll:function(e){return S(e,"previousSibling")},nextUntil:function(e,t,n){return S(e,"nextSibling",n)},prevUntil:function(e,t,n){return S(e,"previousSibling",n)},siblings:function(e){return T((e.parentNode||{}).firstChild,e)},children:function(e){return T(e.firstChild)},contents:function(e){return null!=e.contentDocument&&o(e.contentDocument)?e.contentDocument:(k(e,"template")&&(e=e.content||e),E.merge([],e.childNodes))}},(function(e,t){E.fn[e]=function(n,i){var r=E.map(this,t,n);return"Until"!==e.slice(-5)&&(i=n),i&&"string"==typeof i&&(r=E.filter(i,r)),this.length>1&&(P[e]||E.uniqueSort(r),R.test(e)&&r.reverse()),this.pushStack(r)}}));var N=/[^\x20\t\r\n\f]+/g;function F(e){return e}function z(e){throw e}function U(e,t,n,i){var r;try{e&&v(r=e.promise)?r.call(e).done(t).fail(n):e&&v(r=e.then)?r.call(e,t,n):t.apply(void 0,[e].slice(i))}catch(e){n.apply(void 0,[e])}}E.Callbacks=function(e){e="string"==typeof e?function(e){var t={};return E.each(e.match(N)||[],(function(e,n){t[n]=!0})),t}(e):E.extend({},e);var t,n,i,r,s=[],o=[],a=-1,l=function(){for(r=r||e.once,i=t=!0;o.length;a=-1)for(n=o.shift();++a-1;)s.splice(n,1),n<=a&&a--})),this},has:function(e){return e?E.inArray(e,s)>-1:s.length>0},empty:function(){return s&&(s=[]),this},disable:function(){return r=o=[],s=n="",this},disabled:function(){return!s},lock:function(){return r=o=[],n||t||(s=n=""),this},locked:function(){return!!r},fireWith:function(e,n){return r||(n=[e,(n=n||[]).slice?n.slice():n],o.push(n),t||l()),this},fire:function(){return u.fireWith(this,arguments),this},fired:function(){return!!i}};return u},E.extend({Deferred:function(e){var t=[["notify","progress",E.Callbacks("memory"),E.Callbacks("memory"),2],["resolve","done",E.Callbacks("once memory"),E.Callbacks("once memory"),0,"resolved"],["reject","fail",E.Callbacks("once memory"),E.Callbacks("once memory"),1,"rejected"]],n="pending",r={state:function(){return n},always:function(){return s.done(arguments).fail(arguments),this},catch:function(e){return r.then(null,e)},pipe:function(){var e=arguments;return E.Deferred((function(n){E.each(t,(function(t,i){var r=v(e[i[4]])&&e[i[4]];s[i[1]]((function(){var e=r&&r.apply(this,arguments);e&&v(e.promise)?e.promise().progress(n.notify).done(n.resolve).fail(n.reject):n[i[0]+"With"](this,r?[e]:arguments)}))})),e=null})).promise()},then:function(e,n,r){var s=0;function o(e,t,n,r){return function(){var a=this,l=arguments,u=function(){var i,u;if(!(e=s&&(n!==z&&(a=void 0,l=[i]),t.rejectWith(a,l))}};e?d():(E.Deferred.getStackHook&&(d.stackTrace=E.Deferred.getStackHook()),i.setTimeout(d))}}return E.Deferred((function(i){t[0][3].add(o(0,i,v(r)?r:F,i.notifyWith)),t[1][3].add(o(0,i,v(e)?e:F)),t[2][3].add(o(0,i,v(n)?n:z))})).promise()},promise:function(e){return null!=e?E.extend(e,r):r}},s={};return E.each(t,(function(e,i){var o=i[2],a=i[5];r[i[1]]=o.add,a&&o.add((function(){n=a}),t[3-e][2].disable,t[3-e][3].disable,t[0][2].lock,t[0][3].lock),o.add(i[3].fire),s[i[0]]=function(){return s[i[0]+"With"](this===s?void 0:this,arguments),this},s[i[0]+"With"]=o.fireWith})),r.promise(s),e&&e.call(s,s),s},when:function(e){var t=arguments.length,n=t,i=Array(n),r=a.call(arguments),s=E.Deferred(),o=function(e){return function(n){i[e]=this,r[e]=arguments.length>1?a.call(arguments):n,--t||s.resolveWith(i,r)}};if(t<=1&&(U(e,s.done(o(n)).resolve,s.reject,!t),"pending"===s.state()||v(r[n]&&r[n].then)))return s.then();for(;n--;)U(r[n],o(n),s.reject);return s.promise()}});var $=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;E.Deferred.exceptionHook=function(e,t){i.console&&i.console.warn&&e&&$.test(e.name)&&i.console.warn("jQuery.Deferred exception: "+e.message,e.stack,t)},E.readyException=function(e){i.setTimeout((function(){throw e}))};var W=E.Deferred();function H(){_.removeEventListener("DOMContentLoaded",H),i.removeEventListener("load",H),E.ready()}E.fn.ready=function(e){return W.then(e).catch((function(e){E.readyException(e)})),this},E.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--E.readyWait:E.isReady)||(E.isReady=!0,!0!==e&&--E.readyWait>0||W.resolveWith(_,[E]))}}),E.ready.then=W.then,"complete"===_.readyState||"loading"!==_.readyState&&!_.documentElement.doScroll?i.setTimeout(E.ready):(_.addEventListener("DOMContentLoaded",H),i.addEventListener("load",H));var V=function(e,t,n,i,r,s,o){var a=0,l=e.length,u=null==n;if("object"===w(n))for(a in r=!0,n)V(e,t,a,n[a],!0,s,o);else if(void 0!==i&&(r=!0,v(i)||(o=!0),u&&(o?(t.call(e,i),t=null):(u=t,t=function(e,t,n){return u.call(E(e),n)})),t))for(;a1,null,!0)},removeData:function(e){return this.each((function(){Q.remove(this,e)}))}}),E.extend({queue:function(e,t,n){var i;if(e)return t=(t||"fx")+"queue",i=Z.get(e,t),n&&(!i||Array.isArray(n)?i=Z.access(e,t,E.makeArray(n)):i.push(n)),i||[]},dequeue:function(e,t){t=t||"fx";var n=E.queue(e,t),i=n.length,r=n.shift(),s=E._queueHooks(e,t);"inprogress"===r&&(r=n.shift(),i--),r&&("fx"===t&&n.unshift("inprogress"),delete s.stop,r.call(e,(function(){E.dequeue(e,t)}),s)),!i&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return Z.get(e,n)||Z.access(e,n,{empty:E.Callbacks("once memory").add((function(){Z.remove(e,[t+"queue",n])}))})}}),E.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length\x20\t\r\n\f]*)/i,be=/^$|^module$|\/(?:java|ecma)script/i;ge=_.createDocumentFragment().appendChild(_.createElement("div")),(fe=_.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ge.appendChild(fe),m.checkClone=ge.cloneNode(!0).cloneNode(!0).lastChild.checked,ge.innerHTML="",m.noCloneChecked=!!ge.cloneNode(!0).lastChild.defaultValue,ge.innerHTML="",m.option=!!ge.lastChild;var _e={thead:[1,"","
    "],col:[2,"","
    "],tr:[2,"","
    "],td:[3,"","
    "],_default:[0,"",""]};function Ae(e,t){var n;return n=void 0!==e.getElementsByTagName?e.getElementsByTagName(t||"*"):void 0!==e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&k(e,t)?E.merge([e],n):n}function ye(e,t){for(var n=0,i=e.length;n",""]);var we=/<|&#?\w+;/;function Ce(e,t,n,i,r){for(var s,o,a,l,u,d,c=t.createDocumentFragment(),h=[],p=0,g=e.length;p-1)r&&r.push(s);else if(u=ae(s),o=Ae(c.appendChild(s),"script"),u&&ye(o),n)for(d=0;s=o[d++];)be.test(s.type||"")&&n.push(s);return c}var Ee=/^([^.]*)(?:\.(.+)|)/;function xe(){return!0}function De(){return!1}function Se(e,t){return e===function(){try{return _.activeElement}catch(e){}}()==("focus"===t)}function Te(e,t,n,i,r,s){var o,a;if("object"==typeof t){for(a in"string"!=typeof n&&(i=i||n,n=void 0),t)Te(e,a,n,i,t[a],s);return e}if(null==i&&null==r?(r=n,i=n=void 0):null==r&&("string"==typeof n?(r=i,i=void 0):(r=i,i=n,n=void 0)),!1===r)r=De;else if(!r)return e;return 1===s&&(o=r,r=function(e){return E().off(e),o.apply(this,arguments)},r.guid=o.guid||(o.guid=E.guid++)),e.each((function(){E.event.add(this,t,r,i,n)}))}function Me(e,t,n){n?(Z.set(e,t,!1),E.event.add(e,t,{namespace:!1,handler:function(e){var i,r,s=Z.get(this,t);if(1&e.isTrigger&&this[t]){if(s.length)(E.event.special[t]||{}).delegateType&&e.stopPropagation();else if(s=a.call(arguments),Z.set(this,t,s),i=n(this,t),this[t](),s!==(r=Z.get(this,t))||i?Z.set(this,t,!1):r={},s!==r)return e.stopImmediatePropagation(),e.preventDefault(),r&&r.value}else s.length&&(Z.set(this,t,{value:E.event.trigger(E.extend(s[0],E.Event.prototype),s.slice(1),this)}),e.stopImmediatePropagation())}})):void 0===Z.get(e,t)&&E.event.add(e,t,xe)}E.event={global:{},add:function(e,t,n,i,r){var s,o,a,l,u,d,c,h,p,g,f,m=Z.get(e);if(J(e))for(n.handler&&(n=(s=n).handler,r=s.selector),r&&E.find.matchesSelector(oe,r),n.guid||(n.guid=E.guid++),(l=m.events)||(l=m.events=Object.create(null)),(o=m.handle)||(o=m.handle=function(t){return void 0!==E&&E.event.triggered!==t.type?E.event.dispatch.apply(e,arguments):void 0}),u=(t=(t||"").match(N)||[""]).length;u--;)p=f=(a=Ee.exec(t[u])||[])[1],g=(a[2]||"").split(".").sort(),p&&(c=E.event.special[p]||{},p=(r?c.delegateType:c.bindType)||p,c=E.event.special[p]||{},d=E.extend({type:p,origType:f,data:i,handler:n,guid:n.guid,selector:r,needsContext:r&&E.expr.match.needsContext.test(r),namespace:g.join(".")},s),(h=l[p])||((h=l[p]=[]).delegateCount=0,c.setup&&!1!==c.setup.call(e,i,g,o)||e.addEventListener&&e.addEventListener(p,o)),c.add&&(c.add.call(e,d),d.handler.guid||(d.handler.guid=n.guid)),r?h.splice(h.delegateCount++,0,d):h.push(d),E.event.global[p]=!0)},remove:function(e,t,n,i,r){var s,o,a,l,u,d,c,h,p,g,f,m=Z.hasData(e)&&Z.get(e);if(m&&(l=m.events)){for(u=(t=(t||"").match(N)||[""]).length;u--;)if(p=f=(a=Ee.exec(t[u])||[])[1],g=(a[2]||"").split(".").sort(),p){for(c=E.event.special[p]||{},h=l[p=(i?c.delegateType:c.bindType)||p]||[],a=a[2]&&new RegExp("(^|\\.)"+g.join("\\.(?:.*\\.|)")+"(\\.|$)"),o=s=h.length;s--;)d=h[s],!r&&f!==d.origType||n&&n.guid!==d.guid||a&&!a.test(d.namespace)||i&&i!==d.selector&&("**"!==i||!d.selector)||(h.splice(s,1),d.selector&&h.delegateCount--,c.remove&&c.remove.call(e,d));o&&!h.length&&(c.teardown&&!1!==c.teardown.call(e,g,m.handle)||E.removeEvent(e,p,m.handle),delete l[p])}else for(p in l)E.event.remove(e,p+t[u],n,i,!0);E.isEmptyObject(l)&&Z.remove(e,"handle events")}},dispatch:function(e){var t,n,i,r,s,o,a=new Array(arguments.length),l=E.event.fix(e),u=(Z.get(this,"events")||Object.create(null))[l.type]||[],d=E.event.special[l.type]||{};for(a[0]=l,t=1;t=1))for(;u!==this;u=u.parentNode||this)if(1===u.nodeType&&("click"!==e.type||!0!==u.disabled)){for(s=[],o={},n=0;n-1:E.find(r,this,null,[u]).length),o[r]&&s.push(i);s.length&&a.push({elem:u,handlers:s})}return u=this,l\s*$/g;function Oe(e,t){return k(e,"table")&&k(11!==t.nodeType?t:t.firstChild,"tr")&&E(e).children("tbody")[0]||e}function Ie(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Re(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Pe(e,t){var n,i,r,s,o,a;if(1===t.nodeType){if(Z.hasData(e)&&(a=Z.get(e).events))for(r in Z.remove(t,"handle events"),a)for(n=0,i=a[r].length;n1&&"string"==typeof g&&!m.checkClone&&je.test(g))return e.each((function(r){var s=e.eq(r);f&&(t[0]=g.call(this,r,s.html())),Ne(s,t,n,i)}));if(h&&(s=(r=Ce(t,e[0].ownerDocument,!1,e,i)).firstChild,1===r.childNodes.length&&(r=s),s||i)){for(a=(o=E.map(Ae(r,"script"),Ie)).length;c0&&ye(o,!l&&Ae(e,"script")),a},cleanData:function(e){for(var t,n,i,r=E.event.special,s=0;void 0!==(n=e[s]);s++)if(J(n)){if(t=n[Z.expando]){if(t.events)for(i in t.events)r[i]?E.event.remove(n,i):E.removeEvent(n,i,t.handle);n[Z.expando]=void 0}n[Q.expando]&&(n[Q.expando]=void 0)}}}),E.fn.extend({detach:function(e){return Fe(this,e,!0)},remove:function(e){return Fe(this,e)},text:function(e){return V(this,(function(e){return void 0===e?E.text(this):this.empty().each((function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)}))}),null,e,arguments.length)},append:function(){return Ne(this,arguments,(function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||Oe(this,e).appendChild(e)}))},prepend:function(){return Ne(this,arguments,(function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Oe(this,e);t.insertBefore(e,t.firstChild)}}))},before:function(){return Ne(this,arguments,(function(e){this.parentNode&&this.parentNode.insertBefore(e,this)}))},after:function(){return Ne(this,arguments,(function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)}))},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(E.cleanData(Ae(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map((function(){return E.clone(this,e,t)}))},html:function(e){return V(this,(function(e){var t=this[0]||{},n=0,i=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!ke.test(e)&&!_e[(ve.exec(e)||["",""])[1].toLowerCase()]){e=E.htmlPrefilter(e);try{for(;n=0&&(l+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-s-l-a-.5))||0),l}function rt(e,t,n){var i=$e(e),r=(!m.boxSizingReliable()||n)&&"border-box"===E.css(e,"boxSizing",!1,i),s=r,o=Ge(e,t,i),a="offset"+t[0].toUpperCase()+t.slice(1);if(ze.test(o)){if(!n)return o;o="auto"}return(!m.boxSizingReliable()&&r||!m.reliableTrDimensions()&&k(e,"tr")||"auto"===o||!parseFloat(o)&&"inline"===E.css(e,"display",!1,i))&&e.getClientRects().length&&(r="border-box"===E.css(e,"boxSizing",!1,i),(s=a in e)&&(o=e[a])),(o=parseFloat(o)||0)+it(e,t,n||(r?"border":"content"),s,i,o)+"px"}function st(e,t,n,i,r){return new st.prototype.init(e,t,n,i,r)}E.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Ge(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,gridArea:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnStart:!0,gridRow:!0,gridRowEnd:!0,gridRowStart:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var r,s,o,a=Y(t),l=Ue.test(t),u=e.style;if(l||(t=Ze(a)),o=E.cssHooks[t]||E.cssHooks[a],void 0===n)return o&&"get"in o&&void 0!==(r=o.get(e,!1,i))?r:u[t];"string"==(s=typeof n)&&(r=re.exec(n))&&r[1]&&(n=de(e,t,r),s="number"),null!=n&&n==n&&("number"!==s||l||(n+=r&&r[3]||(E.cssNumber[a]?"":"px")),m.clearCloneStyle||""!==n||0!==t.indexOf("background")||(u[t]="inherit"),o&&"set"in o&&void 0===(n=o.set(e,n,i))||(l?u.setProperty(t,n):u[t]=n))}},css:function(e,t,n,i){var r,s,o,a=Y(t);return Ue.test(t)||(t=Ze(a)),(o=E.cssHooks[t]||E.cssHooks[a])&&"get"in o&&(r=o.get(e,!0,n)),void 0===r&&(r=Ge(e,t,i)),"normal"===r&&t in tt&&(r=tt[t]),""===n||n?(s=parseFloat(r),!0===n||isFinite(s)?s||0:r):r}}),E.each(["height","width"],(function(e,t){E.cssHooks[t]={get:function(e,n,i){if(n)return!Qe.test(E.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?rt(e,t,i):We(e,et,(function(){return rt(e,t,i)}))},set:function(e,n,i){var r,s=$e(e),o=!m.scrollboxSize()&&"absolute"===s.position,a=(o||i)&&"border-box"===E.css(e,"boxSizing",!1,s),l=i?it(e,t,i,a,s):0;return a&&o&&(l-=Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-parseFloat(s[t])-it(e,t,"border",!1,s)-.5)),l&&(r=re.exec(n))&&"px"!==(r[3]||"px")&&(e.style[t]=n,n=E.css(e,t)),nt(0,n,l)}}})),E.cssHooks.marginLeft=Ke(m.reliableMarginLeft,(function(e,t){if(t)return(parseFloat(Ge(e,"marginLeft"))||e.getBoundingClientRect().left-We(e,{marginLeft:0},(function(){return e.getBoundingClientRect().left})))+"px"})),E.each({margin:"",padding:"",border:"Width"},(function(e,t){E.cssHooks[e+t]={expand:function(n){for(var i=0,r={},s="string"==typeof n?n.split(" "):[n];i<4;i++)r[e+se[i]+t]=s[i]||s[i-2]||s[0];return r}},"margin"!==e&&(E.cssHooks[e+t].set=nt)})),E.fn.extend({css:function(e,t){return V(this,(function(e,t,n){var i,r,s={},o=0;if(Array.isArray(t)){for(i=$e(e),r=t.length;o1)}}),E.Tween=st,st.prototype={constructor:st,init:function(e,t,n,i,r,s){this.elem=e,this.prop=n,this.easing=r||E.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=i,this.unit=s||(E.cssNumber[n]?"":"px")},cur:function(){var e=st.propHooks[this.prop];return e&&e.get?e.get(this):st.propHooks._default.get(this)},run:function(e){var t,n=st.propHooks[this.prop];return this.options.duration?this.pos=t=E.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):st.propHooks._default.set(this),this}},st.prototype.init.prototype=st.prototype,st.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=E.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){E.fx.step[e.prop]?E.fx.step[e.prop](e):1!==e.elem.nodeType||!E.cssHooks[e.prop]&&null==e.elem.style[Ze(e.prop)]?e.elem[e.prop]=e.now:E.style(e.elem,e.prop,e.now+e.unit)}}},st.propHooks.scrollTop=st.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},E.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},E.fx=st.prototype.init,E.fx.step={};var ot,at,lt=/^(?:toggle|show|hide)$/,ut=/queueHooks$/;function dt(){at&&(!1===_.hidden&&i.requestAnimationFrame?i.requestAnimationFrame(dt):i.setTimeout(dt,E.fx.interval),E.fx.tick())}function ct(){return i.setTimeout((function(){ot=void 0})),ot=Date.now()}function ht(e,t){var n,i=0,r={height:e};for(t=t?1:0;i<4;i+=2-t)r["margin"+(n=se[i])]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function pt(e,t,n){for(var i,r=(gt.tweeners[t]||[]).concat(gt.tweeners["*"]),s=0,o=r.length;s1)},removeAttr:function(e){return this.each((function(){E.removeAttr(this,e)}))}}),E.extend({attr:function(e,t,n){var i,r,s=e.nodeType;if(3!==s&&8!==s&&2!==s)return void 0===e.getAttribute?E.prop(e,t,n):(1===s&&E.isXMLDoc(e)||(r=E.attrHooks[t.toLowerCase()]||(E.expr.match.bool.test(t)?ft:void 0)),void 0!==n?null===n?void E.removeAttr(e,t):r&&"set"in r&&void 0!==(i=r.set(e,n,t))?i:(e.setAttribute(t,n+""),n):r&&"get"in r&&null!==(i=r.get(e,t))?i:null==(i=E.find.attr(e,t))?void 0:i)},attrHooks:{type:{set:function(e,t){if(!m.radioValue&&"radio"===t&&k(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,i=0,r=t&&t.match(N);if(r&&1===e.nodeType)for(;n=r[i++];)e.removeAttribute(n)}}),ft={set:function(e,t,n){return!1===t?E.removeAttr(e,n):e.setAttribute(n,n),n}},E.each(E.expr.match.bool.source.match(/\w+/g),(function(e,t){var n=mt[t]||E.find.attr;mt[t]=function(e,t,i){var r,s,o=t.toLowerCase();return i||(s=mt[o],mt[o]=r,r=null!=n(e,t,i)?o:null,mt[o]=s),r}}));var vt=/^(?:input|select|textarea|button)$/i,bt=/^(?:a|area)$/i;function _t(e){return(e.match(N)||[]).join(" ")}function At(e){return e.getAttribute&&e.getAttribute("class")||""}function yt(e){return Array.isArray(e)?e:"string"==typeof e&&e.match(N)||[]}E.fn.extend({prop:function(e,t){return V(this,E.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each((function(){delete this[E.propFix[e]||e]}))}}),E.extend({prop:function(e,t,n){var i,r,s=e.nodeType;if(3!==s&&8!==s&&2!==s)return 1===s&&E.isXMLDoc(e)||(t=E.propFix[t]||t,r=E.propHooks[t]),void 0!==n?r&&"set"in r&&void 0!==(i=r.set(e,n,t))?i:e[t]=n:r&&"get"in r&&null!==(i=r.get(e,t))?i:e[t]},propHooks:{tabIndex:{get:function(e){var t=E.find.attr(e,"tabindex");return t?parseInt(t,10):vt.test(e.nodeName)||bt.test(e.nodeName)&&e.href?0:-1}}},propFix:{for:"htmlFor",class:"className"}}),m.optSelected||(E.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),E.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],(function(){E.propFix[this.toLowerCase()]=this})),E.fn.extend({addClass:function(e){var t,n,i,r,s,o;return v(e)?this.each((function(t){E(this).addClass(e.call(this,t,At(this)))})):(t=yt(e)).length?this.each((function(){if(i=At(this),n=1===this.nodeType&&" "+_t(i)+" "){for(s=0;s-1;)n=n.replace(" "+r+" "," ");o=_t(n),i!==o&&this.setAttribute("class",o)}})):this:this.attr("class","")},toggleClass:function(e,t){var n,i,r,s,o=typeof e,a="string"===o||Array.isArray(e);return v(e)?this.each((function(n){E(this).toggleClass(e.call(this,n,At(this),t),t)})):"boolean"==typeof t&&a?t?this.addClass(e):this.removeClass(e):(n=yt(e),this.each((function(){if(a)for(s=E(this),r=0;r-1)return!0;return!1}});var wt=/\r/g;E.fn.extend({val:function(e){var t,n,i,r=this[0];return arguments.length?(i=v(e),this.each((function(n){var r;1===this.nodeType&&(null==(r=i?e.call(this,n,E(this).val()):e)?r="":"number"==typeof r?r+="":Array.isArray(r)&&(r=E.map(r,(function(e){return null==e?"":e+""}))),(t=E.valHooks[this.type]||E.valHooks[this.nodeName.toLowerCase()])&&"set"in t&&void 0!==t.set(this,r,"value")||(this.value=r))}))):r?(t=E.valHooks[r.type]||E.valHooks[r.nodeName.toLowerCase()])&&"get"in t&&void 0!==(n=t.get(r,"value"))?n:"string"==typeof(n=r.value)?n.replace(wt,""):null==n?"":n:void 0}}),E.extend({valHooks:{option:{get:function(e){var t=E.find.attr(e,"value");return null!=t?t:_t(E.text(e))}},select:{get:function(e){var t,n,i,r=e.options,s=e.selectedIndex,o="select-one"===e.type,a=o?null:[],l=o?s+1:r.length;for(i=s<0?l:o?s:0;i-1)&&(n=!0);return n||(e.selectedIndex=-1),s}}}}),E.each(["radio","checkbox"],(function(){E.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=E.inArray(E(e).val(),t)>-1}},m.checkOn||(E.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})})),m.focusin="onfocusin"in i;var Ct=/^(?:focusinfocus|focusoutblur)$/,Et=function(e){e.stopPropagation()};E.extend(E.event,{trigger:function(e,t,n,r){var s,o,a,l,u,d,c,h,g=[n||_],f=p.call(e,"type")?e.type:e,m=p.call(e,"namespace")?e.namespace.split("."):[];if(o=h=a=n=n||_,3!==n.nodeType&&8!==n.nodeType&&!Ct.test(f+E.event.triggered)&&(f.indexOf(".")>-1&&(m=f.split("."),f=m.shift(),m.sort()),u=f.indexOf(":")<0&&"on"+f,(e=e[E.expando]?e:new E.Event(f,"object"==typeof e&&e)).isTrigger=r?2:3,e.namespace=m.join("."),e.rnamespace=e.namespace?new RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=n),t=null==t?[e]:E.makeArray(t,[e]),c=E.event.special[f]||{},r||!c.trigger||!1!==c.trigger.apply(n,t))){if(!r&&!c.noBubble&&!b(n)){for(l=c.delegateType||f,Ct.test(l+f)||(o=o.parentNode);o;o=o.parentNode)g.push(o),a=o;a===(n.ownerDocument||_)&&g.push(a.defaultView||a.parentWindow||i)}for(s=0;(o=g[s++])&&!e.isPropagationStopped();)h=o,e.type=s>1?l:c.bindType||f,(d=(Z.get(o,"events")||Object.create(null))[e.type]&&Z.get(o,"handle"))&&d.apply(o,t),(d=u&&o[u])&&d.apply&&J(o)&&(e.result=d.apply(o,t),!1===e.result&&e.preventDefault());return e.type=f,r||e.isDefaultPrevented()||c._default&&!1!==c._default.apply(g.pop(),t)||!J(n)||u&&v(n[f])&&!b(n)&&((a=n[u])&&(n[u]=null),E.event.triggered=f,e.isPropagationStopped()&&h.addEventListener(f,Et),n[f](),e.isPropagationStopped()&&h.removeEventListener(f,Et),E.event.triggered=void 0,a&&(n[u]=a)),e.result}},simulate:function(e,t,n){var i=E.extend(new E.Event,n,{type:e,isSimulated:!0});E.event.trigger(i,null,t)}}),E.fn.extend({trigger:function(e,t){return this.each((function(){E.event.trigger(e,t,this)}))},triggerHandler:function(e,t){var n=this[0];if(n)return E.event.trigger(e,t,n,!0)}}),m.focusin||E.each({focus:"focusin",blur:"focusout"},(function(e,t){var n=function(e){E.event.simulate(t,e.target,E.event.fix(e))};E.event.special[t]={setup:function(){var i=this.ownerDocument||this.document||this,r=Z.access(i,t);r||i.addEventListener(e,n,!0),Z.access(i,t,(r||0)+1)},teardown:function(){var i=this.ownerDocument||this.document||this,r=Z.access(i,t)-1;r?Z.access(i,t,r):(i.removeEventListener(e,n,!0),Z.remove(i,t))}}}));var xt=i.location,Dt={guid:Date.now()},St=/\?/;E.parseXML=function(e){var t,n;if(!e||"string"!=typeof e)return null;try{t=(new i.DOMParser).parseFromString(e,"text/xml")}catch(e){}return n=t&&t.getElementsByTagName("parsererror")[0],t&&!n||E.error("Invalid XML: "+(n?E.map(n.childNodes,(function(e){return e.textContent})).join("\n"):e)),t};var Tt=/\[\]$/,Mt=/\r?\n/g,kt=/^(?:submit|button|image|reset|file)$/i,jt=/^(?:input|select|textarea|keygen)/i;function Bt(e,t,n,i){var r;if(Array.isArray(t))E.each(t,(function(t,r){n||Tt.test(e)?i(e,r):Bt(e+"["+("object"==typeof r&&null!=r?t:"")+"]",r,n,i)}));else if(n||"object"!==w(t))i(e,t);else for(r in t)Bt(e+"["+r+"]",t[r],n,i)}E.param=function(e,t){var n,i=[],r=function(e,t){var n=v(t)?t():t;i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(null==e)return"";if(Array.isArray(e)||e.jquery&&!E.isPlainObject(e))E.each(e,(function(){r(this.name,this.value)}));else for(n in e)Bt(n,e[n],t,r);return i.join("&")},E.fn.extend({serialize:function(){return E.param(this.serializeArray())},serializeArray:function(){return this.map((function(){var e=E.prop(this,"elements");return e?E.makeArray(e):this})).filter((function(){var e=this.type;return this.name&&!E(this).is(":disabled")&&jt.test(this.nodeName)&&!kt.test(e)&&(this.checked||!me.test(e))})).map((function(e,t){var n=E(this).val();return null==n?null:Array.isArray(n)?E.map(n,(function(e){return{name:t.name,value:e.replace(Mt,"\r\n")}})):{name:t.name,value:n.replace(Mt,"\r\n")}})).get()}});var Ot=/%20/g,It=/#.*$/,Rt=/([?&])_=[^&]*/,Pt=/^(.*?):[ \t]*([^\r\n]*)$/gm,Lt=/^(?:GET|HEAD)$/,Nt=/^\/\//,Ft={},zt={},Ut="*/".concat("*"),$t=_.createElement("a");function Wt(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var i,r=0,s=t.toLowerCase().match(N)||[];if(v(n))for(;i=s[r++];)"+"===i[0]?(i=i.slice(1)||"*",(e[i]=e[i]||[]).unshift(n)):(e[i]=e[i]||[]).push(n)}}function Ht(e,t,n,i){var r={},s=e===zt;function o(a){var l;return r[a]=!0,E.each(e[a]||[],(function(e,a){var u=a(t,n,i);return"string"!=typeof u||s||r[u]?s?!(l=u):void 0:(t.dataTypes.unshift(u),o(u),!1)})),l}return o(t.dataTypes[0])||!r["*"]&&o("*")}function Vt(e,t){var n,i,r=E.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((r[n]?e:i||(i={}))[n]=t[n]);return i&&E.extend(!0,e,i),e}$t.href=xt.href,E.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:xt.href,type:"GET",isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(xt.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Ut,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":E.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Vt(Vt(e,E.ajaxSettings),t):Vt(E.ajaxSettings,e)},ajaxPrefilter:Wt(Ft),ajaxTransport:Wt(zt),ajax:function(e,t){"object"==typeof e&&(t=e,e=void 0),t=t||{};var n,r,s,o,a,l,u,d,c,h,p=E.ajaxSetup({},t),g=p.context||p,f=p.context&&(g.nodeType||g.jquery)?E(g):E.event,m=E.Deferred(),v=E.Callbacks("once memory"),b=p.statusCode||{},A={},y={},w="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(u){if(!o)for(o={};t=Pt.exec(s);)o[t[1].toLowerCase()+" "]=(o[t[1].toLowerCase()+" "]||[]).concat(t[2]);t=o[e.toLowerCase()+" "]}return null==t?null:t.join(", ")},getAllResponseHeaders:function(){return u?s:null},setRequestHeader:function(e,t){return null==u&&(e=y[e.toLowerCase()]=y[e.toLowerCase()]||e,A[e]=t),this},overrideMimeType:function(e){return null==u&&(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(u)C.always(e[C.status]);else for(t in e)b[t]=[b[t],e[t]];return this},abort:function(e){var t=e||w;return n&&n.abort(t),x(0,t),this}};if(m.promise(C),p.url=((e||p.url||xt.href)+"").replace(Nt,xt.protocol+"//"),p.type=t.method||t.type||p.method||p.type,p.dataTypes=(p.dataType||"*").toLowerCase().match(N)||[""],null==p.crossDomain){l=_.createElement("a");try{l.href=p.url,l.href=l.href,p.crossDomain=$t.protocol+"//"+$t.host!=l.protocol+"//"+l.host}catch(e){p.crossDomain=!0}}if(p.data&&p.processData&&"string"!=typeof p.data&&(p.data=E.param(p.data,p.traditional)),Ht(Ft,p,t,C),u)return C;for(c in(d=E.event&&p.global)&&0==E.active++&&E.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Lt.test(p.type),r=p.url.replace(It,""),p.hasContent?p.data&&p.processData&&0===(p.contentType||"").indexOf("application/x-www-form-urlencoded")&&(p.data=p.data.replace(Ot,"+")):(h=p.url.slice(r.length),p.data&&(p.processData||"string"==typeof p.data)&&(r+=(St.test(r)?"&":"?")+p.data,delete p.data),!1===p.cache&&(r=r.replace(Rt,"$1"),h=(St.test(r)?"&":"?")+"_="+Dt.guid+++h),p.url=r+h),p.ifModified&&(E.lastModified[r]&&C.setRequestHeader("If-Modified-Since",E.lastModified[r]),E.etag[r]&&C.setRequestHeader("If-None-Match",E.etag[r])),(p.data&&p.hasContent&&!1!==p.contentType||t.contentType)&&C.setRequestHeader("Content-Type",p.contentType),C.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Ut+"; q=0.01":""):p.accepts["*"]),p.headers)C.setRequestHeader(c,p.headers[c]);if(p.beforeSend&&(!1===p.beforeSend.call(g,C,p)||u))return C.abort();if(w="abort",v.add(p.complete),C.done(p.success),C.fail(p.error),n=Ht(zt,p,t,C)){if(C.readyState=1,d&&f.trigger("ajaxSend",[C,p]),u)return C;p.async&&p.timeout>0&&(a=i.setTimeout((function(){C.abort("timeout")}),p.timeout));try{u=!1,n.send(A,x)}catch(e){if(u)throw e;x(-1,e)}}else x(-1,"No Transport");function x(e,t,o,l){var c,h,_,A,y,w=t;u||(u=!0,a&&i.clearTimeout(a),n=void 0,s=l||"",C.readyState=e>0?4:0,c=e>=200&&e<300||304===e,o&&(A=function(e,t,n){for(var i,r,s,o,a=e.contents,l=e.dataTypes;"*"===l[0];)l.shift(),void 0===i&&(i=e.mimeType||t.getResponseHeader("Content-Type"));if(i)for(r in a)if(a[r]&&a[r].test(i)){l.unshift(r);break}if(l[0]in n)s=l[0];else{for(r in n){if(!l[0]||e.converters[r+" "+l[0]]){s=r;break}o||(o=r)}s=s||o}if(s)return s!==l[0]&&l.unshift(s),n[s]}(p,C,o)),!c&&E.inArray("script",p.dataTypes)>-1&&E.inArray("json",p.dataTypes)<0&&(p.converters["text script"]=function(){}),A=function(e,t,n,i){var r,s,o,a,l,u={},d=e.dataTypes.slice();if(d[1])for(o in e.converters)u[o.toLowerCase()]=e.converters[o];for(s=d.shift();s;)if(e.responseFields[s]&&(n[e.responseFields[s]]=t),!l&&i&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=s,s=d.shift())if("*"===s)s=l;else if("*"!==l&&l!==s){if(!(o=u[l+" "+s]||u["* "+s]))for(r in u)if((a=r.split(" "))[1]===s&&(o=u[l+" "+a[0]]||u["* "+a[0]])){!0===o?o=u[r]:!0!==u[r]&&(s=a[0],d.unshift(a[1]));break}if(!0!==o)if(o&&e.throws)t=o(t);else try{t=o(t)}catch(e){return{state:"parsererror",error:o?e:"No conversion from "+l+" to "+s}}}return{state:"success",data:t}}(p,A,C,c),c?(p.ifModified&&((y=C.getResponseHeader("Last-Modified"))&&(E.lastModified[r]=y),(y=C.getResponseHeader("etag"))&&(E.etag[r]=y)),204===e||"HEAD"===p.type?w="nocontent":304===e?w="notmodified":(w=A.state,h=A.data,c=!(_=A.error))):(_=w,!e&&w||(w="error",e<0&&(e=0))),C.status=e,C.statusText=(t||w)+"",c?m.resolveWith(g,[h,w,C]):m.rejectWith(g,[C,w,_]),C.statusCode(b),b=void 0,d&&f.trigger(c?"ajaxSuccess":"ajaxError",[C,p,c?h:_]),v.fireWith(g,[C,w]),d&&(f.trigger("ajaxComplete",[C,p]),--E.active||E.event.trigger("ajaxStop")))}return C},getJSON:function(e,t,n){return E.get(e,t,n,"json")},getScript:function(e,t){return E.get(e,void 0,t,"script")}}),E.each(["get","post"],(function(e,t){E[t]=function(e,n,i,r){return v(n)&&(r=r||i,i=n,n=void 0),E.ajax(E.extend({url:e,type:t,dataType:r,data:n,success:i},E.isPlainObject(e)&&e))}})),E.ajaxPrefilter((function(e){var t;for(t in e.headers)"content-type"===t.toLowerCase()&&(e.contentType=e.headers[t]||"")})),E._evalUrl=function(e,t,n){return E.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,converters:{"text script":function(){}},dataFilter:function(e){E.globalEval(e,t,n)}})},E.fn.extend({wrapAll:function(e){var t;return this[0]&&(v(e)&&(e=e.call(this[0])),t=E(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map((function(){for(var e=this;e.firstElementChild;)e=e.firstElementChild;return e})).append(this)),this},wrapInner:function(e){return v(e)?this.each((function(t){E(this).wrapInner(e.call(this,t))})):this.each((function(){var t=E(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)}))},wrap:function(e){var t=v(e);return this.each((function(n){E(this).wrapAll(t?e.call(this,n):e)}))},unwrap:function(e){return this.parent(e).not("body").each((function(){E(this).replaceWith(this.childNodes)})),this}}),E.expr.pseudos.hidden=function(e){return!E.expr.pseudos.visible(e)},E.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},E.ajaxSettings.xhr=function(){try{return new i.XMLHttpRequest}catch(e){}};var qt={0:200,1223:204},Gt=E.ajaxSettings.xhr();m.cors=!!Gt&&"withCredentials"in Gt,m.ajax=Gt=!!Gt,E.ajaxTransport((function(e){var t,n;if(m.cors||Gt&&!e.crossDomain)return{send:function(r,s){var o,a=e.xhr();if(a.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(o in e.xhrFields)a[o]=e.xhrFields[o];for(o in e.mimeType&&a.overrideMimeType&&a.overrideMimeType(e.mimeType),e.crossDomain||r["X-Requested-With"]||(r["X-Requested-With"]="XMLHttpRequest"),r)a.setRequestHeader(o,r[o]);t=function(e){return function(){t&&(t=n=a.onload=a.onerror=a.onabort=a.ontimeout=a.onreadystatechange=null,"abort"===e?a.abort():"error"===e?"number"!=typeof a.status?s(0,"error"):s(a.status,a.statusText):s(qt[a.status]||a.status,a.statusText,"text"!==(a.responseType||"text")||"string"!=typeof a.responseText?{binary:a.response}:{text:a.responseText},a.getAllResponseHeaders()))}},a.onload=t(),n=a.onerror=a.ontimeout=t("error"),void 0!==a.onabort?a.onabort=n:a.onreadystatechange=function(){4===a.readyState&&i.setTimeout((function(){t&&n()}))},t=t("abort");try{a.send(e.hasContent&&e.data||null)}catch(e){if(t)throw e}},abort:function(){t&&t()}}})),E.ajaxPrefilter((function(e){e.crossDomain&&(e.contents.script=!1)})),E.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return E.globalEval(e),e}}}),E.ajaxPrefilter("script",(function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")})),E.ajaxTransport("script",(function(e){var t,n;if(e.crossDomain||e.scriptAttrs)return{send:function(i,r){t=E(" +{% endmacro %} diff --git a/book/_build/html/_static/scripts/bootstrap.js b/book/_build/html/_static/scripts/bootstrap.js new file mode 100644 index 0000000..c8178de --- /dev/null +++ b/book/_build/html/_static/scripts/bootstrap.js @@ -0,0 +1,3 @@ +/*! For license information please see bootstrap.js.LICENSE.txt */ +(()=>{"use strict";var t={d:(e,i)=>{for(var n in i)t.o(i,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:i[n]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{afterMain:()=>E,afterRead:()=>v,afterWrite:()=>C,applyStyles:()=>$,arrow:()=>J,auto:()=>a,basePlacements:()=>l,beforeMain:()=>y,beforeRead:()=>_,beforeWrite:()=>A,bottom:()=>s,clippingParents:()=>d,computeStyles:()=>it,createPopper:()=>Dt,createPopperBase:()=>St,createPopperLite:()=>$t,detectOverflow:()=>_t,end:()=>h,eventListeners:()=>st,flip:()=>bt,hide:()=>wt,left:()=>r,main:()=>w,modifierPhases:()=>O,offset:()=>Et,placements:()=>g,popper:()=>f,popperGenerator:()=>Lt,popperOffsets:()=>At,preventOverflow:()=>Tt,read:()=>b,reference:()=>p,right:()=>o,start:()=>c,top:()=>n,variationPlacements:()=>m,viewport:()=>u,write:()=>T});var i={};t.r(i),t.d(i,{Alert:()=>Oe,Button:()=>ke,Carousel:()=>li,Collapse:()=>Ei,Dropdown:()=>Ki,Modal:()=>Ln,Offcanvas:()=>Kn,Popover:()=>bs,ScrollSpy:()=>Ls,Tab:()=>Js,Toast:()=>po,Tooltip:()=>fs});var n="top",s="bottom",o="right",r="left",a="auto",l=[n,s,o,r],c="start",h="end",d="clippingParents",u="viewport",f="popper",p="reference",m=l.reduce((function(t,e){return t.concat([e+"-"+c,e+"-"+h])}),[]),g=[].concat(l,[a]).reduce((function(t,e){return t.concat([e,e+"-"+c,e+"-"+h])}),[]),_="beforeRead",b="read",v="afterRead",y="beforeMain",w="main",E="afterMain",A="beforeWrite",T="write",C="afterWrite",O=[_,b,v,y,w,E,A,T,C];function x(t){return t?(t.nodeName||"").toLowerCase():null}function k(t){if(null==t)return window;if("[object Window]"!==t.toString()){var e=t.ownerDocument;return e&&e.defaultView||window}return t}function L(t){return t instanceof k(t).Element||t instanceof Element}function S(t){return t instanceof k(t).HTMLElement||t instanceof HTMLElement}function D(t){return"undefined"!=typeof ShadowRoot&&(t instanceof k(t).ShadowRoot||t instanceof ShadowRoot)}const $={name:"applyStyles",enabled:!0,phase:"write",fn:function(t){var e=t.state;Object.keys(e.elements).forEach((function(t){var i=e.styles[t]||{},n=e.attributes[t]||{},s=e.elements[t];S(s)&&x(s)&&(Object.assign(s.style,i),Object.keys(n).forEach((function(t){var e=n[t];!1===e?s.removeAttribute(t):s.setAttribute(t,!0===e?"":e)})))}))},effect:function(t){var e=t.state,i={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(e.elements.popper.style,i.popper),e.styles=i,e.elements.arrow&&Object.assign(e.elements.arrow.style,i.arrow),function(){Object.keys(e.elements).forEach((function(t){var n=e.elements[t],s=e.attributes[t]||{},o=Object.keys(e.styles.hasOwnProperty(t)?e.styles[t]:i[t]).reduce((function(t,e){return t[e]="",t}),{});S(n)&&x(n)&&(Object.assign(n.style,o),Object.keys(s).forEach((function(t){n.removeAttribute(t)})))}))}},requires:["computeStyles"]};function I(t){return t.split("-")[0]}var N=Math.max,P=Math.min,M=Math.round;function j(){var t=navigator.userAgentData;return null!=t&&t.brands&&Array.isArray(t.brands)?t.brands.map((function(t){return t.brand+"/"+t.version})).join(" "):navigator.userAgent}function F(){return!/^((?!chrome|android).)*safari/i.test(j())}function H(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=!1);var n=t.getBoundingClientRect(),s=1,o=1;e&&S(t)&&(s=t.offsetWidth>0&&M(n.width)/t.offsetWidth||1,o=t.offsetHeight>0&&M(n.height)/t.offsetHeight||1);var r=(L(t)?k(t):window).visualViewport,a=!F()&&i,l=(n.left+(a&&r?r.offsetLeft:0))/s,c=(n.top+(a&&r?r.offsetTop:0))/o,h=n.width/s,d=n.height/o;return{width:h,height:d,top:c,right:l+h,bottom:c+d,left:l,x:l,y:c}}function B(t){var e=H(t),i=t.offsetWidth,n=t.offsetHeight;return Math.abs(e.width-i)<=1&&(i=e.width),Math.abs(e.height-n)<=1&&(n=e.height),{x:t.offsetLeft,y:t.offsetTop,width:i,height:n}}function W(t,e){var i=e.getRootNode&&e.getRootNode();if(t.contains(e))return!0;if(i&&D(i)){var n=e;do{if(n&&t.isSameNode(n))return!0;n=n.parentNode||n.host}while(n)}return!1}function z(t){return k(t).getComputedStyle(t)}function R(t){return["table","td","th"].indexOf(x(t))>=0}function q(t){return((L(t)?t.ownerDocument:t.document)||window.document).documentElement}function V(t){return"html"===x(t)?t:t.assignedSlot||t.parentNode||(D(t)?t.host:null)||q(t)}function Y(t){return S(t)&&"fixed"!==z(t).position?t.offsetParent:null}function K(t){for(var e=k(t),i=Y(t);i&&R(i)&&"static"===z(i).position;)i=Y(i);return i&&("html"===x(i)||"body"===x(i)&&"static"===z(i).position)?e:i||function(t){var e=/firefox/i.test(j());if(/Trident/i.test(j())&&S(t)&&"fixed"===z(t).position)return null;var i=V(t);for(D(i)&&(i=i.host);S(i)&&["html","body"].indexOf(x(i))<0;){var n=z(i);if("none"!==n.transform||"none"!==n.perspective||"paint"===n.contain||-1!==["transform","perspective"].indexOf(n.willChange)||e&&"filter"===n.willChange||e&&n.filter&&"none"!==n.filter)return i;i=i.parentNode}return null}(t)||e}function Q(t){return["top","bottom"].indexOf(t)>=0?"x":"y"}function X(t,e,i){return N(t,P(e,i))}function U(t){return Object.assign({},{top:0,right:0,bottom:0,left:0},t)}function G(t,e){return e.reduce((function(e,i){return e[i]=t,e}),{})}const J={name:"arrow",enabled:!0,phase:"main",fn:function(t){var e,i=t.state,a=t.name,c=t.options,h=i.elements.arrow,d=i.modifiersData.popperOffsets,u=I(i.placement),f=Q(u),p=[r,o].indexOf(u)>=0?"height":"width";if(h&&d){var m=function(t,e){return U("number"!=typeof(t="function"==typeof t?t(Object.assign({},e.rects,{placement:e.placement})):t)?t:G(t,l))}(c.padding,i),g=B(h),_="y"===f?n:r,b="y"===f?s:o,v=i.rects.reference[p]+i.rects.reference[f]-d[f]-i.rects.popper[p],y=d[f]-i.rects.reference[f],w=K(h),E=w?"y"===f?w.clientHeight||0:w.clientWidth||0:0,A=v/2-y/2,T=m[_],C=E-g[p]-m[b],O=E/2-g[p]/2+A,x=X(T,O,C),k=f;i.modifiersData[a]=((e={})[k]=x,e.centerOffset=x-O,e)}},effect:function(t){var e=t.state,i=t.options.element,n=void 0===i?"[data-popper-arrow]":i;null!=n&&("string"!=typeof n||(n=e.elements.popper.querySelector(n)))&&W(e.elements.popper,n)&&(e.elements.arrow=n)},requires:["popperOffsets"],requiresIfExists:["preventOverflow"]};function Z(t){return t.split("-")[1]}var tt={top:"auto",right:"auto",bottom:"auto",left:"auto"};function et(t){var e,i=t.popper,a=t.popperRect,l=t.placement,c=t.variation,d=t.offsets,u=t.position,f=t.gpuAcceleration,p=t.adaptive,m=t.roundOffsets,g=t.isFixed,_=d.x,b=void 0===_?0:_,v=d.y,y=void 0===v?0:v,w="function"==typeof m?m({x:b,y}):{x:b,y};b=w.x,y=w.y;var E=d.hasOwnProperty("x"),A=d.hasOwnProperty("y"),T=r,C=n,O=window;if(p){var x=K(i),L="clientHeight",S="clientWidth";x===k(i)&&"static"!==z(x=q(i)).position&&"absolute"===u&&(L="scrollHeight",S="scrollWidth"),(l===n||(l===r||l===o)&&c===h)&&(C=s,y-=(g&&x===O&&O.visualViewport?O.visualViewport.height:x[L])-a.height,y*=f?1:-1),l!==r&&(l!==n&&l!==s||c!==h)||(T=o,b-=(g&&x===O&&O.visualViewport?O.visualViewport.width:x[S])-a.width,b*=f?1:-1)}var D,$=Object.assign({position:u},p&&tt),I=!0===m?function(t,e){var i=t.x,n=t.y,s=e.devicePixelRatio||1;return{x:M(i*s)/s||0,y:M(n*s)/s||0}}({x:b,y},k(i)):{x:b,y};return b=I.x,y=I.y,f?Object.assign({},$,((D={})[C]=A?"0":"",D[T]=E?"0":"",D.transform=(O.devicePixelRatio||1)<=1?"translate("+b+"px, "+y+"px)":"translate3d("+b+"px, "+y+"px, 0)",D)):Object.assign({},$,((e={})[C]=A?y+"px":"",e[T]=E?b+"px":"",e.transform="",e))}const it={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:function(t){var e=t.state,i=t.options,n=i.gpuAcceleration,s=void 0===n||n,o=i.adaptive,r=void 0===o||o,a=i.roundOffsets,l=void 0===a||a,c={placement:I(e.placement),variation:Z(e.placement),popper:e.elements.popper,popperRect:e.rects.popper,gpuAcceleration:s,isFixed:"fixed"===e.options.strategy};null!=e.modifiersData.popperOffsets&&(e.styles.popper=Object.assign({},e.styles.popper,et(Object.assign({},c,{offsets:e.modifiersData.popperOffsets,position:e.options.strategy,adaptive:r,roundOffsets:l})))),null!=e.modifiersData.arrow&&(e.styles.arrow=Object.assign({},e.styles.arrow,et(Object.assign({},c,{offsets:e.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:l})))),e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-placement":e.placement})},data:{}};var nt={passive:!0};const st={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:function(t){var e=t.state,i=t.instance,n=t.options,s=n.scroll,o=void 0===s||s,r=n.resize,a=void 0===r||r,l=k(e.elements.popper),c=[].concat(e.scrollParents.reference,e.scrollParents.popper);return o&&c.forEach((function(t){t.addEventListener("scroll",i.update,nt)})),a&&l.addEventListener("resize",i.update,nt),function(){o&&c.forEach((function(t){t.removeEventListener("scroll",i.update,nt)})),a&&l.removeEventListener("resize",i.update,nt)}},data:{}};var ot={left:"right",right:"left",bottom:"top",top:"bottom"};function rt(t){return t.replace(/left|right|bottom|top/g,(function(t){return ot[t]}))}var at={start:"end",end:"start"};function lt(t){return t.replace(/start|end/g,(function(t){return at[t]}))}function ct(t){var e=k(t);return{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function ht(t){return H(q(t)).left+ct(t).scrollLeft}function dt(t){var e=z(t),i=e.overflow,n=e.overflowX,s=e.overflowY;return/auto|scroll|overlay|hidden/.test(i+s+n)}function ut(t){return["html","body","#document"].indexOf(x(t))>=0?t.ownerDocument.body:S(t)&&dt(t)?t:ut(V(t))}function ft(t,e){var i;void 0===e&&(e=[]);var n=ut(t),s=n===(null==(i=t.ownerDocument)?void 0:i.body),o=k(n),r=s?[o].concat(o.visualViewport||[],dt(n)?n:[]):n,a=e.concat(r);return s?a:a.concat(ft(V(r)))}function pt(t){return Object.assign({},t,{left:t.x,top:t.y,right:t.x+t.width,bottom:t.y+t.height})}function mt(t,e,i){return e===u?pt(function(t,e){var i=k(t),n=q(t),s=i.visualViewport,o=n.clientWidth,r=n.clientHeight,a=0,l=0;if(s){o=s.width,r=s.height;var c=F();(c||!c&&"fixed"===e)&&(a=s.offsetLeft,l=s.offsetTop)}return{width:o,height:r,x:a+ht(t),y:l}}(t,i)):L(e)?function(t,e){var i=H(t,!1,"fixed"===e);return i.top=i.top+t.clientTop,i.left=i.left+t.clientLeft,i.bottom=i.top+t.clientHeight,i.right=i.left+t.clientWidth,i.width=t.clientWidth,i.height=t.clientHeight,i.x=i.left,i.y=i.top,i}(e,i):pt(function(t){var e,i=q(t),n=ct(t),s=null==(e=t.ownerDocument)?void 0:e.body,o=N(i.scrollWidth,i.clientWidth,s?s.scrollWidth:0,s?s.clientWidth:0),r=N(i.scrollHeight,i.clientHeight,s?s.scrollHeight:0,s?s.clientHeight:0),a=-n.scrollLeft+ht(t),l=-n.scrollTop;return"rtl"===z(s||i).direction&&(a+=N(i.clientWidth,s?s.clientWidth:0)-o),{width:o,height:r,x:a,y:l}}(q(t)))}function gt(t){var e,i=t.reference,a=t.element,l=t.placement,d=l?I(l):null,u=l?Z(l):null,f=i.x+i.width/2-a.width/2,p=i.y+i.height/2-a.height/2;switch(d){case n:e={x:f,y:i.y-a.height};break;case s:e={x:f,y:i.y+i.height};break;case o:e={x:i.x+i.width,y:p};break;case r:e={x:i.x-a.width,y:p};break;default:e={x:i.x,y:i.y}}var m=d?Q(d):null;if(null!=m){var g="y"===m?"height":"width";switch(u){case c:e[m]=e[m]-(i[g]/2-a[g]/2);break;case h:e[m]=e[m]+(i[g]/2-a[g]/2)}}return e}function _t(t,e){void 0===e&&(e={});var i=e,r=i.placement,a=void 0===r?t.placement:r,c=i.strategy,h=void 0===c?t.strategy:c,m=i.boundary,g=void 0===m?d:m,_=i.rootBoundary,b=void 0===_?u:_,v=i.elementContext,y=void 0===v?f:v,w=i.altBoundary,E=void 0!==w&&w,A=i.padding,T=void 0===A?0:A,C=U("number"!=typeof T?T:G(T,l)),O=y===f?p:f,k=t.rects.popper,D=t.elements[E?O:y],$=function(t,e,i,n){var s="clippingParents"===e?function(t){var e=ft(V(t)),i=["absolute","fixed"].indexOf(z(t).position)>=0&&S(t)?K(t):t;return L(i)?e.filter((function(t){return L(t)&&W(t,i)&&"body"!==x(t)})):[]}(t):[].concat(e),o=[].concat(s,[i]),r=o[0],a=o.reduce((function(e,i){var s=mt(t,i,n);return e.top=N(s.top,e.top),e.right=P(s.right,e.right),e.bottom=P(s.bottom,e.bottom),e.left=N(s.left,e.left),e}),mt(t,r,n));return a.width=a.right-a.left,a.height=a.bottom-a.top,a.x=a.left,a.y=a.top,a}(L(D)?D:D.contextElement||q(t.elements.popper),g,b,h),I=H(t.elements.reference),M=gt({reference:I,element:k,strategy:"absolute",placement:a}),j=pt(Object.assign({},k,M)),F=y===f?j:I,B={top:$.top-F.top+C.top,bottom:F.bottom-$.bottom+C.bottom,left:$.left-F.left+C.left,right:F.right-$.right+C.right},R=t.modifiersData.offset;if(y===f&&R){var Y=R[a];Object.keys(B).forEach((function(t){var e=[o,s].indexOf(t)>=0?1:-1,i=[n,s].indexOf(t)>=0?"y":"x";B[t]+=Y[i]*e}))}return B}const bt={name:"flip",enabled:!0,phase:"main",fn:function(t){var e=t.state,i=t.options,h=t.name;if(!e.modifiersData[h]._skip){for(var d=i.mainAxis,u=void 0===d||d,f=i.altAxis,p=void 0===f||f,_=i.fallbackPlacements,b=i.padding,v=i.boundary,y=i.rootBoundary,w=i.altBoundary,E=i.flipVariations,A=void 0===E||E,T=i.allowedAutoPlacements,C=e.options.placement,O=I(C),x=_||(O!==C&&A?function(t){if(I(t)===a)return[];var e=rt(t);return[lt(t),e,lt(e)]}(C):[rt(C)]),k=[C].concat(x).reduce((function(t,i){return t.concat(I(i)===a?function(t,e){void 0===e&&(e={});var i=e,n=i.placement,s=i.boundary,o=i.rootBoundary,r=i.padding,a=i.flipVariations,c=i.allowedAutoPlacements,h=void 0===c?g:c,d=Z(n),u=d?a?m:m.filter((function(t){return Z(t)===d})):l,f=u.filter((function(t){return h.indexOf(t)>=0}));0===f.length&&(f=u);var p=f.reduce((function(e,i){return e[i]=_t(t,{placement:i,boundary:s,rootBoundary:o,padding:r})[I(i)],e}),{});return Object.keys(p).sort((function(t,e){return p[t]-p[e]}))}(e,{placement:i,boundary:v,rootBoundary:y,padding:b,flipVariations:A,allowedAutoPlacements:T}):i)}),[]),L=e.rects.reference,S=e.rects.popper,D=new Map,$=!0,N=k[0],P=0;P=0,B=H?"width":"height",W=_t(e,{placement:M,boundary:v,rootBoundary:y,altBoundary:w,padding:b}),z=H?F?o:r:F?s:n;L[B]>S[B]&&(z=rt(z));var R=rt(z),q=[];if(u&&q.push(W[j]<=0),p&&q.push(W[z]<=0,W[R]<=0),q.every((function(t){return t}))){N=M,$=!1;break}D.set(M,q)}if($)for(var V=function(t){var e=k.find((function(e){var i=D.get(e);if(i)return i.slice(0,t).every((function(t){return t}))}));if(e)return N=e,"break"},Y=A?3:1;Y>0&&"break"!==V(Y);Y--);e.placement!==N&&(e.modifiersData[h]._skip=!0,e.placement=N,e.reset=!0)}},requiresIfExists:["offset"],data:{_skip:!1}};function vt(t,e,i){return void 0===i&&(i={x:0,y:0}),{top:t.top-e.height-i.y,right:t.right-e.width+i.x,bottom:t.bottom-e.height+i.y,left:t.left-e.width-i.x}}function yt(t){return[n,o,s,r].some((function(e){return t[e]>=0}))}const wt={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:function(t){var e=t.state,i=t.name,n=e.rects.reference,s=e.rects.popper,o=e.modifiersData.preventOverflow,r=_t(e,{elementContext:"reference"}),a=_t(e,{altBoundary:!0}),l=vt(r,n),c=vt(a,s,o),h=yt(l),d=yt(c);e.modifiersData[i]={referenceClippingOffsets:l,popperEscapeOffsets:c,isReferenceHidden:h,hasPopperEscaped:d},e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-reference-hidden":h,"data-popper-escaped":d})}},Et={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:function(t){var e=t.state,i=t.options,s=t.name,a=i.offset,l=void 0===a?[0,0]:a,c=g.reduce((function(t,i){return t[i]=function(t,e,i){var s=I(t),a=[r,n].indexOf(s)>=0?-1:1,l="function"==typeof i?i(Object.assign({},e,{placement:t})):i,c=l[0],h=l[1];return c=c||0,h=(h||0)*a,[r,o].indexOf(s)>=0?{x:h,y:c}:{x:c,y:h}}(i,e.rects,l),t}),{}),h=c[e.placement],d=h.x,u=h.y;null!=e.modifiersData.popperOffsets&&(e.modifiersData.popperOffsets.x+=d,e.modifiersData.popperOffsets.y+=u),e.modifiersData[s]=c}},At={name:"popperOffsets",enabled:!0,phase:"read",fn:function(t){var e=t.state,i=t.name;e.modifiersData[i]=gt({reference:e.rects.reference,element:e.rects.popper,strategy:"absolute",placement:e.placement})},data:{}},Tt={name:"preventOverflow",enabled:!0,phase:"main",fn:function(t){var e=t.state,i=t.options,a=t.name,l=i.mainAxis,h=void 0===l||l,d=i.altAxis,u=void 0!==d&&d,f=i.boundary,p=i.rootBoundary,m=i.altBoundary,g=i.padding,_=i.tether,b=void 0===_||_,v=i.tetherOffset,y=void 0===v?0:v,w=_t(e,{boundary:f,rootBoundary:p,padding:g,altBoundary:m}),E=I(e.placement),A=Z(e.placement),T=!A,C=Q(E),O="x"===C?"y":"x",x=e.modifiersData.popperOffsets,k=e.rects.reference,L=e.rects.popper,S="function"==typeof y?y(Object.assign({},e.rects,{placement:e.placement})):y,D="number"==typeof S?{mainAxis:S,altAxis:S}:Object.assign({mainAxis:0,altAxis:0},S),$=e.modifiersData.offset?e.modifiersData.offset[e.placement]:null,M={x:0,y:0};if(x){if(h){var j,F="y"===C?n:r,H="y"===C?s:o,W="y"===C?"height":"width",z=x[C],R=z+w[F],q=z-w[H],V=b?-L[W]/2:0,Y=A===c?k[W]:L[W],U=A===c?-L[W]:-k[W],G=e.elements.arrow,J=b&&G?B(G):{width:0,height:0},tt=e.modifiersData["arrow#persistent"]?e.modifiersData["arrow#persistent"].padding:{top:0,right:0,bottom:0,left:0},et=tt[F],it=tt[H],nt=X(0,k[W],J[W]),st=T?k[W]/2-V-nt-et-D.mainAxis:Y-nt-et-D.mainAxis,ot=T?-k[W]/2+V+nt+it+D.mainAxis:U+nt+it+D.mainAxis,rt=e.elements.arrow&&K(e.elements.arrow),at=rt?"y"===C?rt.clientTop||0:rt.clientLeft||0:0,lt=null!=(j=null==$?void 0:$[C])?j:0,ct=z+ot-lt,ht=X(b?P(R,z+st-lt-at):R,z,b?N(q,ct):q);x[C]=ht,M[C]=ht-z}if(u){var dt,ut="x"===C?n:r,ft="x"===C?s:o,pt=x[O],mt="y"===O?"height":"width",gt=pt+w[ut],bt=pt-w[ft],vt=-1!==[n,r].indexOf(E),yt=null!=(dt=null==$?void 0:$[O])?dt:0,wt=vt?gt:pt-k[mt]-L[mt]-yt+D.altAxis,Et=vt?pt+k[mt]+L[mt]-yt-D.altAxis:bt,At=b&&vt?function(t,e,i){var n=X(t,e,i);return n>i?i:n}(wt,pt,Et):X(b?wt:gt,pt,b?Et:bt);x[O]=At,M[O]=At-pt}e.modifiersData[a]=M}},requiresIfExists:["offset"]};function Ct(t,e,i){void 0===i&&(i=!1);var n,s,o=S(e),r=S(e)&&function(t){var e=t.getBoundingClientRect(),i=M(e.width)/t.offsetWidth||1,n=M(e.height)/t.offsetHeight||1;return 1!==i||1!==n}(e),a=q(e),l=H(t,r,i),c={scrollLeft:0,scrollTop:0},h={x:0,y:0};return(o||!o&&!i)&&(("body"!==x(e)||dt(a))&&(c=(n=e)!==k(n)&&S(n)?{scrollLeft:(s=n).scrollLeft,scrollTop:s.scrollTop}:ct(n)),S(e)?((h=H(e,!0)).x+=e.clientLeft,h.y+=e.clientTop):a&&(h.x=ht(a))),{x:l.left+c.scrollLeft-h.x,y:l.top+c.scrollTop-h.y,width:l.width,height:l.height}}function Ot(t){var e=new Map,i=new Set,n=[];function s(t){i.add(t.name),[].concat(t.requires||[],t.requiresIfExists||[]).forEach((function(t){if(!i.has(t)){var n=e.get(t);n&&s(n)}})),n.push(t)}return t.forEach((function(t){e.set(t.name,t)})),t.forEach((function(t){i.has(t.name)||s(t)})),n}var xt={placement:"bottom",modifiers:[],strategy:"absolute"};function kt(){for(var t=arguments.length,e=new Array(t),i=0;iIt.has(t)&&It.get(t).get(e)||null,remove(t,e){if(!It.has(t))return;const i=It.get(t);i.delete(e),0===i.size&&It.delete(t)}},Pt="transitionend",Mt=t=>(t&&window.CSS&&window.CSS.escape&&(t=t.replace(/#([^\s"#']+)/g,((t,e)=>`#${CSS.escape(e)}`))),t),jt=t=>{t.dispatchEvent(new Event(Pt))},Ft=t=>!(!t||"object"!=typeof t)&&(void 0!==t.jquery&&(t=t[0]),void 0!==t.nodeType),Ht=t=>Ft(t)?t.jquery?t[0]:t:"string"==typeof t&&t.length>0?document.querySelector(Mt(t)):null,Bt=t=>{if(!Ft(t)||0===t.getClientRects().length)return!1;const e="visible"===getComputedStyle(t).getPropertyValue("visibility"),i=t.closest("details:not([open])");if(!i)return e;if(i!==t){const e=t.closest("summary");if(e&&e.parentNode!==i)return!1;if(null===e)return!1}return e},Wt=t=>!t||t.nodeType!==Node.ELEMENT_NODE||!!t.classList.contains("disabled")||(void 0!==t.disabled?t.disabled:t.hasAttribute("disabled")&&"false"!==t.getAttribute("disabled")),zt=t=>{if(!document.documentElement.attachShadow)return null;if("function"==typeof t.getRootNode){const e=t.getRootNode();return e instanceof ShadowRoot?e:null}return t instanceof ShadowRoot?t:t.parentNode?zt(t.parentNode):null},Rt=()=>{},qt=t=>{t.offsetHeight},Vt=()=>window.jQuery&&!document.body.hasAttribute("data-bs-no-jquery")?window.jQuery:null,Yt=[],Kt=()=>"rtl"===document.documentElement.dir,Qt=t=>{var e;e=()=>{const e=Vt();if(e){const i=t.NAME,n=e.fn[i];e.fn[i]=t.jQueryInterface,e.fn[i].Constructor=t,e.fn[i].noConflict=()=>(e.fn[i]=n,t.jQueryInterface)}},"loading"===document.readyState?(Yt.length||document.addEventListener("DOMContentLoaded",(()=>{for(const t of Yt)t()})),Yt.push(e)):e()},Xt=(t,e=[],i=t)=>"function"==typeof t?t(...e):i,Ut=(t,e,i=!0)=>{if(!i)return void Xt(t);const n=(t=>{if(!t)return 0;let{transitionDuration:e,transitionDelay:i}=window.getComputedStyle(t);const n=Number.parseFloat(e),s=Number.parseFloat(i);return n||s?(e=e.split(",")[0],i=i.split(",")[0],1e3*(Number.parseFloat(e)+Number.parseFloat(i))):0})(e)+5;let s=!1;const o=({target:i})=>{i===e&&(s=!0,e.removeEventListener(Pt,o),Xt(t))};e.addEventListener(Pt,o),setTimeout((()=>{s||jt(e)}),n)},Gt=(t,e,i,n)=>{const s=t.length;let o=t.indexOf(e);return-1===o?!i&&n?t[s-1]:t[0]:(o+=i?1:-1,n&&(o=(o+s)%s),t[Math.max(0,Math.min(o,s-1))])},Jt=/[^.]*(?=\..*)\.|.*/,Zt=/\..*/,te=/::\d+$/,ee={};let ie=1;const ne={mouseenter:"mouseover",mouseleave:"mouseout"},se=new Set(["click","dblclick","mouseup","mousedown","contextmenu","mousewheel","DOMMouseScroll","mouseover","mouseout","mousemove","selectstart","selectend","keydown","keypress","keyup","orientationchange","touchstart","touchmove","touchend","touchcancel","pointerdown","pointermove","pointerup","pointerleave","pointercancel","gesturestart","gesturechange","gestureend","focus","blur","change","reset","select","submit","focusin","focusout","load","unload","beforeunload","resize","move","DOMContentLoaded","readystatechange","error","abort","scroll"]);function oe(t,e){return e&&`${e}::${ie++}`||t.uidEvent||ie++}function re(t){const e=oe(t);return t.uidEvent=e,ee[e]=ee[e]||{},ee[e]}function ae(t,e,i=null){return Object.values(t).find((t=>t.callable===e&&t.delegationSelector===i))}function le(t,e,i){const n="string"==typeof e,s=n?i:e||i;let o=ue(t);return se.has(o)||(o=t),[n,s,o]}function ce(t,e,i,n,s){if("string"!=typeof e||!t)return;let[o,r,a]=le(e,i,n);if(e in ne){const t=t=>function(e){if(!e.relatedTarget||e.relatedTarget!==e.delegateTarget&&!e.delegateTarget.contains(e.relatedTarget))return t.call(this,e)};r=t(r)}const l=re(t),c=l[a]||(l[a]={}),h=ae(c,r,o?i:null);if(h)return void(h.oneOff=h.oneOff&&s);const d=oe(r,e.replace(Jt,"")),u=o?function(t,e,i){return function n(s){const o=t.querySelectorAll(e);for(let{target:r}=s;r&&r!==this;r=r.parentNode)for(const a of o)if(a===r)return pe(s,{delegateTarget:r}),n.oneOff&&fe.off(t,s.type,e,i),i.apply(r,[s])}}(t,i,r):function(t,e){return function i(n){return pe(n,{delegateTarget:t}),i.oneOff&&fe.off(t,n.type,e),e.apply(t,[n])}}(t,r);u.delegationSelector=o?i:null,u.callable=r,u.oneOff=s,u.uidEvent=d,c[d]=u,t.addEventListener(a,u,o)}function he(t,e,i,n,s){const o=ae(e[i],n,s);o&&(t.removeEventListener(i,o,Boolean(s)),delete e[i][o.uidEvent])}function de(t,e,i,n){const s=e[i]||{};for(const[o,r]of Object.entries(s))o.includes(n)&&he(t,e,i,r.callable,r.delegationSelector)}function ue(t){return t=t.replace(Zt,""),ne[t]||t}const fe={on(t,e,i,n){ce(t,e,i,n,!1)},one(t,e,i,n){ce(t,e,i,n,!0)},off(t,e,i,n){if("string"!=typeof e||!t)return;const[s,o,r]=le(e,i,n),a=r!==e,l=re(t),c=l[r]||{},h=e.startsWith(".");if(void 0===o){if(h)for(const i of Object.keys(l))de(t,l,i,e.slice(1));for(const[i,n]of Object.entries(c)){const s=i.replace(te,"");a&&!e.includes(s)||he(t,l,r,n.callable,n.delegationSelector)}}else{if(!Object.keys(c).length)return;he(t,l,r,o,s?i:null)}},trigger(t,e,i){if("string"!=typeof e||!t)return null;const n=Vt();let s=null,o=!0,r=!0,a=!1;e!==ue(e)&&n&&(s=n.Event(e,i),n(t).trigger(s),o=!s.isPropagationStopped(),r=!s.isImmediatePropagationStopped(),a=s.isDefaultPrevented());const l=pe(new Event(e,{bubbles:o,cancelable:!0}),i);return a&&l.preventDefault(),r&&t.dispatchEvent(l),l.defaultPrevented&&s&&s.preventDefault(),l}};function pe(t,e={}){for(const[i,n]of Object.entries(e))try{t[i]=n}catch(e){Object.defineProperty(t,i,{configurable:!0,get:()=>n})}return t}function me(t){if("true"===t)return!0;if("false"===t)return!1;if(t===Number(t).toString())return Number(t);if(""===t||"null"===t)return null;if("string"!=typeof t)return t;try{return JSON.parse(decodeURIComponent(t))}catch(e){return t}}function ge(t){return t.replace(/[A-Z]/g,(t=>`-${t.toLowerCase()}`))}const _e={setDataAttribute(t,e,i){t.setAttribute(`data-bs-${ge(e)}`,i)},removeDataAttribute(t,e){t.removeAttribute(`data-bs-${ge(e)}`)},getDataAttributes(t){if(!t)return{};const e={},i=Object.keys(t.dataset).filter((t=>t.startsWith("bs")&&!t.startsWith("bsConfig")));for(const n of i){let i=n.replace(/^bs/,"");i=i.charAt(0).toLowerCase()+i.slice(1,i.length),e[i]=me(t.dataset[n])}return e},getDataAttribute:(t,e)=>me(t.getAttribute(`data-bs-${ge(e)}`))};class be{static get Default(){return{}}static get DefaultType(){return{}}static get NAME(){throw new Error('You have to implement the static method "NAME", for each component!')}_getConfig(t){return t=this._mergeConfigObj(t),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}_configAfterMerge(t){return t}_mergeConfigObj(t,e){const i=Ft(e)?_e.getDataAttribute(e,"config"):{};return{...this.constructor.Default,..."object"==typeof i?i:{},...Ft(e)?_e.getDataAttributes(e):{},..."object"==typeof t?t:{}}}_typeCheckConfig(t,e=this.constructor.DefaultType){for(const[n,s]of Object.entries(e)){const e=t[n],o=Ft(e)?"element":null==(i=e)?`${i}`:Object.prototype.toString.call(i).match(/\s([a-z]+)/i)[1].toLowerCase();if(!new RegExp(s).test(o))throw new TypeError(`${this.constructor.NAME.toUpperCase()}: Option "${n}" provided type "${o}" but expected type "${s}".`)}var i}}class ve extends be{constructor(t,e){super(),(t=Ht(t))&&(this._element=t,this._config=this._getConfig(e),Nt.set(this._element,this.constructor.DATA_KEY,this))}dispose(){Nt.remove(this._element,this.constructor.DATA_KEY),fe.off(this._element,this.constructor.EVENT_KEY);for(const t of Object.getOwnPropertyNames(this))this[t]=null}_queueCallback(t,e,i=!0){Ut(t,e,i)}_getConfig(t){return t=this._mergeConfigObj(t,this._element),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}static getInstance(t){return Nt.get(Ht(t),this.DATA_KEY)}static getOrCreateInstance(t,e={}){return this.getInstance(t)||new this(t,"object"==typeof e?e:null)}static get VERSION(){return"5.3.3"}static get DATA_KEY(){return`bs.${this.NAME}`}static get EVENT_KEY(){return`.${this.DATA_KEY}`}static eventName(t){return`${t}${this.EVENT_KEY}`}}const ye=t=>{let e=t.getAttribute("data-bs-target");if(!e||"#"===e){let i=t.getAttribute("href");if(!i||!i.includes("#")&&!i.startsWith("."))return null;i.includes("#")&&!i.startsWith("#")&&(i=`#${i.split("#")[1]}`),e=i&&"#"!==i?i.trim():null}return e?e.split(",").map((t=>Mt(t))).join(","):null},we={find:(t,e=document.documentElement)=>[].concat(...Element.prototype.querySelectorAll.call(e,t)),findOne:(t,e=document.documentElement)=>Element.prototype.querySelector.call(e,t),children:(t,e)=>[].concat(...t.children).filter((t=>t.matches(e))),parents(t,e){const i=[];let n=t.parentNode.closest(e);for(;n;)i.push(n),n=n.parentNode.closest(e);return i},prev(t,e){let i=t.previousElementSibling;for(;i;){if(i.matches(e))return[i];i=i.previousElementSibling}return[]},next(t,e){let i=t.nextElementSibling;for(;i;){if(i.matches(e))return[i];i=i.nextElementSibling}return[]},focusableChildren(t){const e=["a","button","input","textarea","select","details","[tabindex]",'[contenteditable="true"]'].map((t=>`${t}:not([tabindex^="-"])`)).join(",");return this.find(e,t).filter((t=>!Wt(t)&&Bt(t)))},getSelectorFromElement(t){const e=ye(t);return e&&we.findOne(e)?e:null},getElementFromSelector(t){const e=ye(t);return e?we.findOne(e):null},getMultipleElementsFromSelector(t){const e=ye(t);return e?we.find(e):[]}},Ee=(t,e="hide")=>{const i=`click.dismiss${t.EVENT_KEY}`,n=t.NAME;fe.on(document,i,`[data-bs-dismiss="${n}"]`,(function(i){if(["A","AREA"].includes(this.tagName)&&i.preventDefault(),Wt(this))return;const s=we.getElementFromSelector(this)||this.closest(`.${n}`);t.getOrCreateInstance(s)[e]()}))},Ae=".bs.alert",Te=`close${Ae}`,Ce=`closed${Ae}`;class Oe extends ve{static get NAME(){return"alert"}close(){if(fe.trigger(this._element,Te).defaultPrevented)return;this._element.classList.remove("show");const t=this._element.classList.contains("fade");this._queueCallback((()=>this._destroyElement()),this._element,t)}_destroyElement(){this._element.remove(),fe.trigger(this._element,Ce),this.dispose()}static jQueryInterface(t){return this.each((function(){const e=Oe.getOrCreateInstance(this);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}Ee(Oe,"close"),Qt(Oe);const xe='[data-bs-toggle="button"]';class ke extends ve{static get NAME(){return"button"}toggle(){this._element.setAttribute("aria-pressed",this._element.classList.toggle("active"))}static jQueryInterface(t){return this.each((function(){const e=ke.getOrCreateInstance(this);"toggle"===t&&e[t]()}))}}fe.on(document,"click.bs.button.data-api",xe,(t=>{t.preventDefault();const e=t.target.closest(xe);ke.getOrCreateInstance(e).toggle()})),Qt(ke);const Le=".bs.swipe",Se=`touchstart${Le}`,De=`touchmove${Le}`,$e=`touchend${Le}`,Ie=`pointerdown${Le}`,Ne=`pointerup${Le}`,Pe={endCallback:null,leftCallback:null,rightCallback:null},Me={endCallback:"(function|null)",leftCallback:"(function|null)",rightCallback:"(function|null)"};class je extends be{constructor(t,e){super(),this._element=t,t&&je.isSupported()&&(this._config=this._getConfig(e),this._deltaX=0,this._supportPointerEvents=Boolean(window.PointerEvent),this._initEvents())}static get Default(){return Pe}static get DefaultType(){return Me}static get NAME(){return"swipe"}dispose(){fe.off(this._element,Le)}_start(t){this._supportPointerEvents?this._eventIsPointerPenTouch(t)&&(this._deltaX=t.clientX):this._deltaX=t.touches[0].clientX}_end(t){this._eventIsPointerPenTouch(t)&&(this._deltaX=t.clientX-this._deltaX),this._handleSwipe(),Xt(this._config.endCallback)}_move(t){this._deltaX=t.touches&&t.touches.length>1?0:t.touches[0].clientX-this._deltaX}_handleSwipe(){const t=Math.abs(this._deltaX);if(t<=40)return;const e=t/this._deltaX;this._deltaX=0,e&&Xt(e>0?this._config.rightCallback:this._config.leftCallback)}_initEvents(){this._supportPointerEvents?(fe.on(this._element,Ie,(t=>this._start(t))),fe.on(this._element,Ne,(t=>this._end(t))),this._element.classList.add("pointer-event")):(fe.on(this._element,Se,(t=>this._start(t))),fe.on(this._element,De,(t=>this._move(t))),fe.on(this._element,$e,(t=>this._end(t))))}_eventIsPointerPenTouch(t){return this._supportPointerEvents&&("pen"===t.pointerType||"touch"===t.pointerType)}static isSupported(){return"ontouchstart"in document.documentElement||navigator.maxTouchPoints>0}}const Fe=".bs.carousel",He=".data-api",Be="ArrowLeft",We="ArrowRight",ze="next",Re="prev",qe="left",Ve="right",Ye=`slide${Fe}`,Ke=`slid${Fe}`,Qe=`keydown${Fe}`,Xe=`mouseenter${Fe}`,Ue=`mouseleave${Fe}`,Ge=`dragstart${Fe}`,Je=`load${Fe}${He}`,Ze=`click${Fe}${He}`,ti="carousel",ei="active",ii=".active",ni=".carousel-item",si=ii+ni,oi={[Be]:Ve,[We]:qe},ri={interval:5e3,keyboard:!0,pause:"hover",ride:!1,touch:!0,wrap:!0},ai={interval:"(number|boolean)",keyboard:"boolean",pause:"(string|boolean)",ride:"(boolean|string)",touch:"boolean",wrap:"boolean"};class li extends ve{constructor(t,e){super(t,e),this._interval=null,this._activeElement=null,this._isSliding=!1,this.touchTimeout=null,this._swipeHelper=null,this._indicatorsElement=we.findOne(".carousel-indicators",this._element),this._addEventListeners(),this._config.ride===ti&&this.cycle()}static get Default(){return ri}static get DefaultType(){return ai}static get NAME(){return"carousel"}next(){this._slide(ze)}nextWhenVisible(){!document.hidden&&Bt(this._element)&&this.next()}prev(){this._slide(Re)}pause(){this._isSliding&&jt(this._element),this._clearInterval()}cycle(){this._clearInterval(),this._updateInterval(),this._interval=setInterval((()=>this.nextWhenVisible()),this._config.interval)}_maybeEnableCycle(){this._config.ride&&(this._isSliding?fe.one(this._element,Ke,(()=>this.cycle())):this.cycle())}to(t){const e=this._getItems();if(t>e.length-1||t<0)return;if(this._isSliding)return void fe.one(this._element,Ke,(()=>this.to(t)));const i=this._getItemIndex(this._getActive());if(i===t)return;const n=t>i?ze:Re;this._slide(n,e[t])}dispose(){this._swipeHelper&&this._swipeHelper.dispose(),super.dispose()}_configAfterMerge(t){return t.defaultInterval=t.interval,t}_addEventListeners(){this._config.keyboard&&fe.on(this._element,Qe,(t=>this._keydown(t))),"hover"===this._config.pause&&(fe.on(this._element,Xe,(()=>this.pause())),fe.on(this._element,Ue,(()=>this._maybeEnableCycle()))),this._config.touch&&je.isSupported()&&this._addTouchEventListeners()}_addTouchEventListeners(){for(const t of we.find(".carousel-item img",this._element))fe.on(t,Ge,(t=>t.preventDefault()));const t={leftCallback:()=>this._slide(this._directionToOrder(qe)),rightCallback:()=>this._slide(this._directionToOrder(Ve)),endCallback:()=>{"hover"===this._config.pause&&(this.pause(),this.touchTimeout&&clearTimeout(this.touchTimeout),this.touchTimeout=setTimeout((()=>this._maybeEnableCycle()),500+this._config.interval))}};this._swipeHelper=new je(this._element,t)}_keydown(t){if(/input|textarea/i.test(t.target.tagName))return;const e=oi[t.key];e&&(t.preventDefault(),this._slide(this._directionToOrder(e)))}_getItemIndex(t){return this._getItems().indexOf(t)}_setActiveIndicatorElement(t){if(!this._indicatorsElement)return;const e=we.findOne(ii,this._indicatorsElement);e.classList.remove(ei),e.removeAttribute("aria-current");const i=we.findOne(`[data-bs-slide-to="${t}"]`,this._indicatorsElement);i&&(i.classList.add(ei),i.setAttribute("aria-current","true"))}_updateInterval(){const t=this._activeElement||this._getActive();if(!t)return;const e=Number.parseInt(t.getAttribute("data-bs-interval"),10);this._config.interval=e||this._config.defaultInterval}_slide(t,e=null){if(this._isSliding)return;const i=this._getActive(),n=t===ze,s=e||Gt(this._getItems(),i,n,this._config.wrap);if(s===i)return;const o=this._getItemIndex(s),r=e=>fe.trigger(this._element,e,{relatedTarget:s,direction:this._orderToDirection(t),from:this._getItemIndex(i),to:o});if(r(Ye).defaultPrevented)return;if(!i||!s)return;const a=Boolean(this._interval);this.pause(),this._isSliding=!0,this._setActiveIndicatorElement(o),this._activeElement=s;const l=n?"carousel-item-start":"carousel-item-end",c=n?"carousel-item-next":"carousel-item-prev";s.classList.add(c),qt(s),i.classList.add(l),s.classList.add(l),this._queueCallback((()=>{s.classList.remove(l,c),s.classList.add(ei),i.classList.remove(ei,c,l),this._isSliding=!1,r(Ke)}),i,this._isAnimated()),a&&this.cycle()}_isAnimated(){return this._element.classList.contains("slide")}_getActive(){return we.findOne(si,this._element)}_getItems(){return we.find(ni,this._element)}_clearInterval(){this._interval&&(clearInterval(this._interval),this._interval=null)}_directionToOrder(t){return Kt()?t===qe?Re:ze:t===qe?ze:Re}_orderToDirection(t){return Kt()?t===Re?qe:Ve:t===Re?Ve:qe}static jQueryInterface(t){return this.each((function(){const e=li.getOrCreateInstance(this,t);if("number"!=typeof t){if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}else e.to(t)}))}}fe.on(document,Ze,"[data-bs-slide], [data-bs-slide-to]",(function(t){const e=we.getElementFromSelector(this);if(!e||!e.classList.contains(ti))return;t.preventDefault();const i=li.getOrCreateInstance(e),n=this.getAttribute("data-bs-slide-to");return n?(i.to(n),void i._maybeEnableCycle()):"next"===_e.getDataAttribute(this,"slide")?(i.next(),void i._maybeEnableCycle()):(i.prev(),void i._maybeEnableCycle())})),fe.on(window,Je,(()=>{const t=we.find('[data-bs-ride="carousel"]');for(const e of t)li.getOrCreateInstance(e)})),Qt(li);const ci=".bs.collapse",hi=`show${ci}`,di=`shown${ci}`,ui=`hide${ci}`,fi=`hidden${ci}`,pi=`click${ci}.data-api`,mi="show",gi="collapse",_i="collapsing",bi=`:scope .${gi} .${gi}`,vi='[data-bs-toggle="collapse"]',yi={parent:null,toggle:!0},wi={parent:"(null|element)",toggle:"boolean"};class Ei extends ve{constructor(t,e){super(t,e),this._isTransitioning=!1,this._triggerArray=[];const i=we.find(vi);for(const t of i){const e=we.getSelectorFromElement(t),i=we.find(e).filter((t=>t===this._element));null!==e&&i.length&&this._triggerArray.push(t)}this._initializeChildren(),this._config.parent||this._addAriaAndCollapsedClass(this._triggerArray,this._isShown()),this._config.toggle&&this.toggle()}static get Default(){return yi}static get DefaultType(){return wi}static get NAME(){return"collapse"}toggle(){this._isShown()?this.hide():this.show()}show(){if(this._isTransitioning||this._isShown())return;let t=[];if(this._config.parent&&(t=this._getFirstLevelChildren(".collapse.show, .collapse.collapsing").filter((t=>t!==this._element)).map((t=>Ei.getOrCreateInstance(t,{toggle:!1})))),t.length&&t[0]._isTransitioning)return;if(fe.trigger(this._element,hi).defaultPrevented)return;for(const e of t)e.hide();const e=this._getDimension();this._element.classList.remove(gi),this._element.classList.add(_i),this._element.style[e]=0,this._addAriaAndCollapsedClass(this._triggerArray,!0),this._isTransitioning=!0;const i=`scroll${e[0].toUpperCase()+e.slice(1)}`;this._queueCallback((()=>{this._isTransitioning=!1,this._element.classList.remove(_i),this._element.classList.add(gi,mi),this._element.style[e]="",fe.trigger(this._element,di)}),this._element,!0),this._element.style[e]=`${this._element[i]}px`}hide(){if(this._isTransitioning||!this._isShown())return;if(fe.trigger(this._element,ui).defaultPrevented)return;const t=this._getDimension();this._element.style[t]=`${this._element.getBoundingClientRect()[t]}px`,qt(this._element),this._element.classList.add(_i),this._element.classList.remove(gi,mi);for(const t of this._triggerArray){const e=we.getElementFromSelector(t);e&&!this._isShown(e)&&this._addAriaAndCollapsedClass([t],!1)}this._isTransitioning=!0,this._element.style[t]="",this._queueCallback((()=>{this._isTransitioning=!1,this._element.classList.remove(_i),this._element.classList.add(gi),fe.trigger(this._element,fi)}),this._element,!0)}_isShown(t=this._element){return t.classList.contains(mi)}_configAfterMerge(t){return t.toggle=Boolean(t.toggle),t.parent=Ht(t.parent),t}_getDimension(){return this._element.classList.contains("collapse-horizontal")?"width":"height"}_initializeChildren(){if(!this._config.parent)return;const t=this._getFirstLevelChildren(vi);for(const e of t){const t=we.getElementFromSelector(e);t&&this._addAriaAndCollapsedClass([e],this._isShown(t))}}_getFirstLevelChildren(t){const e=we.find(bi,this._config.parent);return we.find(t,this._config.parent).filter((t=>!e.includes(t)))}_addAriaAndCollapsedClass(t,e){if(t.length)for(const i of t)i.classList.toggle("collapsed",!e),i.setAttribute("aria-expanded",e)}static jQueryInterface(t){const e={};return"string"==typeof t&&/show|hide/.test(t)&&(e.toggle=!1),this.each((function(){const i=Ei.getOrCreateInstance(this,e);if("string"==typeof t){if(void 0===i[t])throw new TypeError(`No method named "${t}"`);i[t]()}}))}}fe.on(document,pi,vi,(function(t){("A"===t.target.tagName||t.delegateTarget&&"A"===t.delegateTarget.tagName)&&t.preventDefault();for(const t of we.getMultipleElementsFromSelector(this))Ei.getOrCreateInstance(t,{toggle:!1}).toggle()})),Qt(Ei);const Ai="dropdown",Ti=".bs.dropdown",Ci=".data-api",Oi="ArrowUp",xi="ArrowDown",ki=`hide${Ti}`,Li=`hidden${Ti}`,Si=`show${Ti}`,Di=`shown${Ti}`,$i=`click${Ti}${Ci}`,Ii=`keydown${Ti}${Ci}`,Ni=`keyup${Ti}${Ci}`,Pi="show",Mi='[data-bs-toggle="dropdown"]:not(.disabled):not(:disabled)',ji=`${Mi}.${Pi}`,Fi=".dropdown-menu",Hi=Kt()?"top-end":"top-start",Bi=Kt()?"top-start":"top-end",Wi=Kt()?"bottom-end":"bottom-start",zi=Kt()?"bottom-start":"bottom-end",Ri=Kt()?"left-start":"right-start",qi=Kt()?"right-start":"left-start",Vi={autoClose:!0,boundary:"clippingParents",display:"dynamic",offset:[0,2],popperConfig:null,reference:"toggle"},Yi={autoClose:"(boolean|string)",boundary:"(string|element)",display:"string",offset:"(array|string|function)",popperConfig:"(null|object|function)",reference:"(string|element|object)"};class Ki extends ve{constructor(t,e){super(t,e),this._popper=null,this._parent=this._element.parentNode,this._menu=we.next(this._element,Fi)[0]||we.prev(this._element,Fi)[0]||we.findOne(Fi,this._parent),this._inNavbar=this._detectNavbar()}static get Default(){return Vi}static get DefaultType(){return Yi}static get NAME(){return Ai}toggle(){return this._isShown()?this.hide():this.show()}show(){if(Wt(this._element)||this._isShown())return;const t={relatedTarget:this._element};if(!fe.trigger(this._element,Si,t).defaultPrevented){if(this._createPopper(),"ontouchstart"in document.documentElement&&!this._parent.closest(".navbar-nav"))for(const t of[].concat(...document.body.children))fe.on(t,"mouseover",Rt);this._element.focus(),this._element.setAttribute("aria-expanded",!0),this._menu.classList.add(Pi),this._element.classList.add(Pi),fe.trigger(this._element,Di,t)}}hide(){if(Wt(this._element)||!this._isShown())return;const t={relatedTarget:this._element};this._completeHide(t)}dispose(){this._popper&&this._popper.destroy(),super.dispose()}update(){this._inNavbar=this._detectNavbar(),this._popper&&this._popper.update()}_completeHide(t){if(!fe.trigger(this._element,ki,t).defaultPrevented){if("ontouchstart"in document.documentElement)for(const t of[].concat(...document.body.children))fe.off(t,"mouseover",Rt);this._popper&&this._popper.destroy(),this._menu.classList.remove(Pi),this._element.classList.remove(Pi),this._element.setAttribute("aria-expanded","false"),_e.removeDataAttribute(this._menu,"popper"),fe.trigger(this._element,Li,t)}}_getConfig(t){if("object"==typeof(t=super._getConfig(t)).reference&&!Ft(t.reference)&&"function"!=typeof t.reference.getBoundingClientRect)throw new TypeError(`${Ai.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.`);return t}_createPopper(){if(void 0===e)throw new TypeError("Bootstrap's dropdowns require Popper (https://popper.js.org)");let t=this._element;"parent"===this._config.reference?t=this._parent:Ft(this._config.reference)?t=Ht(this._config.reference):"object"==typeof this._config.reference&&(t=this._config.reference);const i=this._getPopperConfig();this._popper=Dt(t,this._menu,i)}_isShown(){return this._menu.classList.contains(Pi)}_getPlacement(){const t=this._parent;if(t.classList.contains("dropend"))return Ri;if(t.classList.contains("dropstart"))return qi;if(t.classList.contains("dropup-center"))return"top";if(t.classList.contains("dropdown-center"))return"bottom";const e="end"===getComputedStyle(this._menu).getPropertyValue("--bs-position").trim();return t.classList.contains("dropup")?e?Bi:Hi:e?zi:Wi}_detectNavbar(){return null!==this._element.closest(".navbar")}_getOffset(){const{offset:t}=this._config;return"string"==typeof t?t.split(",").map((t=>Number.parseInt(t,10))):"function"==typeof t?e=>t(e,this._element):t}_getPopperConfig(){const t={placement:this._getPlacement(),modifiers:[{name:"preventOverflow",options:{boundary:this._config.boundary}},{name:"offset",options:{offset:this._getOffset()}}]};return(this._inNavbar||"static"===this._config.display)&&(_e.setDataAttribute(this._menu,"popper","static"),t.modifiers=[{name:"applyStyles",enabled:!1}]),{...t,...Xt(this._config.popperConfig,[t])}}_selectMenuItem({key:t,target:e}){const i=we.find(".dropdown-menu .dropdown-item:not(.disabled):not(:disabled)",this._menu).filter((t=>Bt(t)));i.length&&Gt(i,e,t===xi,!i.includes(e)).focus()}static jQueryInterface(t){return this.each((function(){const e=Ki.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}static clearMenus(t){if(2===t.button||"keyup"===t.type&&"Tab"!==t.key)return;const e=we.find(ji);for(const i of e){const e=Ki.getInstance(i);if(!e||!1===e._config.autoClose)continue;const n=t.composedPath(),s=n.includes(e._menu);if(n.includes(e._element)||"inside"===e._config.autoClose&&!s||"outside"===e._config.autoClose&&s)continue;if(e._menu.contains(t.target)&&("keyup"===t.type&&"Tab"===t.key||/input|select|option|textarea|form/i.test(t.target.tagName)))continue;const o={relatedTarget:e._element};"click"===t.type&&(o.clickEvent=t),e._completeHide(o)}}static dataApiKeydownHandler(t){const e=/input|textarea/i.test(t.target.tagName),i="Escape"===t.key,n=[Oi,xi].includes(t.key);if(!n&&!i)return;if(e&&!i)return;t.preventDefault();const s=this.matches(Mi)?this:we.prev(this,Mi)[0]||we.next(this,Mi)[0]||we.findOne(Mi,t.delegateTarget.parentNode),o=Ki.getOrCreateInstance(s);if(n)return t.stopPropagation(),o.show(),void o._selectMenuItem(t);o._isShown()&&(t.stopPropagation(),o.hide(),s.focus())}}fe.on(document,Ii,Mi,Ki.dataApiKeydownHandler),fe.on(document,Ii,Fi,Ki.dataApiKeydownHandler),fe.on(document,$i,Ki.clearMenus),fe.on(document,Ni,Ki.clearMenus),fe.on(document,$i,Mi,(function(t){t.preventDefault(),Ki.getOrCreateInstance(this).toggle()})),Qt(Ki);const Qi="backdrop",Xi="show",Ui=`mousedown.bs.${Qi}`,Gi={className:"modal-backdrop",clickCallback:null,isAnimated:!1,isVisible:!0,rootElement:"body"},Ji={className:"string",clickCallback:"(function|null)",isAnimated:"boolean",isVisible:"boolean",rootElement:"(element|string)"};class Zi extends be{constructor(t){super(),this._config=this._getConfig(t),this._isAppended=!1,this._element=null}static get Default(){return Gi}static get DefaultType(){return Ji}static get NAME(){return Qi}show(t){if(!this._config.isVisible)return void Xt(t);this._append();const e=this._getElement();this._config.isAnimated&&qt(e),e.classList.add(Xi),this._emulateAnimation((()=>{Xt(t)}))}hide(t){this._config.isVisible?(this._getElement().classList.remove(Xi),this._emulateAnimation((()=>{this.dispose(),Xt(t)}))):Xt(t)}dispose(){this._isAppended&&(fe.off(this._element,Ui),this._element.remove(),this._isAppended=!1)}_getElement(){if(!this._element){const t=document.createElement("div");t.className=this._config.className,this._config.isAnimated&&t.classList.add("fade"),this._element=t}return this._element}_configAfterMerge(t){return t.rootElement=Ht(t.rootElement),t}_append(){if(this._isAppended)return;const t=this._getElement();this._config.rootElement.append(t),fe.on(t,Ui,(()=>{Xt(this._config.clickCallback)})),this._isAppended=!0}_emulateAnimation(t){Ut(t,this._getElement(),this._config.isAnimated)}}const tn=".bs.focustrap",en=`focusin${tn}`,nn=`keydown.tab${tn}`,sn="backward",on={autofocus:!0,trapElement:null},rn={autofocus:"boolean",trapElement:"element"};class an extends be{constructor(t){super(),this._config=this._getConfig(t),this._isActive=!1,this._lastTabNavDirection=null}static get Default(){return on}static get DefaultType(){return rn}static get NAME(){return"focustrap"}activate(){this._isActive||(this._config.autofocus&&this._config.trapElement.focus(),fe.off(document,tn),fe.on(document,en,(t=>this._handleFocusin(t))),fe.on(document,nn,(t=>this._handleKeydown(t))),this._isActive=!0)}deactivate(){this._isActive&&(this._isActive=!1,fe.off(document,tn))}_handleFocusin(t){const{trapElement:e}=this._config;if(t.target===document||t.target===e||e.contains(t.target))return;const i=we.focusableChildren(e);0===i.length?e.focus():this._lastTabNavDirection===sn?i[i.length-1].focus():i[0].focus()}_handleKeydown(t){"Tab"===t.key&&(this._lastTabNavDirection=t.shiftKey?sn:"forward")}}const ln=".fixed-top, .fixed-bottom, .is-fixed, .sticky-top",cn=".sticky-top",hn="padding-right",dn="margin-right";class un{constructor(){this._element=document.body}getWidth(){const t=document.documentElement.clientWidth;return Math.abs(window.innerWidth-t)}hide(){const t=this.getWidth();this._disableOverFlow(),this._setElementAttributes(this._element,hn,(e=>e+t)),this._setElementAttributes(ln,hn,(e=>e+t)),this._setElementAttributes(cn,dn,(e=>e-t))}reset(){this._resetElementAttributes(this._element,"overflow"),this._resetElementAttributes(this._element,hn),this._resetElementAttributes(ln,hn),this._resetElementAttributes(cn,dn)}isOverflowing(){return this.getWidth()>0}_disableOverFlow(){this._saveInitialAttribute(this._element,"overflow"),this._element.style.overflow="hidden"}_setElementAttributes(t,e,i){const n=this.getWidth();this._applyManipulationCallback(t,(t=>{if(t!==this._element&&window.innerWidth>t.clientWidth+n)return;this._saveInitialAttribute(t,e);const s=window.getComputedStyle(t).getPropertyValue(e);t.style.setProperty(e,`${i(Number.parseFloat(s))}px`)}))}_saveInitialAttribute(t,e){const i=t.style.getPropertyValue(e);i&&_e.setDataAttribute(t,e,i)}_resetElementAttributes(t,e){this._applyManipulationCallback(t,(t=>{const i=_e.getDataAttribute(t,e);null!==i?(_e.removeDataAttribute(t,e),t.style.setProperty(e,i)):t.style.removeProperty(e)}))}_applyManipulationCallback(t,e){if(Ft(t))e(t);else for(const i of we.find(t,this._element))e(i)}}const fn=".bs.modal",pn=`hide${fn}`,mn=`hidePrevented${fn}`,gn=`hidden${fn}`,_n=`show${fn}`,bn=`shown${fn}`,vn=`resize${fn}`,yn=`click.dismiss${fn}`,wn=`mousedown.dismiss${fn}`,En=`keydown.dismiss${fn}`,An=`click${fn}.data-api`,Tn="modal-open",Cn="show",On="modal-static",xn={backdrop:!0,focus:!0,keyboard:!0},kn={backdrop:"(boolean|string)",focus:"boolean",keyboard:"boolean"};class Ln extends ve{constructor(t,e){super(t,e),this._dialog=we.findOne(".modal-dialog",this._element),this._backdrop=this._initializeBackDrop(),this._focustrap=this._initializeFocusTrap(),this._isShown=!1,this._isTransitioning=!1,this._scrollBar=new un,this._addEventListeners()}static get Default(){return xn}static get DefaultType(){return kn}static get NAME(){return"modal"}toggle(t){return this._isShown?this.hide():this.show(t)}show(t){this._isShown||this._isTransitioning||fe.trigger(this._element,_n,{relatedTarget:t}).defaultPrevented||(this._isShown=!0,this._isTransitioning=!0,this._scrollBar.hide(),document.body.classList.add(Tn),this._adjustDialog(),this._backdrop.show((()=>this._showElement(t))))}hide(){this._isShown&&!this._isTransitioning&&(fe.trigger(this._element,pn).defaultPrevented||(this._isShown=!1,this._isTransitioning=!0,this._focustrap.deactivate(),this._element.classList.remove(Cn),this._queueCallback((()=>this._hideModal()),this._element,this._isAnimated())))}dispose(){fe.off(window,fn),fe.off(this._dialog,fn),this._backdrop.dispose(),this._focustrap.deactivate(),super.dispose()}handleUpdate(){this._adjustDialog()}_initializeBackDrop(){return new Zi({isVisible:Boolean(this._config.backdrop),isAnimated:this._isAnimated()})}_initializeFocusTrap(){return new an({trapElement:this._element})}_showElement(t){document.body.contains(this._element)||document.body.append(this._element),this._element.style.display="block",this._element.removeAttribute("aria-hidden"),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),this._element.scrollTop=0;const e=we.findOne(".modal-body",this._dialog);e&&(e.scrollTop=0),qt(this._element),this._element.classList.add(Cn),this._queueCallback((()=>{this._config.focus&&this._focustrap.activate(),this._isTransitioning=!1,fe.trigger(this._element,bn,{relatedTarget:t})}),this._dialog,this._isAnimated())}_addEventListeners(){fe.on(this._element,En,(t=>{"Escape"===t.key&&(this._config.keyboard?this.hide():this._triggerBackdropTransition())})),fe.on(window,vn,(()=>{this._isShown&&!this._isTransitioning&&this._adjustDialog()})),fe.on(this._element,wn,(t=>{fe.one(this._element,yn,(e=>{this._element===t.target&&this._element===e.target&&("static"!==this._config.backdrop?this._config.backdrop&&this.hide():this._triggerBackdropTransition())}))}))}_hideModal(){this._element.style.display="none",this._element.setAttribute("aria-hidden",!0),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._isTransitioning=!1,this._backdrop.hide((()=>{document.body.classList.remove(Tn),this._resetAdjustments(),this._scrollBar.reset(),fe.trigger(this._element,gn)}))}_isAnimated(){return this._element.classList.contains("fade")}_triggerBackdropTransition(){if(fe.trigger(this._element,mn).defaultPrevented)return;const t=this._element.scrollHeight>document.documentElement.clientHeight,e=this._element.style.overflowY;"hidden"===e||this._element.classList.contains(On)||(t||(this._element.style.overflowY="hidden"),this._element.classList.add(On),this._queueCallback((()=>{this._element.classList.remove(On),this._queueCallback((()=>{this._element.style.overflowY=e}),this._dialog)}),this._dialog),this._element.focus())}_adjustDialog(){const t=this._element.scrollHeight>document.documentElement.clientHeight,e=this._scrollBar.getWidth(),i=e>0;if(i&&!t){const t=Kt()?"paddingLeft":"paddingRight";this._element.style[t]=`${e}px`}if(!i&&t){const t=Kt()?"paddingRight":"paddingLeft";this._element.style[t]=`${e}px`}}_resetAdjustments(){this._element.style.paddingLeft="",this._element.style.paddingRight=""}static jQueryInterface(t,e){return this.each((function(){const i=Ln.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===i[t])throw new TypeError(`No method named "${t}"`);i[t](e)}}))}}fe.on(document,An,'[data-bs-toggle="modal"]',(function(t){const e=we.getElementFromSelector(this);["A","AREA"].includes(this.tagName)&&t.preventDefault(),fe.one(e,_n,(t=>{t.defaultPrevented||fe.one(e,gn,(()=>{Bt(this)&&this.focus()}))}));const i=we.findOne(".modal.show");i&&Ln.getInstance(i).hide(),Ln.getOrCreateInstance(e).toggle(this)})),Ee(Ln),Qt(Ln);const Sn=".bs.offcanvas",Dn=".data-api",$n=`load${Sn}${Dn}`,In="show",Nn="showing",Pn="hiding",Mn=".offcanvas.show",jn=`show${Sn}`,Fn=`shown${Sn}`,Hn=`hide${Sn}`,Bn=`hidePrevented${Sn}`,Wn=`hidden${Sn}`,zn=`resize${Sn}`,Rn=`click${Sn}${Dn}`,qn=`keydown.dismiss${Sn}`,Vn={backdrop:!0,keyboard:!0,scroll:!1},Yn={backdrop:"(boolean|string)",keyboard:"boolean",scroll:"boolean"};class Kn extends ve{constructor(t,e){super(t,e),this._isShown=!1,this._backdrop=this._initializeBackDrop(),this._focustrap=this._initializeFocusTrap(),this._addEventListeners()}static get Default(){return Vn}static get DefaultType(){return Yn}static get NAME(){return"offcanvas"}toggle(t){return this._isShown?this.hide():this.show(t)}show(t){this._isShown||fe.trigger(this._element,jn,{relatedTarget:t}).defaultPrevented||(this._isShown=!0,this._backdrop.show(),this._config.scroll||(new un).hide(),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),this._element.classList.add(Nn),this._queueCallback((()=>{this._config.scroll&&!this._config.backdrop||this._focustrap.activate(),this._element.classList.add(In),this._element.classList.remove(Nn),fe.trigger(this._element,Fn,{relatedTarget:t})}),this._element,!0))}hide(){this._isShown&&(fe.trigger(this._element,Hn).defaultPrevented||(this._focustrap.deactivate(),this._element.blur(),this._isShown=!1,this._element.classList.add(Pn),this._backdrop.hide(),this._queueCallback((()=>{this._element.classList.remove(In,Pn),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._config.scroll||(new un).reset(),fe.trigger(this._element,Wn)}),this._element,!0)))}dispose(){this._backdrop.dispose(),this._focustrap.deactivate(),super.dispose()}_initializeBackDrop(){const t=Boolean(this._config.backdrop);return new Zi({className:"offcanvas-backdrop",isVisible:t,isAnimated:!0,rootElement:this._element.parentNode,clickCallback:t?()=>{"static"!==this._config.backdrop?this.hide():fe.trigger(this._element,Bn)}:null})}_initializeFocusTrap(){return new an({trapElement:this._element})}_addEventListeners(){fe.on(this._element,qn,(t=>{"Escape"===t.key&&(this._config.keyboard?this.hide():fe.trigger(this._element,Bn))}))}static jQueryInterface(t){return this.each((function(){const e=Kn.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}fe.on(document,Rn,'[data-bs-toggle="offcanvas"]',(function(t){const e=we.getElementFromSelector(this);if(["A","AREA"].includes(this.tagName)&&t.preventDefault(),Wt(this))return;fe.one(e,Wn,(()=>{Bt(this)&&this.focus()}));const i=we.findOne(Mn);i&&i!==e&&Kn.getInstance(i).hide(),Kn.getOrCreateInstance(e).toggle(this)})),fe.on(window,$n,(()=>{for(const t of we.find(Mn))Kn.getOrCreateInstance(t).show()})),fe.on(window,zn,(()=>{for(const t of we.find("[aria-modal][class*=show][class*=offcanvas-]"))"fixed"!==getComputedStyle(t).position&&Kn.getOrCreateInstance(t).hide()})),Ee(Kn),Qt(Kn);const Qn={"*":["class","dir","id","lang","role",/^aria-[\w-]*$/i],a:["target","href","title","rel"],area:[],b:[],br:[],col:[],code:[],dd:[],div:[],dl:[],dt:[],em:[],hr:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],i:[],img:["src","srcset","alt","title","width","height"],li:[],ol:[],p:[],pre:[],s:[],small:[],span:[],sub:[],sup:[],strong:[],u:[],ul:[]},Xn=new Set(["background","cite","href","itemtype","longdesc","poster","src","xlink:href"]),Un=/^(?!javascript:)(?:[a-z0-9+.-]+:|[^&:/?#]*(?:[/?#]|$))/i,Gn=(t,e)=>{const i=t.nodeName.toLowerCase();return e.includes(i)?!Xn.has(i)||Boolean(Un.test(t.nodeValue)):e.filter((t=>t instanceof RegExp)).some((t=>t.test(i)))},Jn={allowList:Qn,content:{},extraClass:"",html:!1,sanitize:!0,sanitizeFn:null,template:"
    "},Zn={allowList:"object",content:"object",extraClass:"(string|function)",html:"boolean",sanitize:"boolean",sanitizeFn:"(null|function)",template:"string"},ts={entry:"(string|element|function|null)",selector:"(string|element)"};class es extends be{constructor(t){super(),this._config=this._getConfig(t)}static get Default(){return Jn}static get DefaultType(){return Zn}static get NAME(){return"TemplateFactory"}getContent(){return Object.values(this._config.content).map((t=>this._resolvePossibleFunction(t))).filter(Boolean)}hasContent(){return this.getContent().length>0}changeContent(t){return this._checkContent(t),this._config.content={...this._config.content,...t},this}toHtml(){const t=document.createElement("div");t.innerHTML=this._maybeSanitize(this._config.template);for(const[e,i]of Object.entries(this._config.content))this._setContent(t,i,e);const e=t.children[0],i=this._resolvePossibleFunction(this._config.extraClass);return i&&e.classList.add(...i.split(" ")),e}_typeCheckConfig(t){super._typeCheckConfig(t),this._checkContent(t.content)}_checkContent(t){for(const[e,i]of Object.entries(t))super._typeCheckConfig({selector:e,entry:i},ts)}_setContent(t,e,i){const n=we.findOne(i,t);n&&((e=this._resolvePossibleFunction(e))?Ft(e)?this._putElementInTemplate(Ht(e),n):this._config.html?n.innerHTML=this._maybeSanitize(e):n.textContent=e:n.remove())}_maybeSanitize(t){return this._config.sanitize?function(t,e,i){if(!t.length)return t;if(i&&"function"==typeof i)return i(t);const n=(new window.DOMParser).parseFromString(t,"text/html"),s=[].concat(...n.body.querySelectorAll("*"));for(const t of s){const i=t.nodeName.toLowerCase();if(!Object.keys(e).includes(i)){t.remove();continue}const n=[].concat(...t.attributes),s=[].concat(e["*"]||[],e[i]||[]);for(const e of n)Gn(e,s)||t.removeAttribute(e.nodeName)}return n.body.innerHTML}(t,this._config.allowList,this._config.sanitizeFn):t}_resolvePossibleFunction(t){return Xt(t,[this])}_putElementInTemplate(t,e){if(this._config.html)return e.innerHTML="",void e.append(t);e.textContent=t.textContent}}const is=new Set(["sanitize","allowList","sanitizeFn"]),ns="fade",ss="show",os=".tooltip-inner",rs=".modal",as="hide.bs.modal",ls="hover",cs="focus",hs={AUTO:"auto",TOP:"top",RIGHT:Kt()?"left":"right",BOTTOM:"bottom",LEFT:Kt()?"right":"left"},ds={allowList:Qn,animation:!0,boundary:"clippingParents",container:!1,customClass:"",delay:0,fallbackPlacements:["top","right","bottom","left"],html:!1,offset:[0,6],placement:"top",popperConfig:null,sanitize:!0,sanitizeFn:null,selector:!1,template:'',title:"",trigger:"hover focus"},us={allowList:"object",animation:"boolean",boundary:"(string|element)",container:"(string|element|boolean)",customClass:"(string|function)",delay:"(number|object)",fallbackPlacements:"array",html:"boolean",offset:"(array|string|function)",placement:"(string|function)",popperConfig:"(null|object|function)",sanitize:"boolean",sanitizeFn:"(null|function)",selector:"(string|boolean)",template:"string",title:"(string|element|function)",trigger:"string"};class fs extends ve{constructor(t,i){if(void 0===e)throw new TypeError("Bootstrap's tooltips require Popper (https://popper.js.org)");super(t,i),this._isEnabled=!0,this._timeout=0,this._isHovered=null,this._activeTrigger={},this._popper=null,this._templateFactory=null,this._newContent=null,this.tip=null,this._setListeners(),this._config.selector||this._fixTitle()}static get Default(){return ds}static get DefaultType(){return us}static get NAME(){return"tooltip"}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}toggleEnabled(){this._isEnabled=!this._isEnabled}toggle(){this._isEnabled&&(this._activeTrigger.click=!this._activeTrigger.click,this._isShown()?this._leave():this._enter())}dispose(){clearTimeout(this._timeout),fe.off(this._element.closest(rs),as,this._hideModalHandler),this._element.getAttribute("data-bs-original-title")&&this._element.setAttribute("title",this._element.getAttribute("data-bs-original-title")),this._disposePopper(),super.dispose()}show(){if("none"===this._element.style.display)throw new Error("Please use show on visible elements");if(!this._isWithContent()||!this._isEnabled)return;const t=fe.trigger(this._element,this.constructor.eventName("show")),e=(zt(this._element)||this._element.ownerDocument.documentElement).contains(this._element);if(t.defaultPrevented||!e)return;this._disposePopper();const i=this._getTipElement();this._element.setAttribute("aria-describedby",i.getAttribute("id"));const{container:n}=this._config;if(this._element.ownerDocument.documentElement.contains(this.tip)||(n.append(i),fe.trigger(this._element,this.constructor.eventName("inserted"))),this._popper=this._createPopper(i),i.classList.add(ss),"ontouchstart"in document.documentElement)for(const t of[].concat(...document.body.children))fe.on(t,"mouseover",Rt);this._queueCallback((()=>{fe.trigger(this._element,this.constructor.eventName("shown")),!1===this._isHovered&&this._leave(),this._isHovered=!1}),this.tip,this._isAnimated())}hide(){if(this._isShown()&&!fe.trigger(this._element,this.constructor.eventName("hide")).defaultPrevented){if(this._getTipElement().classList.remove(ss),"ontouchstart"in document.documentElement)for(const t of[].concat(...document.body.children))fe.off(t,"mouseover",Rt);this._activeTrigger.click=!1,this._activeTrigger[cs]=!1,this._activeTrigger[ls]=!1,this._isHovered=null,this._queueCallback((()=>{this._isWithActiveTrigger()||(this._isHovered||this._disposePopper(),this._element.removeAttribute("aria-describedby"),fe.trigger(this._element,this.constructor.eventName("hidden")))}),this.tip,this._isAnimated())}}update(){this._popper&&this._popper.update()}_isWithContent(){return Boolean(this._getTitle())}_getTipElement(){return this.tip||(this.tip=this._createTipElement(this._newContent||this._getContentForTemplate())),this.tip}_createTipElement(t){const e=this._getTemplateFactory(t).toHtml();if(!e)return null;e.classList.remove(ns,ss),e.classList.add(`bs-${this.constructor.NAME}-auto`);const i=(t=>{do{t+=Math.floor(1e6*Math.random())}while(document.getElementById(t));return t})(this.constructor.NAME).toString();return e.setAttribute("id",i),this._isAnimated()&&e.classList.add(ns),e}setContent(t){this._newContent=t,this._isShown()&&(this._disposePopper(),this.show())}_getTemplateFactory(t){return this._templateFactory?this._templateFactory.changeContent(t):this._templateFactory=new es({...this._config,content:t,extraClass:this._resolvePossibleFunction(this._config.customClass)}),this._templateFactory}_getContentForTemplate(){return{[os]:this._getTitle()}}_getTitle(){return this._resolvePossibleFunction(this._config.title)||this._element.getAttribute("data-bs-original-title")}_initializeOnDelegatedTarget(t){return this.constructor.getOrCreateInstance(t.delegateTarget,this._getDelegateConfig())}_isAnimated(){return this._config.animation||this.tip&&this.tip.classList.contains(ns)}_isShown(){return this.tip&&this.tip.classList.contains(ss)}_createPopper(t){const e=Xt(this._config.placement,[this,t,this._element]),i=hs[e.toUpperCase()];return Dt(this._element,t,this._getPopperConfig(i))}_getOffset(){const{offset:t}=this._config;return"string"==typeof t?t.split(",").map((t=>Number.parseInt(t,10))):"function"==typeof t?e=>t(e,this._element):t}_resolvePossibleFunction(t){return Xt(t,[this._element])}_getPopperConfig(t){const e={placement:t,modifiers:[{name:"flip",options:{fallbackPlacements:this._config.fallbackPlacements}},{name:"offset",options:{offset:this._getOffset()}},{name:"preventOverflow",options:{boundary:this._config.boundary}},{name:"arrow",options:{element:`.${this.constructor.NAME}-arrow`}},{name:"preSetPlacement",enabled:!0,phase:"beforeMain",fn:t=>{this._getTipElement().setAttribute("data-popper-placement",t.state.placement)}}]};return{...e,...Xt(this._config.popperConfig,[e])}}_setListeners(){const t=this._config.trigger.split(" ");for(const e of t)if("click"===e)fe.on(this._element,this.constructor.eventName("click"),this._config.selector,(t=>{this._initializeOnDelegatedTarget(t).toggle()}));else if("manual"!==e){const t=e===ls?this.constructor.eventName("mouseenter"):this.constructor.eventName("focusin"),i=e===ls?this.constructor.eventName("mouseleave"):this.constructor.eventName("focusout");fe.on(this._element,t,this._config.selector,(t=>{const e=this._initializeOnDelegatedTarget(t);e._activeTrigger["focusin"===t.type?cs:ls]=!0,e._enter()})),fe.on(this._element,i,this._config.selector,(t=>{const e=this._initializeOnDelegatedTarget(t);e._activeTrigger["focusout"===t.type?cs:ls]=e._element.contains(t.relatedTarget),e._leave()}))}this._hideModalHandler=()=>{this._element&&this.hide()},fe.on(this._element.closest(rs),as,this._hideModalHandler)}_fixTitle(){const t=this._element.getAttribute("title");t&&(this._element.getAttribute("aria-label")||this._element.textContent.trim()||this._element.setAttribute("aria-label",t),this._element.setAttribute("data-bs-original-title",t),this._element.removeAttribute("title"))}_enter(){this._isShown()||this._isHovered?this._isHovered=!0:(this._isHovered=!0,this._setTimeout((()=>{this._isHovered&&this.show()}),this._config.delay.show))}_leave(){this._isWithActiveTrigger()||(this._isHovered=!1,this._setTimeout((()=>{this._isHovered||this.hide()}),this._config.delay.hide))}_setTimeout(t,e){clearTimeout(this._timeout),this._timeout=setTimeout(t,e)}_isWithActiveTrigger(){return Object.values(this._activeTrigger).includes(!0)}_getConfig(t){const e=_e.getDataAttributes(this._element);for(const t of Object.keys(e))is.has(t)&&delete e[t];return t={...e,..."object"==typeof t&&t?t:{}},t=this._mergeConfigObj(t),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}_configAfterMerge(t){return t.container=!1===t.container?document.body:Ht(t.container),"number"==typeof t.delay&&(t.delay={show:t.delay,hide:t.delay}),"number"==typeof t.title&&(t.title=t.title.toString()),"number"==typeof t.content&&(t.content=t.content.toString()),t}_getDelegateConfig(){const t={};for(const[e,i]of Object.entries(this._config))this.constructor.Default[e]!==i&&(t[e]=i);return t.selector=!1,t.trigger="manual",t}_disposePopper(){this._popper&&(this._popper.destroy(),this._popper=null),this.tip&&(this.tip.remove(),this.tip=null)}static jQueryInterface(t){return this.each((function(){const e=fs.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}Qt(fs);const ps=".popover-header",ms=".popover-body",gs={...fs.Default,content:"",offset:[0,8],placement:"right",template:'',trigger:"click"},_s={...fs.DefaultType,content:"(null|string|element|function)"};class bs extends fs{static get Default(){return gs}static get DefaultType(){return _s}static get NAME(){return"popover"}_isWithContent(){return this._getTitle()||this._getContent()}_getContentForTemplate(){return{[ps]:this._getTitle(),[ms]:this._getContent()}}_getContent(){return this._resolvePossibleFunction(this._config.content)}static jQueryInterface(t){return this.each((function(){const e=bs.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}Qt(bs);const vs=".bs.scrollspy",ys=`activate${vs}`,ws=`click${vs}`,Es=`load${vs}.data-api`,As="active",Ts="[href]",Cs=".nav-link",Os=`${Cs}, .nav-item > ${Cs}, .list-group-item`,xs={offset:null,rootMargin:"0px 0px -25%",smoothScroll:!1,target:null,threshold:[.1,.5,1]},ks={offset:"(number|null)",rootMargin:"string",smoothScroll:"boolean",target:"element",threshold:"array"};class Ls extends ve{constructor(t,e){super(t,e),this._targetLinks=new Map,this._observableSections=new Map,this._rootElement="visible"===getComputedStyle(this._element).overflowY?null:this._element,this._activeTarget=null,this._observer=null,this._previousScrollData={visibleEntryTop:0,parentScrollTop:0},this.refresh()}static get Default(){return xs}static get DefaultType(){return ks}static get NAME(){return"scrollspy"}refresh(){this._initializeTargetsAndObservables(),this._maybeEnableSmoothScroll(),this._observer?this._observer.disconnect():this._observer=this._getNewObserver();for(const t of this._observableSections.values())this._observer.observe(t)}dispose(){this._observer.disconnect(),super.dispose()}_configAfterMerge(t){return t.target=Ht(t.target)||document.body,t.rootMargin=t.offset?`${t.offset}px 0px -30%`:t.rootMargin,"string"==typeof t.threshold&&(t.threshold=t.threshold.split(",").map((t=>Number.parseFloat(t)))),t}_maybeEnableSmoothScroll(){this._config.smoothScroll&&(fe.off(this._config.target,ws),fe.on(this._config.target,ws,Ts,(t=>{const e=this._observableSections.get(t.target.hash);if(e){t.preventDefault();const i=this._rootElement||window,n=e.offsetTop-this._element.offsetTop;if(i.scrollTo)return void i.scrollTo({top:n,behavior:"smooth"});i.scrollTop=n}})))}_getNewObserver(){const t={root:this._rootElement,threshold:this._config.threshold,rootMargin:this._config.rootMargin};return new IntersectionObserver((t=>this._observerCallback(t)),t)}_observerCallback(t){const e=t=>this._targetLinks.get(`#${t.target.id}`),i=t=>{this._previousScrollData.visibleEntryTop=t.target.offsetTop,this._process(e(t))},n=(this._rootElement||document.documentElement).scrollTop,s=n>=this._previousScrollData.parentScrollTop;this._previousScrollData.parentScrollTop=n;for(const o of t){if(!o.isIntersecting){this._activeTarget=null,this._clearActiveClass(e(o));continue}const t=o.target.offsetTop>=this._previousScrollData.visibleEntryTop;if(s&&t){if(i(o),!n)return}else s||t||i(o)}}_initializeTargetsAndObservables(){this._targetLinks=new Map,this._observableSections=new Map;const t=we.find(Ts,this._config.target);for(const e of t){if(!e.hash||Wt(e))continue;const t=we.findOne(decodeURI(e.hash),this._element);Bt(t)&&(this._targetLinks.set(decodeURI(e.hash),e),this._observableSections.set(e.hash,t))}}_process(t){this._activeTarget!==t&&(this._clearActiveClass(this._config.target),this._activeTarget=t,t.classList.add(As),this._activateParents(t),fe.trigger(this._element,ys,{relatedTarget:t}))}_activateParents(t){if(t.classList.contains("dropdown-item"))we.findOne(".dropdown-toggle",t.closest(".dropdown")).classList.add(As);else for(const e of we.parents(t,".nav, .list-group"))for(const t of we.prev(e,Os))t.classList.add(As)}_clearActiveClass(t){t.classList.remove(As);const e=we.find(`${Ts}.${As}`,t);for(const t of e)t.classList.remove(As)}static jQueryInterface(t){return this.each((function(){const e=Ls.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}))}}fe.on(window,Es,(()=>{for(const t of we.find('[data-bs-spy="scroll"]'))Ls.getOrCreateInstance(t)})),Qt(Ls);const Ss=".bs.tab",Ds=`hide${Ss}`,$s=`hidden${Ss}`,Is=`show${Ss}`,Ns=`shown${Ss}`,Ps=`click${Ss}`,Ms=`keydown${Ss}`,js=`load${Ss}`,Fs="ArrowLeft",Hs="ArrowRight",Bs="ArrowUp",Ws="ArrowDown",zs="Home",Rs="End",qs="active",Vs="fade",Ys="show",Ks=".dropdown-toggle",Qs=`:not(${Ks})`,Xs='[data-bs-toggle="tab"], [data-bs-toggle="pill"], [data-bs-toggle="list"]',Us=`.nav-link${Qs}, .list-group-item${Qs}, [role="tab"]${Qs}, ${Xs}`,Gs=`.${qs}[data-bs-toggle="tab"], .${qs}[data-bs-toggle="pill"], .${qs}[data-bs-toggle="list"]`;class Js extends ve{constructor(t){super(t),this._parent=this._element.closest('.list-group, .nav, [role="tablist"]'),this._parent&&(this._setInitialAttributes(this._parent,this._getChildren()),fe.on(this._element,Ms,(t=>this._keydown(t))))}static get NAME(){return"tab"}show(){const t=this._element;if(this._elemIsActive(t))return;const e=this._getActiveElem(),i=e?fe.trigger(e,Ds,{relatedTarget:t}):null;fe.trigger(t,Is,{relatedTarget:e}).defaultPrevented||i&&i.defaultPrevented||(this._deactivate(e,t),this._activate(t,e))}_activate(t,e){t&&(t.classList.add(qs),this._activate(we.getElementFromSelector(t)),this._queueCallback((()=>{"tab"===t.getAttribute("role")?(t.removeAttribute("tabindex"),t.setAttribute("aria-selected",!0),this._toggleDropDown(t,!0),fe.trigger(t,Ns,{relatedTarget:e})):t.classList.add(Ys)}),t,t.classList.contains(Vs)))}_deactivate(t,e){t&&(t.classList.remove(qs),t.blur(),this._deactivate(we.getElementFromSelector(t)),this._queueCallback((()=>{"tab"===t.getAttribute("role")?(t.setAttribute("aria-selected",!1),t.setAttribute("tabindex","-1"),this._toggleDropDown(t,!1),fe.trigger(t,$s,{relatedTarget:e})):t.classList.remove(Ys)}),t,t.classList.contains(Vs)))}_keydown(t){if(![Fs,Hs,Bs,Ws,zs,Rs].includes(t.key))return;t.stopPropagation(),t.preventDefault();const e=this._getChildren().filter((t=>!Wt(t)));let i;if([zs,Rs].includes(t.key))i=e[t.key===zs?0:e.length-1];else{const n=[Hs,Ws].includes(t.key);i=Gt(e,t.target,n,!0)}i&&(i.focus({preventScroll:!0}),Js.getOrCreateInstance(i).show())}_getChildren(){return we.find(Us,this._parent)}_getActiveElem(){return this._getChildren().find((t=>this._elemIsActive(t)))||null}_setInitialAttributes(t,e){this._setAttributeIfNotExists(t,"role","tablist");for(const t of e)this._setInitialAttributesOnChild(t)}_setInitialAttributesOnChild(t){t=this._getInnerElement(t);const e=this._elemIsActive(t),i=this._getOuterElement(t);t.setAttribute("aria-selected",e),i!==t&&this._setAttributeIfNotExists(i,"role","presentation"),e||t.setAttribute("tabindex","-1"),this._setAttributeIfNotExists(t,"role","tab"),this._setInitialAttributesOnTargetPanel(t)}_setInitialAttributesOnTargetPanel(t){const e=we.getElementFromSelector(t);e&&(this._setAttributeIfNotExists(e,"role","tabpanel"),t.id&&this._setAttributeIfNotExists(e,"aria-labelledby",`${t.id}`))}_toggleDropDown(t,e){const i=this._getOuterElement(t);if(!i.classList.contains("dropdown"))return;const n=(t,n)=>{const s=we.findOne(t,i);s&&s.classList.toggle(n,e)};n(Ks,qs),n(".dropdown-menu",Ys),i.setAttribute("aria-expanded",e)}_setAttributeIfNotExists(t,e,i){t.hasAttribute(e)||t.setAttribute(e,i)}_elemIsActive(t){return t.classList.contains(qs)}_getInnerElement(t){return t.matches(Us)?t:we.findOne(Us,t)}_getOuterElement(t){return t.closest(".nav-item, .list-group-item")||t}static jQueryInterface(t){return this.each((function(){const e=Js.getOrCreateInstance(this);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}))}}fe.on(document,Ps,Xs,(function(t){["A","AREA"].includes(this.tagName)&&t.preventDefault(),Wt(this)||Js.getOrCreateInstance(this).show()})),fe.on(window,js,(()=>{for(const t of we.find(Gs))Js.getOrCreateInstance(t)})),Qt(Js);const Zs=".bs.toast",to=`mouseover${Zs}`,eo=`mouseout${Zs}`,io=`focusin${Zs}`,no=`focusout${Zs}`,so=`hide${Zs}`,oo=`hidden${Zs}`,ro=`show${Zs}`,ao=`shown${Zs}`,lo="hide",co="show",ho="showing",uo={animation:"boolean",autohide:"boolean",delay:"number"},fo={animation:!0,autohide:!0,delay:5e3};class po extends ve{constructor(t,e){super(t,e),this._timeout=null,this._hasMouseInteraction=!1,this._hasKeyboardInteraction=!1,this._setListeners()}static get Default(){return fo}static get DefaultType(){return uo}static get NAME(){return"toast"}show(){fe.trigger(this._element,ro).defaultPrevented||(this._clearTimeout(),this._config.animation&&this._element.classList.add("fade"),this._element.classList.remove(lo),qt(this._element),this._element.classList.add(co,ho),this._queueCallback((()=>{this._element.classList.remove(ho),fe.trigger(this._element,ao),this._maybeScheduleHide()}),this._element,this._config.animation))}hide(){this.isShown()&&(fe.trigger(this._element,so).defaultPrevented||(this._element.classList.add(ho),this._queueCallback((()=>{this._element.classList.add(lo),this._element.classList.remove(ho,co),fe.trigger(this._element,oo)}),this._element,this._config.animation)))}dispose(){this._clearTimeout(),this.isShown()&&this._element.classList.remove(co),super.dispose()}isShown(){return this._element.classList.contains(co)}_maybeScheduleHide(){this._config.autohide&&(this._hasMouseInteraction||this._hasKeyboardInteraction||(this._timeout=setTimeout((()=>{this.hide()}),this._config.delay)))}_onInteraction(t,e){switch(t.type){case"mouseover":case"mouseout":this._hasMouseInteraction=e;break;case"focusin":case"focusout":this._hasKeyboardInteraction=e}if(e)return void this._clearTimeout();const i=t.relatedTarget;this._element===i||this._element.contains(i)||this._maybeScheduleHide()}_setListeners(){fe.on(this._element,to,(t=>this._onInteraction(t,!0))),fe.on(this._element,eo,(t=>this._onInteraction(t,!1))),fe.on(this._element,io,(t=>this._onInteraction(t,!0))),fe.on(this._element,no,(t=>this._onInteraction(t,!1)))}_clearTimeout(){clearTimeout(this._timeout),this._timeout=null}static jQueryInterface(t){return this.each((function(){const e=po.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}function mo(t){"loading"!=document.readyState?t():document.addEventListener("DOMContentLoaded",t)}Ee(po),Qt(po),mo((function(){[].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]')).map((function(t){return new fs(t,{delay:{show:500,hide:100}})}))})),mo((function(){document.getElementById("pst-back-to-top").addEventListener("click",(function(){document.body.scrollTop=0,document.documentElement.scrollTop=0}))})),mo((function(){var t=document.getElementById("pst-back-to-top"),e=document.getElementsByClassName("bd-header")[0].getBoundingClientRect();window.addEventListener("scroll",(function(){this.oldScroll>this.scrollY&&this.scrollY>e.bottom?t.style.display="block":t.style.display="none",this.oldScroll=this.scrollY}))})),window.bootstrap=i})(); +//# sourceMappingURL=bootstrap.js.map \ No newline at end of file diff --git a/book/_build/html/_static/scripts/bootstrap.js.LICENSE.txt b/book/_build/html/_static/scripts/bootstrap.js.LICENSE.txt new file mode 100644 index 0000000..28755c2 --- /dev/null +++ b/book/_build/html/_static/scripts/bootstrap.js.LICENSE.txt @@ -0,0 +1,5 @@ +/*! + * Bootstrap v5.3.3 (https://getbootstrap.com/) + * Copyright 2011-2024 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors) + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + */ diff --git a/book/_build/html/_static/scripts/bootstrap.js.map b/book/_build/html/_static/scripts/bootstrap.js.map new file mode 100644 index 0000000..e9e8158 --- /dev/null +++ b/book/_build/html/_static/scripts/bootstrap.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scripts/bootstrap.js","mappings":";mBACA,IAAIA,EAAsB,CCA1BA,EAAwB,CAACC,EAASC,KACjC,IAAI,IAAIC,KAAOD,EACXF,EAAoBI,EAAEF,EAAYC,KAASH,EAAoBI,EAAEH,EAASE,IAC5EE,OAAOC,eAAeL,EAASE,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,IAE1E,ECNDH,EAAwB,CAACS,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClFV,EAAyBC,IACH,oBAAXa,QAA0BA,OAAOC,aAC1CV,OAAOC,eAAeL,EAASa,OAAOC,YAAa,CAAEC,MAAO,WAE7DX,OA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Z,EAAKyZ,GACd,MAAM,IAAIU,UAAU,oBAAoBV,MAE1CzZ,EAAKyZ,GAAQ9D,KACf,CACF,GACF,ECr0IK,SAAS0qB,GAAcruB,GACD,WAAvBhX,SAASuX,WAAyBP,IACjChX,SAASyF,iBAAiB,mBAAoBuR,EACrD,CDy0IAwK,GAAqBqjB,IAMrB/tB,GAAmB+tB,IEpyInBQ,IAzCA,WAC2B,GAAGt4B,MAAM5U,KAChC6H,SAAS+a,iBAAiB,+BAETtd,KAAI,SAAU6nC,GAC/B,OAAO,IAAI,GAAkBA,EAAkB,CAC7CpK,MAAO,CAAE1Q,KAAM,IAAKD,KAAM,MAE9B,GACF,IAiCA8a,IA5BA,WACYrlC,SAASm9B,eAAe,mBAC9B13B,iBAAiB,SAAS,WAC5BzF,SAAS6G,KAAKT,UAAY,EAC1BpG,SAASC,gBAAgBmG,UAAY,CACvC,GACF,IAuBAi/B,IArBA,WACE,IAAIE,EAAMvlC,SAASm9B,eAAe,mBAC9BqI,EAASxlC,SACVylC,uBAAuB,aAAa,GACpCxnC,wBACH1D,OAAOkL,iBAAiB,UAAU,WAC5BkV,KAAK+qB,UAAY/qB,KAAKgrB,SAAWhrB,KAAKgrB,QAAUH,EAAOjtC,OACzDgtC,EAAI7pC,MAAMgxB,QAAU,QAEpB6Y,EAAI7pC,MAAMgxB,QAAU,OAEtB/R,KAAK+qB,UAAY/qB,KAAKgrB,OACxB,GACF,IAUAprC,OAAOqrC,UAAY","sources":["webpack://pydata_sphinx_theme/webpack/bootstrap","webpack://pydata_sphinx_theme/webpack/runtime/define property getters","webpack://pydata_sphinx_theme/webpack/runtime/hasOwnProperty shorthand","webpack://pydata_sphinx_theme/webpack/runtime/make namespace object","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/enums.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getNodeName.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getWindow.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/instanceOf.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/applyStyles.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/getBasePlacement.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/math.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/userAgent.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/contains.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/isTableElement.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getParentNode.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/within.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/mergePaddingObject.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/getFreshSideObject.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/expandToHashMap.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/arrow.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/getVariation.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/computeStyles.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/eventListeners.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/getOppositePlacement.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/rectToClientRect.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/computeOffsets.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/detectOverflow.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/flip.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/hide.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/offset.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/popperOffsets.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/modifiers/preventOverflow.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/getAltAxis.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/orderModifiers.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/createPopper.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/debounce.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/utils/mergeByName.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/popper.js","webpack://pydata_sphinx_theme/./node_modules/@popperjs/core/lib/popper-lite.js","webpack://pydata_sphinx_theme/./node_modules/bootstrap/dist/js/bootstrap.esm.js","webpack://pydata_sphinx_theme/./src/pydata_sphinx_theme/assets/scripts/mixin.js","webpack://pydata_sphinx_theme/./src/pydata_sphinx_theme/assets/scripts/bootstrap.js"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","export var top = 'top';\nexport var bottom = 'bottom';\nexport var right = 'right';\nexport var left = 'left';\nexport var auto = 'auto';\nexport var basePlacements = [top, bottom, right, left];\nexport var start = 'start';\nexport var end = 'end';\nexport var clippingParents = 'clippingParents';\nexport var viewport = 'viewport';\nexport var popper = 'popper';\nexport var reference = 'reference';\nexport var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {\n return acc.concat([placement + \"-\" + start, placement + \"-\" + end]);\n}, []);\nexport var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) {\n return acc.concat([placement, placement + \"-\" + start, placement + \"-\" + end]);\n}, []); // modifiers that need to read the DOM\n\nexport var beforeRead = 'beforeRead';\nexport var read = 'read';\nexport var afterRead = 'afterRead'; // pure-logic modifiers\n\nexport var beforeMain = 'beforeMain';\nexport var main = 'main';\nexport var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)\n\nexport var beforeWrite = 'beforeWrite';\nexport var write = 'write';\nexport var afterWrite = 'afterWrite';\nexport var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];","export default function getNodeName(element) {\n return element ? (element.nodeName || '').toLowerCase() : null;\n}","export default function getWindow(node) {\n if (node == null) {\n return window;\n }\n\n if (node.toString() !== '[object Window]') {\n var ownerDocument = node.ownerDocument;\n return ownerDocument ? ownerDocument.defaultView || window : window;\n }\n\n return node;\n}","import getWindow from \"./getWindow.js\";\n\nfunction isElement(node) {\n var OwnElement = getWindow(node).Element;\n return node instanceof OwnElement || node instanceof Element;\n}\n\nfunction isHTMLElement(node) {\n var OwnElement = getWindow(node).HTMLElement;\n return node instanceof OwnElement || node instanceof HTMLElement;\n}\n\nfunction isShadowRoot(node) {\n // IE 11 has no ShadowRoot\n if (typeof ShadowRoot === 'undefined') {\n return false;\n }\n\n var OwnElement = getWindow(node).ShadowRoot;\n return node instanceof OwnElement || node instanceof ShadowRoot;\n}\n\nexport { isElement, isHTMLElement, isShadowRoot };","import getNodeName from \"../dom-utils/getNodeName.js\";\nimport { isHTMLElement } from \"../dom-utils/instanceOf.js\"; // This modifier takes the styles prepared by the `computeStyles` modifier\n// and applies them to the HTMLElements such as popper and arrow\n\nfunction applyStyles(_ref) {\n var state = _ref.state;\n Object.keys(state.elements).forEach(function (name) {\n var style = state.styles[name] || {};\n var attributes = state.attributes[name] || {};\n var element = state.elements[name]; // arrow is optional + virtual elements\n\n if (!isHTMLElement(element) || !getNodeName(element)) {\n return;\n } // Flow doesn't support to extend this property, but it's the most\n // effective way to apply styles to an HTMLElement\n // $FlowFixMe[cannot-write]\n\n\n Object.assign(element.style, style);\n Object.keys(attributes).forEach(function (name) {\n var value = attributes[name];\n\n if (value === false) {\n element.removeAttribute(name);\n } else {\n element.setAttribute(name, value === true ? '' : value);\n }\n });\n });\n}\n\nfunction effect(_ref2) {\n var state = _ref2.state;\n var initialStyles = {\n popper: {\n position: state.options.strategy,\n left: '0',\n top: '0',\n margin: '0'\n },\n arrow: {\n position: 'absolute'\n },\n reference: {}\n };\n Object.assign(state.elements.popper.style, initialStyles.popper);\n state.styles = initialStyles;\n\n if (state.elements.arrow) {\n Object.assign(state.elements.arrow.style, initialStyles.arrow);\n }\n\n return function () {\n Object.keys(state.elements).forEach(function (name) {\n var element = state.elements[name];\n var attributes = state.attributes[name] || {};\n var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them\n\n var style = styleProperties.reduce(function (style, property) {\n style[property] = '';\n return style;\n }, {}); // arrow is optional + virtual elements\n\n if (!isHTMLElement(element) || !getNodeName(element)) {\n return;\n }\n\n Object.assign(element.style, style);\n Object.keys(attributes).forEach(function (attribute) {\n element.removeAttribute(attribute);\n });\n });\n };\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'applyStyles',\n enabled: true,\n phase: 'write',\n fn: applyStyles,\n effect: effect,\n requires: ['computeStyles']\n};","import { auto } from \"../enums.js\";\nexport default function getBasePlacement(placement) {\n return placement.split('-')[0];\n}","export var max = Math.max;\nexport var min = Math.min;\nexport var round = Math.round;","export default function getUAString() {\n var uaData = navigator.userAgentData;\n\n if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) {\n return uaData.brands.map(function (item) {\n return item.brand + \"/\" + item.version;\n }).join(' ');\n }\n\n return navigator.userAgent;\n}","import getUAString from \"../utils/userAgent.js\";\nexport default function isLayoutViewport() {\n return !/^((?!chrome|android).)*safari/i.test(getUAString());\n}","import { isElement, isHTMLElement } from \"./instanceOf.js\";\nimport { round } from \"../utils/math.js\";\nimport getWindow from \"./getWindow.js\";\nimport isLayoutViewport from \"./isLayoutViewport.js\";\nexport default function getBoundingClientRect(element, includeScale, isFixedStrategy) {\n if (includeScale === void 0) {\n includeScale = false;\n }\n\n if (isFixedStrategy === void 0) {\n isFixedStrategy = false;\n }\n\n var clientRect = element.getBoundingClientRect();\n var scaleX = 1;\n var scaleY = 1;\n\n if (includeScale && isHTMLElement(element)) {\n scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1;\n scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1;\n }\n\n var _ref = isElement(element) ? getWindow(element) : window,\n visualViewport = _ref.visualViewport;\n\n var addVisualOffsets = !isLayoutViewport() && isFixedStrategy;\n var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;\n var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;\n var width = clientRect.width / scaleX;\n var height = clientRect.height / scaleY;\n return {\n width: width,\n height: height,\n top: y,\n right: x + width,\n bottom: y + height,\n left: x,\n x: x,\n y: y\n };\n}","import getBoundingClientRect from \"./getBoundingClientRect.js\"; // Returns the layout rect of an element relative to its offsetParent. Layout\n// means it doesn't take into account transforms.\n\nexport default function getLayoutRect(element) {\n var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed.\n // Fixes https://github.com/popperjs/popper-core/issues/1223\n\n var width = element.offsetWidth;\n var height = element.offsetHeight;\n\n if (Math.abs(clientRect.width - width) <= 1) {\n width = clientRect.width;\n }\n\n if (Math.abs(clientRect.height - height) <= 1) {\n height = clientRect.height;\n }\n\n return {\n x: element.offsetLeft,\n y: element.offsetTop,\n width: width,\n height: height\n };\n}","import { isShadowRoot } from \"./instanceOf.js\";\nexport default function contains(parent, child) {\n var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method\n\n if (parent.contains(child)) {\n return true;\n } // then fallback to custom implementation with Shadow DOM support\n else if (rootNode && isShadowRoot(rootNode)) {\n var next = child;\n\n do {\n if (next && parent.isSameNode(next)) {\n return true;\n } // $FlowFixMe[prop-missing]: need a better way to handle this...\n\n\n next = next.parentNode || next.host;\n } while (next);\n } // Give up, the result is false\n\n\n return false;\n}","import getWindow from \"./getWindow.js\";\nexport default function getComputedStyle(element) {\n return getWindow(element).getComputedStyle(element);\n}","import getNodeName from \"./getNodeName.js\";\nexport default function isTableElement(element) {\n return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;\n}","import { isElement } from \"./instanceOf.js\";\nexport default function getDocumentElement(element) {\n // $FlowFixMe[incompatible-return]: assume body is always available\n return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing]\n element.document) || window.document).documentElement;\n}","import getNodeName from \"./getNodeName.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport { isShadowRoot } from \"./instanceOf.js\";\nexport default function getParentNode(element) {\n if (getNodeName(element) === 'html') {\n return element;\n }\n\n return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle\n // $FlowFixMe[incompatible-return]\n // $FlowFixMe[prop-missing]\n element.assignedSlot || // step into the shadow DOM of the parent of a slotted node\n element.parentNode || ( // DOM Element detected\n isShadowRoot(element) ? element.host : null) || // ShadowRoot detected\n // $FlowFixMe[incompatible-call]: HTMLElement is a Node\n getDocumentElement(element) // fallback\n\n );\n}","import getWindow from \"./getWindow.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport { isHTMLElement, isShadowRoot } from \"./instanceOf.js\";\nimport isTableElement from \"./isTableElement.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport getUAString from \"../utils/userAgent.js\";\n\nfunction getTrueOffsetParent(element) {\n if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837\n getComputedStyle(element).position === 'fixed') {\n return null;\n }\n\n return element.offsetParent;\n} // `.offsetParent` reports `null` for fixed elements, while absolute elements\n// return the containing block\n\n\nfunction getContainingBlock(element) {\n var isFirefox = /firefox/i.test(getUAString());\n var isIE = /Trident/i.test(getUAString());\n\n if (isIE && isHTMLElement(element)) {\n // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport\n var elementCss = getComputedStyle(element);\n\n if (elementCss.position === 'fixed') {\n return null;\n }\n }\n\n var currentNode = getParentNode(element);\n\n if (isShadowRoot(currentNode)) {\n currentNode = currentNode.host;\n }\n\n while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {\n var css = getComputedStyle(currentNode); // This is non-exhaustive but covers the most common CSS properties that\n // create a containing block.\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n\n if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') {\n return currentNode;\n } else {\n currentNode = currentNode.parentNode;\n }\n }\n\n return null;\n} // Gets the closest ancestor positioned element. Handles some edge cases,\n// such as table ancestors and cross browser bugs.\n\n\nexport default function getOffsetParent(element) {\n var window = getWindow(element);\n var offsetParent = getTrueOffsetParent(element);\n\n while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === 'static') {\n offsetParent = getTrueOffsetParent(offsetParent);\n }\n\n if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static')) {\n return window;\n }\n\n return offsetParent || getContainingBlock(element) || window;\n}","export default function getMainAxisFromPlacement(placement) {\n return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';\n}","import { max as mathMax, min as mathMin } from \"./math.js\";\nexport function within(min, value, max) {\n return mathMax(min, mathMin(value, max));\n}\nexport function withinMaxClamp(min, value, max) {\n var v = within(min, value, max);\n return v > max ? max : v;\n}","import getFreshSideObject from \"./getFreshSideObject.js\";\nexport default function mergePaddingObject(paddingObject) {\n return Object.assign({}, getFreshSideObject(), paddingObject);\n}","export default function getFreshSideObject() {\n return {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0\n };\n}","export default function expandToHashMap(value, keys) {\n return keys.reduce(function (hashMap, key) {\n hashMap[key] = value;\n return hashMap;\n }, {});\n}","import getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getLayoutRect from \"../dom-utils/getLayoutRect.js\";\nimport contains from \"../dom-utils/contains.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport getMainAxisFromPlacement from \"../utils/getMainAxisFromPlacement.js\";\nimport { within } from \"../utils/within.js\";\nimport mergePaddingObject from \"../utils/mergePaddingObject.js\";\nimport expandToHashMap from \"../utils/expandToHashMap.js\";\nimport { left, right, basePlacements, top, bottom } from \"../enums.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar toPaddingObject = function toPaddingObject(padding, state) {\n padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, {\n placement: state.placement\n })) : padding;\n return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));\n};\n\nfunction arrow(_ref) {\n var _state$modifiersData$;\n\n var state = _ref.state,\n name = _ref.name,\n options = _ref.options;\n var arrowElement = state.elements.arrow;\n var popperOffsets = state.modifiersData.popperOffsets;\n var basePlacement = getBasePlacement(state.placement);\n var axis = getMainAxisFromPlacement(basePlacement);\n var isVertical = [left, right].indexOf(basePlacement) >= 0;\n var len = isVertical ? 'height' : 'width';\n\n if (!arrowElement || !popperOffsets) {\n return;\n }\n\n var paddingObject = toPaddingObject(options.padding, state);\n var arrowRect = getLayoutRect(arrowElement);\n var minProp = axis === 'y' ? top : left;\n var maxProp = axis === 'y' ? bottom : right;\n var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];\n var startDiff = popperOffsets[axis] - state.rects.reference[axis];\n var arrowOffsetParent = getOffsetParent(arrowElement);\n var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;\n var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is\n // outside of the popper bounds\n\n var min = paddingObject[minProp];\n var max = clientSize - arrowRect[len] - paddingObject[maxProp];\n var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;\n var offset = within(min, center, max); // Prevents breaking syntax highlighting...\n\n var axisProp = axis;\n state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);\n}\n\nfunction effect(_ref2) {\n var state = _ref2.state,\n options = _ref2.options;\n var _options$element = options.element,\n arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element;\n\n if (arrowElement == null) {\n return;\n } // CSS selector\n\n\n if (typeof arrowElement === 'string') {\n arrowElement = state.elements.popper.querySelector(arrowElement);\n\n if (!arrowElement) {\n return;\n }\n }\n\n if (!contains(state.elements.popper, arrowElement)) {\n return;\n }\n\n state.elements.arrow = arrowElement;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'arrow',\n enabled: true,\n phase: 'main',\n fn: arrow,\n effect: effect,\n requires: ['popperOffsets'],\n requiresIfExists: ['preventOverflow']\n};","export default function getVariation(placement) {\n return placement.split('-')[1];\n}","import { top, left, right, bottom, end } from \"../enums.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport getWindow from \"../dom-utils/getWindow.js\";\nimport getDocumentElement from \"../dom-utils/getDocumentElement.js\";\nimport getComputedStyle from \"../dom-utils/getComputedStyle.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getVariation from \"../utils/getVariation.js\";\nimport { round } from \"../utils/math.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar unsetSides = {\n top: 'auto',\n right: 'auto',\n bottom: 'auto',\n left: 'auto'\n}; // Round the offsets to the nearest suitable subpixel based on the DPR.\n// Zooming can change the DPR, but it seems to report a value that will\n// cleanly divide the values into the appropriate subpixels.\n\nfunction roundOffsetsByDPR(_ref, win) {\n var x = _ref.x,\n y = _ref.y;\n var dpr = win.devicePixelRatio || 1;\n return {\n x: round(x * dpr) / dpr || 0,\n y: round(y * dpr) / dpr || 0\n };\n}\n\nexport function mapToStyles(_ref2) {\n var _Object$assign2;\n\n var popper = _ref2.popper,\n popperRect = _ref2.popperRect,\n placement = _ref2.placement,\n variation = _ref2.variation,\n offsets = _ref2.offsets,\n position = _ref2.position,\n gpuAcceleration = _ref2.gpuAcceleration,\n adaptive = _ref2.adaptive,\n roundOffsets = _ref2.roundOffsets,\n isFixed = _ref2.isFixed;\n var _offsets$x = offsets.x,\n x = _offsets$x === void 0 ? 0 : _offsets$x,\n _offsets$y = offsets.y,\n y = _offsets$y === void 0 ? 0 : _offsets$y;\n\n var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({\n x: x,\n y: y\n }) : {\n x: x,\n y: y\n };\n\n x = _ref3.x;\n y = _ref3.y;\n var hasX = offsets.hasOwnProperty('x');\n var hasY = offsets.hasOwnProperty('y');\n var sideX = left;\n var sideY = top;\n var win = window;\n\n if (adaptive) {\n var offsetParent = getOffsetParent(popper);\n var heightProp = 'clientHeight';\n var widthProp = 'clientWidth';\n\n if (offsetParent === getWindow(popper)) {\n offsetParent = getDocumentElement(popper);\n\n if (getComputedStyle(offsetParent).position !== 'static' && position === 'absolute') {\n heightProp = 'scrollHeight';\n widthProp = 'scrollWidth';\n }\n } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it\n\n\n offsetParent = offsetParent;\n\n if (placement === top || (placement === left || placement === right) && variation === end) {\n sideY = bottom;\n var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : // $FlowFixMe[prop-missing]\n offsetParent[heightProp];\n y -= offsetY - popperRect.height;\n y *= gpuAcceleration ? 1 : -1;\n }\n\n if (placement === left || (placement === top || placement === bottom) && variation === end) {\n sideX = right;\n var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : // $FlowFixMe[prop-missing]\n offsetParent[widthProp];\n x -= offsetX - popperRect.width;\n x *= gpuAcceleration ? 1 : -1;\n }\n }\n\n var commonStyles = Object.assign({\n position: position\n }, adaptive && unsetSides);\n\n var _ref4 = roundOffsets === true ? roundOffsetsByDPR({\n x: x,\n y: y\n }, getWindow(popper)) : {\n x: x,\n y: y\n };\n\n x = _ref4.x;\n y = _ref4.y;\n\n if (gpuAcceleration) {\n var _Object$assign;\n\n return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? \"translate(\" + x + \"px, \" + y + \"px)\" : \"translate3d(\" + x + \"px, \" + y + \"px, 0)\", _Object$assign));\n }\n\n return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + \"px\" : '', _Object$assign2[sideX] = hasX ? x + \"px\" : '', _Object$assign2.transform = '', _Object$assign2));\n}\n\nfunction computeStyles(_ref5) {\n var state = _ref5.state,\n options = _ref5.options;\n var _options$gpuAccelerat = options.gpuAcceleration,\n gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,\n _options$adaptive = options.adaptive,\n adaptive = _options$adaptive === void 0 ? true : _options$adaptive,\n _options$roundOffsets = options.roundOffsets,\n roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;\n var commonStyles = {\n placement: getBasePlacement(state.placement),\n variation: getVariation(state.placement),\n popper: state.elements.popper,\n popperRect: state.rects.popper,\n gpuAcceleration: gpuAcceleration,\n isFixed: state.options.strategy === 'fixed'\n };\n\n if (state.modifiersData.popperOffsets != null) {\n state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {\n offsets: state.modifiersData.popperOffsets,\n position: state.options.strategy,\n adaptive: adaptive,\n roundOffsets: roundOffsets\n })));\n }\n\n if (state.modifiersData.arrow != null) {\n state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {\n offsets: state.modifiersData.arrow,\n position: 'absolute',\n adaptive: false,\n roundOffsets: roundOffsets\n })));\n }\n\n state.attributes.popper = Object.assign({}, state.attributes.popper, {\n 'data-popper-placement': state.placement\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'computeStyles',\n enabled: true,\n phase: 'beforeWrite',\n fn: computeStyles,\n data: {}\n};","import getWindow from \"../dom-utils/getWindow.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar passive = {\n passive: true\n};\n\nfunction effect(_ref) {\n var state = _ref.state,\n instance = _ref.instance,\n options = _ref.options;\n var _options$scroll = options.scroll,\n scroll = _options$scroll === void 0 ? true : _options$scroll,\n _options$resize = options.resize,\n resize = _options$resize === void 0 ? true : _options$resize;\n var window = getWindow(state.elements.popper);\n var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);\n\n if (scroll) {\n scrollParents.forEach(function (scrollParent) {\n scrollParent.addEventListener('scroll', instance.update, passive);\n });\n }\n\n if (resize) {\n window.addEventListener('resize', instance.update, passive);\n }\n\n return function () {\n if (scroll) {\n scrollParents.forEach(function (scrollParent) {\n scrollParent.removeEventListener('scroll', instance.update, passive);\n });\n }\n\n if (resize) {\n window.removeEventListener('resize', instance.update, passive);\n }\n };\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'eventListeners',\n enabled: true,\n phase: 'write',\n fn: function fn() {},\n effect: effect,\n data: {}\n};","var hash = {\n left: 'right',\n right: 'left',\n bottom: 'top',\n top: 'bottom'\n};\nexport default function getOppositePlacement(placement) {\n return placement.replace(/left|right|bottom|top/g, function (matched) {\n return hash[matched];\n });\n}","var hash = {\n start: 'end',\n end: 'start'\n};\nexport default function getOppositeVariationPlacement(placement) {\n return placement.replace(/start|end/g, function (matched) {\n return hash[matched];\n });\n}","import getWindow from \"./getWindow.js\";\nexport default function getWindowScroll(node) {\n var win = getWindow(node);\n var scrollLeft = win.pageXOffset;\n var scrollTop = win.pageYOffset;\n return {\n scrollLeft: scrollLeft,\n scrollTop: scrollTop\n };\n}","import getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getWindowScroll from \"./getWindowScroll.js\";\nexport default function getWindowScrollBarX(element) {\n // If has a CSS width greater than the viewport, then this will be\n // incorrect for RTL.\n // Popper 1 is broken in this case and never had a bug report so let's assume\n // it's not an issue. I don't think anyone ever specifies width on \n // anyway.\n // Browsers where the left scrollbar doesn't cause an issue report `0` for\n // this (e.g. Edge 2019, IE11, Safari)\n return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;\n}","import getComputedStyle from \"./getComputedStyle.js\";\nexport default function isScrollParent(element) {\n // Firefox wants us to check `-x` and `-y` variations as well\n var _getComputedStyle = getComputedStyle(element),\n overflow = _getComputedStyle.overflow,\n overflowX = _getComputedStyle.overflowX,\n overflowY = _getComputedStyle.overflowY;\n\n return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);\n}","import getParentNode from \"./getParentNode.js\";\nimport isScrollParent from \"./isScrollParent.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nexport default function getScrollParent(node) {\n if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {\n // $FlowFixMe[incompatible-return]: assume body is always available\n return node.ownerDocument.body;\n }\n\n if (isHTMLElement(node) && isScrollParent(node)) {\n return node;\n }\n\n return getScrollParent(getParentNode(node));\n}","import getScrollParent from \"./getScrollParent.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport getWindow from \"./getWindow.js\";\nimport isScrollParent from \"./isScrollParent.js\";\n/*\ngiven a DOM element, return the list of all scroll parents, up the list of ancesors\nuntil we get to the top window object. This list is what we attach scroll listeners\nto, because if any of these parent elements scroll, we'll need to re-calculate the\nreference element's position.\n*/\n\nexport default function listScrollParents(element, list) {\n var _element$ownerDocumen;\n\n if (list === void 0) {\n list = [];\n }\n\n var scrollParent = getScrollParent(element);\n var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);\n var win = getWindow(scrollParent);\n var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;\n var updatedList = list.concat(target);\n return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here\n updatedList.concat(listScrollParents(getParentNode(target)));\n}","export default function rectToClientRect(rect) {\n return Object.assign({}, rect, {\n left: rect.x,\n top: rect.y,\n right: rect.x + rect.width,\n bottom: rect.y + rect.height\n });\n}","import { viewport } from \"../enums.js\";\nimport getViewportRect from \"./getViewportRect.js\";\nimport getDocumentRect from \"./getDocumentRect.js\";\nimport listScrollParents from \"./listScrollParents.js\";\nimport getOffsetParent from \"./getOffsetParent.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport { isElement, isHTMLElement } from \"./instanceOf.js\";\nimport getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport contains from \"./contains.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport rectToClientRect from \"../utils/rectToClientRect.js\";\nimport { max, min } from \"../utils/math.js\";\n\nfunction getInnerBoundingClientRect(element, strategy) {\n var rect = getBoundingClientRect(element, false, strategy === 'fixed');\n rect.top = rect.top + element.clientTop;\n rect.left = rect.left + element.clientLeft;\n rect.bottom = rect.top + element.clientHeight;\n rect.right = rect.left + element.clientWidth;\n rect.width = element.clientWidth;\n rect.height = element.clientHeight;\n rect.x = rect.left;\n rect.y = rect.top;\n return rect;\n}\n\nfunction getClientRectFromMixedType(element, clippingParent, strategy) {\n return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element)));\n} // A \"clipping parent\" is an overflowable container with the characteristic of\n// clipping (or hiding) overflowing elements with a position different from\n// `initial`\n\n\nfunction getClippingParents(element) {\n var clippingParents = listScrollParents(getParentNode(element));\n var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle(element).position) >= 0;\n var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;\n\n if (!isElement(clipperElement)) {\n return [];\n } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414\n\n\n return clippingParents.filter(function (clippingParent) {\n return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';\n });\n} // Gets the maximum area that the element is visible in due to any number of\n// clipping parents\n\n\nexport default function getClippingRect(element, boundary, rootBoundary, strategy) {\n var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);\n var clippingParents = [].concat(mainClippingParents, [rootBoundary]);\n var firstClippingParent = clippingParents[0];\n var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {\n var rect = getClientRectFromMixedType(element, clippingParent, strategy);\n accRect.top = max(rect.top, accRect.top);\n accRect.right = min(rect.right, accRect.right);\n accRect.bottom = min(rect.bottom, accRect.bottom);\n accRect.left = max(rect.left, accRect.left);\n return accRect;\n }, getClientRectFromMixedType(element, firstClippingParent, strategy));\n clippingRect.width = clippingRect.right - clippingRect.left;\n clippingRect.height = clippingRect.bottom - clippingRect.top;\n clippingRect.x = clippingRect.left;\n clippingRect.y = clippingRect.top;\n return clippingRect;\n}","import getWindow from \"./getWindow.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport isLayoutViewport from \"./isLayoutViewport.js\";\nexport default function getViewportRect(element, strategy) {\n var win = getWindow(element);\n var html = getDocumentElement(element);\n var visualViewport = win.visualViewport;\n var width = html.clientWidth;\n var height = html.clientHeight;\n var x = 0;\n var y = 0;\n\n if (visualViewport) {\n width = visualViewport.width;\n height = visualViewport.height;\n var layoutViewport = isLayoutViewport();\n\n if (layoutViewport || !layoutViewport && strategy === 'fixed') {\n x = visualViewport.offsetLeft;\n y = visualViewport.offsetTop;\n }\n }\n\n return {\n width: width,\n height: height,\n x: x + getWindowScrollBarX(element),\n y: y\n };\n}","import getDocumentElement from \"./getDocumentElement.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport getWindowScroll from \"./getWindowScroll.js\";\nimport { max } from \"../utils/math.js\"; // Gets the entire size of the scrollable document area, even extending outside\n// of the `` and `` rect bounds if horizontally scrollable\n\nexport default function getDocumentRect(element) {\n var _element$ownerDocumen;\n\n var html = getDocumentElement(element);\n var winScroll = getWindowScroll(element);\n var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;\n var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);\n var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);\n var x = -winScroll.scrollLeft + getWindowScrollBarX(element);\n var y = -winScroll.scrollTop;\n\n if (getComputedStyle(body || html).direction === 'rtl') {\n x += max(html.clientWidth, body ? body.clientWidth : 0) - width;\n }\n\n return {\n width: width,\n height: height,\n x: x,\n y: y\n };\n}","import getBasePlacement from \"./getBasePlacement.js\";\nimport getVariation from \"./getVariation.js\";\nimport getMainAxisFromPlacement from \"./getMainAxisFromPlacement.js\";\nimport { top, right, bottom, left, start, end } from \"../enums.js\";\nexport default function computeOffsets(_ref) {\n var reference = _ref.reference,\n element = _ref.element,\n placement = _ref.placement;\n var basePlacement = placement ? getBasePlacement(placement) : null;\n var variation = placement ? getVariation(placement) : null;\n var commonX = reference.x + reference.width / 2 - element.width / 2;\n var commonY = reference.y + reference.height / 2 - element.height / 2;\n var offsets;\n\n switch (basePlacement) {\n case top:\n offsets = {\n x: commonX,\n y: reference.y - element.height\n };\n break;\n\n case bottom:\n offsets = {\n x: commonX,\n y: reference.y + reference.height\n };\n break;\n\n case right:\n offsets = {\n x: reference.x + reference.width,\n y: commonY\n };\n break;\n\n case left:\n offsets = {\n x: reference.x - element.width,\n y: commonY\n };\n break;\n\n default:\n offsets = {\n x: reference.x,\n y: reference.y\n };\n }\n\n var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;\n\n if (mainAxis != null) {\n var len = mainAxis === 'y' ? 'height' : 'width';\n\n switch (variation) {\n case start:\n offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);\n break;\n\n case end:\n offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);\n break;\n\n default:\n }\n }\n\n return offsets;\n}","import getClippingRect from \"../dom-utils/getClippingRect.js\";\nimport getDocumentElement from \"../dom-utils/getDocumentElement.js\";\nimport getBoundingClientRect from \"../dom-utils/getBoundingClientRect.js\";\nimport computeOffsets from \"./computeOffsets.js\";\nimport rectToClientRect from \"./rectToClientRect.js\";\nimport { clippingParents, reference, popper, bottom, top, right, basePlacements, viewport } from \"../enums.js\";\nimport { isElement } from \"../dom-utils/instanceOf.js\";\nimport mergePaddingObject from \"./mergePaddingObject.js\";\nimport expandToHashMap from \"./expandToHashMap.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport default function detectOverflow(state, options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n _options$placement = _options.placement,\n placement = _options$placement === void 0 ? state.placement : _options$placement,\n _options$strategy = _options.strategy,\n strategy = _options$strategy === void 0 ? state.strategy : _options$strategy,\n _options$boundary = _options.boundary,\n boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,\n _options$rootBoundary = _options.rootBoundary,\n rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,\n _options$elementConte = _options.elementContext,\n elementContext = _options$elementConte === void 0 ? popper : _options$elementConte,\n _options$altBoundary = _options.altBoundary,\n altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,\n _options$padding = _options.padding,\n padding = _options$padding === void 0 ? 0 : _options$padding;\n var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));\n var altContext = elementContext === popper ? reference : popper;\n var popperRect = state.rects.popper;\n var element = state.elements[altBoundary ? altContext : elementContext];\n var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy);\n var referenceClientRect = getBoundingClientRect(state.elements.reference);\n var popperOffsets = computeOffsets({\n reference: referenceClientRect,\n element: popperRect,\n strategy: 'absolute',\n placement: placement\n });\n var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets));\n var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect\n // 0 or negative = within the clipping rect\n\n var overflowOffsets = {\n top: clippingClientRect.top - elementClientRect.top + paddingObject.top,\n bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,\n left: clippingClientRect.left - elementClientRect.left + paddingObject.left,\n right: elementClientRect.right - clippingClientRect.right + paddingObject.right\n };\n var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element\n\n if (elementContext === popper && offsetData) {\n var offset = offsetData[placement];\n Object.keys(overflowOffsets).forEach(function (key) {\n var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;\n var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x';\n overflowOffsets[key] += offset[axis] * multiply;\n });\n }\n\n return overflowOffsets;\n}","import getOppositePlacement from \"../utils/getOppositePlacement.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getOppositeVariationPlacement from \"../utils/getOppositeVariationPlacement.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\nimport computeAutoPlacement from \"../utils/computeAutoPlacement.js\";\nimport { bottom, top, start, right, left, auto } from \"../enums.js\";\nimport getVariation from \"../utils/getVariation.js\"; // eslint-disable-next-line import/no-unused-modules\n\nfunction getExpandedFallbackPlacements(placement) {\n if (getBasePlacement(placement) === auto) {\n return [];\n }\n\n var oppositePlacement = getOppositePlacement(placement);\n return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];\n}\n\nfunction flip(_ref) {\n var state = _ref.state,\n options = _ref.options,\n name = _ref.name;\n\n if (state.modifiersData[name]._skip) {\n return;\n }\n\n var _options$mainAxis = options.mainAxis,\n checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,\n _options$altAxis = options.altAxis,\n checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,\n specifiedFallbackPlacements = options.fallbackPlacements,\n padding = options.padding,\n boundary = options.boundary,\n rootBoundary = options.rootBoundary,\n altBoundary = options.altBoundary,\n _options$flipVariatio = options.flipVariations,\n flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,\n allowedAutoPlacements = options.allowedAutoPlacements;\n var preferredPlacement = state.options.placement;\n var basePlacement = getBasePlacement(preferredPlacement);\n var isBasePlacement = basePlacement === preferredPlacement;\n var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));\n var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {\n return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding,\n flipVariations: flipVariations,\n allowedAutoPlacements: allowedAutoPlacements\n }) : placement);\n }, []);\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var checksMap = new Map();\n var makeFallbackChecks = true;\n var firstFittingPlacement = placements[0];\n\n for (var i = 0; i < placements.length; i++) {\n var placement = placements[i];\n\n var _basePlacement = getBasePlacement(placement);\n\n var isStartVariation = getVariation(placement) === start;\n var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;\n var len = isVertical ? 'width' : 'height';\n var overflow = detectOverflow(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n altBoundary: altBoundary,\n padding: padding\n });\n var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;\n\n if (referenceRect[len] > popperRect[len]) {\n mainVariationSide = getOppositePlacement(mainVariationSide);\n }\n\n var altVariationSide = getOppositePlacement(mainVariationSide);\n var checks = [];\n\n if (checkMainAxis) {\n checks.push(overflow[_basePlacement] <= 0);\n }\n\n if (checkAltAxis) {\n checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);\n }\n\n if (checks.every(function (check) {\n return check;\n })) {\n firstFittingPlacement = placement;\n makeFallbackChecks = false;\n break;\n }\n\n checksMap.set(placement, checks);\n }\n\n if (makeFallbackChecks) {\n // `2` may be desired in some cases – research later\n var numberOfChecks = flipVariations ? 3 : 1;\n\n var _loop = function _loop(_i) {\n var fittingPlacement = placements.find(function (placement) {\n var checks = checksMap.get(placement);\n\n if (checks) {\n return checks.slice(0, _i).every(function (check) {\n return check;\n });\n }\n });\n\n if (fittingPlacement) {\n firstFittingPlacement = fittingPlacement;\n return \"break\";\n }\n };\n\n for (var _i = numberOfChecks; _i > 0; _i--) {\n var _ret = _loop(_i);\n\n if (_ret === \"break\") break;\n }\n }\n\n if (state.placement !== firstFittingPlacement) {\n state.modifiersData[name]._skip = true;\n state.placement = firstFittingPlacement;\n state.reset = true;\n }\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'flip',\n enabled: true,\n phase: 'main',\n fn: flip,\n requiresIfExists: ['offset'],\n data: {\n _skip: false\n }\n};","import getVariation from \"./getVariation.js\";\nimport { variationPlacements, basePlacements, placements as allPlacements } from \"../enums.js\";\nimport detectOverflow from \"./detectOverflow.js\";\nimport getBasePlacement from \"./getBasePlacement.js\";\nexport default function computeAutoPlacement(state, options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n placement = _options.placement,\n boundary = _options.boundary,\n rootBoundary = _options.rootBoundary,\n padding = _options.padding,\n flipVariations = _options.flipVariations,\n _options$allowedAutoP = _options.allowedAutoPlacements,\n allowedAutoPlacements = _options$allowedAutoP === void 0 ? allPlacements : _options$allowedAutoP;\n var variation = getVariation(placement);\n var placements = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {\n return getVariation(placement) === variation;\n }) : basePlacements;\n var allowedPlacements = placements.filter(function (placement) {\n return allowedAutoPlacements.indexOf(placement) >= 0;\n });\n\n if (allowedPlacements.length === 0) {\n allowedPlacements = placements;\n } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...\n\n\n var overflows = allowedPlacements.reduce(function (acc, placement) {\n acc[placement] = detectOverflow(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding\n })[getBasePlacement(placement)];\n return acc;\n }, {});\n return Object.keys(overflows).sort(function (a, b) {\n return overflows[a] - overflows[b];\n });\n}","import { top, bottom, left, right } from \"../enums.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\n\nfunction getSideOffsets(overflow, rect, preventedOffsets) {\n if (preventedOffsets === void 0) {\n preventedOffsets = {\n x: 0,\n y: 0\n };\n }\n\n return {\n top: overflow.top - rect.height - preventedOffsets.y,\n right: overflow.right - rect.width + preventedOffsets.x,\n bottom: overflow.bottom - rect.height + preventedOffsets.y,\n left: overflow.left - rect.width - preventedOffsets.x\n };\n}\n\nfunction isAnySideFullyClipped(overflow) {\n return [top, right, bottom, left].some(function (side) {\n return overflow[side] >= 0;\n });\n}\n\nfunction hide(_ref) {\n var state = _ref.state,\n name = _ref.name;\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var preventedOffsets = state.modifiersData.preventOverflow;\n var referenceOverflow = detectOverflow(state, {\n elementContext: 'reference'\n });\n var popperAltOverflow = detectOverflow(state, {\n altBoundary: true\n });\n var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);\n var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);\n var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);\n var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);\n state.modifiersData[name] = {\n referenceClippingOffsets: referenceClippingOffsets,\n popperEscapeOffsets: popperEscapeOffsets,\n isReferenceHidden: isReferenceHidden,\n hasPopperEscaped: hasPopperEscaped\n };\n state.attributes.popper = Object.assign({}, state.attributes.popper, {\n 'data-popper-reference-hidden': isReferenceHidden,\n 'data-popper-escaped': hasPopperEscaped\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'hide',\n enabled: true,\n phase: 'main',\n requiresIfExists: ['preventOverflow'],\n fn: hide\n};","import getBasePlacement from \"../utils/getBasePlacement.js\";\nimport { top, left, right, placements } from \"../enums.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport function distanceAndSkiddingToXY(placement, rects, offset) {\n var basePlacement = getBasePlacement(placement);\n var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;\n\n var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, {\n placement: placement\n })) : offset,\n skidding = _ref[0],\n distance = _ref[1];\n\n skidding = skidding || 0;\n distance = (distance || 0) * invertDistance;\n return [left, right].indexOf(basePlacement) >= 0 ? {\n x: distance,\n y: skidding\n } : {\n x: skidding,\n y: distance\n };\n}\n\nfunction offset(_ref2) {\n var state = _ref2.state,\n options = _ref2.options,\n name = _ref2.name;\n var _options$offset = options.offset,\n offset = _options$offset === void 0 ? [0, 0] : _options$offset;\n var data = placements.reduce(function (acc, placement) {\n acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);\n return acc;\n }, {});\n var _data$state$placement = data[state.placement],\n x = _data$state$placement.x,\n y = _data$state$placement.y;\n\n if (state.modifiersData.popperOffsets != null) {\n state.modifiersData.popperOffsets.x += x;\n state.modifiersData.popperOffsets.y += y;\n }\n\n state.modifiersData[name] = data;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'offset',\n enabled: true,\n phase: 'main',\n requires: ['popperOffsets'],\n fn: offset\n};","import computeOffsets from \"../utils/computeOffsets.js\";\n\nfunction popperOffsets(_ref) {\n var state = _ref.state,\n name = _ref.name;\n // Offsets are the actual position the popper needs to have to be\n // properly positioned near its reference element\n // This is the most basic placement, and will be adjusted by\n // the modifiers in the next step\n state.modifiersData[name] = computeOffsets({\n reference: state.rects.reference,\n element: state.rects.popper,\n strategy: 'absolute',\n placement: state.placement\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'popperOffsets',\n enabled: true,\n phase: 'read',\n fn: popperOffsets,\n data: {}\n};","import { top, left, right, bottom, start } from \"../enums.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getMainAxisFromPlacement from \"../utils/getMainAxisFromPlacement.js\";\nimport getAltAxis from \"../utils/getAltAxis.js\";\nimport { within, withinMaxClamp } from \"../utils/within.js\";\nimport getLayoutRect from \"../dom-utils/getLayoutRect.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\nimport getVariation from \"../utils/getVariation.js\";\nimport getFreshSideObject from \"../utils/getFreshSideObject.js\";\nimport { min as mathMin, max as mathMax } from \"../utils/math.js\";\n\nfunction preventOverflow(_ref) {\n var state = _ref.state,\n options = _ref.options,\n name = _ref.name;\n var _options$mainAxis = options.mainAxis,\n checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,\n _options$altAxis = options.altAxis,\n checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,\n boundary = options.boundary,\n rootBoundary = options.rootBoundary,\n altBoundary = options.altBoundary,\n padding = options.padding,\n _options$tether = options.tether,\n tether = _options$tether === void 0 ? true : _options$tether,\n _options$tetherOffset = options.tetherOffset,\n tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;\n var overflow = detectOverflow(state, {\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding,\n altBoundary: altBoundary\n });\n var basePlacement = getBasePlacement(state.placement);\n var variation = getVariation(state.placement);\n var isBasePlacement = !variation;\n var mainAxis = getMainAxisFromPlacement(basePlacement);\n var altAxis = getAltAxis(mainAxis);\n var popperOffsets = state.modifiersData.popperOffsets;\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, {\n placement: state.placement\n })) : tetherOffset;\n var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? {\n mainAxis: tetherOffsetValue,\n altAxis: tetherOffsetValue\n } : Object.assign({\n mainAxis: 0,\n altAxis: 0\n }, tetherOffsetValue);\n var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;\n var data = {\n x: 0,\n y: 0\n };\n\n if (!popperOffsets) {\n return;\n }\n\n if (checkMainAxis) {\n var _offsetModifierState$;\n\n var mainSide = mainAxis === 'y' ? top : left;\n var altSide = mainAxis === 'y' ? bottom : right;\n var len = mainAxis === 'y' ? 'height' : 'width';\n var offset = popperOffsets[mainAxis];\n var min = offset + overflow[mainSide];\n var max = offset - overflow[altSide];\n var additive = tether ? -popperRect[len] / 2 : 0;\n var minLen = variation === start ? referenceRect[len] : popperRect[len];\n var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go\n // outside the reference bounds\n\n var arrowElement = state.elements.arrow;\n var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {\n width: 0,\n height: 0\n };\n var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();\n var arrowPaddingMin = arrowPaddingObject[mainSide];\n var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want\n // to include its full size in the calculation. If the reference is small\n // and near the edge of a boundary, the popper can overflow even if the\n // reference is not overflowing as well (e.g. virtual elements with no\n // width or height)\n\n var arrowLen = within(0, referenceRect[len], arrowRect[len]);\n var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;\n var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;\n var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);\n var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;\n var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;\n var tetherMin = offset + minOffset - offsetModifierValue - clientOffset;\n var tetherMax = offset + maxOffset - offsetModifierValue;\n var preventedOffset = within(tether ? mathMin(min, tetherMin) : min, offset, tether ? mathMax(max, tetherMax) : max);\n popperOffsets[mainAxis] = preventedOffset;\n data[mainAxis] = preventedOffset - offset;\n }\n\n if (checkAltAxis) {\n var _offsetModifierState$2;\n\n var _mainSide = mainAxis === 'x' ? top : left;\n\n var _altSide = mainAxis === 'x' ? bottom : right;\n\n var _offset = popperOffsets[altAxis];\n\n var _len = altAxis === 'y' ? 'height' : 'width';\n\n var _min = _offset + overflow[_mainSide];\n\n var _max = _offset - overflow[_altSide];\n\n var isOriginSide = [top, left].indexOf(basePlacement) !== -1;\n\n var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;\n\n var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;\n\n var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;\n\n var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);\n\n popperOffsets[altAxis] = _preventedOffset;\n data[altAxis] = _preventedOffset - _offset;\n }\n\n state.modifiersData[name] = data;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'preventOverflow',\n enabled: true,\n phase: 'main',\n fn: preventOverflow,\n requiresIfExists: ['offset']\n};","export default function getAltAxis(axis) {\n return axis === 'x' ? 'y' : 'x';\n}","import getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getNodeScroll from \"./getNodeScroll.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport isScrollParent from \"./isScrollParent.js\";\nimport { round } from \"../utils/math.js\";\n\nfunction isElementScaled(element) {\n var rect = element.getBoundingClientRect();\n var scaleX = round(rect.width) / element.offsetWidth || 1;\n var scaleY = round(rect.height) / element.offsetHeight || 1;\n return scaleX !== 1 || scaleY !== 1;\n} // Returns the composite rect of an element relative to its offsetParent.\n// Composite means it takes into account transforms as well as layout.\n\n\nexport default function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {\n if (isFixed === void 0) {\n isFixed = false;\n }\n\n var isOffsetParentAnElement = isHTMLElement(offsetParent);\n var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent);\n var documentElement = getDocumentElement(offsetParent);\n var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed);\n var scroll = {\n scrollLeft: 0,\n scrollTop: 0\n };\n var offsets = {\n x: 0,\n y: 0\n };\n\n if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078\n isScrollParent(documentElement)) {\n scroll = getNodeScroll(offsetParent);\n }\n\n if (isHTMLElement(offsetParent)) {\n offsets = getBoundingClientRect(offsetParent, true);\n offsets.x += offsetParent.clientLeft;\n offsets.y += offsetParent.clientTop;\n } else if (documentElement) {\n offsets.x = getWindowScrollBarX(documentElement);\n }\n }\n\n return {\n x: rect.left + scroll.scrollLeft - offsets.x,\n y: rect.top + scroll.scrollTop - offsets.y,\n width: rect.width,\n height: rect.height\n };\n}","import getWindowScroll from \"./getWindowScroll.js\";\nimport getWindow from \"./getWindow.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nimport getHTMLElementScroll from \"./getHTMLElementScroll.js\";\nexport default function getNodeScroll(node) {\n if (node === getWindow(node) || !isHTMLElement(node)) {\n return getWindowScroll(node);\n } else {\n return getHTMLElementScroll(node);\n }\n}","export default function getHTMLElementScroll(element) {\n return {\n scrollLeft: element.scrollLeft,\n scrollTop: element.scrollTop\n };\n}","import { modifierPhases } from \"../enums.js\"; // source: https://stackoverflow.com/questions/49875255\n\nfunction order(modifiers) {\n var map = new Map();\n var visited = new Set();\n var result = [];\n modifiers.forEach(function (modifier) {\n map.set(modifier.name, modifier);\n }); // On visiting object, check for its dependencies and visit them recursively\n\n function sort(modifier) {\n visited.add(modifier.name);\n var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);\n requires.forEach(function (dep) {\n if (!visited.has(dep)) {\n var depModifier = map.get(dep);\n\n if (depModifier) {\n sort(depModifier);\n }\n }\n });\n result.push(modifier);\n }\n\n modifiers.forEach(function (modifier) {\n if (!visited.has(modifier.name)) {\n // check for visited object\n sort(modifier);\n }\n });\n return result;\n}\n\nexport default function orderModifiers(modifiers) {\n // order based on dependencies\n var orderedModifiers = order(modifiers); // order based on phase\n\n return modifierPhases.reduce(function (acc, phase) {\n return acc.concat(orderedModifiers.filter(function (modifier) {\n return modifier.phase === phase;\n }));\n }, []);\n}","import getCompositeRect from \"./dom-utils/getCompositeRect.js\";\nimport getLayoutRect from \"./dom-utils/getLayoutRect.js\";\nimport listScrollParents from \"./dom-utils/listScrollParents.js\";\nimport getOffsetParent from \"./dom-utils/getOffsetParent.js\";\nimport orderModifiers from \"./utils/orderModifiers.js\";\nimport debounce from \"./utils/debounce.js\";\nimport mergeByName from \"./utils/mergeByName.js\";\nimport detectOverflow from \"./utils/detectOverflow.js\";\nimport { isElement } from \"./dom-utils/instanceOf.js\";\nvar DEFAULT_OPTIONS = {\n placement: 'bottom',\n modifiers: [],\n strategy: 'absolute'\n};\n\nfunction areValidElements() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return !args.some(function (element) {\n return !(element && typeof element.getBoundingClientRect === 'function');\n });\n}\n\nexport function popperGenerator(generatorOptions) {\n if (generatorOptions === void 0) {\n generatorOptions = {};\n }\n\n var _generatorOptions = generatorOptions,\n _generatorOptions$def = _generatorOptions.defaultModifiers,\n defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,\n _generatorOptions$def2 = _generatorOptions.defaultOptions,\n defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;\n return function createPopper(reference, popper, options) {\n if (options === void 0) {\n options = defaultOptions;\n }\n\n var state = {\n placement: 'bottom',\n orderedModifiers: [],\n options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),\n modifiersData: {},\n elements: {\n reference: reference,\n popper: popper\n },\n attributes: {},\n styles: {}\n };\n var effectCleanupFns = [];\n var isDestroyed = false;\n var instance = {\n state: state,\n setOptions: function setOptions(setOptionsAction) {\n var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction;\n cleanupModifierEffects();\n state.options = Object.assign({}, defaultOptions, state.options, options);\n state.scrollParents = {\n reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],\n popper: listScrollParents(popper)\n }; // Orders the modifiers based on their dependencies and `phase`\n // properties\n\n var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers\n\n state.orderedModifiers = orderedModifiers.filter(function (m) {\n return m.enabled;\n });\n runModifierEffects();\n return instance.update();\n },\n // Sync update – it will always be executed, even if not necessary. This\n // is useful for low frequency updates where sync behavior simplifies the\n // logic.\n // For high frequency updates (e.g. `resize` and `scroll` events), always\n // prefer the async Popper#update method\n forceUpdate: function forceUpdate() {\n if (isDestroyed) {\n return;\n }\n\n var _state$elements = state.elements,\n reference = _state$elements.reference,\n popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements\n // anymore\n\n if (!areValidElements(reference, popper)) {\n return;\n } // Store the reference and popper rects to be read by modifiers\n\n\n state.rects = {\n reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),\n popper: getLayoutRect(popper)\n }; // Modifiers have the ability to reset the current update cycle. The\n // most common use case for this is the `flip` modifier changing the\n // placement, which then needs to re-run all the modifiers, because the\n // logic was previously ran for the previous placement and is therefore\n // stale/incorrect\n\n state.reset = false;\n state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier\n // is filled with the initial data specified by the modifier. This means\n // it doesn't persist and is fresh on each update.\n // To ensure persistent data, use `${name}#persistent`\n\n state.orderedModifiers.forEach(function (modifier) {\n return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);\n });\n\n for (var index = 0; index < state.orderedModifiers.length; index++) {\n if (state.reset === true) {\n state.reset = false;\n index = -1;\n continue;\n }\n\n var _state$orderedModifie = state.orderedModifiers[index],\n fn = _state$orderedModifie.fn,\n _state$orderedModifie2 = _state$orderedModifie.options,\n _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,\n name = _state$orderedModifie.name;\n\n if (typeof fn === 'function') {\n state = fn({\n state: state,\n options: _options,\n name: name,\n instance: instance\n }) || state;\n }\n }\n },\n // Async and optimistically optimized update – it will not be executed if\n // not necessary (debounced to run at most once-per-tick)\n update: debounce(function () {\n return new Promise(function (resolve) {\n instance.forceUpdate();\n resolve(state);\n });\n }),\n destroy: function destroy() {\n cleanupModifierEffects();\n isDestroyed = true;\n }\n };\n\n if (!areValidElements(reference, popper)) {\n return instance;\n }\n\n instance.setOptions(options).then(function (state) {\n if (!isDestroyed && options.onFirstUpdate) {\n options.onFirstUpdate(state);\n }\n }); // Modifiers have the ability to execute arbitrary code before the first\n // update cycle runs. They will be executed in the same order as the update\n // cycle. This is useful when a modifier adds some persistent data that\n // other modifiers need to use, but the modifier is run after the dependent\n // one.\n\n function runModifierEffects() {\n state.orderedModifiers.forEach(function (_ref) {\n var name = _ref.name,\n _ref$options = _ref.options,\n options = _ref$options === void 0 ? {} : _ref$options,\n effect = _ref.effect;\n\n if (typeof effect === 'function') {\n var cleanupFn = effect({\n state: state,\n name: name,\n instance: instance,\n options: options\n });\n\n var noopFn = function noopFn() {};\n\n effectCleanupFns.push(cleanupFn || noopFn);\n }\n });\n }\n\n function cleanupModifierEffects() {\n effectCleanupFns.forEach(function (fn) {\n return fn();\n });\n effectCleanupFns = [];\n }\n\n return instance;\n };\n}\nexport var createPopper = /*#__PURE__*/popperGenerator(); // eslint-disable-next-line import/no-unused-modules\n\nexport { detectOverflow };","export default function debounce(fn) {\n var pending;\n return function () {\n if (!pending) {\n pending = new Promise(function (resolve) {\n Promise.resolve().then(function () {\n pending = undefined;\n resolve(fn());\n });\n });\n }\n\n return pending;\n };\n}","export default function mergeByName(modifiers) {\n var merged = modifiers.reduce(function (merged, current) {\n var existing = merged[current.name];\n merged[current.name] = existing ? Object.assign({}, existing, current, {\n options: Object.assign({}, existing.options, current.options),\n data: Object.assign({}, existing.data, current.data)\n }) : current;\n return merged;\n }, {}); // IE11 does not support Object.values\n\n return Object.keys(merged).map(function (key) {\n return merged[key];\n });\n}","import { popperGenerator, detectOverflow } from \"./createPopper.js\";\nimport eventListeners from \"./modifiers/eventListeners.js\";\nimport popperOffsets from \"./modifiers/popperOffsets.js\";\nimport computeStyles from \"./modifiers/computeStyles.js\";\nimport applyStyles from \"./modifiers/applyStyles.js\";\nimport offset from \"./modifiers/offset.js\";\nimport flip from \"./modifiers/flip.js\";\nimport preventOverflow from \"./modifiers/preventOverflow.js\";\nimport arrow from \"./modifiers/arrow.js\";\nimport hide from \"./modifiers/hide.js\";\nvar defaultModifiers = [eventListeners, popperOffsets, computeStyles, applyStyles, offset, flip, preventOverflow, arrow, hide];\nvar createPopper = /*#__PURE__*/popperGenerator({\n defaultModifiers: defaultModifiers\n}); // eslint-disable-next-line import/no-unused-modules\n\nexport { createPopper, popperGenerator, defaultModifiers, detectOverflow }; // eslint-disable-next-line import/no-unused-modules\n\nexport { createPopper as createPopperLite } from \"./popper-lite.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport * from \"./modifiers/index.js\";","import { popperGenerator, detectOverflow } from \"./createPopper.js\";\nimport eventListeners from \"./modifiers/eventListeners.js\";\nimport popperOffsets from \"./modifiers/popperOffsets.js\";\nimport computeStyles from \"./modifiers/computeStyles.js\";\nimport applyStyles from \"./modifiers/applyStyles.js\";\nvar defaultModifiers = [eventListeners, popperOffsets, computeStyles, applyStyles];\nvar createPopper = /*#__PURE__*/popperGenerator({\n defaultModifiers: defaultModifiers\n}); // eslint-disable-next-line import/no-unused-modules\n\nexport { createPopper, popperGenerator, defaultModifiers, detectOverflow };","/*!\n * Bootstrap v5.3.3 (https://getbootstrap.com/)\n * Copyright 2011-2024 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n */\nimport * as Popper from '@popperjs/core';\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap dom/data.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n/**\n * Constants\n */\n\nconst elementMap = new Map();\nconst Data = {\n set(element, key, instance) {\n if (!elementMap.has(element)) {\n elementMap.set(element, new Map());\n }\n const instanceMap = elementMap.get(element);\n\n // make it clear we only want one instance per element\n // can be removed later when multiple key/instances are fine to be used\n if (!instanceMap.has(key) && instanceMap.size !== 0) {\n // eslint-disable-next-line no-console\n console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(instanceMap.keys())[0]}.`);\n return;\n }\n instanceMap.set(key, instance);\n },\n get(element, key) {\n if (elementMap.has(element)) {\n return elementMap.get(element).get(key) || null;\n }\n return null;\n },\n remove(element, key) {\n if (!elementMap.has(element)) {\n return;\n }\n const instanceMap = elementMap.get(element);\n instanceMap.delete(key);\n\n // free up element references if there are no instances left for an element\n if (instanceMap.size === 0) {\n elementMap.delete(element);\n }\n }\n};\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/index.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nconst MAX_UID = 1000000;\nconst MILLISECONDS_MULTIPLIER = 1000;\nconst TRANSITION_END = 'transitionend';\n\n/**\n * Properly escape IDs selectors to handle weird IDs\n * @param {string} selector\n * @returns {string}\n */\nconst parseSelector = selector => {\n if (selector && window.CSS && window.CSS.escape) {\n // document.querySelector needs escaping to handle IDs (html5+) containing for instance /\n selector = selector.replace(/#([^\\s\"#']+)/g, (match, id) => `#${CSS.escape(id)}`);\n }\n return selector;\n};\n\n// Shout-out Angus Croll (https://goo.gl/pxwQGp)\nconst toType = object => {\n if (object === null || object === undefined) {\n return `${object}`;\n }\n return Object.prototype.toString.call(object).match(/\\s([a-z]+)/i)[1].toLowerCase();\n};\n\n/**\n * Public Util API\n */\n\nconst getUID = prefix => {\n do {\n prefix += Math.floor(Math.random() * MAX_UID);\n } while (document.getElementById(prefix));\n return prefix;\n};\nconst getTransitionDurationFromElement = element => {\n if (!element) {\n return 0;\n }\n\n // Get transition-duration of the element\n let {\n transitionDuration,\n transitionDelay\n } = window.getComputedStyle(element);\n const floatTransitionDuration = Number.parseFloat(transitionDuration);\n const floatTransitionDelay = Number.parseFloat(transitionDelay);\n\n // Return 0 if element or transition duration is not found\n if (!floatTransitionDuration && !floatTransitionDelay) {\n return 0;\n }\n\n // If multiple durations are defined, take the first\n transitionDuration = transitionDuration.split(',')[0];\n transitionDelay = transitionDelay.split(',')[0];\n return (Number.parseFloat(transitionDuration) + Number.parseFloat(transitionDelay)) * MILLISECONDS_MULTIPLIER;\n};\nconst triggerTransitionEnd = element => {\n element.dispatchEvent(new Event(TRANSITION_END));\n};\nconst isElement = object => {\n if (!object || typeof object !== 'object') {\n return false;\n }\n if (typeof object.jquery !== 'undefined') {\n object = object[0];\n }\n return typeof object.nodeType !== 'undefined';\n};\nconst getElement = object => {\n // it's a jQuery object or a node element\n if (isElement(object)) {\n return object.jquery ? object[0] : object;\n }\n if (typeof object === 'string' && object.length > 0) {\n return document.querySelector(parseSelector(object));\n }\n return null;\n};\nconst isVisible = element => {\n if (!isElement(element) || element.getClientRects().length === 0) {\n return false;\n }\n const elementIsVisible = getComputedStyle(element).getPropertyValue('visibility') === 'visible';\n // Handle `details` element as its content may falsie appear visible when it is closed\n const closedDetails = element.closest('details:not([open])');\n if (!closedDetails) {\n return elementIsVisible;\n }\n if (closedDetails !== element) {\n const summary = element.closest('summary');\n if (summary && summary.parentNode !== closedDetails) {\n return false;\n }\n if (summary === null) {\n return false;\n }\n }\n return elementIsVisible;\n};\nconst isDisabled = element => {\n if (!element || element.nodeType !== Node.ELEMENT_NODE) {\n return true;\n }\n if (element.classList.contains('disabled')) {\n return true;\n }\n if (typeof element.disabled !== 'undefined') {\n return element.disabled;\n }\n return element.hasAttribute('disabled') && element.getAttribute('disabled') !== 'false';\n};\nconst findShadowRoot = element => {\n if (!document.documentElement.attachShadow) {\n return null;\n }\n\n // Can find the shadow root otherwise it'll return the document\n if (typeof element.getRootNode === 'function') {\n const root = element.getRootNode();\n return root instanceof ShadowRoot ? root : null;\n }\n if (element instanceof ShadowRoot) {\n return element;\n }\n\n // when we don't find a shadow root\n if (!element.parentNode) {\n return null;\n }\n return findShadowRoot(element.parentNode);\n};\nconst noop = () => {};\n\n/**\n * Trick to restart an element's animation\n *\n * @param {HTMLElement} element\n * @return void\n *\n * @see https://www.charistheo.io/blog/2021/02/restart-a-css-animation-with-javascript/#restarting-a-css-animation\n */\nconst reflow = element => {\n element.offsetHeight; // eslint-disable-line no-unused-expressions\n};\nconst getjQuery = () => {\n if (window.jQuery && !document.body.hasAttribute('data-bs-no-jquery')) {\n return window.jQuery;\n }\n return null;\n};\nconst DOMContentLoadedCallbacks = [];\nconst onDOMContentLoaded = callback => {\n if (document.readyState === 'loading') {\n // add listener on the first call when the document is in loading state\n if (!DOMContentLoadedCallbacks.length) {\n document.addEventListener('DOMContentLoaded', () => {\n for (const callback of DOMContentLoadedCallbacks) {\n callback();\n }\n });\n }\n DOMContentLoadedCallbacks.push(callback);\n } else {\n callback();\n }\n};\nconst isRTL = () => document.documentElement.dir === 'rtl';\nconst defineJQueryPlugin = plugin => {\n onDOMContentLoaded(() => {\n const $ = getjQuery();\n /* istanbul ignore if */\n if ($) {\n const name = plugin.NAME;\n const JQUERY_NO_CONFLICT = $.fn[name];\n $.fn[name] = plugin.jQueryInterface;\n $.fn[name].Constructor = plugin;\n $.fn[name].noConflict = () => {\n $.fn[name] = JQUERY_NO_CONFLICT;\n return plugin.jQueryInterface;\n };\n }\n });\n};\nconst execute = (possibleCallback, args = [], defaultValue = possibleCallback) => {\n return typeof possibleCallback === 'function' ? possibleCallback(...args) : defaultValue;\n};\nconst executeAfterTransition = (callback, transitionElement, waitForTransition = true) => {\n if (!waitForTransition) {\n execute(callback);\n return;\n }\n const durationPadding = 5;\n const emulatedDuration = getTransitionDurationFromElement(transitionElement) + durationPadding;\n let called = false;\n const handler = ({\n target\n }) => {\n if (target !== transitionElement) {\n return;\n }\n called = true;\n transitionElement.removeEventListener(TRANSITION_END, handler);\n execute(callback);\n };\n transitionElement.addEventListener(TRANSITION_END, handler);\n setTimeout(() => {\n if (!called) {\n triggerTransitionEnd(transitionElement);\n }\n }, emulatedDuration);\n};\n\n/**\n * Return the previous/next element of a list.\n *\n * @param {array} list The list of elements\n * @param activeElement The active element\n * @param shouldGetNext Choose to get next or previous element\n * @param isCycleAllowed\n * @return {Element|elem} The proper element\n */\nconst getNextActiveElement = (list, activeElement, shouldGetNext, isCycleAllowed) => {\n const listLength = list.length;\n let index = list.indexOf(activeElement);\n\n // if the element does not exist in the list return an element\n // depending on the direction and if cycle is allowed\n if (index === -1) {\n return !shouldGetNext && isCycleAllowed ? list[listLength - 1] : list[0];\n }\n index += shouldGetNext ? 1 : -1;\n if (isCycleAllowed) {\n index = (index + listLength) % listLength;\n }\n return list[Math.max(0, Math.min(index, listLength - 1))];\n};\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap dom/event-handler.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst namespaceRegex = /[^.]*(?=\\..*)\\.|.*/;\nconst stripNameRegex = /\\..*/;\nconst stripUidRegex = /::\\d+$/;\nconst eventRegistry = {}; // Events storage\nlet uidEvent = 1;\nconst customEvents = {\n mouseenter: 'mouseover',\n mouseleave: 'mouseout'\n};\nconst nativeEvents = new Set(['click', 'dblclick', 'mouseup', 'mousedown', 'contextmenu', 'mousewheel', 'DOMMouseScroll', 'mouseover', 'mouseout', 'mousemove', 'selectstart', 'selectend', 'keydown', 'keypress', 'keyup', 'orientationchange', 'touchstart', 'touchmove', 'touchend', 'touchcancel', 'pointerdown', 'pointermove', 'pointerup', 'pointerleave', 'pointercancel', 'gesturestart', 'gesturechange', 'gestureend', 'focus', 'blur', 'change', 'reset', 'select', 'submit', 'focusin', 'focusout', 'load', 'unload', 'beforeunload', 'resize', 'move', 'DOMContentLoaded', 'readystatechange', 'error', 'abort', 'scroll']);\n\n/**\n * Private methods\n */\n\nfunction makeEventUid(element, uid) {\n return uid && `${uid}::${uidEvent++}` || element.uidEvent || uidEvent++;\n}\nfunction getElementEvents(element) {\n const uid = makeEventUid(element);\n element.uidEvent = uid;\n eventRegistry[uid] = eventRegistry[uid] || {};\n return eventRegistry[uid];\n}\nfunction bootstrapHandler(element, fn) {\n return function handler(event) {\n hydrateObj(event, {\n delegateTarget: element\n });\n if (handler.oneOff) {\n EventHandler.off(element, event.type, fn);\n }\n return fn.apply(element, [event]);\n };\n}\nfunction bootstrapDelegationHandler(element, selector, fn) {\n return function handler(event) {\n const domElements = element.querySelectorAll(selector);\n for (let {\n target\n } = event; target && target !== this; target = target.parentNode) {\n for (const domElement of domElements) {\n if (domElement !== target) {\n continue;\n }\n hydrateObj(event, {\n delegateTarget: target\n });\n if (handler.oneOff) {\n EventHandler.off(element, event.type, selector, fn);\n }\n return fn.apply(target, [event]);\n }\n }\n };\n}\nfunction findHandler(events, callable, delegationSelector = null) {\n return Object.values(events).find(event => event.callable === callable && event.delegationSelector === delegationSelector);\n}\nfunction normalizeParameters(originalTypeEvent, handler, delegationFunction) {\n const isDelegated = typeof handler === 'string';\n // TODO: tooltip passes `false` instead of selector, so we need to check\n const callable = isDelegated ? delegationFunction : handler || delegationFunction;\n let typeEvent = getTypeEvent(originalTypeEvent);\n if (!nativeEvents.has(typeEvent)) {\n typeEvent = originalTypeEvent;\n }\n return [isDelegated, callable, typeEvent];\n}\nfunction addHandler(element, originalTypeEvent, handler, delegationFunction, oneOff) {\n if (typeof originalTypeEvent !== 'string' || !element) {\n return;\n }\n let [isDelegated, callable, typeEvent] = normalizeParameters(originalTypeEvent, handler, delegationFunction);\n\n // in case of mouseenter or mouseleave wrap the handler within a function that checks for its DOM position\n // this prevents the handler from being dispatched the same way as mouseover or mouseout does\n if (originalTypeEvent in customEvents) {\n const wrapFunction = fn => {\n return function (event) {\n if (!event.relatedTarget || event.relatedTarget !== event.delegateTarget && !event.delegateTarget.contains(event.relatedTarget)) {\n return fn.call(this, event);\n }\n };\n };\n callable = wrapFunction(callable);\n }\n const events = getElementEvents(element);\n const handlers = events[typeEvent] || (events[typeEvent] = {});\n const previousFunction = findHandler(handlers, callable, isDelegated ? handler : null);\n if (previousFunction) {\n previousFunction.oneOff = previousFunction.oneOff && oneOff;\n return;\n }\n const uid = makeEventUid(callable, originalTypeEvent.replace(namespaceRegex, ''));\n const fn = isDelegated ? bootstrapDelegationHandler(element, handler, callable) : bootstrapHandler(element, callable);\n fn.delegationSelector = isDelegated ? handler : null;\n fn.callable = callable;\n fn.oneOff = oneOff;\n fn.uidEvent = uid;\n handlers[uid] = fn;\n element.addEventListener(typeEvent, fn, isDelegated);\n}\nfunction removeHandler(element, events, typeEvent, handler, delegationSelector) {\n const fn = findHandler(events[typeEvent], handler, delegationSelector);\n if (!fn) {\n return;\n }\n element.removeEventListener(typeEvent, fn, Boolean(delegationSelector));\n delete events[typeEvent][fn.uidEvent];\n}\nfunction removeNamespacedHandlers(element, events, typeEvent, namespace) {\n const storeElementEvent = events[typeEvent] || {};\n for (const [handlerKey, event] of Object.entries(storeElementEvent)) {\n if (handlerKey.includes(namespace)) {\n removeHandler(element, events, typeEvent, event.callable, event.delegationSelector);\n }\n }\n}\nfunction getTypeEvent(event) {\n // allow to get the native events from namespaced events ('click.bs.button' --> 'click')\n event = event.replace(stripNameRegex, '');\n return customEvents[event] || event;\n}\nconst EventHandler = {\n on(element, event, handler, delegationFunction) {\n addHandler(element, event, handler, delegationFunction, false);\n },\n one(element, event, handler, delegationFunction) {\n addHandler(element, event, handler, delegationFunction, true);\n },\n off(element, originalTypeEvent, handler, delegationFunction) {\n if (typeof originalTypeEvent !== 'string' || !element) {\n return;\n }\n const [isDelegated, callable, typeEvent] = normalizeParameters(originalTypeEvent, handler, delegationFunction);\n const inNamespace = typeEvent !== originalTypeEvent;\n const events = getElementEvents(element);\n const storeElementEvent = events[typeEvent] || {};\n const isNamespace = originalTypeEvent.startsWith('.');\n if (typeof callable !== 'undefined') {\n // Simplest case: handler is passed, remove that listener ONLY.\n if (!Object.keys(storeElementEvent).length) {\n return;\n }\n removeHandler(element, events, typeEvent, callable, isDelegated ? handler : null);\n return;\n }\n if (isNamespace) {\n for (const elementEvent of Object.keys(events)) {\n removeNamespacedHandlers(element, events, elementEvent, originalTypeEvent.slice(1));\n }\n }\n for (const [keyHandlers, event] of Object.entries(storeElementEvent)) {\n const handlerKey = keyHandlers.replace(stripUidRegex, '');\n if (!inNamespace || originalTypeEvent.includes(handlerKey)) {\n removeHandler(element, events, typeEvent, event.callable, event.delegationSelector);\n }\n }\n },\n trigger(element, event, args) {\n if (typeof event !== 'string' || !element) {\n return null;\n }\n const $ = getjQuery();\n const typeEvent = getTypeEvent(event);\n const inNamespace = event !== typeEvent;\n let jQueryEvent = null;\n let bubbles = true;\n let nativeDispatch = true;\n let defaultPrevented = false;\n if (inNamespace && $) {\n jQueryEvent = $.Event(event, args);\n $(element).trigger(jQueryEvent);\n bubbles = !jQueryEvent.isPropagationStopped();\n nativeDispatch = !jQueryEvent.isImmediatePropagationStopped();\n defaultPrevented = jQueryEvent.isDefaultPrevented();\n }\n const evt = hydrateObj(new Event(event, {\n bubbles,\n cancelable: true\n }), args);\n if (defaultPrevented) {\n evt.preventDefault();\n }\n if (nativeDispatch) {\n element.dispatchEvent(evt);\n }\n if (evt.defaultPrevented && jQueryEvent) {\n jQueryEvent.preventDefault();\n }\n return evt;\n }\n};\nfunction hydrateObj(obj, meta = {}) {\n for (const [key, value] of Object.entries(meta)) {\n try {\n obj[key] = value;\n } catch (_unused) {\n Object.defineProperty(obj, key, {\n configurable: true,\n get() {\n return value;\n }\n });\n }\n }\n return obj;\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap dom/manipulator.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nfunction normalizeData(value) {\n if (value === 'true') {\n return true;\n }\n if (value === 'false') {\n return false;\n }\n if (value === Number(value).toString()) {\n return Number(value);\n }\n if (value === '' || value === 'null') {\n return null;\n }\n if (typeof value !== 'string') {\n return value;\n }\n try {\n return JSON.parse(decodeURIComponent(value));\n } catch (_unused) {\n return value;\n }\n}\nfunction normalizeDataKey(key) {\n return key.replace(/[A-Z]/g, chr => `-${chr.toLowerCase()}`);\n}\nconst Manipulator = {\n setDataAttribute(element, key, value) {\n element.setAttribute(`data-bs-${normalizeDataKey(key)}`, value);\n },\n removeDataAttribute(element, key) {\n element.removeAttribute(`data-bs-${normalizeDataKey(key)}`);\n },\n getDataAttributes(element) {\n if (!element) {\n return {};\n }\n const attributes = {};\n const bsKeys = Object.keys(element.dataset).filter(key => key.startsWith('bs') && !key.startsWith('bsConfig'));\n for (const key of bsKeys) {\n let pureKey = key.replace(/^bs/, '');\n pureKey = pureKey.charAt(0).toLowerCase() + pureKey.slice(1, pureKey.length);\n attributes[pureKey] = normalizeData(element.dataset[key]);\n }\n return attributes;\n },\n getDataAttribute(element, key) {\n return normalizeData(element.getAttribute(`data-bs-${normalizeDataKey(key)}`));\n }\n};\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/config.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Class definition\n */\n\nclass Config {\n // Getters\n static get Default() {\n return {};\n }\n static get DefaultType() {\n return {};\n }\n static get NAME() {\n throw new Error('You have to implement the static method \"NAME\", for each component!');\n }\n _getConfig(config) {\n config = this._mergeConfigObj(config);\n config = this._configAfterMerge(config);\n this._typeCheckConfig(config);\n return config;\n }\n _configAfterMerge(config) {\n return config;\n }\n _mergeConfigObj(config, element) {\n const jsonConfig = isElement(element) ? Manipulator.getDataAttribute(element, 'config') : {}; // try to parse\n\n return {\n ...this.constructor.Default,\n ...(typeof jsonConfig === 'object' ? jsonConfig : {}),\n ...(isElement(element) ? Manipulator.getDataAttributes(element) : {}),\n ...(typeof config === 'object' ? config : {})\n };\n }\n _typeCheckConfig(config, configTypes = this.constructor.DefaultType) {\n for (const [property, expectedTypes] of Object.entries(configTypes)) {\n const value = config[property];\n const valueType = isElement(value) ? 'element' : toType(value);\n if (!new RegExp(expectedTypes).test(valueType)) {\n throw new TypeError(`${this.constructor.NAME.toUpperCase()}: Option \"${property}\" provided type \"${valueType}\" but expected type \"${expectedTypes}\".`);\n }\n }\n }\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap base-component.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst VERSION = '5.3.3';\n\n/**\n * Class definition\n */\n\nclass BaseComponent extends Config {\n constructor(element, config) {\n super();\n element = getElement(element);\n if (!element) {\n return;\n }\n this._element = element;\n this._config = this._getConfig(config);\n Data.set(this._element, this.constructor.DATA_KEY, this);\n }\n\n // Public\n dispose() {\n Data.remove(this._element, this.constructor.DATA_KEY);\n EventHandler.off(this._element, this.constructor.EVENT_KEY);\n for (const propertyName of Object.getOwnPropertyNames(this)) {\n this[propertyName] = null;\n }\n }\n _queueCallback(callback, element, isAnimated = true) {\n executeAfterTransition(callback, element, isAnimated);\n }\n _getConfig(config) {\n config = this._mergeConfigObj(config, this._element);\n config = this._configAfterMerge(config);\n this._typeCheckConfig(config);\n return config;\n }\n\n // Static\n static getInstance(element) {\n return Data.get(getElement(element), this.DATA_KEY);\n }\n static getOrCreateInstance(element, config = {}) {\n return this.getInstance(element) || new this(element, typeof config === 'object' ? config : null);\n }\n static get VERSION() {\n return VERSION;\n }\n static get DATA_KEY() {\n return `bs.${this.NAME}`;\n }\n static get EVENT_KEY() {\n return `.${this.DATA_KEY}`;\n }\n static eventName(name) {\n return `${name}${this.EVENT_KEY}`;\n }\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap dom/selector-engine.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nconst getSelector = element => {\n let selector = element.getAttribute('data-bs-target');\n if (!selector || selector === '#') {\n let hrefAttribute = element.getAttribute('href');\n\n // The only valid content that could double as a selector are IDs or classes,\n // so everything starting with `#` or `.`. If a \"real\" URL is used as the selector,\n // `document.querySelector` will rightfully complain it is invalid.\n // See https://github.com/twbs/bootstrap/issues/32273\n if (!hrefAttribute || !hrefAttribute.includes('#') && !hrefAttribute.startsWith('.')) {\n return null;\n }\n\n // Just in case some CMS puts out a full URL with the anchor appended\n if (hrefAttribute.includes('#') && !hrefAttribute.startsWith('#')) {\n hrefAttribute = `#${hrefAttribute.split('#')[1]}`;\n }\n selector = hrefAttribute && hrefAttribute !== '#' ? hrefAttribute.trim() : null;\n }\n return selector ? selector.split(',').map(sel => parseSelector(sel)).join(',') : null;\n};\nconst SelectorEngine = {\n find(selector, element = document.documentElement) {\n return [].concat(...Element.prototype.querySelectorAll.call(element, selector));\n },\n findOne(selector, element = document.documentElement) {\n return Element.prototype.querySelector.call(element, selector);\n },\n children(element, selector) {\n return [].concat(...element.children).filter(child => child.matches(selector));\n },\n parents(element, selector) {\n const parents = [];\n let ancestor = element.parentNode.closest(selector);\n while (ancestor) {\n parents.push(ancestor);\n ancestor = ancestor.parentNode.closest(selector);\n }\n return parents;\n },\n prev(element, selector) {\n let previous = element.previousElementSibling;\n while (previous) {\n if (previous.matches(selector)) {\n return [previous];\n }\n previous = previous.previousElementSibling;\n }\n return [];\n },\n // TODO: this is now unused; remove later along with prev()\n next(element, selector) {\n let next = element.nextElementSibling;\n while (next) {\n if (next.matches(selector)) {\n return [next];\n }\n next = next.nextElementSibling;\n }\n return [];\n },\n focusableChildren(element) {\n const focusables = ['a', 'button', 'input', 'textarea', 'select', 'details', '[tabindex]', '[contenteditable=\"true\"]'].map(selector => `${selector}:not([tabindex^=\"-\"])`).join(',');\n return this.find(focusables, element).filter(el => !isDisabled(el) && isVisible(el));\n },\n getSelectorFromElement(element) {\n const selector = getSelector(element);\n if (selector) {\n return SelectorEngine.findOne(selector) ? selector : null;\n }\n return null;\n },\n getElementFromSelector(element) {\n const selector = getSelector(element);\n return selector ? SelectorEngine.findOne(selector) : null;\n },\n getMultipleElementsFromSelector(element) {\n const selector = getSelector(element);\n return selector ? SelectorEngine.find(selector) : [];\n }\n};\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/component-functions.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\nconst enableDismissTrigger = (component, method = 'hide') => {\n const clickEvent = `click.dismiss${component.EVENT_KEY}`;\n const name = component.NAME;\n EventHandler.on(document, clickEvent, `[data-bs-dismiss=\"${name}\"]`, function (event) {\n if (['A', 'AREA'].includes(this.tagName)) {\n event.preventDefault();\n }\n if (isDisabled(this)) {\n return;\n }\n const target = SelectorEngine.getElementFromSelector(this) || this.closest(`.${name}`);\n const instance = component.getOrCreateInstance(target);\n\n // Method argument is left, for Alert and only, as it doesn't implement the 'hide' method\n instance[method]();\n });\n};\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap alert.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$f = 'alert';\nconst DATA_KEY$a = 'bs.alert';\nconst EVENT_KEY$b = `.${DATA_KEY$a}`;\nconst EVENT_CLOSE = `close${EVENT_KEY$b}`;\nconst EVENT_CLOSED = `closed${EVENT_KEY$b}`;\nconst CLASS_NAME_FADE$5 = 'fade';\nconst CLASS_NAME_SHOW$8 = 'show';\n\n/**\n * Class definition\n */\n\nclass Alert extends BaseComponent {\n // Getters\n static get NAME() {\n return NAME$f;\n }\n\n // Public\n close() {\n const closeEvent = EventHandler.trigger(this._element, EVENT_CLOSE);\n if (closeEvent.defaultPrevented) {\n return;\n }\n this._element.classList.remove(CLASS_NAME_SHOW$8);\n const isAnimated = this._element.classList.contains(CLASS_NAME_FADE$5);\n this._queueCallback(() => this._destroyElement(), this._element, isAnimated);\n }\n\n // Private\n _destroyElement() {\n this._element.remove();\n EventHandler.trigger(this._element, EVENT_CLOSED);\n this.dispose();\n }\n\n // Static\n static jQueryInterface(config) {\n return this.each(function () {\n const data = Alert.getOrCreateInstance(this);\n if (typeof config !== 'string') {\n return;\n }\n if (data[config] === undefined || config.startsWith('_') || config === 'constructor') {\n throw new TypeError(`No method named \"${config}\"`);\n }\n data[config](this);\n });\n }\n}\n\n/**\n * Data API implementation\n */\n\nenableDismissTrigger(Alert, 'close');\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Alert);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap button.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$e = 'button';\nconst DATA_KEY$9 = 'bs.button';\nconst EVENT_KEY$a = `.${DATA_KEY$9}`;\nconst DATA_API_KEY$6 = '.data-api';\nconst CLASS_NAME_ACTIVE$3 = 'active';\nconst SELECTOR_DATA_TOGGLE$5 = '[data-bs-toggle=\"button\"]';\nconst EVENT_CLICK_DATA_API$6 = `click${EVENT_KEY$a}${DATA_API_KEY$6}`;\n\n/**\n * Class definition\n */\n\nclass Button extends BaseComponent {\n // Getters\n static get NAME() {\n return NAME$e;\n }\n\n // Public\n toggle() {\n // Toggle class and sync the `aria-pressed` attribute with the return value of the `.toggle()` method\n this._element.setAttribute('aria-pressed', this._element.classList.toggle(CLASS_NAME_ACTIVE$3));\n }\n\n // Static\n static jQueryInterface(config) {\n return this.each(function () {\n const data = Button.getOrCreateInstance(this);\n if (config === 'toggle') {\n data[config]();\n }\n });\n }\n}\n\n/**\n * Data API implementation\n */\n\nEventHandler.on(document, EVENT_CLICK_DATA_API$6, SELECTOR_DATA_TOGGLE$5, event => {\n event.preventDefault();\n const button = event.target.closest(SELECTOR_DATA_TOGGLE$5);\n const data = Button.getOrCreateInstance(button);\n data.toggle();\n});\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Button);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/swipe.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$d = 'swipe';\nconst EVENT_KEY$9 = '.bs.swipe';\nconst EVENT_TOUCHSTART = `touchstart${EVENT_KEY$9}`;\nconst EVENT_TOUCHMOVE = `touchmove${EVENT_KEY$9}`;\nconst EVENT_TOUCHEND = `touchend${EVENT_KEY$9}`;\nconst EVENT_POINTERDOWN = `pointerdown${EVENT_KEY$9}`;\nconst EVENT_POINTERUP = `pointerup${EVENT_KEY$9}`;\nconst POINTER_TYPE_TOUCH = 'touch';\nconst POINTER_TYPE_PEN = 'pen';\nconst CLASS_NAME_POINTER_EVENT = 'pointer-event';\nconst SWIPE_THRESHOLD = 40;\nconst Default$c = {\n endCallback: null,\n leftCallback: null,\n rightCallback: null\n};\nconst DefaultType$c = {\n endCallback: '(function|null)',\n leftCallback: '(function|null)',\n rightCallback: '(function|null)'\n};\n\n/**\n * Class definition\n */\n\nclass Swipe extends Config {\n constructor(element, config) {\n super();\n this._element = element;\n if (!element || !Swipe.isSupported()) {\n return;\n }\n this._config = this._getConfig(config);\n this._deltaX = 0;\n this._supportPointerEvents = Boolean(window.PointerEvent);\n this._initEvents();\n }\n\n // Getters\n static get Default() {\n return Default$c;\n }\n static get DefaultType() {\n return DefaultType$c;\n }\n static get NAME() {\n return NAME$d;\n }\n\n // Public\n dispose() {\n EventHandler.off(this._element, EVENT_KEY$9);\n }\n\n // Private\n _start(event) {\n if (!this._supportPointerEvents) {\n this._deltaX = event.touches[0].clientX;\n return;\n }\n if (this._eventIsPointerPenTouch(event)) {\n this._deltaX = event.clientX;\n }\n }\n _end(event) {\n if (this._eventIsPointerPenTouch(event)) {\n this._deltaX = event.clientX - this._deltaX;\n }\n this._handleSwipe();\n execute(this._config.endCallback);\n }\n _move(event) {\n this._deltaX = event.touches && event.touches.length > 1 ? 0 : event.touches[0].clientX - this._deltaX;\n }\n _handleSwipe() {\n const absDeltaX = Math.abs(this._deltaX);\n if (absDeltaX <= SWIPE_THRESHOLD) {\n return;\n }\n const direction = absDeltaX / this._deltaX;\n this._deltaX = 0;\n if (!direction) {\n return;\n }\n execute(direction > 0 ? this._config.rightCallback : this._config.leftCallback);\n }\n _initEvents() {\n if (this._supportPointerEvents) {\n EventHandler.on(this._element, EVENT_POINTERDOWN, event => this._start(event));\n EventHandler.on(this._element, EVENT_POINTERUP, event => this._end(event));\n this._element.classList.add(CLASS_NAME_POINTER_EVENT);\n } else {\n EventHandler.on(this._element, EVENT_TOUCHSTART, event => this._start(event));\n EventHandler.on(this._element, EVENT_TOUCHMOVE, event => this._move(event));\n EventHandler.on(this._element, EVENT_TOUCHEND, event => this._end(event));\n }\n }\n _eventIsPointerPenTouch(event) {\n return this._supportPointerEvents && (event.pointerType === POINTER_TYPE_PEN || event.pointerType === POINTER_TYPE_TOUCH);\n }\n\n // Static\n static isSupported() {\n return 'ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0;\n }\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap carousel.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$c = 'carousel';\nconst DATA_KEY$8 = 'bs.carousel';\nconst EVENT_KEY$8 = `.${DATA_KEY$8}`;\nconst DATA_API_KEY$5 = '.data-api';\nconst ARROW_LEFT_KEY$1 = 'ArrowLeft';\nconst ARROW_RIGHT_KEY$1 = 'ArrowRight';\nconst TOUCHEVENT_COMPAT_WAIT = 500; // Time for mouse compat events to fire after touch\n\nconst ORDER_NEXT = 'next';\nconst ORDER_PREV = 'prev';\nconst DIRECTION_LEFT = 'left';\nconst DIRECTION_RIGHT = 'right';\nconst EVENT_SLIDE = `slide${EVENT_KEY$8}`;\nconst EVENT_SLID = `slid${EVENT_KEY$8}`;\nconst EVENT_KEYDOWN$1 = `keydown${EVENT_KEY$8}`;\nconst EVENT_MOUSEENTER$1 = `mouseenter${EVENT_KEY$8}`;\nconst EVENT_MOUSELEAVE$1 = `mouseleave${EVENT_KEY$8}`;\nconst EVENT_DRAG_START = `dragstart${EVENT_KEY$8}`;\nconst EVENT_LOAD_DATA_API$3 = `load${EVENT_KEY$8}${DATA_API_KEY$5}`;\nconst EVENT_CLICK_DATA_API$5 = `click${EVENT_KEY$8}${DATA_API_KEY$5}`;\nconst CLASS_NAME_CAROUSEL = 'carousel';\nconst CLASS_NAME_ACTIVE$2 = 'active';\nconst CLASS_NAME_SLIDE = 'slide';\nconst CLASS_NAME_END = 'carousel-item-end';\nconst CLASS_NAME_START = 'carousel-item-start';\nconst CLASS_NAME_NEXT = 'carousel-item-next';\nconst CLASS_NAME_PREV = 'carousel-item-prev';\nconst SELECTOR_ACTIVE = '.active';\nconst SELECTOR_ITEM = '.carousel-item';\nconst SELECTOR_ACTIVE_ITEM = SELECTOR_ACTIVE + SELECTOR_ITEM;\nconst SELECTOR_ITEM_IMG = '.carousel-item img';\nconst SELECTOR_INDICATORS = '.carousel-indicators';\nconst SELECTOR_DATA_SLIDE = '[data-bs-slide], [data-bs-slide-to]';\nconst SELECTOR_DATA_RIDE = '[data-bs-ride=\"carousel\"]';\nconst KEY_TO_DIRECTION = {\n [ARROW_LEFT_KEY$1]: DIRECTION_RIGHT,\n [ARROW_RIGHT_KEY$1]: DIRECTION_LEFT\n};\nconst Default$b = {\n interval: 5000,\n keyboard: true,\n pause: 'hover',\n ride: false,\n touch: true,\n wrap: true\n};\nconst DefaultType$b = {\n interval: '(number|boolean)',\n // TODO:v6 remove boolean support\n keyboard: 'boolean',\n pause: '(string|boolean)',\n ride: '(boolean|string)',\n touch: 'boolean',\n wrap: 'boolean'\n};\n\n/**\n * Class definition\n */\n\nclass Carousel extends BaseComponent {\n constructor(element, config) {\n super(element, config);\n this._interval = null;\n this._activeElement = null;\n this._isSliding = false;\n this.touchTimeout = null;\n this._swipeHelper = null;\n this._indicatorsElement = SelectorEngine.findOne(SELECTOR_INDICATORS, this._element);\n this._addEventListeners();\n if (this._config.ride === CLASS_NAME_CAROUSEL) {\n this.cycle();\n }\n }\n\n // Getters\n static get Default() {\n return Default$b;\n }\n static get DefaultType() {\n return DefaultType$b;\n }\n static get NAME() {\n return NAME$c;\n }\n\n // Public\n next() {\n this._slide(ORDER_NEXT);\n }\n nextWhenVisible() {\n // FIXME TODO use `document.visibilityState`\n // Don't call next when the page isn't visible\n // or the carousel or its parent isn't visible\n if (!document.hidden && isVisible(this._element)) {\n this.next();\n }\n }\n prev() {\n this._slide(ORDER_PREV);\n }\n pause() {\n if (this._isSliding) {\n triggerTransitionEnd(this._element);\n }\n this._clearInterval();\n }\n cycle() {\n this._clearInterval();\n this._updateInterval();\n this._interval = setInterval(() => this.nextWhenVisible(), this._config.interval);\n }\n _maybeEnableCycle() {\n if (!this._config.ride) {\n return;\n }\n if (this._isSliding) {\n EventHandler.one(this._element, EVENT_SLID, () => this.cycle());\n return;\n }\n this.cycle();\n }\n to(index) {\n const items = this._getItems();\n if (index > items.length - 1 || index < 0) {\n return;\n }\n if (this._isSliding) {\n EventHandler.one(this._element, EVENT_SLID, () => this.to(index));\n return;\n }\n const activeIndex = this._getItemIndex(this._getActive());\n if (activeIndex === index) {\n return;\n }\n const order = index > activeIndex ? ORDER_NEXT : ORDER_PREV;\n this._slide(order, items[index]);\n }\n dispose() {\n if (this._swipeHelper) {\n this._swipeHelper.dispose();\n }\n super.dispose();\n }\n\n // Private\n _configAfterMerge(config) {\n config.defaultInterval = config.interval;\n return config;\n }\n _addEventListeners() {\n if (this._config.keyboard) {\n EventHandler.on(this._element, EVENT_KEYDOWN$1, event => this._keydown(event));\n }\n if (this._config.pause === 'hover') {\n EventHandler.on(this._element, EVENT_MOUSEENTER$1, () => this.pause());\n EventHandler.on(this._element, EVENT_MOUSELEAVE$1, () => this._maybeEnableCycle());\n }\n if (this._config.touch && Swipe.isSupported()) {\n this._addTouchEventListeners();\n }\n }\n _addTouchEventListeners() {\n for (const img of SelectorEngine.find(SELECTOR_ITEM_IMG, this._element)) {\n EventHandler.on(img, EVENT_DRAG_START, event => event.preventDefault());\n }\n const endCallBack = () => {\n if (this._config.pause !== 'hover') {\n return;\n }\n\n // If it's a touch-enabled device, mouseenter/leave are fired as\n // part of the mouse compatibility events on first tap - the carousel\n // would stop cycling until user tapped out of it;\n // here, we listen for touchend, explicitly pause the carousel\n // (as if it's the second time we tap on it, mouseenter compat event\n // is NOT fired) and after a timeout (to allow for mouse compatibility\n // events to fire) we explicitly restart cycling\n\n this.pause();\n if (this.touchTimeout) {\n clearTimeout(this.touchTimeout);\n }\n this.touchTimeout = setTimeout(() => this._maybeEnableCycle(), TOUCHEVENT_COMPAT_WAIT + this._config.interval);\n };\n const swipeConfig = {\n leftCallback: () => this._slide(this._directionToOrder(DIRECTION_LEFT)),\n rightCallback: () => this._slide(this._directionToOrder(DIRECTION_RIGHT)),\n endCallback: endCallBack\n };\n this._swipeHelper = new Swipe(this._element, swipeConfig);\n }\n _keydown(event) {\n if (/input|textarea/i.test(event.target.tagName)) {\n return;\n }\n const direction = KEY_TO_DIRECTION[event.key];\n if (direction) {\n event.preventDefault();\n this._slide(this._directionToOrder(direction));\n }\n }\n _getItemIndex(element) {\n return this._getItems().indexOf(element);\n }\n _setActiveIndicatorElement(index) {\n if (!this._indicatorsElement) {\n return;\n }\n const activeIndicator = SelectorEngine.findOne(SELECTOR_ACTIVE, this._indicatorsElement);\n activeIndicator.classList.remove(CLASS_NAME_ACTIVE$2);\n activeIndicator.removeAttribute('aria-current');\n const newActiveIndicator = SelectorEngine.findOne(`[data-bs-slide-to=\"${index}\"]`, this._indicatorsElement);\n if (newActiveIndicator) {\n newActiveIndicator.classList.add(CLASS_NAME_ACTIVE$2);\n newActiveIndicator.setAttribute('aria-current', 'true');\n }\n }\n _updateInterval() {\n const element = this._activeElement || this._getActive();\n if (!element) {\n return;\n }\n const elementInterval = Number.parseInt(element.getAttribute('data-bs-interval'), 10);\n this._config.interval = elementInterval || this._config.defaultInterval;\n }\n _slide(order, element = null) {\n if (this._isSliding) {\n return;\n }\n const activeElement = this._getActive();\n const isNext = order === ORDER_NEXT;\n const nextElement = element || getNextActiveElement(this._getItems(), activeElement, isNext, this._config.wrap);\n if (nextElement === activeElement) {\n return;\n }\n const nextElementIndex = this._getItemIndex(nextElement);\n const triggerEvent = eventName => {\n return EventHandler.trigger(this._element, eventName, {\n relatedTarget: nextElement,\n direction: this._orderToDirection(order),\n from: this._getItemIndex(activeElement),\n to: nextElementIndex\n });\n };\n const slideEvent = triggerEvent(EVENT_SLIDE);\n if (slideEvent.defaultPrevented) {\n return;\n }\n if (!activeElement || !nextElement) {\n // Some weirdness is happening, so we bail\n // TODO: change tests that use empty divs to avoid this check\n return;\n }\n const isCycling = Boolean(this._interval);\n this.pause();\n this._isSliding = true;\n this._setActiveIndicatorElement(nextElementIndex);\n this._activeElement = nextElement;\n const directionalClassName = isNext ? CLASS_NAME_START : CLASS_NAME_END;\n const orderClassName = isNext ? CLASS_NAME_NEXT : CLASS_NAME_PREV;\n nextElement.classList.add(orderClassName);\n reflow(nextElement);\n activeElement.classList.add(directionalClassName);\n nextElement.classList.add(directionalClassName);\n const completeCallBack = () => {\n nextElement.classList.remove(directionalClassName, orderClassName);\n nextElement.classList.add(CLASS_NAME_ACTIVE$2);\n activeElement.classList.remove(CLASS_NAME_ACTIVE$2, orderClassName, directionalClassName);\n this._isSliding = false;\n triggerEvent(EVENT_SLID);\n };\n this._queueCallback(completeCallBack, activeElement, this._isAnimated());\n if (isCycling) {\n this.cycle();\n }\n }\n _isAnimated() {\n return this._element.classList.contains(CLASS_NAME_SLIDE);\n }\n _getActive() {\n return SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element);\n }\n _getItems() {\n return SelectorEngine.find(SELECTOR_ITEM, this._element);\n }\n _clearInterval() {\n if (this._interval) {\n clearInterval(this._interval);\n this._interval = null;\n }\n }\n _directionToOrder(direction) {\n if (isRTL()) {\n return direction === DIRECTION_LEFT ? ORDER_PREV : ORDER_NEXT;\n }\n return direction === DIRECTION_LEFT ? ORDER_NEXT : ORDER_PREV;\n }\n _orderToDirection(order) {\n if (isRTL()) {\n return order === ORDER_PREV ? DIRECTION_LEFT : DIRECTION_RIGHT;\n }\n return order === ORDER_PREV ? DIRECTION_RIGHT : DIRECTION_LEFT;\n }\n\n // Static\n static jQueryInterface(config) {\n return this.each(function () {\n const data = Carousel.getOrCreateInstance(this, config);\n if (typeof config === 'number') {\n data.to(config);\n return;\n }\n if (typeof config === 'string') {\n if (data[config] === undefined || config.startsWith('_') || config === 'constructor') {\n throw new TypeError(`No method named \"${config}\"`);\n }\n data[config]();\n }\n });\n }\n}\n\n/**\n * Data API implementation\n */\n\nEventHandler.on(document, EVENT_CLICK_DATA_API$5, SELECTOR_DATA_SLIDE, function (event) {\n const target = SelectorEngine.getElementFromSelector(this);\n if (!target || !target.classList.contains(CLASS_NAME_CAROUSEL)) {\n return;\n }\n event.preventDefault();\n const carousel = Carousel.getOrCreateInstance(target);\n const slideIndex = this.getAttribute('data-bs-slide-to');\n if (slideIndex) {\n carousel.to(slideIndex);\n carousel._maybeEnableCycle();\n return;\n }\n if (Manipulator.getDataAttribute(this, 'slide') === 'next') {\n carousel.next();\n carousel._maybeEnableCycle();\n return;\n }\n carousel.prev();\n carousel._maybeEnableCycle();\n});\nEventHandler.on(window, EVENT_LOAD_DATA_API$3, () => {\n const carousels = SelectorEngine.find(SELECTOR_DATA_RIDE);\n for (const carousel of carousels) {\n Carousel.getOrCreateInstance(carousel);\n }\n});\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Carousel);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap collapse.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$b = 'collapse';\nconst DATA_KEY$7 = 'bs.collapse';\nconst EVENT_KEY$7 = `.${DATA_KEY$7}`;\nconst DATA_API_KEY$4 = '.data-api';\nconst EVENT_SHOW$6 = `show${EVENT_KEY$7}`;\nconst EVENT_SHOWN$6 = `shown${EVENT_KEY$7}`;\nconst EVENT_HIDE$6 = `hide${EVENT_KEY$7}`;\nconst EVENT_HIDDEN$6 = `hidden${EVENT_KEY$7}`;\nconst EVENT_CLICK_DATA_API$4 = `click${EVENT_KEY$7}${DATA_API_KEY$4}`;\nconst CLASS_NAME_SHOW$7 = 'show';\nconst CLASS_NAME_COLLAPSE = 'collapse';\nconst CLASS_NAME_COLLAPSING = 'collapsing';\nconst CLASS_NAME_COLLAPSED = 'collapsed';\nconst CLASS_NAME_DEEPER_CHILDREN = `:scope .${CLASS_NAME_COLLAPSE} .${CLASS_NAME_COLLAPSE}`;\nconst CLASS_NAME_HORIZONTAL = 'collapse-horizontal';\nconst WIDTH = 'width';\nconst HEIGHT = 'height';\nconst SELECTOR_ACTIVES = '.collapse.show, .collapse.collapsing';\nconst SELECTOR_DATA_TOGGLE$4 = '[data-bs-toggle=\"collapse\"]';\nconst Default$a = {\n parent: null,\n toggle: true\n};\nconst DefaultType$a = {\n parent: '(null|element)',\n toggle: 'boolean'\n};\n\n/**\n * Class definition\n */\n\nclass Collapse extends BaseComponent {\n constructor(element, config) {\n super(element, config);\n this._isTransitioning = false;\n this._triggerArray = [];\n const toggleList = SelectorEngine.find(SELECTOR_DATA_TOGGLE$4);\n for (const elem of toggleList) {\n const selector = SelectorEngine.getSelectorFromElement(elem);\n const filterElement = SelectorEngine.find(selector).filter(foundElement => foundElement === this._element);\n if (selector !== null && filterElement.length) {\n this._triggerArray.push(elem);\n }\n }\n this._initializeChildren();\n if (!this._config.parent) {\n this._addAriaAndCollapsedClass(this._triggerArray, this._isShown());\n }\n if (this._config.toggle) {\n this.toggle();\n }\n }\n\n // Getters\n static get Default() {\n return Default$a;\n }\n static get DefaultType() {\n return DefaultType$a;\n }\n static get NAME() {\n return NAME$b;\n }\n\n // Public\n toggle() {\n if (this._isShown()) {\n this.hide();\n } else {\n this.show();\n }\n }\n show() {\n if (this._isTransitioning || this._isShown()) {\n return;\n }\n let activeChildren = [];\n\n // find active children\n if (this._config.parent) {\n activeChildren = this._getFirstLevelChildren(SELECTOR_ACTIVES).filter(element => element !== this._element).map(element => Collapse.getOrCreateInstance(element, {\n toggle: false\n }));\n }\n if (activeChildren.length && activeChildren[0]._isTransitioning) {\n return;\n }\n const startEvent = EventHandler.trigger(this._element, EVENT_SHOW$6);\n if (startEvent.defaultPrevented) {\n return;\n }\n for (const activeInstance of activeChildren) {\n activeInstance.hide();\n }\n const dimension = this._getDimension();\n this._element.classList.remove(CLASS_NAME_COLLAPSE);\n this._element.classList.add(CLASS_NAME_COLLAPSING);\n this._element.style[dimension] = 0;\n this._addAriaAndCollapsedClass(this._triggerArray, true);\n this._isTransitioning = true;\n const complete = () => {\n this._isTransitioning = false;\n this._element.classList.remove(CLASS_NAME_COLLAPSING);\n this._element.classList.add(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7);\n this._element.style[dimension] = '';\n EventHandler.trigger(this._element, EVENT_SHOWN$6);\n };\n const capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1);\n const scrollSize = `scroll${capitalizedDimension}`;\n this._queueCallback(complete, this._element, true);\n this._element.style[dimension] = `${this._element[scrollSize]}px`;\n }\n hide() {\n if (this._isTransitioning || !this._isShown()) {\n return;\n }\n const startEvent = EventHandler.trigger(this._element, EVENT_HIDE$6);\n if (startEvent.defaultPrevented) {\n return;\n }\n const dimension = this._getDimension();\n this._element.style[dimension] = `${this._element.getBoundingClientRect()[dimension]}px`;\n reflow(this._element);\n this._element.classList.add(CLASS_NAME_COLLAPSING);\n this._element.classList.remove(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7);\n for (const trigger of this._triggerArray) {\n const element = SelectorEngine.getElementFromSelector(trigger);\n if (element && !this._isShown(element)) {\n this._addAriaAndCollapsedClass([trigger], false);\n }\n }\n this._isTransitioning = true;\n const complete = () => {\n this._isTransitioning = false;\n this._element.classList.remove(CLASS_NAME_COLLAPSING);\n this._element.classList.add(CLASS_NAME_COLLAPSE);\n EventHandler.trigger(this._element, EVENT_HIDDEN$6);\n };\n this._element.style[dimension] = '';\n this._queueCallback(complete, this._element, true);\n }\n _isShown(element = this._element) {\n return element.classList.contains(CLASS_NAME_SHOW$7);\n }\n\n // Private\n _configAfterMerge(config) {\n config.toggle = Boolean(config.toggle); // Coerce string values\n config.parent = getElement(config.parent);\n return config;\n }\n _getDimension() {\n return this._element.classList.contains(CLASS_NAME_HORIZONTAL) ? WIDTH : HEIGHT;\n }\n _initializeChildren() {\n if (!this._config.parent) {\n return;\n }\n const children = this._getFirstLevelChildren(SELECTOR_DATA_TOGGLE$4);\n for (const element of children) {\n const selected = SelectorEngine.getElementFromSelector(element);\n if (selected) {\n this._addAriaAndCollapsedClass([element], this._isShown(selected));\n }\n }\n }\n _getFirstLevelChildren(selector) {\n const children = SelectorEngine.find(CLASS_NAME_DEEPER_CHILDREN, this._config.parent);\n // remove children if greater depth\n return SelectorEngine.find(selector, this._config.parent).filter(element => !children.includes(element));\n }\n _addAriaAndCollapsedClass(triggerArray, isOpen) {\n if (!triggerArray.length) {\n return;\n }\n for (const element of triggerArray) {\n element.classList.toggle(CLASS_NAME_COLLAPSED, !isOpen);\n element.setAttribute('aria-expanded', isOpen);\n }\n }\n\n // Static\n static jQueryInterface(config) {\n const _config = {};\n if (typeof config === 'string' && /show|hide/.test(config)) {\n _config.toggle = false;\n }\n return this.each(function () {\n const data = Collapse.getOrCreateInstance(this, _config);\n if (typeof config === 'string') {\n if (typeof data[config] === 'undefined') {\n throw new TypeError(`No method named \"${config}\"`);\n }\n data[config]();\n }\n });\n }\n}\n\n/**\n * Data API implementation\n */\n\nEventHandler.on(document, EVENT_CLICK_DATA_API$4, SELECTOR_DATA_TOGGLE$4, function (event) {\n // preventDefault only for elements (which change the URL) not inside the collapsible element\n if (event.target.tagName === 'A' || event.delegateTarget && event.delegateTarget.tagName === 'A') {\n event.preventDefault();\n }\n for (const element of SelectorEngine.getMultipleElementsFromSelector(this)) {\n Collapse.getOrCreateInstance(element, {\n toggle: false\n }).toggle();\n }\n});\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Collapse);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap dropdown.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$a = 'dropdown';\nconst DATA_KEY$6 = 'bs.dropdown';\nconst EVENT_KEY$6 = `.${DATA_KEY$6}`;\nconst DATA_API_KEY$3 = '.data-api';\nconst ESCAPE_KEY$2 = 'Escape';\nconst TAB_KEY$1 = 'Tab';\nconst ARROW_UP_KEY$1 = 'ArrowUp';\nconst ARROW_DOWN_KEY$1 = 'ArrowDown';\nconst RIGHT_MOUSE_BUTTON = 2; // MouseEvent.button value for the secondary button, usually the right button\n\nconst EVENT_HIDE$5 = `hide${EVENT_KEY$6}`;\nconst EVENT_HIDDEN$5 = `hidden${EVENT_KEY$6}`;\nconst EVENT_SHOW$5 = `show${EVENT_KEY$6}`;\nconst EVENT_SHOWN$5 = `shown${EVENT_KEY$6}`;\nconst EVENT_CLICK_DATA_API$3 = `click${EVENT_KEY$6}${DATA_API_KEY$3}`;\nconst EVENT_KEYDOWN_DATA_API = `keydown${EVENT_KEY$6}${DATA_API_KEY$3}`;\nconst EVENT_KEYUP_DATA_API = `keyup${EVENT_KEY$6}${DATA_API_KEY$3}`;\nconst CLASS_NAME_SHOW$6 = 'show';\nconst CLASS_NAME_DROPUP = 'dropup';\nconst CLASS_NAME_DROPEND = 'dropend';\nconst CLASS_NAME_DROPSTART = 'dropstart';\nconst CLASS_NAME_DROPUP_CENTER = 'dropup-center';\nconst CLASS_NAME_DROPDOWN_CENTER = 'dropdown-center';\nconst SELECTOR_DATA_TOGGLE$3 = '[data-bs-toggle=\"dropdown\"]:not(.disabled):not(:disabled)';\nconst SELECTOR_DATA_TOGGLE_SHOWN = `${SELECTOR_DATA_TOGGLE$3}.${CLASS_NAME_SHOW$6}`;\nconst SELECTOR_MENU = '.dropdown-menu';\nconst SELECTOR_NAVBAR = '.navbar';\nconst SELECTOR_NAVBAR_NAV = '.navbar-nav';\nconst SELECTOR_VISIBLE_ITEMS = '.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)';\nconst PLACEMENT_TOP = isRTL() ? 'top-end' : 'top-start';\nconst PLACEMENT_TOPEND = isRTL() ? 'top-start' : 'top-end';\nconst PLACEMENT_BOTTOM = isRTL() ? 'bottom-end' : 'bottom-start';\nconst PLACEMENT_BOTTOMEND = isRTL() ? 'bottom-start' : 'bottom-end';\nconst PLACEMENT_RIGHT = isRTL() ? 'left-start' : 'right-start';\nconst PLACEMENT_LEFT = isRTL() ? 'right-start' : 'left-start';\nconst PLACEMENT_TOPCENTER = 'top';\nconst PLACEMENT_BOTTOMCENTER = 'bottom';\nconst Default$9 = {\n autoClose: true,\n boundary: 'clippingParents',\n display: 'dynamic',\n offset: [0, 2],\n popperConfig: null,\n reference: 'toggle'\n};\nconst DefaultType$9 = {\n autoClose: '(boolean|string)',\n boundary: '(string|element)',\n display: 'string',\n offset: '(array|string|function)',\n popperConfig: '(null|object|function)',\n reference: '(string|element|object)'\n};\n\n/**\n * Class definition\n */\n\nclass Dropdown extends BaseComponent {\n constructor(element, config) {\n super(element, config);\n this._popper = null;\n this._parent = this._element.parentNode; // dropdown wrapper\n // TODO: v6 revert #37011 & change markup https://getbootstrap.com/docs/5.3/forms/input-group/\n this._menu = SelectorEngine.next(this._element, SELECTOR_MENU)[0] || SelectorEngine.prev(this._element, SELECTOR_MENU)[0] || SelectorEngine.findOne(SELECTOR_MENU, this._parent);\n this._inNavbar = this._detectNavbar();\n }\n\n // Getters\n static get Default() {\n return Default$9;\n }\n static get DefaultType() {\n return DefaultType$9;\n }\n static get NAME() {\n return NAME$a;\n }\n\n // Public\n toggle() {\n return this._isShown() ? this.hide() : this.show();\n }\n show() {\n if (isDisabled(this._element) || this._isShown()) {\n return;\n }\n const relatedTarget = {\n relatedTarget: this._element\n };\n const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$5, relatedTarget);\n if (showEvent.defaultPrevented) {\n return;\n }\n this._createPopper();\n\n // If this is a touch-enabled device we add extra\n // empty mouseover listeners to the body's immediate children;\n // only needed because of broken event delegation on iOS\n // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html\n if ('ontouchstart' in document.documentElement && !this._parent.closest(SELECTOR_NAVBAR_NAV)) {\n for (const element of [].concat(...document.body.children)) {\n EventHandler.on(element, 'mouseover', noop);\n }\n }\n this._element.focus();\n this._element.setAttribute('aria-expanded', true);\n this._menu.classList.add(CLASS_NAME_SHOW$6);\n this._element.classList.add(CLASS_NAME_SHOW$6);\n EventHandler.trigger(this._element, EVENT_SHOWN$5, relatedTarget);\n }\n hide() {\n if (isDisabled(this._element) || !this._isShown()) {\n return;\n }\n const relatedTarget = {\n relatedTarget: this._element\n };\n this._completeHide(relatedTarget);\n }\n dispose() {\n if (this._popper) {\n this._popper.destroy();\n }\n super.dispose();\n }\n update() {\n this._inNavbar = this._detectNavbar();\n if (this._popper) {\n this._popper.update();\n }\n }\n\n // Private\n _completeHide(relatedTarget) {\n const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$5, relatedTarget);\n if (hideEvent.defaultPrevented) {\n return;\n }\n\n // If this is a touch-enabled device we remove the extra\n // empty mouseover listeners we added for iOS support\n if ('ontouchstart' in document.documentElement) {\n for (const element of [].concat(...document.body.children)) {\n EventHandler.off(element, 'mouseover', noop);\n }\n }\n if (this._popper) {\n this._popper.destroy();\n }\n this._menu.classList.remove(CLASS_NAME_SHOW$6);\n this._element.classList.remove(CLASS_NAME_SHOW$6);\n this._element.setAttribute('aria-expanded', 'false');\n Manipulator.removeDataAttribute(this._menu, 'popper');\n EventHandler.trigger(this._element, EVENT_HIDDEN$5, relatedTarget);\n }\n _getConfig(config) {\n config = super._getConfig(config);\n if (typeof config.reference === 'object' && !isElement(config.reference) && typeof config.reference.getBoundingClientRect !== 'function') {\n // Popper virtual elements require a getBoundingClientRect method\n throw new TypeError(`${NAME$a.toUpperCase()}: Option \"reference\" provided type \"object\" without a required \"getBoundingClientRect\" method.`);\n }\n return config;\n }\n _createPopper() {\n if (typeof Popper === 'undefined') {\n throw new TypeError('Bootstrap\\'s dropdowns require Popper (https://popper.js.org)');\n }\n let referenceElement = this._element;\n if (this._config.reference === 'parent') {\n referenceElement = this._parent;\n } else if (isElement(this._config.reference)) {\n referenceElement = getElement(this._config.reference);\n } else if (typeof this._config.reference === 'object') {\n referenceElement = this._config.reference;\n }\n const popperConfig = this._getPopperConfig();\n this._popper = Popper.createPopper(referenceElement, this._menu, popperConfig);\n }\n _isShown() {\n return this._menu.classList.contains(CLASS_NAME_SHOW$6);\n }\n _getPlacement() {\n const parentDropdown = this._parent;\n if (parentDropdown.classList.contains(CLASS_NAME_DROPEND)) {\n return PLACEMENT_RIGHT;\n }\n if (parentDropdown.classList.contains(CLASS_NAME_DROPSTART)) {\n return PLACEMENT_LEFT;\n }\n if (parentDropdown.classList.contains(CLASS_NAME_DROPUP_CENTER)) {\n return PLACEMENT_TOPCENTER;\n }\n if (parentDropdown.classList.contains(CLASS_NAME_DROPDOWN_CENTER)) {\n return PLACEMENT_BOTTOMCENTER;\n }\n\n // We need to trim the value because custom properties can also include spaces\n const isEnd = getComputedStyle(this._menu).getPropertyValue('--bs-position').trim() === 'end';\n if (parentDropdown.classList.contains(CLASS_NAME_DROPUP)) {\n return isEnd ? PLACEMENT_TOPEND : PLACEMENT_TOP;\n }\n return isEnd ? PLACEMENT_BOTTOMEND : PLACEMENT_BOTTOM;\n }\n _detectNavbar() {\n return this._element.closest(SELECTOR_NAVBAR) !== null;\n }\n _getOffset() {\n const {\n offset\n } = this._config;\n if (typeof offset === 'string') {\n return offset.split(',').map(value => Number.parseInt(value, 10));\n }\n if (typeof offset === 'function') {\n return popperData => offset(popperData, this._element);\n }\n return offset;\n }\n _getPopperConfig() {\n const defaultBsPopperConfig = {\n placement: this._getPlacement(),\n modifiers: [{\n name: 'preventOverflow',\n options: {\n boundary: this._config.boundary\n }\n }, {\n name: 'offset',\n options: {\n offset: this._getOffset()\n }\n }]\n };\n\n // Disable Popper if we have a static display or Dropdown is in Navbar\n if (this._inNavbar || this._config.display === 'static') {\n Manipulator.setDataAttribute(this._menu, 'popper', 'static'); // TODO: v6 remove\n defaultBsPopperConfig.modifiers = [{\n name: 'applyStyles',\n enabled: false\n }];\n }\n return {\n ...defaultBsPopperConfig,\n ...execute(this._config.popperConfig, [defaultBsPopperConfig])\n };\n }\n _selectMenuItem({\n key,\n target\n }) {\n const items = SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu).filter(element => isVisible(element));\n if (!items.length) {\n return;\n }\n\n // if target isn't included in items (e.g. when expanding the dropdown)\n // allow cycling to get the last item in case key equals ARROW_UP_KEY\n getNextActiveElement(items, target, key === ARROW_DOWN_KEY$1, !items.includes(target)).focus();\n }\n\n // Static\n static jQueryInterface(config) {\n return this.each(function () {\n const data = Dropdown.getOrCreateInstance(this, config);\n if (typeof config !== 'string') {\n return;\n }\n if (typeof data[config] === 'undefined') {\n throw new TypeError(`No method named \"${config}\"`);\n }\n data[config]();\n });\n }\n static clearMenus(event) {\n if (event.button === RIGHT_MOUSE_BUTTON || event.type === 'keyup' && event.key !== TAB_KEY$1) {\n return;\n }\n const openToggles = SelectorEngine.find(SELECTOR_DATA_TOGGLE_SHOWN);\n for (const toggle of openToggles) {\n const context = Dropdown.getInstance(toggle);\n if (!context || context._config.autoClose === false) {\n continue;\n }\n const composedPath = event.composedPath();\n const isMenuTarget = composedPath.includes(context._menu);\n if (composedPath.includes(context._element) || context._config.autoClose === 'inside' && !isMenuTarget || context._config.autoClose === 'outside' && isMenuTarget) {\n continue;\n }\n\n // Tab navigation through the dropdown menu or events from contained inputs shouldn't close the menu\n if (context._menu.contains(event.target) && (event.type === 'keyup' && event.key === TAB_KEY$1 || /input|select|option|textarea|form/i.test(event.target.tagName))) {\n continue;\n }\n const relatedTarget = {\n relatedTarget: context._element\n };\n if (event.type === 'click') {\n relatedTarget.clickEvent = event;\n }\n context._completeHide(relatedTarget);\n }\n }\n static dataApiKeydownHandler(event) {\n // If not an UP | DOWN | ESCAPE key => not a dropdown command\n // If input/textarea && if key is other than ESCAPE => not a dropdown command\n\n const isInput = /input|textarea/i.test(event.target.tagName);\n const isEscapeEvent = event.key === ESCAPE_KEY$2;\n const isUpOrDownEvent = [ARROW_UP_KEY$1, ARROW_DOWN_KEY$1].includes(event.key);\n if (!isUpOrDownEvent && !isEscapeEvent) {\n return;\n }\n if (isInput && !isEscapeEvent) {\n return;\n }\n event.preventDefault();\n\n // TODO: v6 revert #37011 & change markup https://getbootstrap.com/docs/5.3/forms/input-group/\n const getToggleButton = this.matches(SELECTOR_DATA_TOGGLE$3) ? this : SelectorEngine.prev(this, SELECTOR_DATA_TOGGLE$3)[0] || SelectorEngine.next(this, SELECTOR_DATA_TOGGLE$3)[0] || SelectorEngine.findOne(SELECTOR_DATA_TOGGLE$3, event.delegateTarget.parentNode);\n const instance = Dropdown.getOrCreateInstance(getToggleButton);\n if (isUpOrDownEvent) {\n event.stopPropagation();\n instance.show();\n instance._selectMenuItem(event);\n return;\n }\n if (instance._isShown()) {\n // else is escape and we check if it is shown\n event.stopPropagation();\n instance.hide();\n getToggleButton.focus();\n }\n }\n}\n\n/**\n * Data API implementation\n */\n\nEventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_DATA_TOGGLE$3, Dropdown.dataApiKeydownHandler);\nEventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_MENU, Dropdown.dataApiKeydownHandler);\nEventHandler.on(document, EVENT_CLICK_DATA_API$3, Dropdown.clearMenus);\nEventHandler.on(document, EVENT_KEYUP_DATA_API, Dropdown.clearMenus);\nEventHandler.on(document, EVENT_CLICK_DATA_API$3, SELECTOR_DATA_TOGGLE$3, function (event) {\n event.preventDefault();\n Dropdown.getOrCreateInstance(this).toggle();\n});\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Dropdown);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/backdrop.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$9 = 'backdrop';\nconst CLASS_NAME_FADE$4 = 'fade';\nconst CLASS_NAME_SHOW$5 = 'show';\nconst EVENT_MOUSEDOWN = `mousedown.bs.${NAME$9}`;\nconst Default$8 = {\n className: 'modal-backdrop',\n clickCallback: null,\n isAnimated: false,\n isVisible: true,\n // if false, we use the backdrop helper without adding any element to the dom\n rootElement: 'body' // give the choice to place backdrop under different elements\n};\nconst DefaultType$8 = {\n className: 'string',\n clickCallback: '(function|null)',\n isAnimated: 'boolean',\n isVisible: 'boolean',\n rootElement: '(element|string)'\n};\n\n/**\n * Class definition\n */\n\nclass Backdrop extends Config {\n constructor(config) {\n super();\n this._config = this._getConfig(config);\n this._isAppended = false;\n this._element = null;\n }\n\n // Getters\n static get Default() {\n return Default$8;\n }\n static get DefaultType() {\n return DefaultType$8;\n }\n static get NAME() {\n return NAME$9;\n }\n\n // Public\n show(callback) {\n if (!this._config.isVisible) {\n execute(callback);\n return;\n }\n this._append();\n const element = this._getElement();\n if (this._config.isAnimated) {\n reflow(element);\n }\n element.classList.add(CLASS_NAME_SHOW$5);\n this._emulateAnimation(() => {\n execute(callback);\n });\n }\n hide(callback) {\n if (!this._config.isVisible) {\n execute(callback);\n return;\n }\n this._getElement().classList.remove(CLASS_NAME_SHOW$5);\n this._emulateAnimation(() => {\n this.dispose();\n execute(callback);\n });\n }\n dispose() {\n if (!this._isAppended) {\n return;\n }\n EventHandler.off(this._element, EVENT_MOUSEDOWN);\n this._element.remove();\n this._isAppended = false;\n }\n\n // Private\n _getElement() {\n if (!this._element) {\n const backdrop = document.createElement('div');\n backdrop.className = this._config.className;\n if (this._config.isAnimated) {\n backdrop.classList.add(CLASS_NAME_FADE$4);\n }\n this._element = backdrop;\n }\n return this._element;\n }\n _configAfterMerge(config) {\n // use getElement() with the default \"body\" to get a fresh Element on each instantiation\n config.rootElement = getElement(config.rootElement);\n return config;\n }\n _append() {\n if (this._isAppended) {\n return;\n }\n const element = this._getElement();\n this._config.rootElement.append(element);\n EventHandler.on(element, EVENT_MOUSEDOWN, () => {\n execute(this._config.clickCallback);\n });\n this._isAppended = true;\n }\n _emulateAnimation(callback) {\n executeAfterTransition(callback, this._getElement(), this._config.isAnimated);\n }\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/focustrap.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$8 = 'focustrap';\nconst DATA_KEY$5 = 'bs.focustrap';\nconst EVENT_KEY$5 = `.${DATA_KEY$5}`;\nconst EVENT_FOCUSIN$2 = `focusin${EVENT_KEY$5}`;\nconst EVENT_KEYDOWN_TAB = `keydown.tab${EVENT_KEY$5}`;\nconst TAB_KEY = 'Tab';\nconst TAB_NAV_FORWARD = 'forward';\nconst TAB_NAV_BACKWARD = 'backward';\nconst Default$7 = {\n autofocus: true,\n trapElement: null // The element to trap focus inside of\n};\nconst DefaultType$7 = {\n autofocus: 'boolean',\n trapElement: 'element'\n};\n\n/**\n * Class definition\n */\n\nclass FocusTrap extends Config {\n constructor(config) {\n super();\n this._config = this._getConfig(config);\n this._isActive = false;\n this._lastTabNavDirection = null;\n }\n\n // Getters\n static get Default() {\n return Default$7;\n }\n static get DefaultType() {\n return DefaultType$7;\n }\n static get NAME() {\n return NAME$8;\n }\n\n // Public\n activate() {\n if (this._isActive) {\n return;\n }\n if (this._config.autofocus) {\n this._config.trapElement.focus();\n }\n EventHandler.off(document, EVENT_KEY$5); // guard against infinite focus loop\n EventHandler.on(document, EVENT_FOCUSIN$2, event => this._handleFocusin(event));\n EventHandler.on(document, EVENT_KEYDOWN_TAB, event => this._handleKeydown(event));\n this._isActive = true;\n }\n deactivate() {\n if (!this._isActive) {\n return;\n }\n this._isActive = false;\n EventHandler.off(document, EVENT_KEY$5);\n }\n\n // Private\n _handleFocusin(event) {\n const {\n trapElement\n } = this._config;\n if (event.target === document || event.target === trapElement || trapElement.contains(event.target)) {\n return;\n }\n const elements = SelectorEngine.focusableChildren(trapElement);\n if (elements.length === 0) {\n trapElement.focus();\n } else if (this._lastTabNavDirection === TAB_NAV_BACKWARD) {\n elements[elements.length - 1].focus();\n } else {\n elements[0].focus();\n }\n }\n _handleKeydown(event) {\n if (event.key !== TAB_KEY) {\n return;\n }\n this._lastTabNavDirection = event.shiftKey ? TAB_NAV_BACKWARD : TAB_NAV_FORWARD;\n }\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/scrollBar.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst SELECTOR_FIXED_CONTENT = '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top';\nconst SELECTOR_STICKY_CONTENT = '.sticky-top';\nconst PROPERTY_PADDING = 'padding-right';\nconst PROPERTY_MARGIN = 'margin-right';\n\n/**\n * Class definition\n */\n\nclass ScrollBarHelper {\n constructor() {\n this._element = document.body;\n }\n\n // Public\n getWidth() {\n // https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth#usage_notes\n const documentWidth = document.documentElement.clientWidth;\n return Math.abs(window.innerWidth - documentWidth);\n }\n hide() {\n const width = this.getWidth();\n this._disableOverFlow();\n // give padding to element to balance the hidden scrollbar width\n this._setElementAttributes(this._element, PROPERTY_PADDING, calculatedValue => calculatedValue + width);\n // trick: We adjust positive paddingRight and negative marginRight to sticky-top elements to keep showing fullwidth\n this._setElementAttributes(SELECTOR_FIXED_CONTENT, PROPERTY_PADDING, calculatedValue => calculatedValue + width);\n this._setElementAttributes(SELECTOR_STICKY_CONTENT, PROPERTY_MARGIN, calculatedValue => calculatedValue - width);\n }\n reset() {\n this._resetElementAttributes(this._element, 'overflow');\n this._resetElementAttributes(this._element, PROPERTY_PADDING);\n this._resetElementAttributes(SELECTOR_FIXED_CONTENT, PROPERTY_PADDING);\n this._resetElementAttributes(SELECTOR_STICKY_CONTENT, PROPERTY_MARGIN);\n }\n isOverflowing() {\n return this.getWidth() > 0;\n }\n\n // Private\n _disableOverFlow() {\n this._saveInitialAttribute(this._element, 'overflow');\n this._element.style.overflow = 'hidden';\n }\n _setElementAttributes(selector, styleProperty, callback) {\n const scrollbarWidth = this.getWidth();\n const manipulationCallBack = element => {\n if (element !== this._element && window.innerWidth > element.clientWidth + scrollbarWidth) {\n return;\n }\n this._saveInitialAttribute(element, styleProperty);\n const calculatedValue = window.getComputedStyle(element).getPropertyValue(styleProperty);\n element.style.setProperty(styleProperty, `${callback(Number.parseFloat(calculatedValue))}px`);\n };\n this._applyManipulationCallback(selector, manipulationCallBack);\n }\n _saveInitialAttribute(element, styleProperty) {\n const actualValue = element.style.getPropertyValue(styleProperty);\n if (actualValue) {\n Manipulator.setDataAttribute(element, styleProperty, actualValue);\n }\n }\n _resetElementAttributes(selector, styleProperty) {\n const manipulationCallBack = element => {\n const value = Manipulator.getDataAttribute(element, styleProperty);\n // We only want to remove the property if the value is `null`; the value can also be zero\n if (value === null) {\n element.style.removeProperty(styleProperty);\n return;\n }\n Manipulator.removeDataAttribute(element, styleProperty);\n element.style.setProperty(styleProperty, value);\n };\n this._applyManipulationCallback(selector, manipulationCallBack);\n }\n _applyManipulationCallback(selector, callBack) {\n if (isElement(selector)) {\n callBack(selector);\n return;\n }\n for (const sel of SelectorEngine.find(selector, this._element)) {\n callBack(sel);\n }\n }\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap modal.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$7 = 'modal';\nconst DATA_KEY$4 = 'bs.modal';\nconst EVENT_KEY$4 = `.${DATA_KEY$4}`;\nconst DATA_API_KEY$2 = '.data-api';\nconst ESCAPE_KEY$1 = 'Escape';\nconst EVENT_HIDE$4 = `hide${EVENT_KEY$4}`;\nconst EVENT_HIDE_PREVENTED$1 = `hidePrevented${EVENT_KEY$4}`;\nconst EVENT_HIDDEN$4 = `hidden${EVENT_KEY$4}`;\nconst EVENT_SHOW$4 = `show${EVENT_KEY$4}`;\nconst EVENT_SHOWN$4 = `shown${EVENT_KEY$4}`;\nconst EVENT_RESIZE$1 = `resize${EVENT_KEY$4}`;\nconst EVENT_CLICK_DISMISS = `click.dismiss${EVENT_KEY$4}`;\nconst EVENT_MOUSEDOWN_DISMISS = `mousedown.dismiss${EVENT_KEY$4}`;\nconst EVENT_KEYDOWN_DISMISS$1 = `keydown.dismiss${EVENT_KEY$4}`;\nconst EVENT_CLICK_DATA_API$2 = `click${EVENT_KEY$4}${DATA_API_KEY$2}`;\nconst CLASS_NAME_OPEN = 'modal-open';\nconst CLASS_NAME_FADE$3 = 'fade';\nconst CLASS_NAME_SHOW$4 = 'show';\nconst CLASS_NAME_STATIC = 'modal-static';\nconst OPEN_SELECTOR$1 = '.modal.show';\nconst SELECTOR_DIALOG = '.modal-dialog';\nconst SELECTOR_MODAL_BODY = '.modal-body';\nconst SELECTOR_DATA_TOGGLE$2 = '[data-bs-toggle=\"modal\"]';\nconst Default$6 = {\n backdrop: true,\n focus: true,\n keyboard: true\n};\nconst DefaultType$6 = {\n backdrop: '(boolean|string)',\n focus: 'boolean',\n keyboard: 'boolean'\n};\n\n/**\n * Class definition\n */\n\nclass Modal extends BaseComponent {\n constructor(element, config) {\n super(element, config);\n this._dialog = SelectorEngine.findOne(SELECTOR_DIALOG, this._element);\n this._backdrop = this._initializeBackDrop();\n this._focustrap = this._initializeFocusTrap();\n this._isShown = false;\n this._isTransitioning = false;\n this._scrollBar = new ScrollBarHelper();\n this._addEventListeners();\n }\n\n // Getters\n static get Default() {\n return Default$6;\n }\n static get DefaultType() {\n return DefaultType$6;\n }\n static get NAME() {\n return NAME$7;\n }\n\n // Public\n toggle(relatedTarget) {\n return this._isShown ? this.hide() : this.show(relatedTarget);\n }\n show(relatedTarget) {\n if (this._isShown || this._isTransitioning) {\n return;\n }\n const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$4, {\n relatedTarget\n });\n if (showEvent.defaultPrevented) {\n return;\n }\n this._isShown = true;\n this._isTransitioning = true;\n this._scrollBar.hide();\n document.body.classList.add(CLASS_NAME_OPEN);\n this._adjustDialog();\n this._backdrop.show(() => this._showElement(relatedTarget));\n }\n hide() {\n if (!this._isShown || this._isTransitioning) {\n return;\n }\n const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$4);\n if (hideEvent.defaultPrevented) {\n return;\n }\n this._isShown = false;\n this._isTransitioning = true;\n this._focustrap.deactivate();\n this._element.classList.remove(CLASS_NAME_SHOW$4);\n this._queueCallback(() => this._hideModal(), this._element, this._isAnimated());\n }\n dispose() {\n EventHandler.off(window, EVENT_KEY$4);\n EventHandler.off(this._dialog, EVENT_KEY$4);\n this._backdrop.dispose();\n this._focustrap.deactivate();\n super.dispose();\n }\n handleUpdate() {\n this._adjustDialog();\n }\n\n // Private\n _initializeBackDrop() {\n return new Backdrop({\n isVisible: Boolean(this._config.backdrop),\n // 'static' option will be translated to true, and booleans will keep their value,\n isAnimated: this._isAnimated()\n });\n }\n _initializeFocusTrap() {\n return new FocusTrap({\n trapElement: this._element\n });\n }\n _showElement(relatedTarget) {\n // try to append dynamic modal\n if (!document.body.contains(this._element)) {\n document.body.append(this._element);\n }\n this._element.style.display = 'block';\n this._element.removeAttribute('aria-hidden');\n this._element.setAttribute('aria-modal', true);\n this._element.setAttribute('role', 'dialog');\n this._element.scrollTop = 0;\n const modalBody = SelectorEngine.findOne(SELECTOR_MODAL_BODY, this._dialog);\n if (modalBody) {\n modalBody.scrollTop = 0;\n }\n reflow(this._element);\n this._element.classList.add(CLASS_NAME_SHOW$4);\n const transitionComplete = () => {\n if (this._config.focus) {\n this._focustrap.activate();\n }\n this._isTransitioning = false;\n EventHandler.trigger(this._element, EVENT_SHOWN$4, {\n relatedTarget\n });\n };\n this._queueCallback(transitionComplete, this._dialog, this._isAnimated());\n }\n _addEventListeners() {\n EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS$1, event => {\n if (event.key !== ESCAPE_KEY$1) {\n return;\n }\n if (this._config.keyboard) {\n this.hide();\n return;\n }\n this._triggerBackdropTransition();\n });\n EventHandler.on(window, EVENT_RESIZE$1, () => {\n if (this._isShown && !this._isTransitioning) {\n this._adjustDialog();\n }\n });\n EventHandler.on(this._element, EVENT_MOUSEDOWN_DISMISS, event => {\n // a bad trick to segregate clicks that may start inside dialog but end outside, and avoid listen to scrollbar clicks\n EventHandler.one(this._element, EVENT_CLICK_DISMISS, event2 => {\n if (this._element !== event.target || this._element !== event2.target) {\n return;\n }\n if (this._config.backdrop === 'static') {\n this._triggerBackdropTransition();\n return;\n }\n if (this._config.backdrop) {\n this.hide();\n }\n });\n });\n }\n _hideModal() {\n this._element.style.display = 'none';\n this._element.setAttribute('aria-hidden', true);\n this._element.removeAttribute('aria-modal');\n this._element.removeAttribute('role');\n this._isTransitioning = false;\n this._backdrop.hide(() => {\n document.body.classList.remove(CLASS_NAME_OPEN);\n this._resetAdjustments();\n this._scrollBar.reset();\n EventHandler.trigger(this._element, EVENT_HIDDEN$4);\n });\n }\n _isAnimated() {\n return this._element.classList.contains(CLASS_NAME_FADE$3);\n }\n _triggerBackdropTransition() {\n const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED$1);\n if (hideEvent.defaultPrevented) {\n return;\n }\n const isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight;\n const initialOverflowY = this._element.style.overflowY;\n // return if the following background transition hasn't yet completed\n if (initialOverflowY === 'hidden' || this._element.classList.contains(CLASS_NAME_STATIC)) {\n return;\n }\n if (!isModalOverflowing) {\n this._element.style.overflowY = 'hidden';\n }\n this._element.classList.add(CLASS_NAME_STATIC);\n this._queueCallback(() => {\n this._element.classList.remove(CLASS_NAME_STATIC);\n this._queueCallback(() => {\n this._element.style.overflowY = initialOverflowY;\n }, this._dialog);\n }, this._dialog);\n this._element.focus();\n }\n\n /**\n * The following methods are used to handle overflowing modals\n */\n\n _adjustDialog() {\n const isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight;\n const scrollbarWidth = this._scrollBar.getWidth();\n const isBodyOverflowing = scrollbarWidth > 0;\n if (isBodyOverflowing && !isModalOverflowing) {\n const property = isRTL() ? 'paddingLeft' : 'paddingRight';\n this._element.style[property] = `${scrollbarWidth}px`;\n }\n if (!isBodyOverflowing && isModalOverflowing) {\n const property = isRTL() ? 'paddingRight' : 'paddingLeft';\n this._element.style[property] = `${scrollbarWidth}px`;\n }\n }\n _resetAdjustments() {\n this._element.style.paddingLeft = '';\n this._element.style.paddingRight = '';\n }\n\n // Static\n static jQueryInterface(config, relatedTarget) {\n return this.each(function () {\n const data = Modal.getOrCreateInstance(this, config);\n if (typeof config !== 'string') {\n return;\n }\n if (typeof data[config] === 'undefined') {\n throw new TypeError(`No method named \"${config}\"`);\n }\n data[config](relatedTarget);\n });\n }\n}\n\n/**\n * Data API implementation\n */\n\nEventHandler.on(document, EVENT_CLICK_DATA_API$2, SELECTOR_DATA_TOGGLE$2, function (event) {\n const target = SelectorEngine.getElementFromSelector(this);\n if (['A', 'AREA'].includes(this.tagName)) {\n event.preventDefault();\n }\n EventHandler.one(target, EVENT_SHOW$4, showEvent => {\n if (showEvent.defaultPrevented) {\n // only register focus restorer if modal will actually get shown\n return;\n }\n EventHandler.one(target, EVENT_HIDDEN$4, () => {\n if (isVisible(this)) {\n this.focus();\n }\n });\n });\n\n // avoid conflict when clicking modal toggler while another one is open\n const alreadyOpen = SelectorEngine.findOne(OPEN_SELECTOR$1);\n if (alreadyOpen) {\n Modal.getInstance(alreadyOpen).hide();\n }\n const data = Modal.getOrCreateInstance(target);\n data.toggle(this);\n});\nenableDismissTrigger(Modal);\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Modal);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap offcanvas.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$6 = 'offcanvas';\nconst DATA_KEY$3 = 'bs.offcanvas';\nconst EVENT_KEY$3 = `.${DATA_KEY$3}`;\nconst DATA_API_KEY$1 = '.data-api';\nconst EVENT_LOAD_DATA_API$2 = `load${EVENT_KEY$3}${DATA_API_KEY$1}`;\nconst ESCAPE_KEY = 'Escape';\nconst CLASS_NAME_SHOW$3 = 'show';\nconst CLASS_NAME_SHOWING$1 = 'showing';\nconst CLASS_NAME_HIDING = 'hiding';\nconst CLASS_NAME_BACKDROP = 'offcanvas-backdrop';\nconst OPEN_SELECTOR = '.offcanvas.show';\nconst EVENT_SHOW$3 = `show${EVENT_KEY$3}`;\nconst EVENT_SHOWN$3 = `shown${EVENT_KEY$3}`;\nconst EVENT_HIDE$3 = `hide${EVENT_KEY$3}`;\nconst EVENT_HIDE_PREVENTED = `hidePrevented${EVENT_KEY$3}`;\nconst EVENT_HIDDEN$3 = `hidden${EVENT_KEY$3}`;\nconst EVENT_RESIZE = `resize${EVENT_KEY$3}`;\nconst EVENT_CLICK_DATA_API$1 = `click${EVENT_KEY$3}${DATA_API_KEY$1}`;\nconst EVENT_KEYDOWN_DISMISS = `keydown.dismiss${EVENT_KEY$3}`;\nconst SELECTOR_DATA_TOGGLE$1 = '[data-bs-toggle=\"offcanvas\"]';\nconst Default$5 = {\n backdrop: true,\n keyboard: true,\n scroll: false\n};\nconst DefaultType$5 = {\n backdrop: '(boolean|string)',\n keyboard: 'boolean',\n scroll: 'boolean'\n};\n\n/**\n * Class definition\n */\n\nclass Offcanvas extends BaseComponent {\n constructor(element, config) {\n super(element, config);\n this._isShown = false;\n this._backdrop = this._initializeBackDrop();\n this._focustrap = this._initializeFocusTrap();\n this._addEventListeners();\n }\n\n // Getters\n static get Default() {\n return Default$5;\n }\n static get DefaultType() {\n return DefaultType$5;\n }\n static get NAME() {\n return NAME$6;\n }\n\n // Public\n toggle(relatedTarget) {\n return this._isShown ? this.hide() : this.show(relatedTarget);\n }\n show(relatedTarget) {\n if (this._isShown) {\n return;\n }\n const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$3, {\n relatedTarget\n });\n if (showEvent.defaultPrevented) {\n return;\n }\n this._isShown = true;\n this._backdrop.show();\n if (!this._config.scroll) {\n new ScrollBarHelper().hide();\n }\n this._element.setAttribute('aria-modal', true);\n this._element.setAttribute('role', 'dialog');\n this._element.classList.add(CLASS_NAME_SHOWING$1);\n const completeCallBack = () => {\n if (!this._config.scroll || this._config.backdrop) {\n this._focustrap.activate();\n }\n this._element.classList.add(CLASS_NAME_SHOW$3);\n this._element.classList.remove(CLASS_NAME_SHOWING$1);\n EventHandler.trigger(this._element, EVENT_SHOWN$3, {\n relatedTarget\n });\n };\n this._queueCallback(completeCallBack, this._element, true);\n }\n hide() {\n if (!this._isShown) {\n return;\n }\n const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$3);\n if (hideEvent.defaultPrevented) {\n return;\n }\n this._focustrap.deactivate();\n this._element.blur();\n this._isShown = false;\n this._element.classList.add(CLASS_NAME_HIDING);\n this._backdrop.hide();\n const completeCallback = () => {\n this._element.classList.remove(CLASS_NAME_SHOW$3, CLASS_NAME_HIDING);\n this._element.removeAttribute('aria-modal');\n this._element.removeAttribute('role');\n if (!this._config.scroll) {\n new ScrollBarHelper().reset();\n }\n EventHandler.trigger(this._element, EVENT_HIDDEN$3);\n };\n this._queueCallback(completeCallback, this._element, true);\n }\n dispose() {\n this._backdrop.dispose();\n this._focustrap.deactivate();\n super.dispose();\n }\n\n // Private\n _initializeBackDrop() {\n const clickCallback = () => {\n if (this._config.backdrop === 'static') {\n EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED);\n return;\n }\n this.hide();\n };\n\n // 'static' option will be translated to true, and booleans will keep their value\n const isVisible = Boolean(this._config.backdrop);\n return new Backdrop({\n className: CLASS_NAME_BACKDROP,\n isVisible,\n isAnimated: true,\n rootElement: this._element.parentNode,\n clickCallback: isVisible ? clickCallback : null\n });\n }\n _initializeFocusTrap() {\n return new FocusTrap({\n trapElement: this._element\n });\n }\n _addEventListeners() {\n EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS, event => {\n if (event.key !== ESCAPE_KEY) {\n return;\n }\n if (this._config.keyboard) {\n this.hide();\n return;\n }\n EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED);\n });\n }\n\n // Static\n static jQueryInterface(config) {\n return this.each(function () {\n const data = Offcanvas.getOrCreateInstance(this, config);\n if (typeof config !== 'string') {\n return;\n }\n if (data[config] === undefined || config.startsWith('_') || config === 'constructor') {\n throw new TypeError(`No method named \"${config}\"`);\n }\n data[config](this);\n });\n }\n}\n\n/**\n * Data API implementation\n */\n\nEventHandler.on(document, EVENT_CLICK_DATA_API$1, SELECTOR_DATA_TOGGLE$1, function (event) {\n const target = SelectorEngine.getElementFromSelector(this);\n if (['A', 'AREA'].includes(this.tagName)) {\n event.preventDefault();\n }\n if (isDisabled(this)) {\n return;\n }\n EventHandler.one(target, EVENT_HIDDEN$3, () => {\n // focus on trigger when it is closed\n if (isVisible(this)) {\n this.focus();\n }\n });\n\n // avoid conflict when clicking a toggler of an offcanvas, while another is open\n const alreadyOpen = SelectorEngine.findOne(OPEN_SELECTOR);\n if (alreadyOpen && alreadyOpen !== target) {\n Offcanvas.getInstance(alreadyOpen).hide();\n }\n const data = Offcanvas.getOrCreateInstance(target);\n data.toggle(this);\n});\nEventHandler.on(window, EVENT_LOAD_DATA_API$2, () => {\n for (const selector of SelectorEngine.find(OPEN_SELECTOR)) {\n Offcanvas.getOrCreateInstance(selector).show();\n }\n});\nEventHandler.on(window, EVENT_RESIZE, () => {\n for (const element of SelectorEngine.find('[aria-modal][class*=show][class*=offcanvas-]')) {\n if (getComputedStyle(element).position !== 'fixed') {\n Offcanvas.getOrCreateInstance(element).hide();\n }\n }\n});\nenableDismissTrigger(Offcanvas);\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Offcanvas);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/sanitizer.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n// js-docs-start allow-list\nconst ARIA_ATTRIBUTE_PATTERN = /^aria-[\\w-]*$/i;\nconst DefaultAllowlist = {\n // Global attributes allowed on any supplied element below.\n '*': ['class', 'dir', 'id', 'lang', 'role', ARIA_ATTRIBUTE_PATTERN],\n a: ['target', 'href', 'title', 'rel'],\n area: [],\n b: [],\n br: [],\n col: [],\n code: [],\n dd: [],\n div: [],\n dl: [],\n dt: [],\n em: [],\n hr: [],\n h1: [],\n h2: [],\n h3: [],\n h4: [],\n h5: [],\n h6: [],\n i: [],\n img: ['src', 'srcset', 'alt', 'title', 'width', 'height'],\n li: [],\n ol: [],\n p: [],\n pre: [],\n s: [],\n small: [],\n span: [],\n sub: [],\n sup: [],\n strong: [],\n u: [],\n ul: []\n};\n// js-docs-end allow-list\n\nconst uriAttributes = new Set(['background', 'cite', 'href', 'itemtype', 'longdesc', 'poster', 'src', 'xlink:href']);\n\n/**\n * A pattern that recognizes URLs that are safe wrt. XSS in URL navigation\n * contexts.\n *\n * Shout-out to Angular https://github.com/angular/angular/blob/15.2.8/packages/core/src/sanitization/url_sanitizer.ts#L38\n */\n// eslint-disable-next-line unicorn/better-regex\nconst SAFE_URL_PATTERN = /^(?!javascript:)(?:[a-z0-9+.-]+:|[^&:/?#]*(?:[/?#]|$))/i;\nconst allowedAttribute = (attribute, allowedAttributeList) => {\n const attributeName = attribute.nodeName.toLowerCase();\n if (allowedAttributeList.includes(attributeName)) {\n if (uriAttributes.has(attributeName)) {\n return Boolean(SAFE_URL_PATTERN.test(attribute.nodeValue));\n }\n return true;\n }\n\n // Check if a regular expression validates the attribute.\n return allowedAttributeList.filter(attributeRegex => attributeRegex instanceof RegExp).some(regex => regex.test(attributeName));\n};\nfunction sanitizeHtml(unsafeHtml, allowList, sanitizeFunction) {\n if (!unsafeHtml.length) {\n return unsafeHtml;\n }\n if (sanitizeFunction && typeof sanitizeFunction === 'function') {\n return sanitizeFunction(unsafeHtml);\n }\n const domParser = new window.DOMParser();\n const createdDocument = domParser.parseFromString(unsafeHtml, 'text/html');\n const elements = [].concat(...createdDocument.body.querySelectorAll('*'));\n for (const element of elements) {\n const elementName = element.nodeName.toLowerCase();\n if (!Object.keys(allowList).includes(elementName)) {\n element.remove();\n continue;\n }\n const attributeList = [].concat(...element.attributes);\n const allowedAttributes = [].concat(allowList['*'] || [], allowList[elementName] || []);\n for (const attribute of attributeList) {\n if (!allowedAttribute(attribute, allowedAttributes)) {\n element.removeAttribute(attribute.nodeName);\n }\n }\n }\n return createdDocument.body.innerHTML;\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap util/template-factory.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$5 = 'TemplateFactory';\nconst Default$4 = {\n allowList: DefaultAllowlist,\n content: {},\n // { selector : text , selector2 : text2 , }\n extraClass: '',\n html: false,\n sanitize: true,\n sanitizeFn: null,\n template: '
    '\n};\nconst DefaultType$4 = {\n allowList: 'object',\n content: 'object',\n extraClass: '(string|function)',\n html: 'boolean',\n sanitize: 'boolean',\n sanitizeFn: '(null|function)',\n template: 'string'\n};\nconst DefaultContentType = {\n entry: '(string|element|function|null)',\n selector: '(string|element)'\n};\n\n/**\n * Class definition\n */\n\nclass TemplateFactory extends Config {\n constructor(config) {\n super();\n this._config = this._getConfig(config);\n }\n\n // Getters\n static get Default() {\n return Default$4;\n }\n static get DefaultType() {\n return DefaultType$4;\n }\n static get NAME() {\n return NAME$5;\n }\n\n // Public\n getContent() {\n return Object.values(this._config.content).map(config => this._resolvePossibleFunction(config)).filter(Boolean);\n }\n hasContent() {\n return this.getContent().length > 0;\n }\n changeContent(content) {\n this._checkContent(content);\n this._config.content = {\n ...this._config.content,\n ...content\n };\n return this;\n }\n toHtml() {\n const templateWrapper = document.createElement('div');\n templateWrapper.innerHTML = this._maybeSanitize(this._config.template);\n for (const [selector, text] of Object.entries(this._config.content)) {\n this._setContent(templateWrapper, text, selector);\n }\n const template = templateWrapper.children[0];\n const extraClass = this._resolvePossibleFunction(this._config.extraClass);\n if (extraClass) {\n template.classList.add(...extraClass.split(' '));\n }\n return template;\n }\n\n // Private\n _typeCheckConfig(config) {\n super._typeCheckConfig(config);\n this._checkContent(config.content);\n }\n _checkContent(arg) {\n for (const [selector, content] of Object.entries(arg)) {\n super._typeCheckConfig({\n selector,\n entry: content\n }, DefaultContentType);\n }\n }\n _setContent(template, content, selector) {\n const templateElement = SelectorEngine.findOne(selector, template);\n if (!templateElement) {\n return;\n }\n content = this._resolvePossibleFunction(content);\n if (!content) {\n templateElement.remove();\n return;\n }\n if (isElement(content)) {\n this._putElementInTemplate(getElement(content), templateElement);\n return;\n }\n if (this._config.html) {\n templateElement.innerHTML = this._maybeSanitize(content);\n return;\n }\n templateElement.textContent = content;\n }\n _maybeSanitize(arg) {\n return this._config.sanitize ? sanitizeHtml(arg, this._config.allowList, this._config.sanitizeFn) : arg;\n }\n _resolvePossibleFunction(arg) {\n return execute(arg, [this]);\n }\n _putElementInTemplate(element, templateElement) {\n if (this._config.html) {\n templateElement.innerHTML = '';\n templateElement.append(element);\n return;\n }\n templateElement.textContent = element.textContent;\n }\n}\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap tooltip.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$4 = 'tooltip';\nconst DISALLOWED_ATTRIBUTES = new Set(['sanitize', 'allowList', 'sanitizeFn']);\nconst CLASS_NAME_FADE$2 = 'fade';\nconst CLASS_NAME_MODAL = 'modal';\nconst CLASS_NAME_SHOW$2 = 'show';\nconst SELECTOR_TOOLTIP_INNER = '.tooltip-inner';\nconst SELECTOR_MODAL = `.${CLASS_NAME_MODAL}`;\nconst EVENT_MODAL_HIDE = 'hide.bs.modal';\nconst TRIGGER_HOVER = 'hover';\nconst TRIGGER_FOCUS = 'focus';\nconst TRIGGER_CLICK = 'click';\nconst TRIGGER_MANUAL = 'manual';\nconst EVENT_HIDE$2 = 'hide';\nconst EVENT_HIDDEN$2 = 'hidden';\nconst EVENT_SHOW$2 = 'show';\nconst EVENT_SHOWN$2 = 'shown';\nconst EVENT_INSERTED = 'inserted';\nconst EVENT_CLICK$1 = 'click';\nconst EVENT_FOCUSIN$1 = 'focusin';\nconst EVENT_FOCUSOUT$1 = 'focusout';\nconst EVENT_MOUSEENTER = 'mouseenter';\nconst EVENT_MOUSELEAVE = 'mouseleave';\nconst AttachmentMap = {\n AUTO: 'auto',\n TOP: 'top',\n RIGHT: isRTL() ? 'left' : 'right',\n BOTTOM: 'bottom',\n LEFT: isRTL() ? 'right' : 'left'\n};\nconst Default$3 = {\n allowList: DefaultAllowlist,\n animation: true,\n boundary: 'clippingParents',\n container: false,\n customClass: '',\n delay: 0,\n fallbackPlacements: ['top', 'right', 'bottom', 'left'],\n html: false,\n offset: [0, 6],\n placement: 'top',\n popperConfig: null,\n sanitize: true,\n sanitizeFn: null,\n selector: false,\n template: '
    ' + '
    ' + '
    ' + '
    ',\n title: '',\n trigger: 'hover focus'\n};\nconst DefaultType$3 = {\n allowList: 'object',\n animation: 'boolean',\n boundary: '(string|element)',\n container: '(string|element|boolean)',\n customClass: '(string|function)',\n delay: '(number|object)',\n fallbackPlacements: 'array',\n html: 'boolean',\n offset: '(array|string|function)',\n placement: '(string|function)',\n popperConfig: '(null|object|function)',\n sanitize: 'boolean',\n sanitizeFn: '(null|function)',\n selector: '(string|boolean)',\n template: 'string',\n title: '(string|element|function)',\n trigger: 'string'\n};\n\n/**\n * Class definition\n */\n\nclass Tooltip extends BaseComponent {\n constructor(element, config) {\n if (typeof Popper === 'undefined') {\n throw new TypeError('Bootstrap\\'s tooltips require Popper (https://popper.js.org)');\n }\n super(element, config);\n\n // Private\n this._isEnabled = true;\n this._timeout = 0;\n this._isHovered = null;\n this._activeTrigger = {};\n this._popper = null;\n this._templateFactory = null;\n this._newContent = null;\n\n // Protected\n this.tip = null;\n this._setListeners();\n if (!this._config.selector) {\n this._fixTitle();\n }\n }\n\n // Getters\n static get Default() {\n return Default$3;\n }\n static get DefaultType() {\n return DefaultType$3;\n }\n static get NAME() {\n return NAME$4;\n }\n\n // Public\n enable() {\n this._isEnabled = true;\n }\n disable() {\n this._isEnabled = false;\n }\n toggleEnabled() {\n this._isEnabled = !this._isEnabled;\n }\n toggle() {\n if (!this._isEnabled) {\n return;\n }\n this._activeTrigger.click = !this._activeTrigger.click;\n if (this._isShown()) {\n this._leave();\n return;\n }\n this._enter();\n }\n dispose() {\n clearTimeout(this._timeout);\n EventHandler.off(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler);\n if (this._element.getAttribute('data-bs-original-title')) {\n this._element.setAttribute('title', this._element.getAttribute('data-bs-original-title'));\n }\n this._disposePopper();\n super.dispose();\n }\n show() {\n if (this._element.style.display === 'none') {\n throw new Error('Please use show on visible elements');\n }\n if (!(this._isWithContent() && this._isEnabled)) {\n return;\n }\n const showEvent = EventHandler.trigger(this._element, this.constructor.eventName(EVENT_SHOW$2));\n const shadowRoot = findShadowRoot(this._element);\n const isInTheDom = (shadowRoot || this._element.ownerDocument.documentElement).contains(this._element);\n if (showEvent.defaultPrevented || !isInTheDom) {\n return;\n }\n\n // TODO: v6 remove this or make it optional\n this._disposePopper();\n const tip = this._getTipElement();\n this._element.setAttribute('aria-describedby', tip.getAttribute('id'));\n const {\n container\n } = this._config;\n if (!this._element.ownerDocument.documentElement.contains(this.tip)) {\n container.append(tip);\n EventHandler.trigger(this._element, this.constructor.eventName(EVENT_INSERTED));\n }\n this._popper = this._createPopper(tip);\n tip.classList.add(CLASS_NAME_SHOW$2);\n\n // If this is a touch-enabled device we add extra\n // empty mouseover listeners to the body's immediate children;\n // only needed because of broken event delegation on iOS\n // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html\n if ('ontouchstart' in document.documentElement) {\n for (const element of [].concat(...document.body.children)) {\n EventHandler.on(element, 'mouseover', noop);\n }\n }\n const complete = () => {\n EventHandler.trigger(this._element, this.constructor.eventName(EVENT_SHOWN$2));\n if (this._isHovered === false) {\n this._leave();\n }\n this._isHovered = false;\n };\n this._queueCallback(complete, this.tip, this._isAnimated());\n }\n hide() {\n if (!this._isShown()) {\n return;\n }\n const hideEvent = EventHandler.trigger(this._element, this.constructor.eventName(EVENT_HIDE$2));\n if (hideEvent.defaultPrevented) {\n return;\n }\n const tip = this._getTipElement();\n tip.classList.remove(CLASS_NAME_SHOW$2);\n\n // If this is a touch-enabled device we remove the extra\n // empty mouseover listeners we added for iOS support\n if ('ontouchstart' in document.documentElement) {\n for (const element of [].concat(...document.body.children)) {\n EventHandler.off(element, 'mouseover', noop);\n }\n }\n this._activeTrigger[TRIGGER_CLICK] = false;\n this._activeTrigger[TRIGGER_FOCUS] = false;\n this._activeTrigger[TRIGGER_HOVER] = false;\n this._isHovered = null; // it is a trick to support manual triggering\n\n const complete = () => {\n if (this._isWithActiveTrigger()) {\n return;\n }\n if (!this._isHovered) {\n this._disposePopper();\n }\n this._element.removeAttribute('aria-describedby');\n EventHandler.trigger(this._element, this.constructor.eventName(EVENT_HIDDEN$2));\n };\n this._queueCallback(complete, this.tip, this._isAnimated());\n }\n update() {\n if (this._popper) {\n this._popper.update();\n }\n }\n\n // Protected\n _isWithContent() {\n return Boolean(this._getTitle());\n }\n _getTipElement() {\n if (!this.tip) {\n this.tip = this._createTipElement(this._newContent || this._getContentForTemplate());\n }\n return this.tip;\n }\n _createTipElement(content) {\n const tip = this._getTemplateFactory(content).toHtml();\n\n // TODO: remove this check in v6\n if (!tip) {\n return null;\n }\n tip.classList.remove(CLASS_NAME_FADE$2, CLASS_NAME_SHOW$2);\n // TODO: v6 the following can be achieved with CSS only\n tip.classList.add(`bs-${this.constructor.NAME}-auto`);\n const tipId = getUID(this.constructor.NAME).toString();\n tip.setAttribute('id', tipId);\n if (this._isAnimated()) {\n tip.classList.add(CLASS_NAME_FADE$2);\n }\n return tip;\n }\n setContent(content) {\n this._newContent = content;\n if (this._isShown()) {\n this._disposePopper();\n this.show();\n }\n }\n _getTemplateFactory(content) {\n if (this._templateFactory) {\n this._templateFactory.changeContent(content);\n } else {\n this._templateFactory = new TemplateFactory({\n ...this._config,\n // the `content` var has to be after `this._config`\n // to override config.content in case of popover\n content,\n extraClass: this._resolvePossibleFunction(this._config.customClass)\n });\n }\n return this._templateFactory;\n }\n _getContentForTemplate() {\n return {\n [SELECTOR_TOOLTIP_INNER]: this._getTitle()\n };\n }\n _getTitle() {\n return this._resolvePossibleFunction(this._config.title) || this._element.getAttribute('data-bs-original-title');\n }\n\n // Private\n _initializeOnDelegatedTarget(event) {\n return this.constructor.getOrCreateInstance(event.delegateTarget, this._getDelegateConfig());\n }\n _isAnimated() {\n return this._config.animation || this.tip && this.tip.classList.contains(CLASS_NAME_FADE$2);\n }\n _isShown() {\n return this.tip && this.tip.classList.contains(CLASS_NAME_SHOW$2);\n }\n _createPopper(tip) {\n const placement = execute(this._config.placement, [this, tip, this._element]);\n const attachment = AttachmentMap[placement.toUpperCase()];\n return Popper.createPopper(this._element, tip, this._getPopperConfig(attachment));\n }\n _getOffset() {\n const {\n offset\n } = this._config;\n if (typeof offset === 'string') {\n return offset.split(',').map(value => Number.parseInt(value, 10));\n }\n if (typeof offset === 'function') {\n return popperData => offset(popperData, this._element);\n }\n return offset;\n }\n _resolvePossibleFunction(arg) {\n return execute(arg, [this._element]);\n }\n _getPopperConfig(attachment) {\n const defaultBsPopperConfig = {\n placement: attachment,\n modifiers: [{\n name: 'flip',\n options: {\n fallbackPlacements: this._config.fallbackPlacements\n }\n }, {\n name: 'offset',\n options: {\n offset: this._getOffset()\n }\n }, {\n name: 'preventOverflow',\n options: {\n boundary: this._config.boundary\n }\n }, {\n name: 'arrow',\n options: {\n element: `.${this.constructor.NAME}-arrow`\n }\n }, {\n name: 'preSetPlacement',\n enabled: true,\n phase: 'beforeMain',\n fn: data => {\n // Pre-set Popper's placement attribute in order to read the arrow sizes properly.\n // Otherwise, Popper mixes up the width and height dimensions since the initial arrow style is for top placement\n this._getTipElement().setAttribute('data-popper-placement', data.state.placement);\n }\n }]\n };\n return {\n ...defaultBsPopperConfig,\n ...execute(this._config.popperConfig, [defaultBsPopperConfig])\n };\n }\n _setListeners() {\n const triggers = this._config.trigger.split(' ');\n for (const trigger of triggers) {\n if (trigger === 'click') {\n EventHandler.on(this._element, this.constructor.eventName(EVENT_CLICK$1), this._config.selector, event => {\n const context = this._initializeOnDelegatedTarget(event);\n context.toggle();\n });\n } else if (trigger !== TRIGGER_MANUAL) {\n const eventIn = trigger === TRIGGER_HOVER ? this.constructor.eventName(EVENT_MOUSEENTER) : this.constructor.eventName(EVENT_FOCUSIN$1);\n const eventOut = trigger === TRIGGER_HOVER ? this.constructor.eventName(EVENT_MOUSELEAVE) : this.constructor.eventName(EVENT_FOCUSOUT$1);\n EventHandler.on(this._element, eventIn, this._config.selector, event => {\n const context = this._initializeOnDelegatedTarget(event);\n context._activeTrigger[event.type === 'focusin' ? TRIGGER_FOCUS : TRIGGER_HOVER] = true;\n context._enter();\n });\n EventHandler.on(this._element, eventOut, this._config.selector, event => {\n const context = this._initializeOnDelegatedTarget(event);\n context._activeTrigger[event.type === 'focusout' ? TRIGGER_FOCUS : TRIGGER_HOVER] = context._element.contains(event.relatedTarget);\n context._leave();\n });\n }\n }\n this._hideModalHandler = () => {\n if (this._element) {\n this.hide();\n }\n };\n EventHandler.on(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler);\n }\n _fixTitle() {\n const title = this._element.getAttribute('title');\n if (!title) {\n return;\n }\n if (!this._element.getAttribute('aria-label') && !this._element.textContent.trim()) {\n this._element.setAttribute('aria-label', title);\n }\n this._element.setAttribute('data-bs-original-title', title); // DO NOT USE IT. Is only for backwards compatibility\n this._element.removeAttribute('title');\n }\n _enter() {\n if (this._isShown() || this._isHovered) {\n this._isHovered = true;\n return;\n }\n this._isHovered = true;\n this._setTimeout(() => {\n if (this._isHovered) {\n this.show();\n }\n }, this._config.delay.show);\n }\n _leave() {\n if (this._isWithActiveTrigger()) {\n return;\n }\n this._isHovered = false;\n this._setTimeout(() => {\n if (!this._isHovered) {\n this.hide();\n }\n }, this._config.delay.hide);\n }\n _setTimeout(handler, timeout) {\n clearTimeout(this._timeout);\n this._timeout = setTimeout(handler, timeout);\n }\n _isWithActiveTrigger() {\n return Object.values(this._activeTrigger).includes(true);\n }\n _getConfig(config) {\n const dataAttributes = Manipulator.getDataAttributes(this._element);\n for (const dataAttribute of Object.keys(dataAttributes)) {\n if (DISALLOWED_ATTRIBUTES.has(dataAttribute)) {\n delete dataAttributes[dataAttribute];\n }\n }\n config = {\n ...dataAttributes,\n ...(typeof config === 'object' && config ? config : {})\n };\n config = this._mergeConfigObj(config);\n config = this._configAfterMerge(config);\n this._typeCheckConfig(config);\n return config;\n }\n _configAfterMerge(config) {\n config.container = config.container === false ? document.body : getElement(config.container);\n if (typeof config.delay === 'number') {\n config.delay = {\n show: config.delay,\n hide: config.delay\n };\n }\n if (typeof config.title === 'number') {\n config.title = config.title.toString();\n }\n if (typeof config.content === 'number') {\n config.content = config.content.toString();\n }\n return config;\n }\n _getDelegateConfig() {\n const config = {};\n for (const [key, value] of Object.entries(this._config)) {\n if (this.constructor.Default[key] !== value) {\n config[key] = value;\n }\n }\n config.selector = false;\n config.trigger = 'manual';\n\n // In the future can be replaced with:\n // const keysWithDifferentValues = Object.entries(this._config).filter(entry => this.constructor.Default[entry[0]] !== this._config[entry[0]])\n // `Object.fromEntries(keysWithDifferentValues)`\n return config;\n }\n _disposePopper() {\n if (this._popper) {\n this._popper.destroy();\n this._popper = null;\n }\n if (this.tip) {\n this.tip.remove();\n this.tip = null;\n }\n }\n\n // Static\n static jQueryInterface(config) {\n return this.each(function () {\n const data = Tooltip.getOrCreateInstance(this, config);\n if (typeof config !== 'string') {\n return;\n }\n if (typeof data[config] === 'undefined') {\n throw new TypeError(`No method named \"${config}\"`);\n }\n data[config]();\n });\n }\n}\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Tooltip);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap popover.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$3 = 'popover';\nconst SELECTOR_TITLE = '.popover-header';\nconst SELECTOR_CONTENT = '.popover-body';\nconst Default$2 = {\n ...Tooltip.Default,\n content: '',\n offset: [0, 8],\n placement: 'right',\n template: '
    ' + '
    ' + '

    ' + '
    ' + '
    ',\n trigger: 'click'\n};\nconst DefaultType$2 = {\n ...Tooltip.DefaultType,\n content: '(null|string|element|function)'\n};\n\n/**\n * Class definition\n */\n\nclass Popover extends Tooltip {\n // Getters\n static get Default() {\n return Default$2;\n }\n static get DefaultType() {\n return DefaultType$2;\n }\n static get NAME() {\n return NAME$3;\n }\n\n // Overrides\n _isWithContent() {\n return this._getTitle() || this._getContent();\n }\n\n // Private\n _getContentForTemplate() {\n return {\n [SELECTOR_TITLE]: this._getTitle(),\n [SELECTOR_CONTENT]: this._getContent()\n };\n }\n _getContent() {\n return this._resolvePossibleFunction(this._config.content);\n }\n\n // Static\n static jQueryInterface(config) {\n return this.each(function () {\n const data = Popover.getOrCreateInstance(this, config);\n if (typeof config !== 'string') {\n return;\n }\n if (typeof data[config] === 'undefined') {\n throw new TypeError(`No method named \"${config}\"`);\n }\n data[config]();\n });\n }\n}\n\n/**\n * jQuery\n */\n\ndefineJQueryPlugin(Popover);\n\n/**\n * --------------------------------------------------------------------------\n * Bootstrap scrollspy.js\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)\n * --------------------------------------------------------------------------\n */\n\n\n/**\n * Constants\n */\n\nconst NAME$2 = 'scrollspy';\nconst DATA_KEY$2 = 'bs.scrollspy';\nconst EVENT_KEY$2 = `.${DATA_KEY$2}`;\nconst DATA_API_KEY = '.data-api';\nconst EVENT_ACTIVATE = `activate${EVENT_KEY$2}`;\nconst EVENT_CLICK = `click${EVENT_KEY$2}`;\nconst EVENT_LOAD_DATA_API$1 = `load${EVENT_KEY$2}${DATA_API_KEY}`;\nconst CLASS_NAME_DROPDOWN_ITEM = 'dropdown-item';\nconst CLASS_NAME_ACTIVE$1 = 'active';\nconst SELECTOR_DATA_SPY = '[data-bs-spy=\"scroll\"]';\nconst SELECTOR_TARGET_LINKS = '[href]';\nconst SELECTOR_NAV_LIST_GROUP = '.nav, .list-group';\nconst SELECTOR_NAV_LINKS = '.nav-link';\nconst SELECTOR_NAV_ITEMS = '.nav-item';\nconst SELECTOR_LIST_ITEMS = '.list-group-item';\nconst SELECTOR_LINK_ITEMS = `${SELECTOR_NAV_LINKS}, ${SELECTOR_NAV_ITEMS} > ${SELECTOR_NAV_LINKS}, ${SELECTOR_LIST_ITEMS}`;\nconst SELECTOR_DROPDOWN = '.dropdown';\nconst SELECTOR_DROPDOWN_TOGGLE$1 = '.dropdown-toggle';\nconst Default$1 = {\n offset: null,\n // TODO: v6 @deprecated, keep it for backwards compatibility reasons\n rootMargin: '0px 0px -25%',\n smoothScroll: false,\n target: null,\n threshold: [0.1, 0.5, 1]\n};\nconst DefaultType$1 = {\n offset: '(number|null)',\n // TODO v6 @deprecated, keep it for backwards compatibility reasons\n rootMargin: 'string',\n smoothScroll: 'boolean',\n target: 'element',\n threshold: 'array'\n};\n\n/**\n * Class definition\n */\n\nclass ScrollSpy extends BaseComponent {\n constructor(element, config) {\n super(element, config);\n\n // this._element is the observablesContainer and config.target the menu links wrapper\n this._targetLinks = new Map();\n this._observableSections = new Map();\n this._rootElement = getComputedStyle(this._element).overflowY === 'visible' ? null : this._element;\n this._activeTarget = null;\n this._observer = null;\n this._previousScrollData = {\n visibleEntryTop: 0,\n parentScrollTop: 0\n };\n this.refresh(); // initialize\n }\n\n // Getters\n static get Default() {\n return Default$1;\n }\n static get DefaultType() {\n return DefaultType$1;\n }\n static get NAME() {\n return NAME$2;\n }\n\n // Public\n refresh() {\n this._initializeTargetsAndObservables();\n this._maybeEnableSmoothScroll();\n if (this._observer) {\n this._observer.disconnect();\n } else {\n this._observer = this._getNewObserver();\n }\n for (const section of this._observableSections.values()) {\n this._observer.observe(section);\n }\n }\n dispose() {\n this._observer.disconnect();\n super.dispose();\n }\n\n // Private\n _configAfterMerge(config) {\n // TODO: on v6 target should be given explicitly & remove the {target: 'ss-target'} case\n config.target = getElement(config.target) || document.body;\n\n // TODO: v6 Only for backwards compatibility reasons. Use rootMargin only\n config.rootMargin = config.offset ? `${config.offset}px 0px -30%` : config.rootMargin;\n if (typeof config.threshold === 'string') {\n config.threshold = config.threshold.split(',').map(value => Number.parseFloat(value));\n }\n return config;\n }\n _maybeEnableSmoothScroll() {\n if (!this._config.smoothScroll) {\n return;\n }\n\n // unregister any previous listeners\n EventHandler.off(this._config.target, EVENT_CLICK);\n EventHandler.on(this._config.target, EVENT_CLICK, SELECTOR_TARGET_LINKS, event => {\n const observableSection = this._observableSections.get(event.target.hash);\n if (observableSection) {\n event.preventDefault();\n const root = this._rootElement || window;\n const height = observableSection.offsetTop - this._element.offsetTop;\n if (root.scrollTo) {\n root.scrollTo({\n top: height,\n behavior: 'smooth'\n });\n return;\n }\n\n // Chrome 60 doesn't support `scrollTo`\n root.scrollTop = height;\n }\n });\n }\n _getNewObserver() {\n const options = {\n root: this._rootElement,\n threshold: this._config.threshold,\n rootMargin: this._config.rootMargin\n };\n return new IntersectionObserver(entries => this._observerCallback(entries), options);\n }\n\n // The logic of selection\n _observerCallback(entries) {\n const targetElement = entry => this._targetLinks.get(`#${entry.target.id}`);\n const activate = entry => {\n this._previousScrollData.visibleEntryTop = entry.target.offsetTop;\n this._process(targetElement(entry));\n };\n const parentScrollTop = (this._rootElement || document.documentElement).scrollTop;\n const userScrollsDown = parentScrollTop >= this._previousScrollData.parentScrollTop;\n this._previousScrollData.parentScrollTop = parentScrollTop;\n for (const entry of entries) {\n if (!entry.isIntersecting) {\n this._activeTarget = null;\n this._clearActiveClass(targetElement(entry));\n continue;\n }\n const entryIsLowerThanPrevious = entry.target.offsetTop >= this._previousScrollData.visibleEntryTop;\n // if we are scrolling down, pick the bigger offsetTop\n if (userScrollsDown && entryIsLowerThanPrevious) {\n activate(entry);\n // if parent isn't scrolled, let's keep the first visible item, breaking the iteration\n if (!parentScrollTop) {\n return;\n }\n continue;\n }\n\n // if we are scrolling up, pick the smallest offsetTop\n if (!userScrollsDown && !entryIsLowerThanPrevious) {\n activate(entry);\n }\n }\n }\n _initializeTargetsAndObservables() {\n this._targetLinks = new Map();\n this._observableSections = new Map();\n const targetLinks = SelectorEngine.find(SELECTOR_TARGET_LINKS, this._config.target);\n for (const anchor of targetLinks) {\n // ensure that the anchor has an id and is not disabled\n if (!anchor.hash || isDisabled(anchor)) {\n continue;\n }\n const observableSection = SelectorEngine.findOne(decodeURI(anchor.hash), this._element);\n\n // ensure that the observableSection exists & is visible\n if (isVisible(observableSection)) {\n this._targetLinks.set(decodeURI(anchor.hash), anchor);\n this._observableSections.set(anchor.hash, observableSection);\n }\n }\n }\n _process(target) {\n if (this._activeTarget === target) {\n return;\n }\n this._clearActiveClass(this._config.target);\n this._activeTarget = target;\n target.classList.add(CLASS_NAME_ACTIVE$1);\n this._activateParents(target);\n EventHandler.trigger(this._element, EVENT_ACTIVATE, {\n relatedTarget: target\n });\n }\n _activateParents(target) {\n // Activate dropdown parents\n if (target.classList.contains(CLASS_NAME_DROPDOWN_ITEM)) {\n SelectorEngine.findOne(SELECTOR_DROPDOWN_TOGGLE$1, target.closest(SELECTOR_DROPDOWN)).classList.add(CLASS_NAME_ACTIVE$1);\n return;\n }\n for (const listGroup of SelectorEngine.parents(target, SELECTOR_NAV_LIST_GROUP)) {\n // Set triggered links parents as active\n // With both